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"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.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, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getDataLayout();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDiv(32, 8);
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462 // support continuation, user-level threading, and etc.. As a result, no
463 // other SjLj exception interfaces are implemented and please don't build
464 // your own exception handling based on them.
465 // LLVM/Clang supports zero-cost DWARF exception handling.
466 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
470 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
471 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
473 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
474 if (Subtarget->is64Bit())
475 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
477 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
480 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
481 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
482 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
483 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
485 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
488 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
492 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
495 if (Subtarget->hasSSE1())
496 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
498 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
499 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
501 // On X86 and X86-64, atomic operations are lowered to locked instructions.
502 // Locked instructions, in turn, have implicit fence semantics (all memory
503 // operations are flushed before issuing the locked instruction, and they
504 // are not buffered), so we can fold away the common pattern of
505 // fence-atomic-fence.
506 setShouldFoldAtomicFences(true);
508 // Expand certain atomics
509 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
511 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
516 if (!Subtarget->is64Bit()) {
517 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
531 if (Subtarget->hasCmpxchg16b()) {
532 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
535 // FIXME - use subtarget debug flags
536 if (!Subtarget->isTargetDarwin() &&
537 !Subtarget->isTargetELF() &&
538 !Subtarget->isTargetCygMing()) {
539 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
542 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
544 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
546 if (Subtarget->is64Bit()) {
547 setExceptionPointerRegister(X86::RAX);
548 setExceptionSelectorRegister(X86::RDX);
550 setExceptionPointerRegister(X86::EAX);
551 setExceptionSelectorRegister(X86::EDX);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
556 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
559 setOperationAction(ISD::TRAP, MVT::Other, Legal);
560 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
562 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563 setOperationAction(ISD::VASTART , MVT::Other, Custom);
564 setOperationAction(ISD::VAEND , MVT::Other, Expand);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::VAARG , MVT::Other, Custom);
567 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
569 setOperationAction(ISD::VAARG , MVT::Other, Expand);
570 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
573 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
574 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
576 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578 MVT::i64 : MVT::i32, Custom);
579 else if (TM.Options.EnableSegmentedStacks)
580 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581 MVT::i64 : MVT::i32, Custom);
583 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584 MVT::i64 : MVT::i32, Expand);
586 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587 // f32 and f64 use SSE.
588 // Set up the FP register classes.
589 addRegisterClass(MVT::f32, &X86::FR32RegClass);
590 addRegisterClass(MVT::f64, &X86::FR64RegClass);
592 // Use ANDPD to simulate FABS.
593 setOperationAction(ISD::FABS , MVT::f64, Custom);
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f64, Custom);
598 setOperationAction(ISD::FNEG , MVT::f32, Custom);
600 // Use ANDPD and ORPD to simulate FCOPYSIGN.
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604 // Lower this to FGETSIGNx86 plus an AND.
605 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
608 // We don't support sin/cos/fmod
609 setOperationAction(ISD::FSIN , MVT::f64, Expand);
610 setOperationAction(ISD::FCOS , MVT::f64, Expand);
611 setOperationAction(ISD::FSIN , MVT::f32, Expand);
612 setOperationAction(ISD::FCOS , MVT::f32, Expand);
614 // Expand FP immediates into loads from the stack, except for the special
616 addLegalFPImmediate(APFloat(+0.0)); // xorpd
617 addLegalFPImmediate(APFloat(+0.0f)); // xorps
618 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619 // Use SSE for f32, x87 for f64.
620 // Set up the FP register classes.
621 addRegisterClass(MVT::f32, &X86::FR32RegClass);
622 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
624 // Use ANDPS to simulate FABS.
625 setOperationAction(ISD::FABS , MVT::f32, Custom);
627 // Use XORP to simulate FNEG.
628 setOperationAction(ISD::FNEG , MVT::f32, Custom);
630 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
632 // Use ANDPS and ORPS to simulate FCOPYSIGN.
633 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
636 // We don't support sin/cos/fmod
637 setOperationAction(ISD::FSIN , MVT::f32, Expand);
638 setOperationAction(ISD::FCOS , MVT::f32, Expand);
640 // Special cases we handle for FP constants.
641 addLegalFPImmediate(APFloat(+0.0f)); // xorps
642 addLegalFPImmediate(APFloat(+0.0)); // FLD0
643 addLegalFPImmediate(APFloat(+1.0)); // FLD1
644 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647 if (!TM.Options.UnsafeFPMath) {
648 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
649 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
651 } else if (!TM.Options.UseSoftFloat) {
652 // f32 and f64 in x87.
653 // Set up the FP register classes.
654 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
657 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
658 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
662 if (!TM.Options.UnsafeFPMath) {
663 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
664 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
666 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
668 addLegalFPImmediate(APFloat(+0.0)); // FLD0
669 addLegalFPImmediate(APFloat(+1.0)); // FLD1
670 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
678 // We don't support FMA.
679 setOperationAction(ISD::FMA, MVT::f64, Expand);
680 setOperationAction(ISD::FMA, MVT::f32, Expand);
682 // Long double always uses X87.
683 if (!TM.Options.UseSoftFloat) {
684 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
686 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
688 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689 addLegalFPImmediate(TmpFlt); // FLD0
691 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
694 APFloat TmpFlt2(+1.0);
695 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
697 addLegalFPImmediate(TmpFlt2); // FLD1
698 TmpFlt2.changeSign();
699 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
702 if (!TM.Options.UnsafeFPMath) {
703 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
704 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
707 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
709 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710 setOperationAction(ISD::FRINT, MVT::f80, Expand);
711 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712 setOperationAction(ISD::FMA, MVT::f80, Expand);
715 // Always use a library call for pow.
716 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
718 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
720 setOperationAction(ISD::FLOG, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP, MVT::f80, Expand);
724 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
726 // First set operation action for all vector types to either promote
727 // (for widening) or expand (for scalarization). Then we will selectively
728 // turn on ones that can be effectively codegen'd.
729 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
786 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
787 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
788 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
789 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
790 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792 setTruncStoreAction((MVT::SimpleValueType)VT,
793 (MVT::SimpleValueType)InnerVT, Expand);
794 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
799 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800 // with -msoft-float, disable use of MMX as well.
801 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803 // No operations on x86mmx supported, everything uses intrinsics.
806 // MMX-sized vectors (other than x86mmx) are expected to be expanded
807 // into smaller operations.
808 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
809 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
810 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
811 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
812 setOperationAction(ISD::AND, MVT::v8i8, Expand);
813 setOperationAction(ISD::AND, MVT::v4i16, Expand);
814 setOperationAction(ISD::AND, MVT::v2i32, Expand);
815 setOperationAction(ISD::AND, MVT::v1i64, Expand);
816 setOperationAction(ISD::OR, MVT::v8i8, Expand);
817 setOperationAction(ISD::OR, MVT::v4i16, Expand);
818 setOperationAction(ISD::OR, MVT::v2i32, Expand);
819 setOperationAction(ISD::OR, MVT::v1i64, Expand);
820 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
821 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
822 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
823 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
829 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
830 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
831 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
832 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
833 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
834 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
835 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
836 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
838 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
841 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
842 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
843 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
844 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
845 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
846 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
847 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
848 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
849 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
850 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
855 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
858 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859 // registers cannot be used even for integer operations.
860 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
865 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
866 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
867 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
868 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
869 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
870 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
871 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
872 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
873 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
874 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
875 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
876 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
877 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
878 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
879 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
880 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
881 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
883 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
884 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
885 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
886 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
897 // Do not attempt to custom lower non-power-of-2 vectors
898 if (!isPowerOf2_32(VT.getVectorNumElements()))
900 // Do not attempt to custom lower non-128-bit vectors
901 if (!VT.is128BitVector())
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
909 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
911 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
915 if (Subtarget->is64Bit()) {
916 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
920 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922 MVT VT = (MVT::SimpleValueType)i;
924 // Do not attempt to promote non-128-bit vectors
925 if (!VT.is128BitVector())
928 setOperationAction(ISD::AND, VT, Promote);
929 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
930 setOperationAction(ISD::OR, VT, Promote);
931 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
932 setOperationAction(ISD::XOR, VT, Promote);
933 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
934 setOperationAction(ISD::LOAD, VT, Promote);
935 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
936 setOperationAction(ISD::SELECT, VT, Promote);
937 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
940 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // Custom lower v2i64 and v2f64 selects.
943 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
944 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
945 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
946 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
948 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
949 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
951 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
952 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
954 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
957 if (Subtarget->hasSSE41()) {
958 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
959 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
960 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
961 setOperationAction(ISD::FRINT, MVT::f32, Legal);
962 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
963 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
964 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
965 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
966 setOperationAction(ISD::FRINT, MVT::f64, Legal);
967 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
969 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
970 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
972 // FIXME: Do we need to handle scalar-to-vector here?
973 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
975 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
976 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
977 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
978 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
979 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
981 // i8 and i16 vectors are custom , because the source register and source
982 // source memory operand types are not the same width. f32 vectors are
983 // custom since the immediate controlling the insert encodes additional
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
995 // FIXME: these should be Legal but thats only for the case where
996 // the index is constant. For now custom expand to deal with that.
997 if (Subtarget->is64Bit()) {
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003 if (Subtarget->hasSSE2()) {
1004 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1005 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1007 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1008 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1010 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1013 if (Subtarget->hasAVX2()) {
1014 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1015 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1017 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1022 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1023 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1025 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1032 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1033 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1040 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1042 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1044 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1051 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1053 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1060 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1062 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1064 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1066 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1068 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1070 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1072 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1073 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1075 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1076 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1078 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1079 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1081 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1083 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1084 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1086 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1087 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1090 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1091 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1092 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1093 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1095 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1096 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1097 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1098 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1099 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1100 setOperationAction(ISD::FMA, MVT::f32, Custom);
1101 setOperationAction(ISD::FMA, MVT::f64, Custom);
1104 if (Subtarget->hasAVX2()) {
1105 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1106 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1107 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1108 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1110 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1111 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1112 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1113 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1115 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1116 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1117 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1118 // Don't lower v32i8 because there is no 128-bit byte mul
1120 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1122 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1123 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1125 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1126 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1128 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1130 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1131 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1132 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1133 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1135 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1136 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1137 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1138 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1140 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1141 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1142 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1143 // Don't lower v32i8 because there is no 128-bit byte mul
1145 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1146 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1148 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1149 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1151 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1154 // Custom lower several nodes for 256-bit types.
1155 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1156 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1157 MVT VT = (MVT::SimpleValueType)i;
1159 // Extract subvector is special because the value type
1160 // (result) is 128-bit but the source is 256-bit wide.
1161 if (VT.is128BitVector())
1162 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1164 // Do not attempt to custom lower other non-256-bit vectors
1165 if (!VT.is256BitVector())
1168 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1169 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1170 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1171 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1172 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1173 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1174 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1177 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1178 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1179 MVT VT = (MVT::SimpleValueType)i;
1181 // Do not attempt to promote non-256-bit vectors
1182 if (!VT.is256BitVector())
1185 setOperationAction(ISD::AND, VT, Promote);
1186 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1187 setOperationAction(ISD::OR, VT, Promote);
1188 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1189 setOperationAction(ISD::XOR, VT, Promote);
1190 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1191 setOperationAction(ISD::LOAD, VT, Promote);
1192 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1193 setOperationAction(ISD::SELECT, VT, Promote);
1194 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1198 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1199 // of this type with custom code.
1200 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1201 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1202 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1206 // We want to custom lower some of our intrinsics.
1207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1208 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1211 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1212 // handle type legalization for these operations here.
1214 // FIXME: We really should do custom legalization for addition and
1215 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1216 // than generic legalization for 64-bit multiplication-with-overflow, though.
1217 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1218 // Add/Sub/Mul with overflow operations are custom lowered.
1220 setOperationAction(ISD::SADDO, VT, Custom);
1221 setOperationAction(ISD::UADDO, VT, Custom);
1222 setOperationAction(ISD::SSUBO, VT, Custom);
1223 setOperationAction(ISD::USUBO, VT, Custom);
1224 setOperationAction(ISD::SMULO, VT, Custom);
1225 setOperationAction(ISD::UMULO, VT, Custom);
1228 // There are no 8-bit 3-address imul/mul instructions
1229 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1230 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1232 if (!Subtarget->is64Bit()) {
1233 // These libcalls are not available in 32-bit.
1234 setLibcallName(RTLIB::SHL_I128, 0);
1235 setLibcallName(RTLIB::SRL_I128, 0);
1236 setLibcallName(RTLIB::SRA_I128, 0);
1239 // We have target-specific dag combine patterns for the following nodes:
1240 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1241 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1242 setTargetDAGCombine(ISD::VSELECT);
1243 setTargetDAGCombine(ISD::SELECT);
1244 setTargetDAGCombine(ISD::SHL);
1245 setTargetDAGCombine(ISD::SRA);
1246 setTargetDAGCombine(ISD::SRL);
1247 setTargetDAGCombine(ISD::OR);
1248 setTargetDAGCombine(ISD::AND);
1249 setTargetDAGCombine(ISD::ADD);
1250 setTargetDAGCombine(ISD::FADD);
1251 setTargetDAGCombine(ISD::FSUB);
1252 setTargetDAGCombine(ISD::FMA);
1253 setTargetDAGCombine(ISD::SUB);
1254 setTargetDAGCombine(ISD::LOAD);
1255 setTargetDAGCombine(ISD::STORE);
1256 setTargetDAGCombine(ISD::ZERO_EXTEND);
1257 setTargetDAGCombine(ISD::ANY_EXTEND);
1258 setTargetDAGCombine(ISD::SIGN_EXTEND);
1259 setTargetDAGCombine(ISD::TRUNCATE);
1260 setTargetDAGCombine(ISD::UINT_TO_FP);
1261 setTargetDAGCombine(ISD::SINT_TO_FP);
1262 setTargetDAGCombine(ISD::SETCC);
1263 if (Subtarget->is64Bit())
1264 setTargetDAGCombine(ISD::MUL);
1265 setTargetDAGCombine(ISD::XOR);
1267 computeRegisterProperties();
1269 // On Darwin, -Os means optimize for size without hurting performance,
1270 // do not reduce the limit.
1271 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1272 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1273 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1274 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1275 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1276 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1277 setPrefLoopAlignment(4); // 2^4 bytes.
1278 benefitFromCodePlacementOpt = true;
1280 // Predictable cmov don't hurt on atom because it's in-order.
1281 predictableSelectIsExpensive = !Subtarget->isAtom();
1283 setPrefFunctionAlignment(4); // 2^4 bytes.
1287 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1288 if (!VT.isVector()) return MVT::i8;
1289 return VT.changeVectorElementTypeToInteger();
1293 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1294 /// the desired ByVal argument alignment.
1295 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1298 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1299 if (VTy->getBitWidth() == 128)
1301 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1302 unsigned EltAlign = 0;
1303 getMaxByValAlign(ATy->getElementType(), EltAlign);
1304 if (EltAlign > MaxAlign)
1305 MaxAlign = EltAlign;
1306 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1307 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1308 unsigned EltAlign = 0;
1309 getMaxByValAlign(STy->getElementType(i), EltAlign);
1310 if (EltAlign > MaxAlign)
1311 MaxAlign = EltAlign;
1318 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1319 /// function arguments in the caller parameter area. For X86, aggregates
1320 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1321 /// are at 4-byte boundaries.
1322 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1323 if (Subtarget->is64Bit()) {
1324 // Max of 8 and alignment of type.
1325 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1332 if (Subtarget->hasSSE1())
1333 getMaxByValAlign(Ty, Align);
1337 /// getOptimalMemOpType - Returns the target specific optimal type for load
1338 /// and store operations as a result of memset, memcpy, and memmove
1339 /// lowering. If DstAlign is zero that means it's safe to destination
1340 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1341 /// means there isn't a need to check it against alignment requirement,
1342 /// probably because the source does not need to be loaded. If
1343 /// 'IsZeroVal' is true, that means it's safe to return a
1344 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1345 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1346 /// constant so it does not need to be loaded.
1347 /// It returns EVT::Other if the type should be determined using generic
1348 /// target-independent logic.
1350 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1351 unsigned DstAlign, unsigned SrcAlign,
1354 MachineFunction &MF) const {
1355 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1356 // linux. This is because the stack realignment code can't handle certain
1357 // cases like PR2962. This should be removed when PR2962 is fixed.
1358 const Function *F = MF.getFunction();
1360 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1362 (Subtarget->isUnalignedMemAccessFast() ||
1363 ((DstAlign == 0 || DstAlign >= 16) &&
1364 (SrcAlign == 0 || SrcAlign >= 16))) &&
1365 Subtarget->getStackAlignment() >= 16) {
1366 if (Subtarget->getStackAlignment() >= 32) {
1367 if (Subtarget->hasAVX2())
1369 if (Subtarget->hasAVX())
1372 if (Subtarget->hasSSE2())
1374 if (Subtarget->hasSSE1())
1376 } else if (!MemcpyStrSrc && Size >= 8 &&
1377 !Subtarget->is64Bit() &&
1378 Subtarget->getStackAlignment() >= 8 &&
1379 Subtarget->hasSSE2()) {
1380 // Do not use f64 to lower memcpy if source is string constant. It's
1381 // better to use i32 to avoid the loads.
1385 if (Subtarget->is64Bit() && Size >= 8)
1390 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1391 /// current function. The returned value is a member of the
1392 /// MachineJumpTableInfo::JTEntryKind enum.
1393 unsigned X86TargetLowering::getJumpTableEncoding() const {
1394 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1396 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1397 Subtarget->isPICStyleGOT())
1398 return MachineJumpTableInfo::EK_Custom32;
1400 // Otherwise, use the normal jump table encoding heuristics.
1401 return TargetLowering::getJumpTableEncoding();
1405 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1406 const MachineBasicBlock *MBB,
1407 unsigned uid,MCContext &Ctx) const{
1408 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1409 Subtarget->isPICStyleGOT());
1410 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1412 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1413 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1416 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1418 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1419 SelectionDAG &DAG) const {
1420 if (!Subtarget->is64Bit())
1421 // This doesn't have DebugLoc associated with it, but is not really the
1422 // same as a Register.
1423 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1427 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1428 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1430 const MCExpr *X86TargetLowering::
1431 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1432 MCContext &Ctx) const {
1433 // X86-64 uses RIP relative addressing based on the jump table label.
1434 if (Subtarget->isPICStyleRIPRel())
1435 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1437 // Otherwise, the reference is relative to the PIC base.
1438 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1441 // FIXME: Why this routine is here? Move to RegInfo!
1442 std::pair<const TargetRegisterClass*, uint8_t>
1443 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1444 const TargetRegisterClass *RRC = 0;
1446 switch (VT.getSimpleVT().SimpleTy) {
1448 return TargetLowering::findRepresentativeClass(VT);
1449 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1450 RRC = Subtarget->is64Bit() ?
1451 (const TargetRegisterClass*)&X86::GR64RegClass :
1452 (const TargetRegisterClass*)&X86::GR32RegClass;
1455 RRC = &X86::VR64RegClass;
1457 case MVT::f32: case MVT::f64:
1458 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1459 case MVT::v4f32: case MVT::v2f64:
1460 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1462 RRC = &X86::VR128RegClass;
1465 return std::make_pair(RRC, Cost);
1468 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1469 unsigned &Offset) const {
1470 if (!Subtarget->isTargetLinux())
1473 if (Subtarget->is64Bit()) {
1474 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1476 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1489 //===----------------------------------------------------------------------===//
1490 // Return Value Calling Convention Implementation
1491 //===----------------------------------------------------------------------===//
1493 #include "X86GenCallingConv.inc"
1496 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1497 MachineFunction &MF, bool isVarArg,
1498 const SmallVectorImpl<ISD::OutputArg> &Outs,
1499 LLVMContext &Context) const {
1500 SmallVector<CCValAssign, 16> RVLocs;
1501 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1503 return CCInfo.CheckReturn(Outs, RetCC_X86);
1507 X86TargetLowering::LowerReturn(SDValue Chain,
1508 CallingConv::ID CallConv, bool isVarArg,
1509 const SmallVectorImpl<ISD::OutputArg> &Outs,
1510 const SmallVectorImpl<SDValue> &OutVals,
1511 DebugLoc dl, SelectionDAG &DAG) const {
1512 MachineFunction &MF = DAG.getMachineFunction();
1513 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1515 SmallVector<CCValAssign, 16> RVLocs;
1516 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1517 RVLocs, *DAG.getContext());
1518 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1520 // Add the regs to the liveout set for the function.
1521 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1522 for (unsigned i = 0; i != RVLocs.size(); ++i)
1523 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1524 MRI.addLiveOut(RVLocs[i].getLocReg());
1528 SmallVector<SDValue, 6> RetOps;
1529 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1530 // Operand #1 = Bytes To Pop
1531 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1534 // Copy the result values into the output registers.
1535 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1536 CCValAssign &VA = RVLocs[i];
1537 assert(VA.isRegLoc() && "Can only return in registers!");
1538 SDValue ValToCopy = OutVals[i];
1539 EVT ValVT = ValToCopy.getValueType();
1541 // Promote values to the appropriate types
1542 if (VA.getLocInfo() == CCValAssign::SExt)
1543 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1544 else if (VA.getLocInfo() == CCValAssign::ZExt)
1545 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1546 else if (VA.getLocInfo() == CCValAssign::AExt)
1547 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1548 else if (VA.getLocInfo() == CCValAssign::BCvt)
1549 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1551 // If this is x86-64, and we disabled SSE, we can't return FP values,
1552 // or SSE or MMX vectors.
1553 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1554 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1555 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1556 report_fatal_error("SSE register return with SSE disabled");
1558 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1559 // llvm-gcc has never done it right and no one has noticed, so this
1560 // should be OK for now.
1561 if (ValVT == MVT::f64 &&
1562 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1563 report_fatal_error("SSE2 register return with SSE2 disabled");
1565 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1566 // the RET instruction and handled by the FP Stackifier.
1567 if (VA.getLocReg() == X86::ST0 ||
1568 VA.getLocReg() == X86::ST1) {
1569 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1570 // change the value to the FP stack register class.
1571 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1572 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1573 RetOps.push_back(ValToCopy);
1574 // Don't emit a copytoreg.
1578 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1579 // which is returned in RAX / RDX.
1580 if (Subtarget->is64Bit()) {
1581 if (ValVT == MVT::x86mmx) {
1582 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1583 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1584 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1586 // If we don't have SSE2 available, convert to v4f32 so the generated
1587 // register is legal.
1588 if (!Subtarget->hasSSE2())
1589 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1594 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1595 Flag = Chain.getValue(1);
1598 // The x86-64 ABI for returning structs by value requires that we copy
1599 // the sret argument into %rax for the return. We saved the argument into
1600 // a virtual register in the entry block, so now we copy the value out
1602 if (Subtarget->is64Bit() &&
1603 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1604 MachineFunction &MF = DAG.getMachineFunction();
1605 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1606 unsigned Reg = FuncInfo->getSRetReturnReg();
1608 "SRetReturnReg should have been set in LowerFormalArguments().");
1609 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1611 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1612 Flag = Chain.getValue(1);
1614 // RAX now acts like a return value.
1615 MRI.addLiveOut(X86::RAX);
1618 RetOps[0] = Chain; // Update chain.
1620 // Add the flag if we have it.
1622 RetOps.push_back(Flag);
1624 return DAG.getNode(X86ISD::RET_FLAG, dl,
1625 MVT::Other, &RetOps[0], RetOps.size());
1628 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1629 if (N->getNumValues() != 1)
1631 if (!N->hasNUsesOfValue(1, 0))
1634 SDValue TCChain = Chain;
1635 SDNode *Copy = *N->use_begin();
1636 if (Copy->getOpcode() == ISD::CopyToReg) {
1637 // If the copy has a glue operand, we conservatively assume it isn't safe to
1638 // perform a tail call.
1639 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1641 TCChain = Copy->getOperand(0);
1642 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1645 bool HasRet = false;
1646 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1648 if (UI->getOpcode() != X86ISD::RET_FLAG)
1661 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1662 ISD::NodeType ExtendKind) const {
1664 // TODO: Is this also valid on 32-bit?
1665 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1666 ReturnMVT = MVT::i8;
1668 ReturnMVT = MVT::i32;
1670 EVT MinVT = getRegisterType(Context, ReturnMVT);
1671 return VT.bitsLT(MinVT) ? MinVT : VT;
1674 /// LowerCallResult - Lower the result values of a call into the
1675 /// appropriate copies out of appropriate physical registers.
1678 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1679 CallingConv::ID CallConv, bool isVarArg,
1680 const SmallVectorImpl<ISD::InputArg> &Ins,
1681 DebugLoc dl, SelectionDAG &DAG,
1682 SmallVectorImpl<SDValue> &InVals) const {
1684 // Assign locations to each value returned by this call.
1685 SmallVector<CCValAssign, 16> RVLocs;
1686 bool Is64Bit = Subtarget->is64Bit();
1687 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1688 getTargetMachine(), RVLocs, *DAG.getContext());
1689 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1691 // Copy all of the result registers out of their specified physreg.
1692 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1693 CCValAssign &VA = RVLocs[i];
1694 EVT CopyVT = VA.getValVT();
1696 // If this is x86-64, and we disabled SSE, we can't return FP values
1697 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1698 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1699 report_fatal_error("SSE register return with SSE disabled");
1704 // If this is a call to a function that returns an fp value on the floating
1705 // point stack, we must guarantee the value is popped from the stack, so
1706 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1707 // if the return value is not used. We use the FpPOP_RETVAL instruction
1709 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1710 // If we prefer to use the value in xmm registers, copy it out as f80 and
1711 // use a truncate to move it from fp stack reg to xmm reg.
1712 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1713 SDValue Ops[] = { Chain, InFlag };
1714 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1715 MVT::Other, MVT::Glue, Ops, 2), 1);
1716 Val = Chain.getValue(0);
1718 // Round the f80 to the right size, which also moves it to the appropriate
1720 if (CopyVT != VA.getValVT())
1721 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1722 // This truncation won't change the value.
1723 DAG.getIntPtrConstant(1));
1725 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1726 CopyVT, InFlag).getValue(1);
1727 Val = Chain.getValue(0);
1729 InFlag = Chain.getValue(2);
1730 InVals.push_back(Val);
1737 //===----------------------------------------------------------------------===//
1738 // C & StdCall & Fast Calling Convention implementation
1739 //===----------------------------------------------------------------------===//
1740 // StdCall calling convention seems to be standard for many Windows' API
1741 // routines and around. It differs from C calling convention just a little:
1742 // callee should clean up the stack, not caller. Symbols should be also
1743 // decorated in some fancy way :) It doesn't support any vector arguments.
1744 // For info on fast calling convention see Fast Calling Convention (tail call)
1745 // implementation LowerX86_32FastCCCallTo.
1747 /// CallIsStructReturn - Determines whether a call uses struct return
1749 enum StructReturnType {
1754 static StructReturnType
1755 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1757 return NotStructReturn;
1759 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1760 if (!Flags.isSRet())
1761 return NotStructReturn;
1762 if (Flags.isInReg())
1763 return RegStructReturn;
1764 return StackStructReturn;
1767 /// ArgsAreStructReturn - Determines whether a function uses struct
1768 /// return semantics.
1769 static StructReturnType
1770 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1772 return NotStructReturn;
1774 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1775 if (!Flags.isSRet())
1776 return NotStructReturn;
1777 if (Flags.isInReg())
1778 return RegStructReturn;
1779 return StackStructReturn;
1782 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1783 /// by "Src" to address "Dst" with size and alignment information specified by
1784 /// the specific parameter attribute. The copy will be passed as a byval
1785 /// function parameter.
1787 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1788 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1790 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1792 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1793 /*isVolatile*/false, /*AlwaysInline=*/true,
1794 MachinePointerInfo(), MachinePointerInfo());
1797 /// IsTailCallConvention - Return true if the calling convention is one that
1798 /// supports tail call optimization.
1799 static bool IsTailCallConvention(CallingConv::ID CC) {
1800 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1803 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1804 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1808 CallingConv::ID CalleeCC = CS.getCallingConv();
1809 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1815 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1816 /// a tailcall target by changing its ABI.
1817 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1818 bool GuaranteedTailCallOpt) {
1819 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1823 X86TargetLowering::LowerMemArgument(SDValue Chain,
1824 CallingConv::ID CallConv,
1825 const SmallVectorImpl<ISD::InputArg> &Ins,
1826 DebugLoc dl, SelectionDAG &DAG,
1827 const CCValAssign &VA,
1828 MachineFrameInfo *MFI,
1830 // Create the nodes corresponding to a load from this parameter slot.
1831 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1832 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1833 getTargetMachine().Options.GuaranteedTailCallOpt);
1834 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1837 // If value is passed by pointer we have address passed instead of the value
1839 if (VA.getLocInfo() == CCValAssign::Indirect)
1840 ValVT = VA.getLocVT();
1842 ValVT = VA.getValVT();
1844 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1845 // changed with more analysis.
1846 // In case of tail call optimization mark all arguments mutable. Since they
1847 // could be overwritten by lowering of arguments in case of a tail call.
1848 if (Flags.isByVal()) {
1849 unsigned Bytes = Flags.getByValSize();
1850 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1851 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1852 return DAG.getFrameIndex(FI, getPointerTy());
1854 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1855 VA.getLocMemOffset(), isImmutable);
1856 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1857 return DAG.getLoad(ValVT, dl, Chain, FIN,
1858 MachinePointerInfo::getFixedStack(FI),
1859 false, false, false, 0);
1864 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1865 CallingConv::ID CallConv,
1867 const SmallVectorImpl<ISD::InputArg> &Ins,
1870 SmallVectorImpl<SDValue> &InVals)
1872 MachineFunction &MF = DAG.getMachineFunction();
1873 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1875 const Function* Fn = MF.getFunction();
1876 if (Fn->hasExternalLinkage() &&
1877 Subtarget->isTargetCygMing() &&
1878 Fn->getName() == "main")
1879 FuncInfo->setForceFramePointer(true);
1881 MachineFrameInfo *MFI = MF.getFrameInfo();
1882 bool Is64Bit = Subtarget->is64Bit();
1883 bool IsWindows = Subtarget->isTargetWindows();
1884 bool IsWin64 = Subtarget->isTargetWin64();
1886 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1887 "Var args not supported with calling convention fastcc or ghc");
1889 // Assign locations to all of the incoming arguments.
1890 SmallVector<CCValAssign, 16> ArgLocs;
1891 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1892 ArgLocs, *DAG.getContext());
1894 // Allocate shadow area for Win64
1896 CCInfo.AllocateStack(32, 8);
1899 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1901 unsigned LastVal = ~0U;
1903 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1904 CCValAssign &VA = ArgLocs[i];
1905 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1907 assert(VA.getValNo() != LastVal &&
1908 "Don't support value assigned to multiple locs yet");
1910 LastVal = VA.getValNo();
1912 if (VA.isRegLoc()) {
1913 EVT RegVT = VA.getLocVT();
1914 const TargetRegisterClass *RC;
1915 if (RegVT == MVT::i32)
1916 RC = &X86::GR32RegClass;
1917 else if (Is64Bit && RegVT == MVT::i64)
1918 RC = &X86::GR64RegClass;
1919 else if (RegVT == MVT::f32)
1920 RC = &X86::FR32RegClass;
1921 else if (RegVT == MVT::f64)
1922 RC = &X86::FR64RegClass;
1923 else if (RegVT.is256BitVector())
1924 RC = &X86::VR256RegClass;
1925 else if (RegVT.is128BitVector())
1926 RC = &X86::VR128RegClass;
1927 else if (RegVT == MVT::x86mmx)
1928 RC = &X86::VR64RegClass;
1930 llvm_unreachable("Unknown argument type!");
1932 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1933 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1935 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1936 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1938 if (VA.getLocInfo() == CCValAssign::SExt)
1939 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1940 DAG.getValueType(VA.getValVT()));
1941 else if (VA.getLocInfo() == CCValAssign::ZExt)
1942 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1943 DAG.getValueType(VA.getValVT()));
1944 else if (VA.getLocInfo() == CCValAssign::BCvt)
1945 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1947 if (VA.isExtInLoc()) {
1948 // Handle MMX values passed in XMM regs.
1949 if (RegVT.isVector()) {
1950 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1953 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1956 assert(VA.isMemLoc());
1957 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1960 // If value is passed via pointer - do a load.
1961 if (VA.getLocInfo() == CCValAssign::Indirect)
1962 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1963 MachinePointerInfo(), false, false, false, 0);
1965 InVals.push_back(ArgValue);
1968 // The x86-64 ABI for returning structs by value requires that we copy
1969 // the sret argument into %rax for the return. Save the argument into
1970 // a virtual register so that we can access it from the return points.
1971 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1972 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1973 unsigned Reg = FuncInfo->getSRetReturnReg();
1975 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1976 FuncInfo->setSRetReturnReg(Reg);
1978 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1979 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1982 unsigned StackSize = CCInfo.getNextStackOffset();
1983 // Align stack specially for tail calls.
1984 if (FuncIsMadeTailCallSafe(CallConv,
1985 MF.getTarget().Options.GuaranteedTailCallOpt))
1986 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1988 // If the function takes variable number of arguments, make a frame index for
1989 // the start of the first vararg value... for expansion of llvm.va_start.
1991 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1992 CallConv != CallingConv::X86_ThisCall)) {
1993 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1996 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1998 // FIXME: We should really autogenerate these arrays
1999 static const uint16_t GPR64ArgRegsWin64[] = {
2000 X86::RCX, X86::RDX, X86::R8, X86::R9
2002 static const uint16_t GPR64ArgRegs64Bit[] = {
2003 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2005 static const uint16_t XMMArgRegs64Bit[] = {
2006 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2007 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2009 const uint16_t *GPR64ArgRegs;
2010 unsigned NumXMMRegs = 0;
2013 // The XMM registers which might contain var arg parameters are shadowed
2014 // in their paired GPR. So we only need to save the GPR to their home
2016 TotalNumIntRegs = 4;
2017 GPR64ArgRegs = GPR64ArgRegsWin64;
2019 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2020 GPR64ArgRegs = GPR64ArgRegs64Bit;
2022 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2025 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2028 bool NoImplicitFloatOps = Fn->getFnAttributes().
2029 hasAttribute(Attributes::NoImplicitFloat);
2030 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2031 "SSE register cannot be used when SSE is disabled!");
2032 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2033 NoImplicitFloatOps) &&
2034 "SSE register cannot be used when SSE is disabled!");
2035 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2036 !Subtarget->hasSSE1())
2037 // Kernel mode asks for SSE to be disabled, so don't push them
2039 TotalNumXMMRegs = 0;
2042 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2043 // Get to the caller-allocated home save location. Add 8 to account
2044 // for the return address.
2045 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2046 FuncInfo->setRegSaveFrameIndex(
2047 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2048 // Fixup to set vararg frame on shadow area (4 x i64).
2050 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2052 // For X86-64, if there are vararg parameters that are passed via
2053 // registers, then we must store them to their spots on the stack so
2054 // they may be loaded by deferencing the result of va_next.
2055 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2056 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2057 FuncInfo->setRegSaveFrameIndex(
2058 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2062 // Store the integer parameter registers.
2063 SmallVector<SDValue, 8> MemOps;
2064 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2066 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2067 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2068 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2069 DAG.getIntPtrConstant(Offset));
2070 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2071 &X86::GR64RegClass);
2072 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2074 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2075 MachinePointerInfo::getFixedStack(
2076 FuncInfo->getRegSaveFrameIndex(), Offset),
2078 MemOps.push_back(Store);
2082 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2083 // Now store the XMM (fp + vector) parameter registers.
2084 SmallVector<SDValue, 11> SaveXMMOps;
2085 SaveXMMOps.push_back(Chain);
2087 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2088 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2089 SaveXMMOps.push_back(ALVal);
2091 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2092 FuncInfo->getRegSaveFrameIndex()));
2093 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2094 FuncInfo->getVarArgsFPOffset()));
2096 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2097 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2098 &X86::VR128RegClass);
2099 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2100 SaveXMMOps.push_back(Val);
2102 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2104 &SaveXMMOps[0], SaveXMMOps.size()));
2107 if (!MemOps.empty())
2108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2109 &MemOps[0], MemOps.size());
2113 // Some CCs need callee pop.
2114 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2115 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2116 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2118 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2119 // If this is an sret function, the return should pop the hidden pointer.
2120 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2121 argsAreStructReturn(Ins) == StackStructReturn)
2122 FuncInfo->setBytesToPopOnReturn(4);
2126 // RegSaveFrameIndex is X86-64 only.
2127 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2128 if (CallConv == CallingConv::X86_FastCall ||
2129 CallConv == CallingConv::X86_ThisCall)
2130 // fastcc functions can't have varargs.
2131 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2134 FuncInfo->setArgumentStackSize(StackSize);
2140 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2141 SDValue StackPtr, SDValue Arg,
2142 DebugLoc dl, SelectionDAG &DAG,
2143 const CCValAssign &VA,
2144 ISD::ArgFlagsTy Flags) const {
2145 unsigned LocMemOffset = VA.getLocMemOffset();
2146 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2147 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2148 if (Flags.isByVal())
2149 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2151 return DAG.getStore(Chain, dl, Arg, PtrOff,
2152 MachinePointerInfo::getStack(LocMemOffset),
2156 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2157 /// optimization is performed and it is required.
2159 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2160 SDValue &OutRetAddr, SDValue Chain,
2161 bool IsTailCall, bool Is64Bit,
2162 int FPDiff, DebugLoc dl) const {
2163 // Adjust the Return address stack slot.
2164 EVT VT = getPointerTy();
2165 OutRetAddr = getReturnAddressFrameIndex(DAG);
2167 // Load the "old" Return address.
2168 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2169 false, false, false, 0);
2170 return SDValue(OutRetAddr.getNode(), 1);
2173 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2174 /// optimization is performed and it is required (FPDiff!=0).
2176 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2177 SDValue Chain, SDValue RetAddrFrIdx,
2178 bool Is64Bit, int FPDiff, DebugLoc dl) {
2179 // Store the return address to the appropriate stack slot.
2180 if (!FPDiff) return Chain;
2181 // Calculate the new stack slot for the return address.
2182 int SlotSize = Is64Bit ? 8 : 4;
2183 int NewReturnAddrFI =
2184 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2185 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2186 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2187 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2188 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2194 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2195 SmallVectorImpl<SDValue> &InVals) const {
2196 SelectionDAG &DAG = CLI.DAG;
2197 DebugLoc &dl = CLI.DL;
2198 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2199 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2200 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2201 SDValue Chain = CLI.Chain;
2202 SDValue Callee = CLI.Callee;
2203 CallingConv::ID CallConv = CLI.CallConv;
2204 bool &isTailCall = CLI.IsTailCall;
2205 bool isVarArg = CLI.IsVarArg;
2207 MachineFunction &MF = DAG.getMachineFunction();
2208 bool Is64Bit = Subtarget->is64Bit();
2209 bool IsWin64 = Subtarget->isTargetWin64();
2210 bool IsWindows = Subtarget->isTargetWindows();
2211 StructReturnType SR = callIsStructReturn(Outs);
2212 bool IsSibcall = false;
2214 if (MF.getTarget().Options.DisableTailCalls)
2218 // Check if it's really possible to do a tail call.
2219 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2220 isVarArg, SR != NotStructReturn,
2221 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2222 Outs, OutVals, Ins, DAG);
2224 // Sibcalls are automatically detected tailcalls which do not require
2226 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2233 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2234 "Var args not supported with calling convention fastcc or ghc");
2236 // Analyze operands of the call, assigning locations to each operand.
2237 SmallVector<CCValAssign, 16> ArgLocs;
2238 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2239 ArgLocs, *DAG.getContext());
2241 // Allocate shadow area for Win64
2243 CCInfo.AllocateStack(32, 8);
2246 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2248 // Get a count of how many bytes are to be pushed on the stack.
2249 unsigned NumBytes = CCInfo.getNextStackOffset();
2251 // This is a sibcall. The memory operands are available in caller's
2252 // own caller's stack.
2254 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2255 IsTailCallConvention(CallConv))
2256 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2259 if (isTailCall && !IsSibcall) {
2260 // Lower arguments at fp - stackoffset + fpdiff.
2261 unsigned NumBytesCallerPushed =
2262 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2263 FPDiff = NumBytesCallerPushed - NumBytes;
2265 // Set the delta of movement of the returnaddr stackslot.
2266 // But only set if delta is greater than previous delta.
2267 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2268 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2272 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2274 SDValue RetAddrFrIdx;
2275 // Load return address for tail calls.
2276 if (isTailCall && FPDiff)
2277 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2278 Is64Bit, FPDiff, dl);
2280 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2281 SmallVector<SDValue, 8> MemOpChains;
2284 // Walk the register/memloc assignments, inserting copies/loads. In the case
2285 // of tail call optimization arguments are handle later.
2286 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2287 CCValAssign &VA = ArgLocs[i];
2288 EVT RegVT = VA.getLocVT();
2289 SDValue Arg = OutVals[i];
2290 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2291 bool isByVal = Flags.isByVal();
2293 // Promote the value if needed.
2294 switch (VA.getLocInfo()) {
2295 default: llvm_unreachable("Unknown loc info!");
2296 case CCValAssign::Full: break;
2297 case CCValAssign::SExt:
2298 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2300 case CCValAssign::ZExt:
2301 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2303 case CCValAssign::AExt:
2304 if (RegVT.is128BitVector()) {
2305 // Special case: passing MMX values in XMM registers.
2306 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2307 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2308 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2310 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2312 case CCValAssign::BCvt:
2313 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2315 case CCValAssign::Indirect: {
2316 // Store the argument.
2317 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2318 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2319 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2320 MachinePointerInfo::getFixedStack(FI),
2327 if (VA.isRegLoc()) {
2328 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2329 if (isVarArg && IsWin64) {
2330 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2331 // shadow reg if callee is a varargs function.
2332 unsigned ShadowReg = 0;
2333 switch (VA.getLocReg()) {
2334 case X86::XMM0: ShadowReg = X86::RCX; break;
2335 case X86::XMM1: ShadowReg = X86::RDX; break;
2336 case X86::XMM2: ShadowReg = X86::R8; break;
2337 case X86::XMM3: ShadowReg = X86::R9; break;
2340 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2342 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2343 assert(VA.isMemLoc());
2344 if (StackPtr.getNode() == 0)
2345 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2346 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2347 dl, DAG, VA, Flags));
2351 if (!MemOpChains.empty())
2352 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2353 &MemOpChains[0], MemOpChains.size());
2355 if (Subtarget->isPICStyleGOT()) {
2356 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2359 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2360 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2362 // If we are tail calling and generating PIC/GOT style code load the
2363 // address of the callee into ECX. The value in ecx is used as target of
2364 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2365 // for tail calls on PIC/GOT architectures. Normally we would just put the
2366 // address of GOT into ebx and then call target@PLT. But for tail calls
2367 // ebx would be restored (since ebx is callee saved) before jumping to the
2370 // Note: The actual moving to ECX is done further down.
2371 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2372 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2373 !G->getGlobal()->hasProtectedVisibility())
2374 Callee = LowerGlobalAddress(Callee, DAG);
2375 else if (isa<ExternalSymbolSDNode>(Callee))
2376 Callee = LowerExternalSymbol(Callee, DAG);
2380 if (Is64Bit && isVarArg && !IsWin64) {
2381 // From AMD64 ABI document:
2382 // For calls that may call functions that use varargs or stdargs
2383 // (prototype-less calls or calls to functions containing ellipsis (...) in
2384 // the declaration) %al is used as hidden argument to specify the number
2385 // of SSE registers used. The contents of %al do not need to match exactly
2386 // the number of registers, but must be an ubound on the number of SSE
2387 // registers used and is in the range 0 - 8 inclusive.
2389 // Count the number of XMM registers allocated.
2390 static const uint16_t XMMArgRegs[] = {
2391 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2392 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2394 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2395 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2396 && "SSE registers cannot be used when SSE is disabled");
2398 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2399 DAG.getConstant(NumXMMRegs, MVT::i8)));
2402 // For tail calls lower the arguments to the 'real' stack slot.
2404 // Force all the incoming stack arguments to be loaded from the stack
2405 // before any new outgoing arguments are stored to the stack, because the
2406 // outgoing stack slots may alias the incoming argument stack slots, and
2407 // the alias isn't otherwise explicit. This is slightly more conservative
2408 // than necessary, because it means that each store effectively depends
2409 // on every argument instead of just those arguments it would clobber.
2410 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2412 SmallVector<SDValue, 8> MemOpChains2;
2415 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2416 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2417 CCValAssign &VA = ArgLocs[i];
2420 assert(VA.isMemLoc());
2421 SDValue Arg = OutVals[i];
2422 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2423 // Create frame index.
2424 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2425 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2426 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2427 FIN = DAG.getFrameIndex(FI, getPointerTy());
2429 if (Flags.isByVal()) {
2430 // Copy relative to framepointer.
2431 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2432 if (StackPtr.getNode() == 0)
2433 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2435 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2437 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2441 // Store relative to framepointer.
2442 MemOpChains2.push_back(
2443 DAG.getStore(ArgChain, dl, Arg, FIN,
2444 MachinePointerInfo::getFixedStack(FI),
2450 if (!MemOpChains2.empty())
2451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2452 &MemOpChains2[0], MemOpChains2.size());
2454 // Store the return address to the appropriate stack slot.
2455 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2459 // Build a sequence of copy-to-reg nodes chained together with token chain
2460 // and flag operands which copy the outgoing args into registers.
2462 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2463 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2464 RegsToPass[i].second, InFlag);
2465 InFlag = Chain.getValue(1);
2468 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2469 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2470 // In the 64-bit large code model, we have to make all calls
2471 // through a register, since the call instruction's 32-bit
2472 // pc-relative offset may not be large enough to hold the whole
2474 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2475 // If the callee is a GlobalAddress node (quite common, every direct call
2476 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2479 // We should use extra load for direct calls to dllimported functions in
2481 const GlobalValue *GV = G->getGlobal();
2482 if (!GV->hasDLLImportLinkage()) {
2483 unsigned char OpFlags = 0;
2484 bool ExtraLoad = false;
2485 unsigned WrapperKind = ISD::DELETED_NODE;
2487 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2488 // external symbols most go through the PLT in PIC mode. If the symbol
2489 // has hidden or protected visibility, or if it is static or local, then
2490 // we don't need to use the PLT - we can directly call it.
2491 if (Subtarget->isTargetELF() &&
2492 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2493 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2494 OpFlags = X86II::MO_PLT;
2495 } else if (Subtarget->isPICStyleStubAny() &&
2496 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2497 (!Subtarget->getTargetTriple().isMacOSX() ||
2498 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2499 // PC-relative references to external symbols should go through $stub,
2500 // unless we're building with the leopard linker or later, which
2501 // automatically synthesizes these stubs.
2502 OpFlags = X86II::MO_DARWIN_STUB;
2503 } else if (Subtarget->isPICStyleRIPRel() &&
2504 isa<Function>(GV) &&
2505 cast<Function>(GV)->getFnAttributes().
2506 hasAttribute(Attributes::NonLazyBind)) {
2507 // If the function is marked as non-lazy, generate an indirect call
2508 // which loads from the GOT directly. This avoids runtime overhead
2509 // at the cost of eager binding (and one extra byte of encoding).
2510 OpFlags = X86II::MO_GOTPCREL;
2511 WrapperKind = X86ISD::WrapperRIP;
2515 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2516 G->getOffset(), OpFlags);
2518 // Add a wrapper if needed.
2519 if (WrapperKind != ISD::DELETED_NODE)
2520 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2521 // Add extra indirection if needed.
2523 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2524 MachinePointerInfo::getGOT(),
2525 false, false, false, 0);
2527 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2528 unsigned char OpFlags = 0;
2530 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2531 // external symbols should go through the PLT.
2532 if (Subtarget->isTargetELF() &&
2533 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2534 OpFlags = X86II::MO_PLT;
2535 } else if (Subtarget->isPICStyleStubAny() &&
2536 (!Subtarget->getTargetTriple().isMacOSX() ||
2537 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2538 // PC-relative references to external symbols should go through $stub,
2539 // unless we're building with the leopard linker or later, which
2540 // automatically synthesizes these stubs.
2541 OpFlags = X86II::MO_DARWIN_STUB;
2544 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2548 // Returns a chain & a flag for retval copy to use.
2549 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2550 SmallVector<SDValue, 8> Ops;
2552 if (!IsSibcall && isTailCall) {
2553 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2554 DAG.getIntPtrConstant(0, true), InFlag);
2555 InFlag = Chain.getValue(1);
2558 Ops.push_back(Chain);
2559 Ops.push_back(Callee);
2562 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2564 // Add argument registers to the end of the list so that they are known live
2566 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2567 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2568 RegsToPass[i].second.getValueType()));
2570 // Add a register mask operand representing the call-preserved registers.
2571 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2572 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2573 assert(Mask && "Missing call preserved mask for calling convention");
2574 Ops.push_back(DAG.getRegisterMask(Mask));
2576 if (InFlag.getNode())
2577 Ops.push_back(InFlag);
2581 //// If this is the first return lowered for this function, add the regs
2582 //// to the liveout set for the function.
2583 // This isn't right, although it's probably harmless on x86; liveouts
2584 // should be computed from returns not tail calls. Consider a void
2585 // function making a tail call to a function returning int.
2586 return DAG.getNode(X86ISD::TC_RETURN, dl,
2587 NodeTys, &Ops[0], Ops.size());
2590 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2591 InFlag = Chain.getValue(1);
2593 // Create the CALLSEQ_END node.
2594 unsigned NumBytesForCalleeToPush;
2595 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2596 getTargetMachine().Options.GuaranteedTailCallOpt))
2597 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2598 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2599 SR == StackStructReturn)
2600 // If this is a call to a struct-return function, the callee
2601 // pops the hidden struct pointer, so we have to push it back.
2602 // This is common for Darwin/X86, Linux & Mingw32 targets.
2603 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2604 NumBytesForCalleeToPush = 4;
2606 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2608 // Returns a flag for retval copy to use.
2610 Chain = DAG.getCALLSEQ_END(Chain,
2611 DAG.getIntPtrConstant(NumBytes, true),
2612 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2615 InFlag = Chain.getValue(1);
2618 // Handle result values, copying them out of physregs into vregs that we
2620 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2621 Ins, dl, DAG, InVals);
2625 //===----------------------------------------------------------------------===//
2626 // Fast Calling Convention (tail call) implementation
2627 //===----------------------------------------------------------------------===//
2629 // Like std call, callee cleans arguments, convention except that ECX is
2630 // reserved for storing the tail called function address. Only 2 registers are
2631 // free for argument passing (inreg). Tail call optimization is performed
2633 // * tailcallopt is enabled
2634 // * caller/callee are fastcc
2635 // On X86_64 architecture with GOT-style position independent code only local
2636 // (within module) calls are supported at the moment.
2637 // To keep the stack aligned according to platform abi the function
2638 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2639 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2640 // If a tail called function callee has more arguments than the caller the
2641 // caller needs to make sure that there is room to move the RETADDR to. This is
2642 // achieved by reserving an area the size of the argument delta right after the
2643 // original REtADDR, but before the saved framepointer or the spilled registers
2644 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2656 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2657 /// for a 16 byte align requirement.
2659 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2660 SelectionDAG& DAG) const {
2661 MachineFunction &MF = DAG.getMachineFunction();
2662 const TargetMachine &TM = MF.getTarget();
2663 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2664 unsigned StackAlignment = TFI.getStackAlignment();
2665 uint64_t AlignMask = StackAlignment - 1;
2666 int64_t Offset = StackSize;
2667 uint64_t SlotSize = TD->getPointerSize(0);
2668 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2669 // Number smaller than 12 so just add the difference.
2670 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2672 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2673 Offset = ((~AlignMask) & Offset) + StackAlignment +
2674 (StackAlignment-SlotSize);
2679 /// MatchingStackOffset - Return true if the given stack call argument is
2680 /// already available in the same position (relatively) of the caller's
2681 /// incoming argument stack.
2683 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2684 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2685 const X86InstrInfo *TII) {
2686 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2688 if (Arg.getOpcode() == ISD::CopyFromReg) {
2689 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2690 if (!TargetRegisterInfo::isVirtualRegister(VR))
2692 MachineInstr *Def = MRI->getVRegDef(VR);
2695 if (!Flags.isByVal()) {
2696 if (!TII->isLoadFromStackSlot(Def, FI))
2699 unsigned Opcode = Def->getOpcode();
2700 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2701 Def->getOperand(1).isFI()) {
2702 FI = Def->getOperand(1).getIndex();
2703 Bytes = Flags.getByValSize();
2707 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2708 if (Flags.isByVal())
2709 // ByVal argument is passed in as a pointer but it's now being
2710 // dereferenced. e.g.
2711 // define @foo(%struct.X* %A) {
2712 // tail call @bar(%struct.X* byval %A)
2715 SDValue Ptr = Ld->getBasePtr();
2716 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2719 FI = FINode->getIndex();
2720 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2721 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2722 FI = FINode->getIndex();
2723 Bytes = Flags.getByValSize();
2727 assert(FI != INT_MAX);
2728 if (!MFI->isFixedObjectIndex(FI))
2730 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2733 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2734 /// for tail call optimization. Targets which want to do tail call
2735 /// optimization should implement this function.
2737 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2738 CallingConv::ID CalleeCC,
2740 bool isCalleeStructRet,
2741 bool isCallerStructRet,
2743 const SmallVectorImpl<ISD::OutputArg> &Outs,
2744 const SmallVectorImpl<SDValue> &OutVals,
2745 const SmallVectorImpl<ISD::InputArg> &Ins,
2746 SelectionDAG& DAG) const {
2747 if (!IsTailCallConvention(CalleeCC) &&
2748 CalleeCC != CallingConv::C)
2751 // If -tailcallopt is specified, make fastcc functions tail-callable.
2752 const MachineFunction &MF = DAG.getMachineFunction();
2753 const Function *CallerF = DAG.getMachineFunction().getFunction();
2755 // If the function return type is x86_fp80 and the callee return type is not,
2756 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2757 // perform a tailcall optimization here.
2758 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2761 CallingConv::ID CallerCC = CallerF->getCallingConv();
2762 bool CCMatch = CallerCC == CalleeCC;
2764 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2765 if (IsTailCallConvention(CalleeCC) && CCMatch)
2770 // Look for obvious safe cases to perform tail call optimization that do not
2771 // require ABI changes. This is what gcc calls sibcall.
2773 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2774 // emit a special epilogue.
2775 if (RegInfo->needsStackRealignment(MF))
2778 // Also avoid sibcall optimization if either caller or callee uses struct
2779 // return semantics.
2780 if (isCalleeStructRet || isCallerStructRet)
2783 // An stdcall caller is expected to clean up its arguments; the callee
2784 // isn't going to do that.
2785 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2788 // Do not sibcall optimize vararg calls unless all arguments are passed via
2790 if (isVarArg && !Outs.empty()) {
2792 // Optimizing for varargs on Win64 is unlikely to be safe without
2793 // additional testing.
2794 if (Subtarget->isTargetWin64())
2797 SmallVector<CCValAssign, 16> ArgLocs;
2798 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2799 getTargetMachine(), ArgLocs, *DAG.getContext());
2801 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2802 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2803 if (!ArgLocs[i].isRegLoc())
2807 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2808 // stack. Therefore, if it's not used by the call it is not safe to optimize
2809 // this into a sibcall.
2810 bool Unused = false;
2811 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2818 SmallVector<CCValAssign, 16> RVLocs;
2819 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2820 getTargetMachine(), RVLocs, *DAG.getContext());
2821 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2822 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2823 CCValAssign &VA = RVLocs[i];
2824 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2829 // If the calling conventions do not match, then we'd better make sure the
2830 // results are returned in the same way as what the caller expects.
2832 SmallVector<CCValAssign, 16> RVLocs1;
2833 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2834 getTargetMachine(), RVLocs1, *DAG.getContext());
2835 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2837 SmallVector<CCValAssign, 16> RVLocs2;
2838 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2839 getTargetMachine(), RVLocs2, *DAG.getContext());
2840 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2842 if (RVLocs1.size() != RVLocs2.size())
2844 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2845 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2847 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2849 if (RVLocs1[i].isRegLoc()) {
2850 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2853 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2859 // If the callee takes no arguments then go on to check the results of the
2861 if (!Outs.empty()) {
2862 // Check if stack adjustment is needed. For now, do not do this if any
2863 // argument is passed on the stack.
2864 SmallVector<CCValAssign, 16> ArgLocs;
2865 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2866 getTargetMachine(), ArgLocs, *DAG.getContext());
2868 // Allocate shadow area for Win64
2869 if (Subtarget->isTargetWin64()) {
2870 CCInfo.AllocateStack(32, 8);
2873 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2874 if (CCInfo.getNextStackOffset()) {
2875 MachineFunction &MF = DAG.getMachineFunction();
2876 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2879 // Check if the arguments are already laid out in the right way as
2880 // the caller's fixed stack objects.
2881 MachineFrameInfo *MFI = MF.getFrameInfo();
2882 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2883 const X86InstrInfo *TII =
2884 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886 CCValAssign &VA = ArgLocs[i];
2887 SDValue Arg = OutVals[i];
2888 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2889 if (VA.getLocInfo() == CCValAssign::Indirect)
2891 if (!VA.isRegLoc()) {
2892 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2899 // If the tailcall address may be in a register, then make sure it's
2900 // possible to register allocate for it. In 32-bit, the call address can
2901 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2902 // callee-saved registers are restored. These happen to be the same
2903 // registers used to pass 'inreg' arguments so watch out for those.
2904 if (!Subtarget->is64Bit() &&
2905 !isa<GlobalAddressSDNode>(Callee) &&
2906 !isa<ExternalSymbolSDNode>(Callee)) {
2907 unsigned NumInRegs = 0;
2908 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2909 CCValAssign &VA = ArgLocs[i];
2912 unsigned Reg = VA.getLocReg();
2915 case X86::EAX: case X86::EDX: case X86::ECX:
2916 if (++NumInRegs == 3)
2928 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2929 const TargetLibraryInfo *libInfo) const {
2930 return X86::createFastISel(funcInfo, libInfo);
2934 //===----------------------------------------------------------------------===//
2935 // Other Lowering Hooks
2936 //===----------------------------------------------------------------------===//
2938 static bool MayFoldLoad(SDValue Op) {
2939 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2942 static bool MayFoldIntoStore(SDValue Op) {
2943 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2946 static bool isTargetShuffle(unsigned Opcode) {
2948 default: return false;
2949 case X86ISD::PSHUFD:
2950 case X86ISD::PSHUFHW:
2951 case X86ISD::PSHUFLW:
2953 case X86ISD::PALIGN:
2954 case X86ISD::MOVLHPS:
2955 case X86ISD::MOVLHPD:
2956 case X86ISD::MOVHLPS:
2957 case X86ISD::MOVLPS:
2958 case X86ISD::MOVLPD:
2959 case X86ISD::MOVSHDUP:
2960 case X86ISD::MOVSLDUP:
2961 case X86ISD::MOVDDUP:
2964 case X86ISD::UNPCKL:
2965 case X86ISD::UNPCKH:
2966 case X86ISD::VPERMILP:
2967 case X86ISD::VPERM2X128:
2968 case X86ISD::VPERMI:
2973 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2974 SDValue V1, SelectionDAG &DAG) {
2976 default: llvm_unreachable("Unknown x86 shuffle node");
2977 case X86ISD::MOVSHDUP:
2978 case X86ISD::MOVSLDUP:
2979 case X86ISD::MOVDDUP:
2980 return DAG.getNode(Opc, dl, VT, V1);
2984 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2985 SDValue V1, unsigned TargetMask,
2986 SelectionDAG &DAG) {
2988 default: llvm_unreachable("Unknown x86 shuffle node");
2989 case X86ISD::PSHUFD:
2990 case X86ISD::PSHUFHW:
2991 case X86ISD::PSHUFLW:
2992 case X86ISD::VPERMILP:
2993 case X86ISD::VPERMI:
2994 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2998 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2999 SDValue V1, SDValue V2, unsigned TargetMask,
3000 SelectionDAG &DAG) {
3002 default: llvm_unreachable("Unknown x86 shuffle node");
3003 case X86ISD::PALIGN:
3005 case X86ISD::VPERM2X128:
3006 return DAG.getNode(Opc, dl, VT, V1, V2,
3007 DAG.getConstant(TargetMask, MVT::i8));
3011 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3012 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3014 default: llvm_unreachable("Unknown x86 shuffle node");
3015 case X86ISD::MOVLHPS:
3016 case X86ISD::MOVLHPD:
3017 case X86ISD::MOVHLPS:
3018 case X86ISD::MOVLPS:
3019 case X86ISD::MOVLPD:
3022 case X86ISD::UNPCKL:
3023 case X86ISD::UNPCKH:
3024 return DAG.getNode(Opc, dl, VT, V1, V2);
3028 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3029 MachineFunction &MF = DAG.getMachineFunction();
3030 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3031 int ReturnAddrIndex = FuncInfo->getRAIndex();
3033 if (ReturnAddrIndex == 0) {
3034 // Set up a frame object for the return address.
3035 uint64_t SlotSize = TD->getPointerSize(0);
3036 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3038 FuncInfo->setRAIndex(ReturnAddrIndex);
3041 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3045 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3046 bool hasSymbolicDisplacement) {
3047 // Offset should fit into 32 bit immediate field.
3048 if (!isInt<32>(Offset))
3051 // If we don't have a symbolic displacement - we don't have any extra
3053 if (!hasSymbolicDisplacement)
3056 // FIXME: Some tweaks might be needed for medium code model.
3057 if (M != CodeModel::Small && M != CodeModel::Kernel)
3060 // For small code model we assume that latest object is 16MB before end of 31
3061 // bits boundary. We may also accept pretty large negative constants knowing
3062 // that all objects are in the positive half of address space.
3063 if (M == CodeModel::Small && Offset < 16*1024*1024)
3066 // For kernel code model we know that all object resist in the negative half
3067 // of 32bits address space. We may not accept negative offsets, since they may
3068 // be just off and we may accept pretty large positive ones.
3069 if (M == CodeModel::Kernel && Offset > 0)
3075 /// isCalleePop - Determines whether the callee is required to pop its
3076 /// own arguments. Callee pop is necessary to support tail calls.
3077 bool X86::isCalleePop(CallingConv::ID CallingConv,
3078 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3082 switch (CallingConv) {
3085 case CallingConv::X86_StdCall:
3087 case CallingConv::X86_FastCall:
3089 case CallingConv::X86_ThisCall:
3091 case CallingConv::Fast:
3093 case CallingConv::GHC:
3098 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3099 /// specific condition code, returning the condition code and the LHS/RHS of the
3100 /// comparison to make.
3101 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3102 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3104 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3105 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3106 // X > -1 -> X == 0, jump !sign.
3107 RHS = DAG.getConstant(0, RHS.getValueType());
3108 return X86::COND_NS;
3110 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3111 // X < 0 -> X == 0, jump on sign.
3114 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3116 RHS = DAG.getConstant(0, RHS.getValueType());
3117 return X86::COND_LE;
3121 switch (SetCCOpcode) {
3122 default: llvm_unreachable("Invalid integer condition!");
3123 case ISD::SETEQ: return X86::COND_E;
3124 case ISD::SETGT: return X86::COND_G;
3125 case ISD::SETGE: return X86::COND_GE;
3126 case ISD::SETLT: return X86::COND_L;
3127 case ISD::SETLE: return X86::COND_LE;
3128 case ISD::SETNE: return X86::COND_NE;
3129 case ISD::SETULT: return X86::COND_B;
3130 case ISD::SETUGT: return X86::COND_A;
3131 case ISD::SETULE: return X86::COND_BE;
3132 case ISD::SETUGE: return X86::COND_AE;
3136 // First determine if it is required or is profitable to flip the operands.
3138 // If LHS is a foldable load, but RHS is not, flip the condition.
3139 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3140 !ISD::isNON_EXTLoad(RHS.getNode())) {
3141 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3142 std::swap(LHS, RHS);
3145 switch (SetCCOpcode) {
3151 std::swap(LHS, RHS);
3155 // On a floating point condition, the flags are set as follows:
3157 // 0 | 0 | 0 | X > Y
3158 // 0 | 0 | 1 | X < Y
3159 // 1 | 0 | 0 | X == Y
3160 // 1 | 1 | 1 | unordered
3161 switch (SetCCOpcode) {
3162 default: llvm_unreachable("Condcode should be pre-legalized away");
3164 case ISD::SETEQ: return X86::COND_E;
3165 case ISD::SETOLT: // flipped
3167 case ISD::SETGT: return X86::COND_A;
3168 case ISD::SETOLE: // flipped
3170 case ISD::SETGE: return X86::COND_AE;
3171 case ISD::SETUGT: // flipped
3173 case ISD::SETLT: return X86::COND_B;
3174 case ISD::SETUGE: // flipped
3176 case ISD::SETLE: return X86::COND_BE;
3178 case ISD::SETNE: return X86::COND_NE;
3179 case ISD::SETUO: return X86::COND_P;
3180 case ISD::SETO: return X86::COND_NP;
3182 case ISD::SETUNE: return X86::COND_INVALID;
3186 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3187 /// code. Current x86 isa includes the following FP cmov instructions:
3188 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3189 static bool hasFPCMov(unsigned X86CC) {
3205 /// isFPImmLegal - Returns true if the target can instruction select the
3206 /// specified FP immediate natively. If false, the legalizer will
3207 /// materialize the FP immediate as a load from a constant pool.
3208 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3209 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3210 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3216 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3217 /// the specified range (L, H].
3218 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3219 return (Val < 0) || (Val >= Low && Val < Hi);
3222 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3223 /// specified value.
3224 static bool isUndefOrEqual(int Val, int CmpVal) {
3225 if (Val < 0 || Val == CmpVal)
3230 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3231 /// from position Pos and ending in Pos+Size, falls within the specified
3232 /// sequential range (L, L+Pos]. or is undef.
3233 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3234 unsigned Pos, unsigned Size, int Low) {
3235 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3236 if (!isUndefOrEqual(Mask[i], Low))
3241 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3242 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3243 /// the second operand.
3244 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3245 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3246 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3247 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3248 return (Mask[0] < 2 && Mask[1] < 2);
3252 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PSHUFHW.
3254 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3255 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3258 // Lower quadword copied in order or undef.
3259 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3262 // Upper quadword shuffled.
3263 for (unsigned i = 4; i != 8; ++i)
3264 if (!isUndefOrInRange(Mask[i], 4, 8))
3267 if (VT == MVT::v16i16) {
3268 // Lower quadword copied in order or undef.
3269 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3272 // Upper quadword shuffled.
3273 for (unsigned i = 12; i != 16; ++i)
3274 if (!isUndefOrInRange(Mask[i], 12, 16))
3281 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3282 /// is suitable for input to PSHUFLW.
3283 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3284 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3287 // Upper quadword copied in order.
3288 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3291 // Lower quadword shuffled.
3292 for (unsigned i = 0; i != 4; ++i)
3293 if (!isUndefOrInRange(Mask[i], 0, 4))
3296 if (VT == MVT::v16i16) {
3297 // Upper quadword copied in order.
3298 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3301 // Lower quadword shuffled.
3302 for (unsigned i = 8; i != 12; ++i)
3303 if (!isUndefOrInRange(Mask[i], 8, 12))
3310 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3311 /// is suitable for input to PALIGNR.
3312 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3313 const X86Subtarget *Subtarget) {
3314 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3315 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3318 unsigned NumElts = VT.getVectorNumElements();
3319 unsigned NumLanes = VT.getSizeInBits()/128;
3320 unsigned NumLaneElts = NumElts/NumLanes;
3322 // Do not handle 64-bit element shuffles with palignr.
3323 if (NumLaneElts == 2)
3326 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3328 for (i = 0; i != NumLaneElts; ++i) {
3333 // Lane is all undef, go to next lane
3334 if (i == NumLaneElts)
3337 int Start = Mask[i+l];
3339 // Make sure its in this lane in one of the sources
3340 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3341 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3344 // If not lane 0, then we must match lane 0
3345 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3348 // Correct second source to be contiguous with first source
3349 if (Start >= (int)NumElts)
3350 Start -= NumElts - NumLaneElts;
3352 // Make sure we're shifting in the right direction.
3353 if (Start <= (int)(i+l))
3358 // Check the rest of the elements to see if they are consecutive.
3359 for (++i; i != NumLaneElts; ++i) {
3360 int Idx = Mask[i+l];
3362 // Make sure its in this lane
3363 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3364 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3367 // If not lane 0, then we must match lane 0
3368 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3371 if (Idx >= (int)NumElts)
3372 Idx -= NumElts - NumLaneElts;
3374 if (!isUndefOrEqual(Idx, Start+i))
3383 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3384 /// the two vector operands have swapped position.
3385 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3386 unsigned NumElems) {
3387 for (unsigned i = 0; i != NumElems; ++i) {
3391 else if (idx < (int)NumElems)
3392 Mask[i] = idx + NumElems;
3394 Mask[i] = idx - NumElems;
3398 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3399 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3400 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3401 /// reverse of what x86 shuffles want.
3402 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3403 bool Commuted = false) {
3404 if (!HasAVX && VT.getSizeInBits() == 256)
3407 unsigned NumElems = VT.getVectorNumElements();
3408 unsigned NumLanes = VT.getSizeInBits()/128;
3409 unsigned NumLaneElems = NumElems/NumLanes;
3411 if (NumLaneElems != 2 && NumLaneElems != 4)
3414 // VSHUFPSY divides the resulting vector into 4 chunks.
3415 // The sources are also splitted into 4 chunks, and each destination
3416 // chunk must come from a different source chunk.
3418 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3419 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3421 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3422 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3424 // VSHUFPDY divides the resulting vector into 4 chunks.
3425 // The sources are also splitted into 4 chunks, and each destination
3426 // chunk must come from a different source chunk.
3428 // SRC1 => X3 X2 X1 X0
3429 // SRC2 => Y3 Y2 Y1 Y0
3431 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3433 unsigned HalfLaneElems = NumLaneElems/2;
3434 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3435 for (unsigned i = 0; i != NumLaneElems; ++i) {
3436 int Idx = Mask[i+l];
3437 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3438 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3440 // For VSHUFPSY, the mask of the second half must be the same as the
3441 // first but with the appropriate offsets. This works in the same way as
3442 // VPERMILPS works with masks.
3443 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3445 if (!isUndefOrEqual(Idx, Mask[i]+l))
3453 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3455 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3456 if (!VT.is128BitVector())
3459 unsigned NumElems = VT.getVectorNumElements();
3464 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3465 return isUndefOrEqual(Mask[0], 6) &&
3466 isUndefOrEqual(Mask[1], 7) &&
3467 isUndefOrEqual(Mask[2], 2) &&
3468 isUndefOrEqual(Mask[3], 3);
3471 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3472 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3474 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3475 if (!VT.is128BitVector())
3478 unsigned NumElems = VT.getVectorNumElements();
3483 return isUndefOrEqual(Mask[0], 2) &&
3484 isUndefOrEqual(Mask[1], 3) &&
3485 isUndefOrEqual(Mask[2], 2) &&
3486 isUndefOrEqual(Mask[3], 3);
3489 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3491 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3492 if (!VT.is128BitVector())
3495 unsigned NumElems = VT.getVectorNumElements();
3497 if (NumElems != 2 && NumElems != 4)
3500 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3501 if (!isUndefOrEqual(Mask[i], i + NumElems))
3504 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3505 if (!isUndefOrEqual(Mask[i], i))
3511 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3513 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3514 if (!VT.is128BitVector())
3517 unsigned NumElems = VT.getVectorNumElements();
3519 if (NumElems != 2 && NumElems != 4)
3522 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3523 if (!isUndefOrEqual(Mask[i], i))
3526 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3527 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3534 // Some special combinations that can be optimized.
3537 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3538 SelectionDAG &DAG) {
3539 EVT VT = SVOp->getValueType(0);
3540 DebugLoc dl = SVOp->getDebugLoc();
3542 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3545 ArrayRef<int> Mask = SVOp->getMask();
3547 // These are the special masks that may be optimized.
3548 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3549 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3550 bool MatchEvenMask = true;
3551 bool MatchOddMask = true;
3552 for (int i=0; i<8; ++i) {
3553 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3554 MatchEvenMask = false;
3555 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3556 MatchOddMask = false;
3559 if (!MatchEvenMask && !MatchOddMask)
3562 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3564 SDValue Op0 = SVOp->getOperand(0);
3565 SDValue Op1 = SVOp->getOperand(1);
3567 if (MatchEvenMask) {
3568 // Shift the second operand right to 32 bits.
3569 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3570 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3572 // Shift the first operand left to 32 bits.
3573 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3574 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3576 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3577 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3580 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3581 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3582 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3583 bool HasAVX2, bool V2IsSplat = false) {
3584 unsigned NumElts = VT.getVectorNumElements();
3586 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3587 "Unsupported vector type for unpckh");
3589 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3590 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3593 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3594 // independently on 128-bit lanes.
3595 unsigned NumLanes = VT.getSizeInBits()/128;
3596 unsigned NumLaneElts = NumElts/NumLanes;
3598 for (unsigned l = 0; l != NumLanes; ++l) {
3599 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3600 i != (l+1)*NumLaneElts;
3603 int BitI1 = Mask[i+1];
3604 if (!isUndefOrEqual(BitI, j))
3607 if (!isUndefOrEqual(BitI1, NumElts))
3610 if (!isUndefOrEqual(BitI1, j + NumElts))
3619 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3620 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3621 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3622 bool HasAVX2, bool V2IsSplat = false) {
3623 unsigned NumElts = VT.getVectorNumElements();
3625 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3626 "Unsupported vector type for unpckh");
3628 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3629 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3632 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633 // independently on 128-bit lanes.
3634 unsigned NumLanes = VT.getSizeInBits()/128;
3635 unsigned NumLaneElts = NumElts/NumLanes;
3637 for (unsigned l = 0; l != NumLanes; ++l) {
3638 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3639 i != (l+1)*NumLaneElts; i += 2, ++j) {
3641 int BitI1 = Mask[i+1];
3642 if (!isUndefOrEqual(BitI, j))
3645 if (isUndefOrEqual(BitI1, NumElts))
3648 if (!isUndefOrEqual(BitI1, j+NumElts))
3656 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3657 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3659 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3661 unsigned NumElts = VT.getVectorNumElements();
3663 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3664 "Unsupported vector type for unpckh");
3666 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3667 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3670 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3671 // FIXME: Need a better way to get rid of this, there's no latency difference
3672 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3673 // the former later. We should also remove the "_undef" special mask.
3674 if (NumElts == 4 && VT.getSizeInBits() == 256)
3677 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678 // independently on 128-bit lanes.
3679 unsigned NumLanes = VT.getSizeInBits()/128;
3680 unsigned NumLaneElts = NumElts/NumLanes;
3682 for (unsigned l = 0; l != NumLanes; ++l) {
3683 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3684 i != (l+1)*NumLaneElts;
3687 int BitI1 = Mask[i+1];
3689 if (!isUndefOrEqual(BitI, j))
3691 if (!isUndefOrEqual(BitI1, j))
3699 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3700 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3702 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3703 unsigned NumElts = VT.getVectorNumElements();
3705 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3706 "Unsupported vector type for unpckh");
3708 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3709 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3712 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713 // independently on 128-bit lanes.
3714 unsigned NumLanes = VT.getSizeInBits()/128;
3715 unsigned NumLaneElts = NumElts/NumLanes;
3717 for (unsigned l = 0; l != NumLanes; ++l) {
3718 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3719 i != (l+1)*NumLaneElts; i += 2, ++j) {
3721 int BitI1 = Mask[i+1];
3722 if (!isUndefOrEqual(BitI, j))
3724 if (!isUndefOrEqual(BitI1, j))
3731 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3732 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3733 /// MOVSD, and MOVD, i.e. setting the lowest element.
3734 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3735 if (VT.getVectorElementType().getSizeInBits() < 32)
3737 if (!VT.is128BitVector())
3740 unsigned NumElts = VT.getVectorNumElements();
3742 if (!isUndefOrEqual(Mask[0], NumElts))
3745 for (unsigned i = 1; i != NumElts; ++i)
3746 if (!isUndefOrEqual(Mask[i], i))
3752 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3753 /// as permutations between 128-bit chunks or halves. As an example: this
3755 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3756 /// The first half comes from the second half of V1 and the second half from the
3757 /// the second half of V2.
3758 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3759 if (!HasAVX || !VT.is256BitVector())
3762 // The shuffle result is divided into half A and half B. In total the two
3763 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3764 // B must come from C, D, E or F.
3765 unsigned HalfSize = VT.getVectorNumElements()/2;
3766 bool MatchA = false, MatchB = false;
3768 // Check if A comes from one of C, D, E, F.
3769 for (unsigned Half = 0; Half != 4; ++Half) {
3770 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3776 // Check if B comes from one of C, D, E, F.
3777 for (unsigned Half = 0; Half != 4; ++Half) {
3778 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3784 return MatchA && MatchB;
3787 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3788 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3789 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3790 EVT VT = SVOp->getValueType(0);
3792 unsigned HalfSize = VT.getVectorNumElements()/2;
3794 unsigned FstHalf = 0, SndHalf = 0;
3795 for (unsigned i = 0; i < HalfSize; ++i) {
3796 if (SVOp->getMaskElt(i) > 0) {
3797 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3801 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3802 if (SVOp->getMaskElt(i) > 0) {
3803 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3808 return (FstHalf | (SndHalf << 4));
3811 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3812 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3813 /// Note that VPERMIL mask matching is different depending whether theunderlying
3814 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3815 /// to the same elements of the low, but to the higher half of the source.
3816 /// In VPERMILPD the two lanes could be shuffled independently of each other
3817 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3818 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3822 unsigned NumElts = VT.getVectorNumElements();
3823 // Only match 256-bit with 32/64-bit types
3824 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3827 unsigned NumLanes = VT.getSizeInBits()/128;
3828 unsigned LaneSize = NumElts/NumLanes;
3829 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3830 for (unsigned i = 0; i != LaneSize; ++i) {
3831 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3833 if (NumElts != 8 || l == 0)
3835 // VPERMILPS handling
3838 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3846 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3847 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3848 /// element of vector 2 and the other elements to come from vector 1 in order.
3849 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3850 bool V2IsSplat = false, bool V2IsUndef = false) {
3851 if (!VT.is128BitVector())
3854 unsigned NumOps = VT.getVectorNumElements();
3855 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3858 if (!isUndefOrEqual(Mask[0], 0))
3861 for (unsigned i = 1; i != NumOps; ++i)
3862 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3863 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3864 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3870 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3872 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3873 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3874 const X86Subtarget *Subtarget) {
3875 if (!Subtarget->hasSSE3())
3878 unsigned NumElems = VT.getVectorNumElements();
3880 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3881 (VT.getSizeInBits() == 256 && NumElems != 8))
3884 // "i+1" is the value the indexed mask element must have
3885 for (unsigned i = 0; i != NumElems; i += 2)
3886 if (!isUndefOrEqual(Mask[i], i+1) ||
3887 !isUndefOrEqual(Mask[i+1], i+1))
3893 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3895 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3896 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3897 const X86Subtarget *Subtarget) {
3898 if (!Subtarget->hasSSE3())
3901 unsigned NumElems = VT.getVectorNumElements();
3903 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3904 (VT.getSizeInBits() == 256 && NumElems != 8))
3907 // "i" is the value the indexed mask element must have
3908 for (unsigned i = 0; i != NumElems; i += 2)
3909 if (!isUndefOrEqual(Mask[i], i) ||
3910 !isUndefOrEqual(Mask[i+1], i))
3916 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to 256-bit
3918 /// version of MOVDDUP.
3919 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3920 if (!HasAVX || !VT.is256BitVector())
3923 unsigned NumElts = VT.getVectorNumElements();
3927 for (unsigned i = 0; i != NumElts/2; ++i)
3928 if (!isUndefOrEqual(Mask[i], 0))
3930 for (unsigned i = NumElts/2; i != NumElts; ++i)
3931 if (!isUndefOrEqual(Mask[i], NumElts/2))
3936 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to 128-bit
3938 /// version of MOVDDUP.
3939 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3940 if (!VT.is128BitVector())
3943 unsigned e = VT.getVectorNumElements() / 2;
3944 for (unsigned i = 0; i != e; ++i)
3945 if (!isUndefOrEqual(Mask[i], i))
3947 for (unsigned i = 0; i != e; ++i)
3948 if (!isUndefOrEqual(Mask[e+i], i))
3953 /// isVEXTRACTF128Index - Return true if the specified
3954 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3955 /// suitable for input to VEXTRACTF128.
3956 bool X86::isVEXTRACTF128Index(SDNode *N) {
3957 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3960 // The index should be aligned on a 128-bit boundary.
3962 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3964 unsigned VL = N->getValueType(0).getVectorNumElements();
3965 unsigned VBits = N->getValueType(0).getSizeInBits();
3966 unsigned ElSize = VBits / VL;
3967 bool Result = (Index * ElSize) % 128 == 0;
3972 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3973 /// operand specifies a subvector insert that is suitable for input to
3975 bool X86::isVINSERTF128Index(SDNode *N) {
3976 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3979 // The index should be aligned on a 128-bit boundary.
3981 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3983 unsigned VL = N->getValueType(0).getVectorNumElements();
3984 unsigned VBits = N->getValueType(0).getSizeInBits();
3985 unsigned ElSize = VBits / VL;
3986 bool Result = (Index * ElSize) % 128 == 0;
3991 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3993 /// Handles 128-bit and 256-bit.
3994 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3995 EVT VT = N->getValueType(0);
3997 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3998 "Unsupported vector type for PSHUF/SHUFP");
4000 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4001 // independently on 128-bit lanes.
4002 unsigned NumElts = VT.getVectorNumElements();
4003 unsigned NumLanes = VT.getSizeInBits()/128;
4004 unsigned NumLaneElts = NumElts/NumLanes;
4006 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4007 "Only supports 2 or 4 elements per lane");
4009 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4011 for (unsigned i = 0; i != NumElts; ++i) {
4012 int Elt = N->getMaskElt(i);
4013 if (Elt < 0) continue;
4014 Elt &= NumLaneElts - 1;
4015 unsigned ShAmt = (i << Shift) % 8;
4016 Mask |= Elt << ShAmt;
4022 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4023 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4024 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4025 EVT VT = N->getValueType(0);
4027 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4028 "Unsupported vector type for PSHUFHW");
4030 unsigned NumElts = VT.getVectorNumElements();
4033 for (unsigned l = 0; l != NumElts; l += 8) {
4034 // 8 nodes per lane, but we only care about the last 4.
4035 for (unsigned i = 0; i < 4; ++i) {
4036 int Elt = N->getMaskElt(l+i+4);
4037 if (Elt < 0) continue;
4038 Elt &= 0x3; // only 2-bits.
4039 Mask |= Elt << (i * 2);
4046 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4047 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4048 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4049 EVT VT = N->getValueType(0);
4051 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4052 "Unsupported vector type for PSHUFHW");
4054 unsigned NumElts = VT.getVectorNumElements();
4057 for (unsigned l = 0; l != NumElts; l += 8) {
4058 // 8 nodes per lane, but we only care about the first 4.
4059 for (unsigned i = 0; i < 4; ++i) {
4060 int Elt = N->getMaskElt(l+i);
4061 if (Elt < 0) continue;
4062 Elt &= 0x3; // only 2-bits
4063 Mask |= Elt << (i * 2);
4070 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4072 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4073 EVT VT = SVOp->getValueType(0);
4074 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4076 unsigned NumElts = VT.getVectorNumElements();
4077 unsigned NumLanes = VT.getSizeInBits()/128;
4078 unsigned NumLaneElts = NumElts/NumLanes;
4082 for (i = 0; i != NumElts; ++i) {
4083 Val = SVOp->getMaskElt(i);
4087 if (Val >= (int)NumElts)
4088 Val -= NumElts - NumLaneElts;
4090 assert(Val - i > 0 && "PALIGNR imm should be positive");
4091 return (Val - i) * EltSize;
4094 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4095 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4097 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4098 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4099 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4102 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4104 EVT VecVT = N->getOperand(0).getValueType();
4105 EVT ElVT = VecVT.getVectorElementType();
4107 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4108 return Index / NumElemsPerChunk;
4111 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4112 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4114 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4115 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4116 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4119 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4121 EVT VecVT = N->getValueType(0);
4122 EVT ElVT = VecVT.getVectorElementType();
4124 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4125 return Index / NumElemsPerChunk;
4128 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4129 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4130 /// Handles 256-bit.
4131 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4132 EVT VT = N->getValueType(0);
4134 unsigned NumElts = VT.getVectorNumElements();
4136 assert((VT.is256BitVector() && NumElts == 4) &&
4137 "Unsupported vector type for VPERMQ/VPERMPD");
4140 for (unsigned i = 0; i != NumElts; ++i) {
4141 int Elt = N->getMaskElt(i);
4144 Mask |= Elt << (i*2);
4149 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4151 bool X86::isZeroNode(SDValue Elt) {
4152 return ((isa<ConstantSDNode>(Elt) &&
4153 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4154 (isa<ConstantFPSDNode>(Elt) &&
4155 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4158 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4159 /// their permute mask.
4160 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4161 SelectionDAG &DAG) {
4162 EVT VT = SVOp->getValueType(0);
4163 unsigned NumElems = VT.getVectorNumElements();
4164 SmallVector<int, 8> MaskVec;
4166 for (unsigned i = 0; i != NumElems; ++i) {
4167 int Idx = SVOp->getMaskElt(i);
4169 if (Idx < (int)NumElems)
4174 MaskVec.push_back(Idx);
4176 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4177 SVOp->getOperand(0), &MaskVec[0]);
4180 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4181 /// match movhlps. The lower half elements should come from upper half of
4182 /// V1 (and in order), and the upper half elements should come from the upper
4183 /// half of V2 (and in order).
4184 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4185 if (!VT.is128BitVector())
4187 if (VT.getVectorNumElements() != 4)
4189 for (unsigned i = 0, e = 2; i != e; ++i)
4190 if (!isUndefOrEqual(Mask[i], i+2))
4192 for (unsigned i = 2; i != 4; ++i)
4193 if (!isUndefOrEqual(Mask[i], i+4))
4198 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4199 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4201 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4202 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4204 N = N->getOperand(0).getNode();
4205 if (!ISD::isNON_EXTLoad(N))
4208 *LD = cast<LoadSDNode>(N);
4212 // Test whether the given value is a vector value which will be legalized
4214 static bool WillBeConstantPoolLoad(SDNode *N) {
4215 if (N->getOpcode() != ISD::BUILD_VECTOR)
4218 // Check for any non-constant elements.
4219 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4220 switch (N->getOperand(i).getNode()->getOpcode()) {
4222 case ISD::ConstantFP:
4229 // Vectors of all-zeros and all-ones are materialized with special
4230 // instructions rather than being loaded.
4231 return !ISD::isBuildVectorAllZeros(N) &&
4232 !ISD::isBuildVectorAllOnes(N);
4235 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4236 /// match movlp{s|d}. The lower half elements should come from lower half of
4237 /// V1 (and in order), and the upper half elements should come from the upper
4238 /// half of V2 (and in order). And since V1 will become the source of the
4239 /// MOVLP, it must be either a vector load or a scalar load to vector.
4240 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4241 ArrayRef<int> Mask, EVT VT) {
4242 if (!VT.is128BitVector())
4245 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4247 // Is V2 is a vector load, don't do this transformation. We will try to use
4248 // load folding shufps op.
4249 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4252 unsigned NumElems = VT.getVectorNumElements();
4254 if (NumElems != 2 && NumElems != 4)
4256 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4257 if (!isUndefOrEqual(Mask[i], i))
4259 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4260 if (!isUndefOrEqual(Mask[i], i+NumElems))
4265 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4267 static bool isSplatVector(SDNode *N) {
4268 if (N->getOpcode() != ISD::BUILD_VECTOR)
4271 SDValue SplatValue = N->getOperand(0);
4272 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4273 if (N->getOperand(i) != SplatValue)
4278 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4279 /// to an zero vector.
4280 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4281 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4282 SDValue V1 = N->getOperand(0);
4283 SDValue V2 = N->getOperand(1);
4284 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4285 for (unsigned i = 0; i != NumElems; ++i) {
4286 int Idx = N->getMaskElt(i);
4287 if (Idx >= (int)NumElems) {
4288 unsigned Opc = V2.getOpcode();
4289 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4291 if (Opc != ISD::BUILD_VECTOR ||
4292 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4294 } else if (Idx >= 0) {
4295 unsigned Opc = V1.getOpcode();
4296 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4298 if (Opc != ISD::BUILD_VECTOR ||
4299 !X86::isZeroNode(V1.getOperand(Idx)))
4306 /// getZeroVector - Returns a vector of specified type with all zero elements.
4308 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4309 SelectionDAG &DAG, DebugLoc dl) {
4310 assert(VT.isVector() && "Expected a vector type");
4311 unsigned Size = VT.getSizeInBits();
4313 // Always build SSE zero vectors as <4 x i32> bitcasted
4314 // to their dest type. This ensures they get CSE'd.
4316 if (Size == 128) { // SSE
4317 if (Subtarget->hasSSE2()) { // SSE2
4318 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4321 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4322 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4324 } else if (Size == 256) { // AVX
4325 if (Subtarget->hasAVX2()) { // AVX2
4326 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4327 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4328 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4330 // 256-bit logic and arithmetic instructions in AVX are all
4331 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4332 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4333 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4337 llvm_unreachable("Unexpected vector type");
4339 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4342 /// getOnesVector - Returns a vector of specified type with all bits set.
4343 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4344 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4345 /// Then bitcast to their original type, ensuring they get CSE'd.
4346 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4348 assert(VT.isVector() && "Expected a vector type");
4349 unsigned Size = VT.getSizeInBits();
4351 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4354 if (HasAVX2) { // AVX2
4355 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4358 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4359 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4361 } else if (Size == 128) {
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4364 llvm_unreachable("Unexpected vector type");
4366 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4369 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4370 /// that point to V2 points to its first element.
4371 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4372 for (unsigned i = 0; i != NumElems; ++i) {
4373 if (Mask[i] > (int)NumElems) {
4379 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4380 /// operation of specified width.
4381 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4383 unsigned NumElems = VT.getVectorNumElements();
4384 SmallVector<int, 8> Mask;
4385 Mask.push_back(NumElems);
4386 for (unsigned i = 1; i != NumElems; ++i)
4388 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4391 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4392 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4394 unsigned NumElems = VT.getVectorNumElements();
4395 SmallVector<int, 8> Mask;
4396 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4398 Mask.push_back(i + NumElems);
4400 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4403 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4404 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4406 unsigned NumElems = VT.getVectorNumElements();
4407 SmallVector<int, 8> Mask;
4408 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4409 Mask.push_back(i + Half);
4410 Mask.push_back(i + NumElems + Half);
4412 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4415 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4416 // a generic shuffle instruction because the target has no such instructions.
4417 // Generate shuffles which repeat i16 and i8 several times until they can be
4418 // represented by v4f32 and then be manipulated by target suported shuffles.
4419 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4420 EVT VT = V.getValueType();
4421 int NumElems = VT.getVectorNumElements();
4422 DebugLoc dl = V.getDebugLoc();
4424 while (NumElems > 4) {
4425 if (EltNo < NumElems/2) {
4426 V = getUnpackl(DAG, dl, VT, V, V);
4428 V = getUnpackh(DAG, dl, VT, V, V);
4429 EltNo -= NumElems/2;
4436 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4437 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4438 EVT VT = V.getValueType();
4439 DebugLoc dl = V.getDebugLoc();
4440 unsigned Size = VT.getSizeInBits();
4443 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4444 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4445 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4447 } else if (Size == 256) {
4448 // To use VPERMILPS to splat scalars, the second half of indicies must
4449 // refer to the higher part, which is a duplication of the lower one,
4450 // because VPERMILPS can only handle in-lane permutations.
4451 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4452 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4454 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4455 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4458 llvm_unreachable("Vector size not supported");
4460 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4463 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4464 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4465 EVT SrcVT = SV->getValueType(0);
4466 SDValue V1 = SV->getOperand(0);
4467 DebugLoc dl = SV->getDebugLoc();
4469 int EltNo = SV->getSplatIndex();
4470 int NumElems = SrcVT.getVectorNumElements();
4471 unsigned Size = SrcVT.getSizeInBits();
4473 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4474 "Unknown how to promote splat for type");
4476 // Extract the 128-bit part containing the splat element and update
4477 // the splat element index when it refers to the higher register.
4479 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4480 if (EltNo >= NumElems/2)
4481 EltNo -= NumElems/2;
4484 // All i16 and i8 vector types can't be used directly by a generic shuffle
4485 // instruction because the target has no such instruction. Generate shuffles
4486 // which repeat i16 and i8 several times until they fit in i32, and then can
4487 // be manipulated by target suported shuffles.
4488 EVT EltVT = SrcVT.getVectorElementType();
4489 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4490 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4492 // Recreate the 256-bit vector and place the same 128-bit vector
4493 // into the low and high part. This is necessary because we want
4494 // to use VPERM* to shuffle the vectors
4496 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4499 return getLegalSplat(DAG, V1, EltNo);
4502 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4503 /// vector of zero or undef vector. This produces a shuffle where the low
4504 /// element of V2 is swizzled into the zero/undef vector, landing at element
4505 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4506 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4508 const X86Subtarget *Subtarget,
4509 SelectionDAG &DAG) {
4510 EVT VT = V2.getValueType();
4512 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4513 unsigned NumElems = VT.getVectorNumElements();
4514 SmallVector<int, 16> MaskVec;
4515 for (unsigned i = 0; i != NumElems; ++i)
4516 // If this is the insertion idx, put the low elt of V2 here.
4517 MaskVec.push_back(i == Idx ? NumElems : i);
4518 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4521 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4522 /// target specific opcode. Returns true if the Mask could be calculated.
4523 /// Sets IsUnary to true if only uses one source.
4524 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4525 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4526 unsigned NumElems = VT.getVectorNumElements();
4530 switch(N->getOpcode()) {
4532 ImmN = N->getOperand(N->getNumOperands()-1);
4533 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535 case X86ISD::UNPCKH:
4536 DecodeUNPCKHMask(VT, Mask);
4538 case X86ISD::UNPCKL:
4539 DecodeUNPCKLMask(VT, Mask);
4541 case X86ISD::MOVHLPS:
4542 DecodeMOVHLPSMask(NumElems, Mask);
4544 case X86ISD::MOVLHPS:
4545 DecodeMOVLHPSMask(NumElems, Mask);
4547 case X86ISD::PSHUFD:
4548 case X86ISD::VPERMILP:
4549 ImmN = N->getOperand(N->getNumOperands()-1);
4550 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4553 case X86ISD::PSHUFHW:
4554 ImmN = N->getOperand(N->getNumOperands()-1);
4555 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4558 case X86ISD::PSHUFLW:
4559 ImmN = N->getOperand(N->getNumOperands()-1);
4560 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563 case X86ISD::VPERMI:
4564 ImmN = N->getOperand(N->getNumOperands()-1);
4565 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569 case X86ISD::MOVSD: {
4570 // The index 0 always comes from the first element of the second source,
4571 // this is why MOVSS and MOVSD are used in the first place. The other
4572 // elements come from the other positions of the first source vector
4573 Mask.push_back(NumElems);
4574 for (unsigned i = 1; i != NumElems; ++i) {
4579 case X86ISD::VPERM2X128:
4580 ImmN = N->getOperand(N->getNumOperands()-1);
4581 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4582 if (Mask.empty()) return false;
4584 case X86ISD::MOVDDUP:
4585 case X86ISD::MOVLHPD:
4586 case X86ISD::MOVLPD:
4587 case X86ISD::MOVLPS:
4588 case X86ISD::MOVSHDUP:
4589 case X86ISD::MOVSLDUP:
4590 case X86ISD::PALIGN:
4591 // Not yet implemented
4593 default: llvm_unreachable("unknown target shuffle node");
4599 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4600 /// element of the result of the vector shuffle.
4601 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4604 return SDValue(); // Limit search depth.
4606 SDValue V = SDValue(N, 0);
4607 EVT VT = V.getValueType();
4608 unsigned Opcode = V.getOpcode();
4610 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4611 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4612 int Elt = SV->getMaskElt(Index);
4615 return DAG.getUNDEF(VT.getVectorElementType());
4617 unsigned NumElems = VT.getVectorNumElements();
4618 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4619 : SV->getOperand(1);
4620 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4623 // Recurse into target specific vector shuffles to find scalars.
4624 if (isTargetShuffle(Opcode)) {
4625 MVT ShufVT = V.getValueType().getSimpleVT();
4626 unsigned NumElems = ShufVT.getVectorNumElements();
4627 SmallVector<int, 16> ShuffleMask;
4631 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4634 int Elt = ShuffleMask[Index];
4636 return DAG.getUNDEF(ShufVT.getVectorElementType());
4638 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4640 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4644 // Actual nodes that may contain scalar elements
4645 if (Opcode == ISD::BITCAST) {
4646 V = V.getOperand(0);
4647 EVT SrcVT = V.getValueType();
4648 unsigned NumElems = VT.getVectorNumElements();
4650 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4654 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4655 return (Index == 0) ? V.getOperand(0)
4656 : DAG.getUNDEF(VT.getVectorElementType());
4658 if (V.getOpcode() == ISD::BUILD_VECTOR)
4659 return V.getOperand(Index);
4664 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4665 /// shuffle operation which come from a consecutively from a zero. The
4666 /// search can start in two different directions, from left or right.
4668 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4669 bool ZerosFromLeft, SelectionDAG &DAG) {
4671 for (i = 0; i != NumElems; ++i) {
4672 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4673 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4674 if (!(Elt.getNode() &&
4675 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4682 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4683 /// correspond consecutively to elements from one of the vector operands,
4684 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4686 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4687 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4688 unsigned NumElems, unsigned &OpNum) {
4689 bool SeenV1 = false;
4690 bool SeenV2 = false;
4692 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4693 int Idx = SVOp->getMaskElt(i);
4694 // Ignore undef indicies
4698 if (Idx < (int)NumElems)
4703 // Only accept consecutive elements from the same vector
4704 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4708 OpNum = SeenV1 ? 0 : 1;
4712 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4713 /// logical left shift of a vector.
4714 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4715 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4716 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4717 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4718 false /* check zeros from right */, DAG);
4724 // Considering the elements in the mask that are not consecutive zeros,
4725 // check if they consecutively come from only one of the source vectors.
4727 // V1 = {X, A, B, C} 0
4729 // vector_shuffle V1, V2 <1, 2, 3, X>
4731 if (!isShuffleMaskConsecutive(SVOp,
4732 0, // Mask Start Index
4733 NumElems-NumZeros, // Mask End Index(exclusive)
4734 NumZeros, // Where to start looking in the src vector
4735 NumElems, // Number of elements in vector
4736 OpSrc)) // Which source operand ?
4741 ShVal = SVOp->getOperand(OpSrc);
4745 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4746 /// logical left shift of a vector.
4747 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4748 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4749 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4750 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4751 true /* check zeros from left */, DAG);
4757 // Considering the elements in the mask that are not consecutive zeros,
4758 // check if they consecutively come from only one of the source vectors.
4760 // 0 { A, B, X, X } = V2
4762 // vector_shuffle V1, V2 <X, X, 4, 5>
4764 if (!isShuffleMaskConsecutive(SVOp,
4765 NumZeros, // Mask Start Index
4766 NumElems, // Mask End Index(exclusive)
4767 0, // Where to start looking in the src vector
4768 NumElems, // Number of elements in vector
4769 OpSrc)) // Which source operand ?
4774 ShVal = SVOp->getOperand(OpSrc);
4778 /// isVectorShift - Returns true if the shuffle can be implemented as a
4779 /// logical left or right shift of a vector.
4780 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4781 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4782 // Although the logic below support any bitwidth size, there are no
4783 // shift instructions which handle more than 128-bit vectors.
4784 if (!SVOp->getValueType(0).is128BitVector())
4787 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4788 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4794 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4796 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4797 unsigned NumNonZero, unsigned NumZero,
4799 const X86Subtarget* Subtarget,
4800 const TargetLowering &TLI) {
4804 DebugLoc dl = Op.getDebugLoc();
4807 for (unsigned i = 0; i < 16; ++i) {
4808 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4809 if (ThisIsNonZero && First) {
4811 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4813 V = DAG.getUNDEF(MVT::v8i16);
4818 SDValue ThisElt(0, 0), LastElt(0, 0);
4819 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4820 if (LastIsNonZero) {
4821 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4822 MVT::i16, Op.getOperand(i-1));
4824 if (ThisIsNonZero) {
4825 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4826 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4827 ThisElt, DAG.getConstant(8, MVT::i8));
4829 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4833 if (ThisElt.getNode())
4834 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4835 DAG.getIntPtrConstant(i/2));
4839 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4842 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4844 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4845 unsigned NumNonZero, unsigned NumZero,
4847 const X86Subtarget* Subtarget,
4848 const TargetLowering &TLI) {
4852 DebugLoc dl = Op.getDebugLoc();
4855 for (unsigned i = 0; i < 8; ++i) {
4856 bool isNonZero = (NonZeros & (1 << i)) != 0;
4860 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4862 V = DAG.getUNDEF(MVT::v8i16);
4865 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4866 MVT::v8i16, V, Op.getOperand(i),
4867 DAG.getIntPtrConstant(i));
4874 /// getVShift - Return a vector logical shift node.
4876 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4877 unsigned NumBits, SelectionDAG &DAG,
4878 const TargetLowering &TLI, DebugLoc dl) {
4879 assert(VT.is128BitVector() && "Unknown type for VShift");
4880 EVT ShVT = MVT::v2i64;
4881 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4882 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4883 return DAG.getNode(ISD::BITCAST, dl, VT,
4884 DAG.getNode(Opc, dl, ShVT, SrcOp,
4885 DAG.getConstant(NumBits,
4886 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4890 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4891 SelectionDAG &DAG) const {
4893 // Check if the scalar load can be widened into a vector load. And if
4894 // the address is "base + cst" see if the cst can be "absorbed" into
4895 // the shuffle mask.
4896 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4897 SDValue Ptr = LD->getBasePtr();
4898 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4900 EVT PVT = LD->getValueType(0);
4901 if (PVT != MVT::i32 && PVT != MVT::f32)
4906 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4907 FI = FINode->getIndex();
4909 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4910 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4911 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4912 Offset = Ptr.getConstantOperandVal(1);
4913 Ptr = Ptr.getOperand(0);
4918 // FIXME: 256-bit vector instructions don't require a strict alignment,
4919 // improve this code to support it better.
4920 unsigned RequiredAlign = VT.getSizeInBits()/8;
4921 SDValue Chain = LD->getChain();
4922 // Make sure the stack object alignment is at least 16 or 32.
4923 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4924 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4925 if (MFI->isFixedObjectIndex(FI)) {
4926 // Can't change the alignment. FIXME: It's possible to compute
4927 // the exact stack offset and reference FI + adjust offset instead.
4928 // If someone *really* cares about this. That's the way to implement it.
4931 MFI->setObjectAlignment(FI, RequiredAlign);
4935 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4936 // Ptr + (Offset & ~15).
4939 if ((Offset % RequiredAlign) & 3)
4941 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4943 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4944 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4946 int EltNo = (Offset - StartOffset) >> 2;
4947 unsigned NumElems = VT.getVectorNumElements();
4949 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4950 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4951 LD->getPointerInfo().getWithOffset(StartOffset),
4952 false, false, false, 0);
4954 SmallVector<int, 8> Mask;
4955 for (unsigned i = 0; i != NumElems; ++i)
4956 Mask.push_back(EltNo);
4958 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4964 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4965 /// vector of type 'VT', see if the elements can be replaced by a single large
4966 /// load which has the same value as a build_vector whose operands are 'elts'.
4968 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4970 /// FIXME: we'd also like to handle the case where the last elements are zero
4971 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4972 /// There's even a handy isZeroNode for that purpose.
4973 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4974 DebugLoc &DL, SelectionDAG &DAG) {
4975 EVT EltVT = VT.getVectorElementType();
4976 unsigned NumElems = Elts.size();
4978 LoadSDNode *LDBase = NULL;
4979 unsigned LastLoadedElt = -1U;
4981 // For each element in the initializer, see if we've found a load or an undef.
4982 // If we don't find an initial load element, or later load elements are
4983 // non-consecutive, bail out.
4984 for (unsigned i = 0; i < NumElems; ++i) {
4985 SDValue Elt = Elts[i];
4987 if (!Elt.getNode() ||
4988 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4991 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4993 LDBase = cast<LoadSDNode>(Elt.getNode());
4997 if (Elt.getOpcode() == ISD::UNDEF)
5000 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5001 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5006 // If we have found an entire vector of loads and undefs, then return a large
5007 // load of the entire vector width starting at the base pointer. If we found
5008 // consecutive loads for the low half, generate a vzext_load node.
5009 if (LastLoadedElt == NumElems - 1) {
5010 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5011 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5012 LDBase->getPointerInfo(),
5013 LDBase->isVolatile(), LDBase->isNonTemporal(),
5014 LDBase->isInvariant(), 0);
5015 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5016 LDBase->getPointerInfo(),
5017 LDBase->isVolatile(), LDBase->isNonTemporal(),
5018 LDBase->isInvariant(), LDBase->getAlignment());
5020 if (NumElems == 4 && LastLoadedElt == 1 &&
5021 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5022 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5023 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5025 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5026 LDBase->getPointerInfo(),
5027 LDBase->getAlignment(),
5028 false/*isVolatile*/, true/*ReadMem*/,
5031 // Make sure the newly-created LOAD is in the same position as LDBase in
5032 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5033 // update uses of LDBase's output chain to use the TokenFactor.
5034 if (LDBase->hasAnyUseOfValue(1)) {
5035 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5036 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5037 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5038 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5039 SDValue(ResNode.getNode(), 1));
5042 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5047 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5048 /// to generate a splat value for the following cases:
5049 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5050 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5051 /// a scalar load, or a constant.
5052 /// The VBROADCAST node is returned when a pattern is found,
5053 /// or SDValue() otherwise.
5055 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5056 if (!Subtarget->hasAVX())
5059 EVT VT = Op.getValueType();
5060 DebugLoc dl = Op.getDebugLoc();
5062 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5063 "Unsupported vector type for broadcast.");
5068 switch (Op.getOpcode()) {
5070 // Unknown pattern found.
5073 case ISD::BUILD_VECTOR: {
5074 // The BUILD_VECTOR node must be a splat.
5075 if (!isSplatVector(Op.getNode()))
5078 Ld = Op.getOperand(0);
5079 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5080 Ld.getOpcode() == ISD::ConstantFP);
5082 // The suspected load node has several users. Make sure that all
5083 // of its users are from the BUILD_VECTOR node.
5084 // Constants may have multiple users.
5085 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5090 case ISD::VECTOR_SHUFFLE: {
5091 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5093 // Shuffles must have a splat mask where the first element is
5095 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5098 SDValue Sc = Op.getOperand(0);
5099 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5100 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5102 if (!Subtarget->hasAVX2())
5105 // Use the register form of the broadcast instruction available on AVX2.
5106 if (VT.is256BitVector())
5107 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5108 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5111 Ld = Sc.getOperand(0);
5112 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5113 Ld.getOpcode() == ISD::ConstantFP);
5115 // The scalar_to_vector node and the suspected
5116 // load node must have exactly one user.
5117 // Constants may have multiple users.
5118 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5124 bool Is256 = VT.is256BitVector();
5126 // Handle the broadcasting a single constant scalar from the constant pool
5127 // into a vector. On Sandybridge it is still better to load a constant vector
5128 // from the constant pool and not to broadcast it from a scalar.
5129 if (ConstSplatVal && Subtarget->hasAVX2()) {
5130 EVT CVT = Ld.getValueType();
5131 assert(!CVT.isVector() && "Must not broadcast a vector type");
5132 unsigned ScalarSize = CVT.getSizeInBits();
5134 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5135 const Constant *C = 0;
5136 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5137 C = CI->getConstantIntValue();
5138 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5139 C = CF->getConstantFPValue();
5141 assert(C && "Invalid constant type");
5143 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5144 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5145 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5146 MachinePointerInfo::getConstantPool(),
5147 false, false, false, Alignment);
5149 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5153 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5154 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5156 // Handle AVX2 in-register broadcasts.
5157 if (!IsLoad && Subtarget->hasAVX2() &&
5158 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5159 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5161 // The scalar source must be a normal load.
5165 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5166 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5168 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5169 // double since there is no vbroadcastsd xmm
5170 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5171 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5172 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5175 // Unsupported broadcast.
5180 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5181 EVT VT = Op.getValueType();
5183 // Skip if insert_vec_elt is not supported.
5184 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5187 DebugLoc DL = Op.getDebugLoc();
5188 unsigned NumElems = Op.getNumOperands();
5192 SmallVector<unsigned, 4> InsertIndices;
5193 SmallVector<int, 8> Mask(NumElems, -1);
5195 for (unsigned i = 0; i != NumElems; ++i) {
5196 unsigned Opc = Op.getOperand(i).getOpcode();
5198 if (Opc == ISD::UNDEF)
5201 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5202 // Quit if more than 1 elements need inserting.
5203 if (InsertIndices.size() > 1)
5206 InsertIndices.push_back(i);
5210 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5211 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5213 // Quit if extracted from vector of different type.
5214 if (ExtractedFromVec.getValueType() != VT)
5217 // Quit if non-constant index.
5218 if (!isa<ConstantSDNode>(ExtIdx))
5221 if (VecIn1.getNode() == 0)
5222 VecIn1 = ExtractedFromVec;
5223 else if (VecIn1 != ExtractedFromVec) {
5224 if (VecIn2.getNode() == 0)
5225 VecIn2 = ExtractedFromVec;
5226 else if (VecIn2 != ExtractedFromVec)
5227 // Quit if more than 2 vectors to shuffle
5231 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5233 if (ExtractedFromVec == VecIn1)
5235 else if (ExtractedFromVec == VecIn2)
5236 Mask[i] = Idx + NumElems;
5239 if (VecIn1.getNode() == 0)
5242 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5243 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5244 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5245 unsigned Idx = InsertIndices[i];
5246 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5247 DAG.getIntPtrConstant(Idx));
5254 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5255 DebugLoc dl = Op.getDebugLoc();
5257 EVT VT = Op.getValueType();
5258 EVT ExtVT = VT.getVectorElementType();
5259 unsigned NumElems = Op.getNumOperands();
5261 // Vectors containing all zeros can be matched by pxor and xorps later
5262 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5263 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5264 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5265 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5268 return getZeroVector(VT, Subtarget, DAG, dl);
5271 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5272 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5273 // vpcmpeqd on 256-bit vectors.
5274 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5275 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5278 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5281 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5282 if (Broadcast.getNode())
5285 unsigned EVTBits = ExtVT.getSizeInBits();
5287 unsigned NumZero = 0;
5288 unsigned NumNonZero = 0;
5289 unsigned NonZeros = 0;
5290 bool IsAllConstants = true;
5291 SmallSet<SDValue, 8> Values;
5292 for (unsigned i = 0; i < NumElems; ++i) {
5293 SDValue Elt = Op.getOperand(i);
5294 if (Elt.getOpcode() == ISD::UNDEF)
5297 if (Elt.getOpcode() != ISD::Constant &&
5298 Elt.getOpcode() != ISD::ConstantFP)
5299 IsAllConstants = false;
5300 if (X86::isZeroNode(Elt))
5303 NonZeros |= (1 << i);
5308 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5309 if (NumNonZero == 0)
5310 return DAG.getUNDEF(VT);
5312 // Special case for single non-zero, non-undef, element.
5313 if (NumNonZero == 1) {
5314 unsigned Idx = CountTrailingZeros_32(NonZeros);
5315 SDValue Item = Op.getOperand(Idx);
5317 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5318 // the value are obviously zero, truncate the value to i32 and do the
5319 // insertion that way. Only do this if the value is non-constant or if the
5320 // value is a constant being inserted into element 0. It is cheaper to do
5321 // a constant pool load than it is to do a movd + shuffle.
5322 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5323 (!IsAllConstants || Idx == 0)) {
5324 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5326 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5327 EVT VecVT = MVT::v4i32;
5328 unsigned VecElts = 4;
5330 // Truncate the value (which may itself be a constant) to i32, and
5331 // convert it to a vector with movd (S2V+shuffle to zero extend).
5332 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5333 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5334 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5336 // Now we have our 32-bit value zero extended in the low element of
5337 // a vector. If Idx != 0, swizzle it into place.
5339 SmallVector<int, 4> Mask;
5340 Mask.push_back(Idx);
5341 for (unsigned i = 1; i != VecElts; ++i)
5343 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5346 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5350 // If we have a constant or non-constant insertion into the low element of
5351 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5352 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5353 // depending on what the source datatype is.
5356 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5358 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5359 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5360 if (VT.is256BitVector()) {
5361 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5362 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5363 Item, DAG.getIntPtrConstant(0));
5365 assert(VT.is128BitVector() && "Expected an SSE value type!");
5366 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5368 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5371 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5372 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5373 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5374 if (VT.is256BitVector()) {
5375 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5376 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5378 assert(VT.is128BitVector() && "Expected an SSE value type!");
5379 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5381 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5385 // Is it a vector logical left shift?
5386 if (NumElems == 2 && Idx == 1 &&
5387 X86::isZeroNode(Op.getOperand(0)) &&
5388 !X86::isZeroNode(Op.getOperand(1))) {
5389 unsigned NumBits = VT.getSizeInBits();
5390 return getVShift(true, VT,
5391 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5392 VT, Op.getOperand(1)),
5393 NumBits/2, DAG, *this, dl);
5396 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5399 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5400 // is a non-constant being inserted into an element other than the low one,
5401 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5402 // movd/movss) to move this into the low element, then shuffle it into
5404 if (EVTBits == 32) {
5405 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5407 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5408 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5409 SmallVector<int, 8> MaskVec;
5410 for (unsigned i = 0; i != NumElems; ++i)
5411 MaskVec.push_back(i == Idx ? 0 : 1);
5412 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5416 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5417 if (Values.size() == 1) {
5418 if (EVTBits == 32) {
5419 // Instead of a shuffle like this:
5420 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5421 // Check if it's possible to issue this instead.
5422 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5423 unsigned Idx = CountTrailingZeros_32(NonZeros);
5424 SDValue Item = Op.getOperand(Idx);
5425 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5426 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5431 // A vector full of immediates; various special cases are already
5432 // handled, so this is best done with a single constant-pool load.
5436 // For AVX-length vectors, build the individual 128-bit pieces and use
5437 // shuffles to put them in place.
5438 if (VT.is256BitVector()) {
5439 SmallVector<SDValue, 32> V;
5440 for (unsigned i = 0; i != NumElems; ++i)
5441 V.push_back(Op.getOperand(i));
5443 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5445 // Build both the lower and upper subvector.
5446 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5447 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5450 // Recreate the wider vector with the lower and upper part.
5451 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5454 // Let legalizer expand 2-wide build_vectors.
5455 if (EVTBits == 64) {
5456 if (NumNonZero == 1) {
5457 // One half is zero or undef.
5458 unsigned Idx = CountTrailingZeros_32(NonZeros);
5459 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5460 Op.getOperand(Idx));
5461 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5466 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5467 if (EVTBits == 8 && NumElems == 16) {
5468 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5470 if (V.getNode()) return V;
5473 if (EVTBits == 16 && NumElems == 8) {
5474 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5476 if (V.getNode()) return V;
5479 // If element VT is == 32 bits, turn it into a number of shuffles.
5480 SmallVector<SDValue, 8> V(NumElems);
5481 if (NumElems == 4 && NumZero > 0) {
5482 for (unsigned i = 0; i < 4; ++i) {
5483 bool isZero = !(NonZeros & (1 << i));
5485 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5487 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5490 for (unsigned i = 0; i < 2; ++i) {
5491 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5494 V[i] = V[i*2]; // Must be a zero vector.
5497 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5500 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5503 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5508 bool Reverse1 = (NonZeros & 0x3) == 2;
5509 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5513 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5514 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5516 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5519 if (Values.size() > 1 && VT.is128BitVector()) {
5520 // Check for a build vector of consecutive loads.
5521 for (unsigned i = 0; i < NumElems; ++i)
5522 V[i] = Op.getOperand(i);
5524 // Check for elements which are consecutive loads.
5525 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5529 // Check for a build vector from mostly shuffle plus few inserting.
5530 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5534 // For SSE 4.1, use insertps to put the high elements into the low element.
5535 if (getSubtarget()->hasSSE41()) {
5537 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5538 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5540 Result = DAG.getUNDEF(VT);
5542 for (unsigned i = 1; i < NumElems; ++i) {
5543 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5544 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5545 Op.getOperand(i), DAG.getIntPtrConstant(i));
5550 // Otherwise, expand into a number of unpckl*, start by extending each of
5551 // our (non-undef) elements to the full vector width with the element in the
5552 // bottom slot of the vector (which generates no code for SSE).
5553 for (unsigned i = 0; i < NumElems; ++i) {
5554 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5555 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5557 V[i] = DAG.getUNDEF(VT);
5560 // Next, we iteratively mix elements, e.g. for v4f32:
5561 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5562 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5563 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5564 unsigned EltStride = NumElems >> 1;
5565 while (EltStride != 0) {
5566 for (unsigned i = 0; i < EltStride; ++i) {
5567 // If V[i+EltStride] is undef and this is the first round of mixing,
5568 // then it is safe to just drop this shuffle: V[i] is already in the
5569 // right place, the one element (since it's the first round) being
5570 // inserted as undef can be dropped. This isn't safe for successive
5571 // rounds because they will permute elements within both vectors.
5572 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5573 EltStride == NumElems/2)
5576 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5585 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5586 // to create 256-bit vectors from two other 128-bit ones.
5587 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5588 DebugLoc dl = Op.getDebugLoc();
5589 EVT ResVT = Op.getValueType();
5591 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5593 SDValue V1 = Op.getOperand(0);
5594 SDValue V2 = Op.getOperand(1);
5595 unsigned NumElems = ResVT.getVectorNumElements();
5597 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5600 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5601 assert(Op.getNumOperands() == 2);
5603 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5604 // from two other 128-bit ones.
5605 return LowerAVXCONCAT_VECTORS(Op, DAG);
5608 // Try to lower a shuffle node into a simple blend instruction.
5610 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5611 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5612 SDValue V1 = SVOp->getOperand(0);
5613 SDValue V2 = SVOp->getOperand(1);
5614 DebugLoc dl = SVOp->getDebugLoc();
5615 MVT VT = SVOp->getValueType(0).getSimpleVT();
5616 unsigned NumElems = VT.getVectorNumElements();
5618 if (!Subtarget->hasSSE41())
5624 switch (VT.SimpleTy) {
5625 default: return SDValue();
5627 ISDNo = X86ISD::BLENDPW;
5632 ISDNo = X86ISD::BLENDPS;
5637 ISDNo = X86ISD::BLENDPD;
5642 if (!Subtarget->hasAVX())
5644 ISDNo = X86ISD::BLENDPS;
5649 if (!Subtarget->hasAVX())
5651 ISDNo = X86ISD::BLENDPD;
5655 assert(ISDNo && "Invalid Op Number");
5657 unsigned MaskVals = 0;
5659 for (unsigned i = 0; i != NumElems; ++i) {
5660 int EltIdx = SVOp->getMaskElt(i);
5661 if (EltIdx == (int)i || EltIdx < 0)
5663 else if (EltIdx == (int)(i + NumElems))
5664 continue; // Bit is set to zero;
5669 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5670 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5671 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5672 DAG.getConstant(MaskVals, MVT::i32));
5673 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5676 // v8i16 shuffles - Prefer shuffles in the following order:
5677 // 1. [all] pshuflw, pshufhw, optional move
5678 // 2. [ssse3] 1 x pshufb
5679 // 3. [ssse3] 2 x pshufb + 1 x por
5680 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5682 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5683 SelectionDAG &DAG) {
5684 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5685 SDValue V1 = SVOp->getOperand(0);
5686 SDValue V2 = SVOp->getOperand(1);
5687 DebugLoc dl = SVOp->getDebugLoc();
5688 SmallVector<int, 8> MaskVals;
5690 // Determine if more than 1 of the words in each of the low and high quadwords
5691 // of the result come from the same quadword of one of the two inputs. Undef
5692 // mask values count as coming from any quadword, for better codegen.
5693 unsigned LoQuad[] = { 0, 0, 0, 0 };
5694 unsigned HiQuad[] = { 0, 0, 0, 0 };
5695 std::bitset<4> InputQuads;
5696 for (unsigned i = 0; i < 8; ++i) {
5697 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5698 int EltIdx = SVOp->getMaskElt(i);
5699 MaskVals.push_back(EltIdx);
5708 InputQuads.set(EltIdx / 4);
5711 int BestLoQuad = -1;
5712 unsigned MaxQuad = 1;
5713 for (unsigned i = 0; i < 4; ++i) {
5714 if (LoQuad[i] > MaxQuad) {
5716 MaxQuad = LoQuad[i];
5720 int BestHiQuad = -1;
5722 for (unsigned i = 0; i < 4; ++i) {
5723 if (HiQuad[i] > MaxQuad) {
5725 MaxQuad = HiQuad[i];
5729 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5730 // of the two input vectors, shuffle them into one input vector so only a
5731 // single pshufb instruction is necessary. If There are more than 2 input
5732 // quads, disable the next transformation since it does not help SSSE3.
5733 bool V1Used = InputQuads[0] || InputQuads[1];
5734 bool V2Used = InputQuads[2] || InputQuads[3];
5735 if (Subtarget->hasSSSE3()) {
5736 if (InputQuads.count() == 2 && V1Used && V2Used) {
5737 BestLoQuad = InputQuads[0] ? 0 : 1;
5738 BestHiQuad = InputQuads[2] ? 2 : 3;
5740 if (InputQuads.count() > 2) {
5746 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5747 // the shuffle mask. If a quad is scored as -1, that means that it contains
5748 // words from all 4 input quadwords.
5750 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5752 BestLoQuad < 0 ? 0 : BestLoQuad,
5753 BestHiQuad < 0 ? 1 : BestHiQuad
5755 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5756 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5757 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5758 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5760 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5761 // source words for the shuffle, to aid later transformations.
5762 bool AllWordsInNewV = true;
5763 bool InOrder[2] = { true, true };
5764 for (unsigned i = 0; i != 8; ++i) {
5765 int idx = MaskVals[i];
5767 InOrder[i/4] = false;
5768 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5770 AllWordsInNewV = false;
5774 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5775 if (AllWordsInNewV) {
5776 for (int i = 0; i != 8; ++i) {
5777 int idx = MaskVals[i];
5780 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5781 if ((idx != i) && idx < 4)
5783 if ((idx != i) && idx > 3)
5792 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5793 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5794 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5795 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5796 unsigned TargetMask = 0;
5797 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5798 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5800 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5801 getShufflePSHUFLWImmediate(SVOp);
5802 V1 = NewV.getOperand(0);
5803 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5807 // If we have SSSE3, and all words of the result are from 1 input vector,
5808 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5809 // is present, fall back to case 4.
5810 if (Subtarget->hasSSSE3()) {
5811 SmallVector<SDValue,16> pshufbMask;
5813 // If we have elements from both input vectors, set the high bit of the
5814 // shuffle mask element to zero out elements that come from V2 in the V1
5815 // mask, and elements that come from V1 in the V2 mask, so that the two
5816 // results can be OR'd together.
5817 bool TwoInputs = V1Used && V2Used;
5818 for (unsigned i = 0; i != 8; ++i) {
5819 int EltIdx = MaskVals[i] * 2;
5820 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5821 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5822 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5823 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5825 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5826 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5827 DAG.getNode(ISD::BUILD_VECTOR, dl,
5828 MVT::v16i8, &pshufbMask[0], 16));
5830 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5832 // Calculate the shuffle mask for the second input, shuffle it, and
5833 // OR it with the first shuffled input.
5835 for (unsigned i = 0; i != 8; ++i) {
5836 int EltIdx = MaskVals[i] * 2;
5837 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5838 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5839 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5840 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5842 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5843 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5844 DAG.getNode(ISD::BUILD_VECTOR, dl,
5845 MVT::v16i8, &pshufbMask[0], 16));
5846 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5847 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5850 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5851 // and update MaskVals with new element order.
5852 std::bitset<8> InOrder;
5853 if (BestLoQuad >= 0) {
5854 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5855 for (int i = 0; i != 4; ++i) {
5856 int idx = MaskVals[i];
5859 } else if ((idx / 4) == BestLoQuad) {
5864 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5867 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5868 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5871 getShufflePSHUFLWImmediate(SVOp), DAG);
5875 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5876 // and update MaskVals with the new element order.
5877 if (BestHiQuad >= 0) {
5878 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5879 for (unsigned i = 4; i != 8; ++i) {
5880 int idx = MaskVals[i];
5883 } else if ((idx / 4) == BestHiQuad) {
5884 MaskV[i] = (idx & 3) + 4;
5888 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5891 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5893 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5895 getShufflePSHUFHWImmediate(SVOp), DAG);
5899 // In case BestHi & BestLo were both -1, which means each quadword has a word
5900 // from each of the four input quadwords, calculate the InOrder bitvector now
5901 // before falling through to the insert/extract cleanup.
5902 if (BestLoQuad == -1 && BestHiQuad == -1) {
5904 for (int i = 0; i != 8; ++i)
5905 if (MaskVals[i] < 0 || MaskVals[i] == i)
5909 // The other elements are put in the right place using pextrw and pinsrw.
5910 for (unsigned i = 0; i != 8; ++i) {
5913 int EltIdx = MaskVals[i];
5916 SDValue ExtOp = (EltIdx < 8) ?
5917 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5918 DAG.getIntPtrConstant(EltIdx)) :
5919 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5920 DAG.getIntPtrConstant(EltIdx - 8));
5921 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5922 DAG.getIntPtrConstant(i));
5927 // v16i8 shuffles - Prefer shuffles in the following order:
5928 // 1. [ssse3] 1 x pshufb
5929 // 2. [ssse3] 2 x pshufb + 1 x por
5930 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5932 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5934 const X86TargetLowering &TLI) {
5935 SDValue V1 = SVOp->getOperand(0);
5936 SDValue V2 = SVOp->getOperand(1);
5937 DebugLoc dl = SVOp->getDebugLoc();
5938 ArrayRef<int> MaskVals = SVOp->getMask();
5940 // If we have SSSE3, case 1 is generated when all result bytes come from
5941 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5942 // present, fall back to case 3.
5944 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5945 if (TLI.getSubtarget()->hasSSSE3()) {
5946 SmallVector<SDValue,16> pshufbMask;
5948 // If all result elements are from one input vector, then only translate
5949 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5951 // Otherwise, we have elements from both input vectors, and must zero out
5952 // elements that come from V2 in the first mask, and V1 in the second mask
5953 // so that we can OR them together.
5954 for (unsigned i = 0; i != 16; ++i) {
5955 int EltIdx = MaskVals[i];
5956 if (EltIdx < 0 || EltIdx >= 16)
5958 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5960 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5961 DAG.getNode(ISD::BUILD_VECTOR, dl,
5962 MVT::v16i8, &pshufbMask[0], 16));
5964 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5965 // the 2nd operand if it's undefined or zero.
5966 if (V2.getOpcode() == ISD::UNDEF ||
5967 ISD::isBuildVectorAllZeros(V2.getNode()))
5970 // Calculate the shuffle mask for the second input, shuffle it, and
5971 // OR it with the first shuffled input.
5973 for (unsigned i = 0; i != 16; ++i) {
5974 int EltIdx = MaskVals[i];
5975 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5976 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5978 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5979 DAG.getNode(ISD::BUILD_VECTOR, dl,
5980 MVT::v16i8, &pshufbMask[0], 16));
5981 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5984 // No SSSE3 - Calculate in place words and then fix all out of place words
5985 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5986 // the 16 different words that comprise the two doublequadword input vectors.
5987 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5988 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5990 for (int i = 0; i != 8; ++i) {
5991 int Elt0 = MaskVals[i*2];
5992 int Elt1 = MaskVals[i*2+1];
5994 // This word of the result is all undef, skip it.
5995 if (Elt0 < 0 && Elt1 < 0)
5998 // This word of the result is already in the correct place, skip it.
5999 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6002 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6003 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6006 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6007 // using a single extract together, load it and store it.
6008 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6009 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6010 DAG.getIntPtrConstant(Elt1 / 2));
6011 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6012 DAG.getIntPtrConstant(i));
6016 // If Elt1 is defined, extract it from the appropriate source. If the
6017 // source byte is not also odd, shift the extracted word left 8 bits
6018 // otherwise clear the bottom 8 bits if we need to do an or.
6020 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6021 DAG.getIntPtrConstant(Elt1 / 2));
6022 if ((Elt1 & 1) == 0)
6023 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6025 TLI.getShiftAmountTy(InsElt.getValueType())));
6027 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6028 DAG.getConstant(0xFF00, MVT::i16));
6030 // If Elt0 is defined, extract it from the appropriate source. If the
6031 // source byte is not also even, shift the extracted word right 8 bits. If
6032 // Elt1 was also defined, OR the extracted values together before
6033 // inserting them in the result.
6035 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6036 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6037 if ((Elt0 & 1) != 0)
6038 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6040 TLI.getShiftAmountTy(InsElt0.getValueType())));
6042 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6043 DAG.getConstant(0x00FF, MVT::i16));
6044 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6047 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6048 DAG.getIntPtrConstant(i));
6050 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6053 // v32i8 shuffles - Translate to VPSHUFB if possible.
6055 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6056 const X86Subtarget *Subtarget,
6057 SelectionDAG &DAG) {
6058 EVT VT = SVOp->getValueType(0);
6059 SDValue V1 = SVOp->getOperand(0);
6060 SDValue V2 = SVOp->getOperand(1);
6061 DebugLoc dl = SVOp->getDebugLoc();
6062 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6064 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6065 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6066 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6068 // VPSHUFB may be generated if
6069 // (1) one of input vector is undefined or zeroinitializer.
6070 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6071 // And (2) the mask indexes don't cross the 128-bit lane.
6072 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6073 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6076 if (V1IsAllZero && !V2IsAllZero) {
6077 CommuteVectorShuffleMask(MaskVals, 32);
6080 SmallVector<SDValue, 32> pshufbMask;
6081 for (unsigned i = 0; i != 32; i++) {
6082 int EltIdx = MaskVals[i];
6083 if (EltIdx < 0 || EltIdx >= 32)
6086 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6087 // Cross lane is not allowed.
6091 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6093 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6094 DAG.getNode(ISD::BUILD_VECTOR, dl,
6095 MVT::v32i8, &pshufbMask[0], 32));
6098 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6099 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6100 /// done when every pair / quad of shuffle mask elements point to elements in
6101 /// the right sequence. e.g.
6102 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6104 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6105 SelectionDAG &DAG, DebugLoc dl) {
6106 MVT VT = SVOp->getValueType(0).getSimpleVT();
6107 unsigned NumElems = VT.getVectorNumElements();
6110 switch (VT.SimpleTy) {
6111 default: llvm_unreachable("Unexpected!");
6112 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6113 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6114 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6115 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6116 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6117 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6120 SmallVector<int, 8> MaskVec;
6121 for (unsigned i = 0; i != NumElems; i += Scale) {
6123 for (unsigned j = 0; j != Scale; ++j) {
6124 int EltIdx = SVOp->getMaskElt(i+j);
6128 StartIdx = (EltIdx / Scale);
6129 if (EltIdx != (int)(StartIdx*Scale + j))
6132 MaskVec.push_back(StartIdx);
6135 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6136 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6137 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6140 /// getVZextMovL - Return a zero-extending vector move low node.
6142 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6143 SDValue SrcOp, SelectionDAG &DAG,
6144 const X86Subtarget *Subtarget, DebugLoc dl) {
6145 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6146 LoadSDNode *LD = NULL;
6147 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6148 LD = dyn_cast<LoadSDNode>(SrcOp);
6150 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6152 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6153 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6154 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6155 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6156 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6158 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6159 return DAG.getNode(ISD::BITCAST, dl, VT,
6160 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6161 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6169 return DAG.getNode(ISD::BITCAST, dl, VT,
6170 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6171 DAG.getNode(ISD::BITCAST, dl,
6175 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6176 /// which could not be matched by any known target speficic shuffle
6178 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6180 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6181 if (NewOp.getNode())
6184 EVT VT = SVOp->getValueType(0);
6186 unsigned NumElems = VT.getVectorNumElements();
6187 unsigned NumLaneElems = NumElems / 2;
6189 DebugLoc dl = SVOp->getDebugLoc();
6190 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6191 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6194 SmallVector<int, 16> Mask;
6195 for (unsigned l = 0; l < 2; ++l) {
6196 // Build a shuffle mask for the output, discovering on the fly which
6197 // input vectors to use as shuffle operands (recorded in InputUsed).
6198 // If building a suitable shuffle vector proves too hard, then bail
6199 // out with UseBuildVector set.
6200 bool UseBuildVector = false;
6201 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6202 unsigned LaneStart = l * NumLaneElems;
6203 for (unsigned i = 0; i != NumLaneElems; ++i) {
6204 // The mask element. This indexes into the input.
6205 int Idx = SVOp->getMaskElt(i+LaneStart);
6207 // the mask element does not index into any input vector.
6212 // The input vector this mask element indexes into.
6213 int Input = Idx / NumLaneElems;
6215 // Turn the index into an offset from the start of the input vector.
6216 Idx -= Input * NumLaneElems;
6218 // Find or create a shuffle vector operand to hold this input.
6220 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6221 if (InputUsed[OpNo] == Input)
6222 // This input vector is already an operand.
6224 if (InputUsed[OpNo] < 0) {
6225 // Create a new operand for this input vector.
6226 InputUsed[OpNo] = Input;
6231 if (OpNo >= array_lengthof(InputUsed)) {
6232 // More than two input vectors used! Give up on trying to create a
6233 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6234 UseBuildVector = true;
6238 // Add the mask index for the new shuffle vector.
6239 Mask.push_back(Idx + OpNo * NumLaneElems);
6242 if (UseBuildVector) {
6243 SmallVector<SDValue, 16> SVOps;
6244 for (unsigned i = 0; i != NumLaneElems; ++i) {
6245 // The mask element. This indexes into the input.
6246 int Idx = SVOp->getMaskElt(i+LaneStart);
6248 SVOps.push_back(DAG.getUNDEF(EltVT));
6252 // The input vector this mask element indexes into.
6253 int Input = Idx / NumElems;
6255 // Turn the index into an offset from the start of the input vector.
6256 Idx -= Input * NumElems;
6258 // Extract the vector element by hand.
6259 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6260 SVOp->getOperand(Input),
6261 DAG.getIntPtrConstant(Idx)));
6264 // Construct the output using a BUILD_VECTOR.
6265 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6267 } else if (InputUsed[0] < 0) {
6268 // No input vectors were used! The result is undefined.
6269 Output[l] = DAG.getUNDEF(NVT);
6271 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6272 (InputUsed[0] % 2) * NumLaneElems,
6274 // If only one input was used, use an undefined vector for the other.
6275 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6276 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6277 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6278 // At least one input vector was used. Create a new shuffle vector.
6279 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6285 // Concatenate the result back
6286 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6289 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6290 /// 4 elements, and match them with several different shuffle types.
6292 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6293 SDValue V1 = SVOp->getOperand(0);
6294 SDValue V2 = SVOp->getOperand(1);
6295 DebugLoc dl = SVOp->getDebugLoc();
6296 EVT VT = SVOp->getValueType(0);
6298 assert(VT.is128BitVector() && "Unsupported vector size");
6300 std::pair<int, int> Locs[4];
6301 int Mask1[] = { -1, -1, -1, -1 };
6302 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6306 for (unsigned i = 0; i != 4; ++i) {
6307 int Idx = PermMask[i];
6309 Locs[i] = std::make_pair(-1, -1);
6311 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6313 Locs[i] = std::make_pair(0, NumLo);
6317 Locs[i] = std::make_pair(1, NumHi);
6319 Mask1[2+NumHi] = Idx;
6325 if (NumLo <= 2 && NumHi <= 2) {
6326 // If no more than two elements come from either vector. This can be
6327 // implemented with two shuffles. First shuffle gather the elements.
6328 // The second shuffle, which takes the first shuffle as both of its
6329 // vector operands, put the elements into the right order.
6330 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6332 int Mask2[] = { -1, -1, -1, -1 };
6334 for (unsigned i = 0; i != 4; ++i)
6335 if (Locs[i].first != -1) {
6336 unsigned Idx = (i < 2) ? 0 : 4;
6337 Idx += Locs[i].first * 2 + Locs[i].second;
6341 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6344 if (NumLo == 3 || NumHi == 3) {
6345 // Otherwise, we must have three elements from one vector, call it X, and
6346 // one element from the other, call it Y. First, use a shufps to build an
6347 // intermediate vector with the one element from Y and the element from X
6348 // that will be in the same half in the final destination (the indexes don't
6349 // matter). Then, use a shufps to build the final vector, taking the half
6350 // containing the element from Y from the intermediate, and the other half
6353 // Normalize it so the 3 elements come from V1.
6354 CommuteVectorShuffleMask(PermMask, 4);
6358 // Find the element from V2.
6360 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6361 int Val = PermMask[HiIndex];
6368 Mask1[0] = PermMask[HiIndex];
6370 Mask1[2] = PermMask[HiIndex^1];
6372 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6375 Mask1[0] = PermMask[0];
6376 Mask1[1] = PermMask[1];
6377 Mask1[2] = HiIndex & 1 ? 6 : 4;
6378 Mask1[3] = HiIndex & 1 ? 4 : 6;
6379 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6382 Mask1[0] = HiIndex & 1 ? 2 : 0;
6383 Mask1[1] = HiIndex & 1 ? 0 : 2;
6384 Mask1[2] = PermMask[2];
6385 Mask1[3] = PermMask[3];
6390 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6393 // Break it into (shuffle shuffle_hi, shuffle_lo).
6394 int LoMask[] = { -1, -1, -1, -1 };
6395 int HiMask[] = { -1, -1, -1, -1 };
6397 int *MaskPtr = LoMask;
6398 unsigned MaskIdx = 0;
6401 for (unsigned i = 0; i != 4; ++i) {
6408 int Idx = PermMask[i];
6410 Locs[i] = std::make_pair(-1, -1);
6411 } else if (Idx < 4) {
6412 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6413 MaskPtr[LoIdx] = Idx;
6416 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6417 MaskPtr[HiIdx] = Idx;
6422 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6423 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6424 int MaskOps[] = { -1, -1, -1, -1 };
6425 for (unsigned i = 0; i != 4; ++i)
6426 if (Locs[i].first != -1)
6427 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6428 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6431 static bool MayFoldVectorLoad(SDValue V) {
6432 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6433 V = V.getOperand(0);
6434 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6435 V = V.getOperand(0);
6436 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6437 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6438 // BUILD_VECTOR (load), undef
6439 V = V.getOperand(0);
6445 // FIXME: the version above should always be used. Since there's
6446 // a bug where several vector shuffles can't be folded because the
6447 // DAG is not updated during lowering and a node claims to have two
6448 // uses while it only has one, use this version, and let isel match
6449 // another instruction if the load really happens to have more than
6450 // one use. Remove this version after this bug get fixed.
6451 // rdar://8434668, PR8156
6452 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6453 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6454 V = V.getOperand(0);
6455 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6456 V = V.getOperand(0);
6457 if (ISD::isNormalLoad(V.getNode()))
6463 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6464 EVT VT = Op.getValueType();
6466 // Canonizalize to v2f64.
6467 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6468 return DAG.getNode(ISD::BITCAST, dl, VT,
6469 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6474 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6476 SDValue V1 = Op.getOperand(0);
6477 SDValue V2 = Op.getOperand(1);
6478 EVT VT = Op.getValueType();
6480 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6482 if (HasSSE2 && VT == MVT::v2f64)
6483 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6485 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6486 return DAG.getNode(ISD::BITCAST, dl, VT,
6487 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6488 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6489 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6493 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6494 SDValue V1 = Op.getOperand(0);
6495 SDValue V2 = Op.getOperand(1);
6496 EVT VT = Op.getValueType();
6498 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6499 "unsupported shuffle type");
6501 if (V2.getOpcode() == ISD::UNDEF)
6505 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6509 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6510 SDValue V1 = Op.getOperand(0);
6511 SDValue V2 = Op.getOperand(1);
6512 EVT VT = Op.getValueType();
6513 unsigned NumElems = VT.getVectorNumElements();
6515 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6516 // operand of these instructions is only memory, so check if there's a
6517 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6519 bool CanFoldLoad = false;
6521 // Trivial case, when V2 comes from a load.
6522 if (MayFoldVectorLoad(V2))
6525 // When V1 is a load, it can be folded later into a store in isel, example:
6526 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6528 // (MOVLPSmr addr:$src1, VR128:$src2)
6529 // So, recognize this potential and also use MOVLPS or MOVLPD
6530 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6533 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6535 if (HasSSE2 && NumElems == 2)
6536 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6539 // If we don't care about the second element, proceed to use movss.
6540 if (SVOp->getMaskElt(1) != -1)
6541 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6544 // movl and movlp will both match v2i64, but v2i64 is never matched by
6545 // movl earlier because we make it strict to avoid messing with the movlp load
6546 // folding logic (see the code above getMOVLP call). Match it here then,
6547 // this is horrible, but will stay like this until we move all shuffle
6548 // matching to x86 specific nodes. Note that for the 1st condition all
6549 // types are matched with movsd.
6551 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6552 // as to remove this logic from here, as much as possible
6553 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6554 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6555 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6558 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6560 // Invert the operand order and use SHUFPS to match it.
6561 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6562 getShuffleSHUFImmediate(SVOp), DAG);
6566 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6567 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6568 EVT VT = Op.getValueType();
6569 DebugLoc dl = Op.getDebugLoc();
6570 SDValue V1 = Op.getOperand(0);
6571 SDValue V2 = Op.getOperand(1);
6573 if (isZeroShuffle(SVOp))
6574 return getZeroVector(VT, Subtarget, DAG, dl);
6576 // Handle splat operations
6577 if (SVOp->isSplat()) {
6578 unsigned NumElem = VT.getVectorNumElements();
6579 int Size = VT.getSizeInBits();
6581 // Use vbroadcast whenever the splat comes from a foldable load
6582 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6583 if (Broadcast.getNode())
6586 // Handle splats by matching through known shuffle masks
6587 if ((Size == 128 && NumElem <= 4) ||
6588 (Size == 256 && NumElem < 8))
6591 // All remaning splats are promoted to target supported vector shuffles.
6592 return PromoteSplat(SVOp, DAG);
6595 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6597 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6598 VT == MVT::v16i16 || VT == MVT::v32i8) {
6599 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6600 if (NewOp.getNode())
6601 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6602 } else if ((VT == MVT::v4i32 ||
6603 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6604 // FIXME: Figure out a cleaner way to do this.
6605 // Try to make use of movq to zero out the top part.
6606 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6607 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6608 if (NewOp.getNode()) {
6609 EVT NewVT = NewOp.getValueType();
6610 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6611 NewVT, true, false))
6612 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6613 DAG, Subtarget, dl);
6615 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6616 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6617 if (NewOp.getNode()) {
6618 EVT NewVT = NewOp.getValueType();
6619 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6620 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6621 DAG, Subtarget, dl);
6629 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6630 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6631 SDValue V1 = Op.getOperand(0);
6632 SDValue V2 = Op.getOperand(1);
6633 EVT VT = Op.getValueType();
6634 DebugLoc dl = Op.getDebugLoc();
6635 unsigned NumElems = VT.getVectorNumElements();
6636 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6637 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6638 bool V1IsSplat = false;
6639 bool V2IsSplat = false;
6640 bool HasSSE2 = Subtarget->hasSSE2();
6641 bool HasAVX = Subtarget->hasAVX();
6642 bool HasAVX2 = Subtarget->hasAVX2();
6643 MachineFunction &MF = DAG.getMachineFunction();
6644 bool OptForSize = MF.getFunction()->getFnAttributes().
6645 hasAttribute(Attributes::OptimizeForSize);
6647 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6649 if (V1IsUndef && V2IsUndef)
6650 return DAG.getUNDEF(VT);
6652 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6654 // Vector shuffle lowering takes 3 steps:
6656 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6657 // narrowing and commutation of operands should be handled.
6658 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6660 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6661 // so the shuffle can be broken into other shuffles and the legalizer can
6662 // try the lowering again.
6664 // The general idea is that no vector_shuffle operation should be left to
6665 // be matched during isel, all of them must be converted to a target specific
6668 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6669 // narrowing and commutation of operands should be handled. The actual code
6670 // doesn't include all of those, work in progress...
6671 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6672 if (NewOp.getNode())
6675 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6677 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6678 // unpckh_undef). Only use pshufd if speed is more important than size.
6679 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6680 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6681 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6682 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6684 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6685 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6686 return getMOVDDup(Op, dl, V1, DAG);
6688 if (isMOVHLPS_v_undef_Mask(M, VT))
6689 return getMOVHighToLow(Op, dl, DAG);
6691 // Use to match splats
6692 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6693 (VT == MVT::v2f64 || VT == MVT::v2i64))
6694 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6696 if (isPSHUFDMask(M, VT)) {
6697 // The actual implementation will match the mask in the if above and then
6698 // during isel it can match several different instructions, not only pshufd
6699 // as its name says, sad but true, emulate the behavior for now...
6700 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6701 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6703 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6705 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6706 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6708 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6709 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6711 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6715 // Check if this can be converted into a logical shift.
6716 bool isLeft = false;
6719 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6720 if (isShift && ShVal.hasOneUse()) {
6721 // If the shifted value has multiple uses, it may be cheaper to use
6722 // v_set0 + movlhps or movhlps, etc.
6723 EVT EltVT = VT.getVectorElementType();
6724 ShAmt *= EltVT.getSizeInBits();
6725 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6728 if (isMOVLMask(M, VT)) {
6729 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6730 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6731 if (!isMOVLPMask(M, VT)) {
6732 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6733 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6735 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6736 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6740 // FIXME: fold these into legal mask.
6741 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6742 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6744 if (isMOVHLPSMask(M, VT))
6745 return getMOVHighToLow(Op, dl, DAG);
6747 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6748 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6750 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6751 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6753 if (isMOVLPMask(M, VT))
6754 return getMOVLP(Op, dl, DAG, HasSSE2);
6756 if (ShouldXformToMOVHLPS(M, VT) ||
6757 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6758 return CommuteVectorShuffle(SVOp, DAG);
6761 // No better options. Use a vshldq / vsrldq.
6762 EVT EltVT = VT.getVectorElementType();
6763 ShAmt *= EltVT.getSizeInBits();
6764 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6767 bool Commuted = false;
6768 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6769 // 1,1,1,1 -> v8i16 though.
6770 V1IsSplat = isSplatVector(V1.getNode());
6771 V2IsSplat = isSplatVector(V2.getNode());
6773 // Canonicalize the splat or undef, if present, to be on the RHS.
6774 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6775 CommuteVectorShuffleMask(M, NumElems);
6777 std::swap(V1IsSplat, V2IsSplat);
6781 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6782 // Shuffling low element of v1 into undef, just return v1.
6785 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6786 // the instruction selector will not match, so get a canonical MOVL with
6787 // swapped operands to undo the commute.
6788 return getMOVL(DAG, dl, VT, V2, V1);
6791 if (isUNPCKLMask(M, VT, HasAVX2))
6792 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6794 if (isUNPCKHMask(M, VT, HasAVX2))
6795 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6798 // Normalize mask so all entries that point to V2 points to its first
6799 // element then try to match unpck{h|l} again. If match, return a
6800 // new vector_shuffle with the corrected mask.p
6801 SmallVector<int, 8> NewMask(M.begin(), M.end());
6802 NormalizeMask(NewMask, NumElems);
6803 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6804 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6805 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6806 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6810 // Commute is back and try unpck* again.
6811 // FIXME: this seems wrong.
6812 CommuteVectorShuffleMask(M, NumElems);
6814 std::swap(V1IsSplat, V2IsSplat);
6817 if (isUNPCKLMask(M, VT, HasAVX2))
6818 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6820 if (isUNPCKHMask(M, VT, HasAVX2))
6821 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6824 // Normalize the node to match x86 shuffle ops if needed
6825 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6826 return CommuteVectorShuffle(SVOp, DAG);
6828 // The checks below are all present in isShuffleMaskLegal, but they are
6829 // inlined here right now to enable us to directly emit target specific
6830 // nodes, and remove one by one until they don't return Op anymore.
6832 if (isPALIGNRMask(M, VT, Subtarget))
6833 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6834 getShufflePALIGNRImmediate(SVOp),
6837 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6838 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6839 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6840 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6843 if (isPSHUFHWMask(M, VT, HasAVX2))
6844 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6845 getShufflePSHUFHWImmediate(SVOp),
6848 if (isPSHUFLWMask(M, VT, HasAVX2))
6849 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6850 getShufflePSHUFLWImmediate(SVOp),
6853 if (isSHUFPMask(M, VT, HasAVX))
6854 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6855 getShuffleSHUFImmediate(SVOp), DAG);
6857 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6858 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6859 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6860 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6862 //===--------------------------------------------------------------------===//
6863 // Generate target specific nodes for 128 or 256-bit shuffles only
6864 // supported in the AVX instruction set.
6867 // Handle VMOVDDUPY permutations
6868 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6869 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6871 // Handle VPERMILPS/D* permutations
6872 if (isVPERMILPMask(M, VT, HasAVX)) {
6873 if (HasAVX2 && VT == MVT::v8i32)
6874 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6875 getShuffleSHUFImmediate(SVOp), DAG);
6876 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6877 getShuffleSHUFImmediate(SVOp), DAG);
6880 // Handle VPERM2F128/VPERM2I128 permutations
6881 if (isVPERM2X128Mask(M, VT, HasAVX))
6882 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6883 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6885 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6886 if (BlendOp.getNode())
6889 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6890 SmallVector<SDValue, 8> permclMask;
6891 for (unsigned i = 0; i != 8; ++i) {
6892 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6894 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6896 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6897 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6898 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6901 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6902 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6903 getShuffleCLImmediate(SVOp), DAG);
6906 //===--------------------------------------------------------------------===//
6907 // Since no target specific shuffle was selected for this generic one,
6908 // lower it into other known shuffles. FIXME: this isn't true yet, but
6909 // this is the plan.
6912 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6913 if (VT == MVT::v8i16) {
6914 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6915 if (NewOp.getNode())
6919 if (VT == MVT::v16i8) {
6920 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6921 if (NewOp.getNode())
6925 if (VT == MVT::v32i8) {
6926 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6927 if (NewOp.getNode())
6931 // Handle all 128-bit wide vectors with 4 elements, and match them with
6932 // several different shuffle types.
6933 if (NumElems == 4 && VT.is128BitVector())
6934 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6936 // Handle general 256-bit shuffles
6937 if (VT.is256BitVector())
6938 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6944 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6945 SelectionDAG &DAG) const {
6946 EVT VT = Op.getValueType();
6947 DebugLoc dl = Op.getDebugLoc();
6949 if (!Op.getOperand(0).getValueType().is128BitVector())
6952 if (VT.getSizeInBits() == 8) {
6953 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6954 Op.getOperand(0), Op.getOperand(1));
6955 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6956 DAG.getValueType(VT));
6957 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6960 if (VT.getSizeInBits() == 16) {
6961 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6962 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6964 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6965 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6966 DAG.getNode(ISD::BITCAST, dl,
6970 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6971 Op.getOperand(0), Op.getOperand(1));
6972 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6973 DAG.getValueType(VT));
6974 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6977 if (VT == MVT::f32) {
6978 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6979 // the result back to FR32 register. It's only worth matching if the
6980 // result has a single use which is a store or a bitcast to i32. And in
6981 // the case of a store, it's not worth it if the index is a constant 0,
6982 // because a MOVSSmr can be used instead, which is smaller and faster.
6983 if (!Op.hasOneUse())
6985 SDNode *User = *Op.getNode()->use_begin();
6986 if ((User->getOpcode() != ISD::STORE ||
6987 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6988 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6989 (User->getOpcode() != ISD::BITCAST ||
6990 User->getValueType(0) != MVT::i32))
6992 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6993 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6996 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6999 if (VT == MVT::i32 || VT == MVT::i64) {
7000 // ExtractPS/pextrq works with constant index.
7001 if (isa<ConstantSDNode>(Op.getOperand(1)))
7009 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7010 SelectionDAG &DAG) const {
7011 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7014 SDValue Vec = Op.getOperand(0);
7015 EVT VecVT = Vec.getValueType();
7017 // If this is a 256-bit vector result, first extract the 128-bit vector and
7018 // then extract the element from the 128-bit vector.
7019 if (VecVT.is256BitVector()) {
7020 DebugLoc dl = Op.getNode()->getDebugLoc();
7021 unsigned NumElems = VecVT.getVectorNumElements();
7022 SDValue Idx = Op.getOperand(1);
7023 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7025 // Get the 128-bit vector.
7026 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7028 if (IdxVal >= NumElems/2)
7029 IdxVal -= NumElems/2;
7030 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7031 DAG.getConstant(IdxVal, MVT::i32));
7034 assert(VecVT.is128BitVector() && "Unexpected vector length");
7036 if (Subtarget->hasSSE41()) {
7037 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7042 EVT VT = Op.getValueType();
7043 DebugLoc dl = Op.getDebugLoc();
7044 // TODO: handle v16i8.
7045 if (VT.getSizeInBits() == 16) {
7046 SDValue Vec = Op.getOperand(0);
7047 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7049 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7050 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7051 DAG.getNode(ISD::BITCAST, dl,
7054 // Transform it so it match pextrw which produces a 32-bit result.
7055 EVT EltVT = MVT::i32;
7056 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7057 Op.getOperand(0), Op.getOperand(1));
7058 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7059 DAG.getValueType(VT));
7060 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7063 if (VT.getSizeInBits() == 32) {
7064 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7068 // SHUFPS the element to the lowest double word, then movss.
7069 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7070 EVT VVT = Op.getOperand(0).getValueType();
7071 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7072 DAG.getUNDEF(VVT), Mask);
7073 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7074 DAG.getIntPtrConstant(0));
7077 if (VT.getSizeInBits() == 64) {
7078 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7079 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7080 // to match extract_elt for f64.
7081 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7085 // UNPCKHPD the element to the lowest double word, then movsd.
7086 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7087 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7088 int Mask[2] = { 1, -1 };
7089 EVT VVT = Op.getOperand(0).getValueType();
7090 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7091 DAG.getUNDEF(VVT), Mask);
7092 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7093 DAG.getIntPtrConstant(0));
7100 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7101 SelectionDAG &DAG) const {
7102 EVT VT = Op.getValueType();
7103 EVT EltVT = VT.getVectorElementType();
7104 DebugLoc dl = Op.getDebugLoc();
7106 SDValue N0 = Op.getOperand(0);
7107 SDValue N1 = Op.getOperand(1);
7108 SDValue N2 = Op.getOperand(2);
7110 if (!VT.is128BitVector())
7113 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7114 isa<ConstantSDNode>(N2)) {
7116 if (VT == MVT::v8i16)
7117 Opc = X86ISD::PINSRW;
7118 else if (VT == MVT::v16i8)
7119 Opc = X86ISD::PINSRB;
7121 Opc = X86ISD::PINSRB;
7123 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7125 if (N1.getValueType() != MVT::i32)
7126 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7127 if (N2.getValueType() != MVT::i32)
7128 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7129 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7132 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7133 // Bits [7:6] of the constant are the source select. This will always be
7134 // zero here. The DAG Combiner may combine an extract_elt index into these
7135 // bits. For example (insert (extract, 3), 2) could be matched by putting
7136 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7137 // Bits [5:4] of the constant are the destination select. This is the
7138 // value of the incoming immediate.
7139 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7140 // combine either bitwise AND or insert of float 0.0 to set these bits.
7141 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7142 // Create this as a scalar to vector..
7143 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7144 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7147 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7148 // PINSR* works with constant index.
7155 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7156 EVT VT = Op.getValueType();
7157 EVT EltVT = VT.getVectorElementType();
7159 DebugLoc dl = Op.getDebugLoc();
7160 SDValue N0 = Op.getOperand(0);
7161 SDValue N1 = Op.getOperand(1);
7162 SDValue N2 = Op.getOperand(2);
7164 // If this is a 256-bit vector result, first extract the 128-bit vector,
7165 // insert the element into the extracted half and then place it back.
7166 if (VT.is256BitVector()) {
7167 if (!isa<ConstantSDNode>(N2))
7170 // Get the desired 128-bit vector half.
7171 unsigned NumElems = VT.getVectorNumElements();
7172 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7173 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7175 // Insert the element into the desired half.
7176 bool Upper = IdxVal >= NumElems/2;
7177 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7178 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7180 // Insert the changed part back to the 256-bit vector
7181 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7184 if (Subtarget->hasSSE41())
7185 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7187 if (EltVT == MVT::i8)
7190 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7191 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7192 // as its second argument.
7193 if (N1.getValueType() != MVT::i32)
7194 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7195 if (N2.getValueType() != MVT::i32)
7196 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7197 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7202 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7203 LLVMContext *Context = DAG.getContext();
7204 DebugLoc dl = Op.getDebugLoc();
7205 EVT OpVT = Op.getValueType();
7207 // If this is a 256-bit vector result, first insert into a 128-bit
7208 // vector and then insert into the 256-bit vector.
7209 if (!OpVT.is128BitVector()) {
7210 // Insert into a 128-bit vector.
7211 EVT VT128 = EVT::getVectorVT(*Context,
7212 OpVT.getVectorElementType(),
7213 OpVT.getVectorNumElements() / 2);
7215 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7217 // Insert the 128-bit vector.
7218 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7221 if (OpVT == MVT::v1i64 &&
7222 Op.getOperand(0).getValueType() == MVT::i64)
7223 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7225 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7226 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7227 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7228 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7231 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7232 // a simple subregister reference or explicit instructions to grab
7233 // upper bits of a vector.
7234 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7235 SelectionDAG &DAG) {
7236 if (Subtarget->hasAVX()) {
7237 DebugLoc dl = Op.getNode()->getDebugLoc();
7238 SDValue Vec = Op.getNode()->getOperand(0);
7239 SDValue Idx = Op.getNode()->getOperand(1);
7241 if (Op.getNode()->getValueType(0).is128BitVector() &&
7242 Vec.getNode()->getValueType(0).is256BitVector() &&
7243 isa<ConstantSDNode>(Idx)) {
7244 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7245 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7251 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7252 // simple superregister reference or explicit instructions to insert
7253 // the upper bits of a vector.
7254 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7255 SelectionDAG &DAG) {
7256 if (Subtarget->hasAVX()) {
7257 DebugLoc dl = Op.getNode()->getDebugLoc();
7258 SDValue Vec = Op.getNode()->getOperand(0);
7259 SDValue SubVec = Op.getNode()->getOperand(1);
7260 SDValue Idx = Op.getNode()->getOperand(2);
7262 if (Op.getNode()->getValueType(0).is256BitVector() &&
7263 SubVec.getNode()->getValueType(0).is128BitVector() &&
7264 isa<ConstantSDNode>(Idx)) {
7265 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7266 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7272 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7273 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7274 // one of the above mentioned nodes. It has to be wrapped because otherwise
7275 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7276 // be used to form addressing mode. These wrapped nodes will be selected
7279 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7280 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7282 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7284 unsigned char OpFlag = 0;
7285 unsigned WrapperKind = X86ISD::Wrapper;
7286 CodeModel::Model M = getTargetMachine().getCodeModel();
7288 if (Subtarget->isPICStyleRIPRel() &&
7289 (M == CodeModel::Small || M == CodeModel::Kernel))
7290 WrapperKind = X86ISD::WrapperRIP;
7291 else if (Subtarget->isPICStyleGOT())
7292 OpFlag = X86II::MO_GOTOFF;
7293 else if (Subtarget->isPICStyleStubPIC())
7294 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7296 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7298 CP->getOffset(), OpFlag);
7299 DebugLoc DL = CP->getDebugLoc();
7300 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7301 // With PIC, the address is actually $g + Offset.
7303 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7304 DAG.getNode(X86ISD::GlobalBaseReg,
7305 DebugLoc(), getPointerTy()),
7312 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7313 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7315 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7317 unsigned char OpFlag = 0;
7318 unsigned WrapperKind = X86ISD::Wrapper;
7319 CodeModel::Model M = getTargetMachine().getCodeModel();
7321 if (Subtarget->isPICStyleRIPRel() &&
7322 (M == CodeModel::Small || M == CodeModel::Kernel))
7323 WrapperKind = X86ISD::WrapperRIP;
7324 else if (Subtarget->isPICStyleGOT())
7325 OpFlag = X86II::MO_GOTOFF;
7326 else if (Subtarget->isPICStyleStubPIC())
7327 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7329 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7331 DebugLoc DL = JT->getDebugLoc();
7332 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7334 // With PIC, the address is actually $g + Offset.
7336 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7337 DAG.getNode(X86ISD::GlobalBaseReg,
7338 DebugLoc(), getPointerTy()),
7345 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7346 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7348 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7350 unsigned char OpFlag = 0;
7351 unsigned WrapperKind = X86ISD::Wrapper;
7352 CodeModel::Model M = getTargetMachine().getCodeModel();
7354 if (Subtarget->isPICStyleRIPRel() &&
7355 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7356 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7357 OpFlag = X86II::MO_GOTPCREL;
7358 WrapperKind = X86ISD::WrapperRIP;
7359 } else if (Subtarget->isPICStyleGOT()) {
7360 OpFlag = X86II::MO_GOT;
7361 } else if (Subtarget->isPICStyleStubPIC()) {
7362 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7363 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7364 OpFlag = X86II::MO_DARWIN_NONLAZY;
7367 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7369 DebugLoc DL = Op.getDebugLoc();
7370 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7373 // With PIC, the address is actually $g + Offset.
7374 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7375 !Subtarget->is64Bit()) {
7376 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7377 DAG.getNode(X86ISD::GlobalBaseReg,
7378 DebugLoc(), getPointerTy()),
7382 // For symbols that require a load from a stub to get the address, emit the
7384 if (isGlobalStubReference(OpFlag))
7385 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7386 MachinePointerInfo::getGOT(), false, false, false, 0);
7392 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7393 // Create the TargetBlockAddressAddress node.
7394 unsigned char OpFlags =
7395 Subtarget->ClassifyBlockAddressReference();
7396 CodeModel::Model M = getTargetMachine().getCodeModel();
7397 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7398 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7399 DebugLoc dl = Op.getDebugLoc();
7400 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7403 if (Subtarget->isPICStyleRIPRel() &&
7404 (M == CodeModel::Small || M == CodeModel::Kernel))
7405 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7407 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7409 // With PIC, the address is actually $g + Offset.
7410 if (isGlobalRelativeToPICBase(OpFlags)) {
7411 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7412 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7420 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7422 SelectionDAG &DAG) const {
7423 // Create the TargetGlobalAddress node, folding in the constant
7424 // offset if it is legal.
7425 unsigned char OpFlags =
7426 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7427 CodeModel::Model M = getTargetMachine().getCodeModel();
7429 if (OpFlags == X86II::MO_NO_FLAG &&
7430 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7431 // A direct static reference to a global.
7432 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7435 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7438 if (Subtarget->isPICStyleRIPRel() &&
7439 (M == CodeModel::Small || M == CodeModel::Kernel))
7440 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7442 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7444 // With PIC, the address is actually $g + Offset.
7445 if (isGlobalRelativeToPICBase(OpFlags)) {
7446 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7447 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7451 // For globals that require a load from a stub to get the address, emit the
7453 if (isGlobalStubReference(OpFlags))
7454 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7455 MachinePointerInfo::getGOT(), false, false, false, 0);
7457 // If there was a non-zero offset that we didn't fold, create an explicit
7460 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7461 DAG.getConstant(Offset, getPointerTy()));
7467 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7468 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7469 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7470 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7474 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7475 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7476 unsigned char OperandFlags, bool LocalDynamic = false) {
7477 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7478 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7479 DebugLoc dl = GA->getDebugLoc();
7480 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7481 GA->getValueType(0),
7485 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7489 SDValue Ops[] = { Chain, TGA, *InFlag };
7490 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7492 SDValue Ops[] = { Chain, TGA };
7493 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7496 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7497 MFI->setAdjustsStack(true);
7499 SDValue Flag = Chain.getValue(1);
7500 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7503 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7505 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7508 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7509 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7510 DAG.getNode(X86ISD::GlobalBaseReg,
7511 DebugLoc(), PtrVT), InFlag);
7512 InFlag = Chain.getValue(1);
7514 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7517 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7519 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7521 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7522 X86::RAX, X86II::MO_TLSGD);
7525 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7529 DebugLoc dl = GA->getDebugLoc();
7531 // Get the start address of the TLS block for this module.
7532 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7533 .getInfo<X86MachineFunctionInfo>();
7534 MFI->incNumLocalDynamicTLSAccesses();
7538 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7539 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7542 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7543 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7544 InFlag = Chain.getValue(1);
7545 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7546 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7549 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7553 unsigned char OperandFlags = X86II::MO_DTPOFF;
7554 unsigned WrapperKind = X86ISD::Wrapper;
7555 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7556 GA->getValueType(0),
7557 GA->getOffset(), OperandFlags);
7558 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7560 // Add x@dtpoff with the base.
7561 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7564 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7565 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7566 const EVT PtrVT, TLSModel::Model model,
7567 bool is64Bit, bool isPIC) {
7568 DebugLoc dl = GA->getDebugLoc();
7570 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7571 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7572 is64Bit ? 257 : 256));
7574 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7575 DAG.getIntPtrConstant(0),
7576 MachinePointerInfo(Ptr),
7577 false, false, false, 0);
7579 unsigned char OperandFlags = 0;
7580 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7582 unsigned WrapperKind = X86ISD::Wrapper;
7583 if (model == TLSModel::LocalExec) {
7584 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7585 } else if (model == TLSModel::InitialExec) {
7587 OperandFlags = X86II::MO_GOTTPOFF;
7588 WrapperKind = X86ISD::WrapperRIP;
7590 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7593 llvm_unreachable("Unexpected model");
7596 // emit "addl x@ntpoff,%eax" (local exec)
7597 // or "addl x@indntpoff,%eax" (initial exec)
7598 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7599 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7600 GA->getValueType(0),
7601 GA->getOffset(), OperandFlags);
7602 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7604 if (model == TLSModel::InitialExec) {
7605 if (isPIC && !is64Bit) {
7606 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7607 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7611 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7612 MachinePointerInfo::getGOT(), false, false, false,
7616 // The address of the thread local variable is the add of the thread
7617 // pointer with the offset of the variable.
7618 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7622 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7624 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7625 const GlobalValue *GV = GA->getGlobal();
7627 if (Subtarget->isTargetELF()) {
7628 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7631 case TLSModel::GeneralDynamic:
7632 if (Subtarget->is64Bit())
7633 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7634 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7635 case TLSModel::LocalDynamic:
7636 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7637 Subtarget->is64Bit());
7638 case TLSModel::InitialExec:
7639 case TLSModel::LocalExec:
7640 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7641 Subtarget->is64Bit(),
7642 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7644 llvm_unreachable("Unknown TLS model.");
7647 if (Subtarget->isTargetDarwin()) {
7648 // Darwin only has one model of TLS. Lower to that.
7649 unsigned char OpFlag = 0;
7650 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7651 X86ISD::WrapperRIP : X86ISD::Wrapper;
7653 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7655 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7656 !Subtarget->is64Bit();
7658 OpFlag = X86II::MO_TLVP_PIC_BASE;
7660 OpFlag = X86II::MO_TLVP;
7661 DebugLoc DL = Op.getDebugLoc();
7662 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7663 GA->getValueType(0),
7664 GA->getOffset(), OpFlag);
7665 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7667 // With PIC32, the address is actually $g + Offset.
7669 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7670 DAG.getNode(X86ISD::GlobalBaseReg,
7671 DebugLoc(), getPointerTy()),
7674 // Lowering the machine isd will make sure everything is in the right
7676 SDValue Chain = DAG.getEntryNode();
7677 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7678 SDValue Args[] = { Chain, Offset };
7679 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7681 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7682 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7683 MFI->setAdjustsStack(true);
7685 // And our return value (tls address) is in the standard call return value
7687 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7688 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7692 if (Subtarget->isTargetWindows()) {
7693 // Just use the implicit TLS architecture
7694 // Need to generate someting similar to:
7695 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7697 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7698 // mov rcx, qword [rdx+rcx*8]
7699 // mov eax, .tls$:tlsvar
7700 // [rax+rcx] contains the address
7701 // Windows 64bit: gs:0x58
7702 // Windows 32bit: fs:__tls_array
7704 // If GV is an alias then use the aliasee for determining
7705 // thread-localness.
7706 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7707 GV = GA->resolveAliasedGlobal(false);
7708 DebugLoc dl = GA->getDebugLoc();
7709 SDValue Chain = DAG.getEntryNode();
7711 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7712 // %gs:0x58 (64-bit).
7713 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7714 ? Type::getInt8PtrTy(*DAG.getContext(),
7716 : Type::getInt32PtrTy(*DAG.getContext(),
7719 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7720 Subtarget->is64Bit()
7721 ? DAG.getIntPtrConstant(0x58)
7722 : DAG.getExternalSymbol("_tls_array",
7724 MachinePointerInfo(Ptr),
7725 false, false, false, 0);
7727 // Load the _tls_index variable
7728 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7729 if (Subtarget->is64Bit())
7730 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7731 IDX, MachinePointerInfo(), MVT::i32,
7734 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7735 false, false, false, 0);
7737 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7739 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7741 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7742 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7743 false, false, false, 0);
7745 // Get the offset of start of .tls section
7746 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7747 GA->getValueType(0),
7748 GA->getOffset(), X86II::MO_SECREL);
7749 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7751 // The address of the thread local variable is the add of the thread
7752 // pointer with the offset of the variable.
7753 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7756 llvm_unreachable("TLS not implemented for this target.");
7760 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7761 /// and take a 2 x i32 value to shift plus a shift amount.
7762 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7763 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7764 EVT VT = Op.getValueType();
7765 unsigned VTBits = VT.getSizeInBits();
7766 DebugLoc dl = Op.getDebugLoc();
7767 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7768 SDValue ShOpLo = Op.getOperand(0);
7769 SDValue ShOpHi = Op.getOperand(1);
7770 SDValue ShAmt = Op.getOperand(2);
7771 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7772 DAG.getConstant(VTBits - 1, MVT::i8))
7773 : DAG.getConstant(0, VT);
7776 if (Op.getOpcode() == ISD::SHL_PARTS) {
7777 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7778 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7780 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7781 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7784 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7785 DAG.getConstant(VTBits, MVT::i8));
7786 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7787 AndNode, DAG.getConstant(0, MVT::i8));
7790 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7791 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7792 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7794 if (Op.getOpcode() == ISD::SHL_PARTS) {
7795 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7796 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7798 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7799 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7802 SDValue Ops[2] = { Lo, Hi };
7803 return DAG.getMergeValues(Ops, 2, dl);
7806 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7807 SelectionDAG &DAG) const {
7808 EVT SrcVT = Op.getOperand(0).getValueType();
7810 if (SrcVT.isVector())
7813 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7814 "Unknown SINT_TO_FP to lower!");
7816 // These are really Legal; return the operand so the caller accepts it as
7818 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7820 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7821 Subtarget->is64Bit()) {
7825 DebugLoc dl = Op.getDebugLoc();
7826 unsigned Size = SrcVT.getSizeInBits()/8;
7827 MachineFunction &MF = DAG.getMachineFunction();
7828 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7829 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7830 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7832 MachinePointerInfo::getFixedStack(SSFI),
7834 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7837 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7839 SelectionDAG &DAG) const {
7841 DebugLoc DL = Op.getDebugLoc();
7843 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7845 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7847 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7849 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7851 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7852 MachineMemOperand *MMO;
7854 int SSFI = FI->getIndex();
7856 DAG.getMachineFunction()
7857 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7858 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7860 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7861 StackSlot = StackSlot.getOperand(1);
7863 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7864 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7866 Tys, Ops, array_lengthof(Ops),
7870 Chain = Result.getValue(1);
7871 SDValue InFlag = Result.getValue(2);
7873 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7874 // shouldn't be necessary except that RFP cannot be live across
7875 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7876 MachineFunction &MF = DAG.getMachineFunction();
7877 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7878 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7879 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7880 Tys = DAG.getVTList(MVT::Other);
7882 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7884 MachineMemOperand *MMO =
7885 DAG.getMachineFunction()
7886 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7887 MachineMemOperand::MOStore, SSFISize, SSFISize);
7889 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7890 Ops, array_lengthof(Ops),
7891 Op.getValueType(), MMO);
7892 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7893 MachinePointerInfo::getFixedStack(SSFI),
7894 false, false, false, 0);
7900 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7901 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7902 SelectionDAG &DAG) const {
7903 // This algorithm is not obvious. Here it is what we're trying to output:
7906 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7907 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7911 pshufd $0x4e, %xmm0, %xmm1
7916 DebugLoc dl = Op.getDebugLoc();
7917 LLVMContext *Context = DAG.getContext();
7919 // Build some magic constants.
7920 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7921 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7922 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7924 SmallVector<Constant*,2> CV1;
7926 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7928 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7929 Constant *C1 = ConstantVector::get(CV1);
7930 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7932 // Load the 64-bit value into an XMM register.
7933 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7935 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7936 MachinePointerInfo::getConstantPool(),
7937 false, false, false, 16);
7938 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7939 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7942 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7943 MachinePointerInfo::getConstantPool(),
7944 false, false, false, 16);
7945 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7946 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7949 if (Subtarget->hasSSE3()) {
7950 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7951 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7953 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7954 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7956 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7957 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7961 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7962 DAG.getIntPtrConstant(0));
7965 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7966 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7967 SelectionDAG &DAG) const {
7968 DebugLoc dl = Op.getDebugLoc();
7969 // FP constant to bias correct the final result.
7970 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7973 // Load the 32-bit value into an XMM register.
7974 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7977 // Zero out the upper parts of the register.
7978 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7980 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7981 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7982 DAG.getIntPtrConstant(0));
7984 // Or the load with the bias.
7985 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7986 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7987 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7989 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7990 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7991 MVT::v2f64, Bias)));
7992 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7993 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7994 DAG.getIntPtrConstant(0));
7996 // Subtract the bias.
7997 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7999 // Handle final rounding.
8000 EVT DestVT = Op.getValueType();
8002 if (DestVT.bitsLT(MVT::f64))
8003 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8004 DAG.getIntPtrConstant(0));
8005 if (DestVT.bitsGT(MVT::f64))
8006 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8008 // Handle final rounding.
8012 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8013 SelectionDAG &DAG) const {
8014 SDValue N0 = Op.getOperand(0);
8015 DebugLoc dl = Op.getDebugLoc();
8017 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8018 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8019 // the optimization here.
8020 if (DAG.SignBitIsZero(N0))
8021 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8023 EVT SrcVT = N0.getValueType();
8024 EVT DstVT = Op.getValueType();
8025 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8026 return LowerUINT_TO_FP_i64(Op, DAG);
8027 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8028 return LowerUINT_TO_FP_i32(Op, DAG);
8029 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8032 // Make a 64-bit buffer, and use it to build an FILD.
8033 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8034 if (SrcVT == MVT::i32) {
8035 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8036 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8037 getPointerTy(), StackSlot, WordOff);
8038 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8039 StackSlot, MachinePointerInfo(),
8041 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8042 OffsetSlot, MachinePointerInfo(),
8044 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8048 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8049 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8050 StackSlot, MachinePointerInfo(),
8052 // For i64 source, we need to add the appropriate power of 2 if the input
8053 // was negative. This is the same as the optimization in
8054 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8055 // we must be careful to do the computation in x87 extended precision, not
8056 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8057 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8058 MachineMemOperand *MMO =
8059 DAG.getMachineFunction()
8060 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8061 MachineMemOperand::MOLoad, 8, 8);
8063 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8064 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8065 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8068 APInt FF(32, 0x5F800000ULL);
8070 // Check whether the sign bit is set.
8071 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8072 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8075 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8076 SDValue FudgePtr = DAG.getConstantPool(
8077 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8080 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8081 SDValue Zero = DAG.getIntPtrConstant(0);
8082 SDValue Four = DAG.getIntPtrConstant(4);
8083 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8085 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8087 // Load the value out, extending it from f32 to f80.
8088 // FIXME: Avoid the extend by constructing the right constant pool?
8089 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8090 FudgePtr, MachinePointerInfo::getConstantPool(),
8091 MVT::f32, false, false, 4);
8092 // Extend everything to 80 bits to force it to be done on x87.
8093 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8094 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8097 std::pair<SDValue,SDValue> X86TargetLowering::
8098 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8099 DebugLoc DL = Op.getDebugLoc();
8101 EVT DstTy = Op.getValueType();
8103 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8104 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8108 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8109 DstTy.getSimpleVT() >= MVT::i16 &&
8110 "Unknown FP_TO_INT to lower!");
8112 // These are really Legal.
8113 if (DstTy == MVT::i32 &&
8114 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8115 return std::make_pair(SDValue(), SDValue());
8116 if (Subtarget->is64Bit() &&
8117 DstTy == MVT::i64 &&
8118 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8119 return std::make_pair(SDValue(), SDValue());
8121 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8122 // stack slot, or into the FTOL runtime function.
8123 MachineFunction &MF = DAG.getMachineFunction();
8124 unsigned MemSize = DstTy.getSizeInBits()/8;
8125 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8126 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8129 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8130 Opc = X86ISD::WIN_FTOL;
8132 switch (DstTy.getSimpleVT().SimpleTy) {
8133 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8134 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8135 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8136 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8139 SDValue Chain = DAG.getEntryNode();
8140 SDValue Value = Op.getOperand(0);
8141 EVT TheVT = Op.getOperand(0).getValueType();
8142 // FIXME This causes a redundant load/store if the SSE-class value is already
8143 // in memory, such as if it is on the callstack.
8144 if (isScalarFPTypeInSSEReg(TheVT)) {
8145 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8146 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8147 MachinePointerInfo::getFixedStack(SSFI),
8149 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8151 Chain, StackSlot, DAG.getValueType(TheVT)
8154 MachineMemOperand *MMO =
8155 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8156 MachineMemOperand::MOLoad, MemSize, MemSize);
8157 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8159 Chain = Value.getValue(1);
8160 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8161 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8164 MachineMemOperand *MMO =
8165 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8166 MachineMemOperand::MOStore, MemSize, MemSize);
8168 if (Opc != X86ISD::WIN_FTOL) {
8169 // Build the FP_TO_INT*_IN_MEM
8170 SDValue Ops[] = { Chain, Value, StackSlot };
8171 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8172 Ops, 3, DstTy, MMO);
8173 return std::make_pair(FIST, StackSlot);
8175 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8176 DAG.getVTList(MVT::Other, MVT::Glue),
8178 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8179 MVT::i32, ftol.getValue(1));
8180 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8181 MVT::i32, eax.getValue(2));
8182 SDValue Ops[] = { eax, edx };
8183 SDValue pair = IsReplace
8184 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8185 : DAG.getMergeValues(Ops, 2, DL);
8186 return std::make_pair(pair, SDValue());
8190 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8191 DebugLoc DL = Op.getDebugLoc();
8192 EVT VT = Op.getValueType();
8193 EVT SVT = Op.getOperand(0).getValueType();
8195 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8196 VT.getVectorNumElements() != SVT.getVectorNumElements())
8199 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8201 unsigned NumElems = VT.getVectorNumElements();
8202 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8205 SDValue In = Op.getOperand(0);
8206 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8207 // Prepare truncation shuffle mask
8208 for (unsigned i = 0; i != NumElems; ++i)
8210 SDValue V = DAG.getVectorShuffle(NVT, DL,
8211 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8212 DAG.getUNDEF(NVT), &MaskVec[0]);
8213 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8214 DAG.getIntPtrConstant(0));
8217 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8218 SelectionDAG &DAG) const {
8219 if (Op.getValueType().isVector()) {
8220 if (Op.getValueType() == MVT::v8i16)
8221 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8222 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8223 MVT::v8i32, Op.getOperand(0)));
8227 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8228 /*IsSigned=*/ true, /*IsReplace=*/ false);
8229 SDValue FIST = Vals.first, StackSlot = Vals.second;
8230 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8231 if (FIST.getNode() == 0) return Op;
8233 if (StackSlot.getNode())
8235 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8236 FIST, StackSlot, MachinePointerInfo(),
8237 false, false, false, 0);
8239 // The node is the result.
8243 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8244 SelectionDAG &DAG) const {
8245 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8246 /*IsSigned=*/ false, /*IsReplace=*/ false);
8247 SDValue FIST = Vals.first, StackSlot = Vals.second;
8248 assert(FIST.getNode() && "Unexpected failure");
8250 if (StackSlot.getNode())
8252 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8253 FIST, StackSlot, MachinePointerInfo(),
8254 false, false, false, 0);
8256 // The node is the result.
8260 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8261 SelectionDAG &DAG) const {
8262 DebugLoc DL = Op.getDebugLoc();
8263 EVT VT = Op.getValueType();
8264 SDValue In = Op.getOperand(0);
8265 EVT SVT = In.getValueType();
8267 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8269 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8270 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8271 In, DAG.getUNDEF(SVT)));
8274 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8275 LLVMContext *Context = DAG.getContext();
8276 DebugLoc dl = Op.getDebugLoc();
8277 EVT VT = Op.getValueType();
8279 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8280 if (VT.isVector()) {
8281 EltVT = VT.getVectorElementType();
8282 NumElts = VT.getVectorNumElements();
8285 if (EltVT == MVT::f64)
8286 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8288 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8289 C = ConstantVector::getSplat(NumElts, C);
8290 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8291 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8292 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8293 MachinePointerInfo::getConstantPool(),
8294 false, false, false, Alignment);
8295 if (VT.isVector()) {
8296 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8297 return DAG.getNode(ISD::BITCAST, dl, VT,
8298 DAG.getNode(ISD::AND, dl, ANDVT,
8299 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8301 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8303 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8306 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8307 LLVMContext *Context = DAG.getContext();
8308 DebugLoc dl = Op.getDebugLoc();
8309 EVT VT = Op.getValueType();
8311 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8312 if (VT.isVector()) {
8313 EltVT = VT.getVectorElementType();
8314 NumElts = VT.getVectorNumElements();
8317 if (EltVT == MVT::f64)
8318 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8320 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8321 C = ConstantVector::getSplat(NumElts, C);
8322 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8323 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8324 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8325 MachinePointerInfo::getConstantPool(),
8326 false, false, false, Alignment);
8327 if (VT.isVector()) {
8328 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8329 return DAG.getNode(ISD::BITCAST, dl, VT,
8330 DAG.getNode(ISD::XOR, dl, XORVT,
8331 DAG.getNode(ISD::BITCAST, dl, XORVT,
8333 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8336 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8339 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8340 LLVMContext *Context = DAG.getContext();
8341 SDValue Op0 = Op.getOperand(0);
8342 SDValue Op1 = Op.getOperand(1);
8343 DebugLoc dl = Op.getDebugLoc();
8344 EVT VT = Op.getValueType();
8345 EVT SrcVT = Op1.getValueType();
8347 // If second operand is smaller, extend it first.
8348 if (SrcVT.bitsLT(VT)) {
8349 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8352 // And if it is bigger, shrink it first.
8353 if (SrcVT.bitsGT(VT)) {
8354 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8358 // At this point the operands and the result should have the same
8359 // type, and that won't be f80 since that is not custom lowered.
8361 // First get the sign bit of second operand.
8362 SmallVector<Constant*,4> CV;
8363 if (SrcVT == MVT::f64) {
8364 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8365 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8367 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8368 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8369 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8370 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8372 Constant *C = ConstantVector::get(CV);
8373 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8374 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8375 MachinePointerInfo::getConstantPool(),
8376 false, false, false, 16);
8377 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8379 // Shift sign bit right or left if the two operands have different types.
8380 if (SrcVT.bitsGT(VT)) {
8381 // Op0 is MVT::f32, Op1 is MVT::f64.
8382 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8383 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8384 DAG.getConstant(32, MVT::i32));
8385 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8386 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8387 DAG.getIntPtrConstant(0));
8390 // Clear first operand sign bit.
8392 if (VT == MVT::f64) {
8393 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8394 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8396 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8397 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8398 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8399 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8401 C = ConstantVector::get(CV);
8402 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8403 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8404 MachinePointerInfo::getConstantPool(),
8405 false, false, false, 16);
8406 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8408 // Or the value with the sign bit.
8409 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8412 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8413 SDValue N0 = Op.getOperand(0);
8414 DebugLoc dl = Op.getDebugLoc();
8415 EVT VT = Op.getValueType();
8417 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8418 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8419 DAG.getConstant(1, VT));
8420 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8423 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8425 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8426 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8428 if (!Subtarget->hasSSE41())
8431 if (!Op->hasOneUse())
8434 SDNode *N = Op.getNode();
8435 DebugLoc DL = N->getDebugLoc();
8437 SmallVector<SDValue, 8> Opnds;
8438 DenseMap<SDValue, unsigned> VecInMap;
8439 EVT VT = MVT::Other;
8441 // Recognize a special case where a vector is casted into wide integer to
8443 Opnds.push_back(N->getOperand(0));
8444 Opnds.push_back(N->getOperand(1));
8446 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8447 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8448 // BFS traverse all OR'd operands.
8449 if (I->getOpcode() == ISD::OR) {
8450 Opnds.push_back(I->getOperand(0));
8451 Opnds.push_back(I->getOperand(1));
8452 // Re-evaluate the number of nodes to be traversed.
8453 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8457 // Quit if a non-EXTRACT_VECTOR_ELT
8458 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8461 // Quit if without a constant index.
8462 SDValue Idx = I->getOperand(1);
8463 if (!isa<ConstantSDNode>(Idx))
8466 SDValue ExtractedFromVec = I->getOperand(0);
8467 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8468 if (M == VecInMap.end()) {
8469 VT = ExtractedFromVec.getValueType();
8470 // Quit if not 128/256-bit vector.
8471 if (!VT.is128BitVector() && !VT.is256BitVector())
8473 // Quit if not the same type.
8474 if (VecInMap.begin() != VecInMap.end() &&
8475 VT != VecInMap.begin()->first.getValueType())
8477 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8479 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8482 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8483 "Not extracted from 128-/256-bit vector.");
8485 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8486 SmallVector<SDValue, 8> VecIns;
8488 for (DenseMap<SDValue, unsigned>::const_iterator
8489 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8490 // Quit if not all elements are used.
8491 if (I->second != FullMask)
8493 VecIns.push_back(I->first);
8496 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8498 // Cast all vectors into TestVT for PTEST.
8499 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8500 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8502 // If more than one full vectors are evaluated, OR them first before PTEST.
8503 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8504 // Each iteration will OR 2 nodes and append the result until there is only
8505 // 1 node left, i.e. the final OR'd value of all vectors.
8506 SDValue LHS = VecIns[Slot];
8507 SDValue RHS = VecIns[Slot + 1];
8508 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8511 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8512 VecIns.back(), VecIns.back());
8515 /// Emit nodes that will be selected as "test Op0,Op0", or something
8517 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8518 SelectionDAG &DAG) const {
8519 DebugLoc dl = Op.getDebugLoc();
8521 // CF and OF aren't always set the way we want. Determine which
8522 // of these we need.
8523 bool NeedCF = false;
8524 bool NeedOF = false;
8527 case X86::COND_A: case X86::COND_AE:
8528 case X86::COND_B: case X86::COND_BE:
8531 case X86::COND_G: case X86::COND_GE:
8532 case X86::COND_L: case X86::COND_LE:
8533 case X86::COND_O: case X86::COND_NO:
8538 // See if we can use the EFLAGS value from the operand instead of
8539 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8540 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8541 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8542 // Emit a CMP with 0, which is the TEST pattern.
8543 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8544 DAG.getConstant(0, Op.getValueType()));
8546 unsigned Opcode = 0;
8547 unsigned NumOperands = 0;
8549 // Truncate operations may prevent the merge of the SETCC instruction
8550 // and the arithmetic intruction before it. Attempt to truncate the operands
8551 // of the arithmetic instruction and use a reduced bit-width instruction.
8552 bool NeedTruncation = false;
8553 SDValue ArithOp = Op;
8554 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8555 SDValue Arith = Op->getOperand(0);
8556 // Both the trunc and the arithmetic op need to have one user each.
8557 if (Arith->hasOneUse())
8558 switch (Arith.getOpcode()) {
8565 NeedTruncation = true;
8571 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8572 // which may be the result of a CAST. We use the variable 'Op', which is the
8573 // non-casted variable when we check for possible users.
8574 switch (ArithOp.getOpcode()) {
8576 // Due to an isel shortcoming, be conservative if this add is likely to be
8577 // selected as part of a load-modify-store instruction. When the root node
8578 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8579 // uses of other nodes in the match, such as the ADD in this case. This
8580 // leads to the ADD being left around and reselected, with the result being
8581 // two adds in the output. Alas, even if none our users are stores, that
8582 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8583 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8584 // climbing the DAG back to the root, and it doesn't seem to be worth the
8586 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8587 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8588 if (UI->getOpcode() != ISD::CopyToReg &&
8589 UI->getOpcode() != ISD::SETCC &&
8590 UI->getOpcode() != ISD::STORE)
8593 if (ConstantSDNode *C =
8594 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8595 // An add of one will be selected as an INC.
8596 if (C->getAPIntValue() == 1) {
8597 Opcode = X86ISD::INC;
8602 // An add of negative one (subtract of one) will be selected as a DEC.
8603 if (C->getAPIntValue().isAllOnesValue()) {
8604 Opcode = X86ISD::DEC;
8610 // Otherwise use a regular EFLAGS-setting add.
8611 Opcode = X86ISD::ADD;
8615 // If the primary and result isn't used, don't bother using X86ISD::AND,
8616 // because a TEST instruction will be better.
8617 bool NonFlagUse = false;
8618 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8619 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8621 unsigned UOpNo = UI.getOperandNo();
8622 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8623 // Look pass truncate.
8624 UOpNo = User->use_begin().getOperandNo();
8625 User = *User->use_begin();
8628 if (User->getOpcode() != ISD::BRCOND &&
8629 User->getOpcode() != ISD::SETCC &&
8630 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8643 // Due to the ISEL shortcoming noted above, be conservative if this op is
8644 // likely to be selected as part of a load-modify-store instruction.
8645 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8646 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8647 if (UI->getOpcode() == ISD::STORE)
8650 // Otherwise use a regular EFLAGS-setting instruction.
8651 switch (ArithOp.getOpcode()) {
8652 default: llvm_unreachable("unexpected operator!");
8653 case ISD::SUB: Opcode = X86ISD::SUB; break;
8654 case ISD::XOR: Opcode = X86ISD::XOR; break;
8655 case ISD::AND: Opcode = X86ISD::AND; break;
8657 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8658 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8659 if (EFLAGS.getNode())
8662 Opcode = X86ISD::OR;
8676 return SDValue(Op.getNode(), 1);
8682 // If we found that truncation is beneficial, perform the truncation and
8684 if (NeedTruncation) {
8685 EVT VT = Op.getValueType();
8686 SDValue WideVal = Op->getOperand(0);
8687 EVT WideVT = WideVal.getValueType();
8688 unsigned ConvertedOp = 0;
8689 // Use a target machine opcode to prevent further DAGCombine
8690 // optimizations that may separate the arithmetic operations
8691 // from the setcc node.
8692 switch (WideVal.getOpcode()) {
8694 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8695 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8696 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8697 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8698 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8703 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8704 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8705 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8706 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8712 // Emit a CMP with 0, which is the TEST pattern.
8713 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8714 DAG.getConstant(0, Op.getValueType()));
8716 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8717 SmallVector<SDValue, 4> Ops;
8718 for (unsigned i = 0; i != NumOperands; ++i)
8719 Ops.push_back(Op.getOperand(i));
8721 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8722 DAG.ReplaceAllUsesWith(Op, New);
8723 return SDValue(New.getNode(), 1);
8726 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8728 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8729 SelectionDAG &DAG) const {
8730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8731 if (C->getAPIntValue() == 0)
8732 return EmitTest(Op0, X86CC, DAG);
8734 DebugLoc dl = Op0.getDebugLoc();
8735 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8736 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8737 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8738 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8739 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8741 return SDValue(Sub.getNode(), 1);
8743 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8746 /// Convert a comparison if required by the subtarget.
8747 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8748 SelectionDAG &DAG) const {
8749 // If the subtarget does not support the FUCOMI instruction, floating-point
8750 // comparisons have to be converted.
8751 if (Subtarget->hasCMov() ||
8752 Cmp.getOpcode() != X86ISD::CMP ||
8753 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8754 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8757 // The instruction selector will select an FUCOM instruction instead of
8758 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8759 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8760 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8761 DebugLoc dl = Cmp.getDebugLoc();
8762 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8763 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8764 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8765 DAG.getConstant(8, MVT::i8));
8766 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8767 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8770 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8771 /// if it's possible.
8772 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8773 DebugLoc dl, SelectionDAG &DAG) const {
8774 SDValue Op0 = And.getOperand(0);
8775 SDValue Op1 = And.getOperand(1);
8776 if (Op0.getOpcode() == ISD::TRUNCATE)
8777 Op0 = Op0.getOperand(0);
8778 if (Op1.getOpcode() == ISD::TRUNCATE)
8779 Op1 = Op1.getOperand(0);
8782 if (Op1.getOpcode() == ISD::SHL)
8783 std::swap(Op0, Op1);
8784 if (Op0.getOpcode() == ISD::SHL) {
8785 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8786 if (And00C->getZExtValue() == 1) {
8787 // If we looked past a truncate, check that it's only truncating away
8789 unsigned BitWidth = Op0.getValueSizeInBits();
8790 unsigned AndBitWidth = And.getValueSizeInBits();
8791 if (BitWidth > AndBitWidth) {
8793 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8794 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8798 RHS = Op0.getOperand(1);
8800 } else if (Op1.getOpcode() == ISD::Constant) {
8801 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8802 uint64_t AndRHSVal = AndRHS->getZExtValue();
8803 SDValue AndLHS = Op0;
8805 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8806 LHS = AndLHS.getOperand(0);
8807 RHS = AndLHS.getOperand(1);
8810 // Use BT if the immediate can't be encoded in a TEST instruction.
8811 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8813 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8817 if (LHS.getNode()) {
8818 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8819 // instruction. Since the shift amount is in-range-or-undefined, we know
8820 // that doing a bittest on the i32 value is ok. We extend to i32 because
8821 // the encoding for the i16 version is larger than the i32 version.
8822 // Also promote i16 to i32 for performance / code size reason.
8823 if (LHS.getValueType() == MVT::i8 ||
8824 LHS.getValueType() == MVT::i16)
8825 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8827 // If the operand types disagree, extend the shift amount to match. Since
8828 // BT ignores high bits (like shifts) we can use anyextend.
8829 if (LHS.getValueType() != RHS.getValueType())
8830 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8832 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8833 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8834 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8835 DAG.getConstant(Cond, MVT::i8), BT);
8841 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8843 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8845 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8846 SDValue Op0 = Op.getOperand(0);
8847 SDValue Op1 = Op.getOperand(1);
8848 DebugLoc dl = Op.getDebugLoc();
8849 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8851 // Optimize to BT if possible.
8852 // Lower (X & (1 << N)) == 0 to BT(X, N).
8853 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8854 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8855 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8856 Op1.getOpcode() == ISD::Constant &&
8857 cast<ConstantSDNode>(Op1)->isNullValue() &&
8858 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8859 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8860 if (NewSetCC.getNode())
8864 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8866 if (Op1.getOpcode() == ISD::Constant &&
8867 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8868 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8869 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8871 // If the input is a setcc, then reuse the input setcc or use a new one with
8872 // the inverted condition.
8873 if (Op0.getOpcode() == X86ISD::SETCC) {
8874 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8875 bool Invert = (CC == ISD::SETNE) ^
8876 cast<ConstantSDNode>(Op1)->isNullValue();
8877 if (!Invert) return Op0;
8879 CCode = X86::GetOppositeBranchCondition(CCode);
8880 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8881 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8885 bool isFP = Op1.getValueType().isFloatingPoint();
8886 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8887 if (X86CC == X86::COND_INVALID)
8890 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8891 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8892 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8893 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8896 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8897 // ones, and then concatenate the result back.
8898 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8899 EVT VT = Op.getValueType();
8901 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8902 "Unsupported value type for operation");
8904 unsigned NumElems = VT.getVectorNumElements();
8905 DebugLoc dl = Op.getDebugLoc();
8906 SDValue CC = Op.getOperand(2);
8908 // Extract the LHS vectors
8909 SDValue LHS = Op.getOperand(0);
8910 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8911 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8913 // Extract the RHS vectors
8914 SDValue RHS = Op.getOperand(1);
8915 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8916 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8918 // Issue the operation on the smaller types and concatenate the result back
8919 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8920 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8921 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8922 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8923 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8927 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8929 SDValue Op0 = Op.getOperand(0);
8930 SDValue Op1 = Op.getOperand(1);
8931 SDValue CC = Op.getOperand(2);
8932 EVT VT = Op.getValueType();
8933 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8934 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8935 DebugLoc dl = Op.getDebugLoc();
8939 EVT EltVT = Op0.getValueType().getVectorElementType();
8940 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8946 // SSE Condition code mapping:
8955 switch (SetCCOpcode) {
8956 default: llvm_unreachable("Unexpected SETCC condition");
8958 case ISD::SETEQ: SSECC = 0; break;
8960 case ISD::SETGT: Swap = true; // Fallthrough
8962 case ISD::SETOLT: SSECC = 1; break;
8964 case ISD::SETGE: Swap = true; // Fallthrough
8966 case ISD::SETOLE: SSECC = 2; break;
8967 case ISD::SETUO: SSECC = 3; break;
8969 case ISD::SETNE: SSECC = 4; break;
8970 case ISD::SETULE: Swap = true; // Fallthrough
8971 case ISD::SETUGE: SSECC = 5; break;
8972 case ISD::SETULT: Swap = true; // Fallthrough
8973 case ISD::SETUGT: SSECC = 6; break;
8974 case ISD::SETO: SSECC = 7; break;
8976 case ISD::SETONE: SSECC = 8; break;
8979 std::swap(Op0, Op1);
8981 // In the two special cases we can't handle, emit two comparisons.
8984 unsigned CombineOpc;
8985 if (SetCCOpcode == ISD::SETUEQ) {
8986 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8988 assert(SetCCOpcode == ISD::SETONE);
8989 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8992 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8993 DAG.getConstant(CC0, MVT::i8));
8994 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8995 DAG.getConstant(CC1, MVT::i8));
8996 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8998 // Handle all other FP comparisons here.
8999 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9000 DAG.getConstant(SSECC, MVT::i8));
9003 // Break 256-bit integer vector compare into smaller ones.
9004 if (VT.is256BitVector() && !Subtarget->hasAVX2())
9005 return Lower256IntVSETCC(Op, DAG);
9007 // We are handling one of the integer comparisons here. Since SSE only has
9008 // GT and EQ comparisons for integer, swapping operands and multiple
9009 // operations may be required for some comparisons.
9011 bool Swap = false, Invert = false, FlipSigns = false;
9013 switch (SetCCOpcode) {
9014 default: llvm_unreachable("Unexpected SETCC condition");
9015 case ISD::SETNE: Invert = true;
9016 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9017 case ISD::SETLT: Swap = true;
9018 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9019 case ISD::SETGE: Swap = true;
9020 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9021 case ISD::SETULT: Swap = true;
9022 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9023 case ISD::SETUGE: Swap = true;
9024 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9027 std::swap(Op0, Op1);
9029 // Check that the operation in question is available (most are plain SSE2,
9030 // but PCMPGTQ and PCMPEQQ have different requirements).
9031 if (VT == MVT::v2i64) {
9032 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9034 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9038 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9039 // bits of the inputs before performing those operations.
9041 EVT EltVT = VT.getVectorElementType();
9042 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9044 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9045 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9047 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9048 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9051 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9053 // If the logical-not of the result is required, perform that now.
9055 Result = DAG.getNOT(dl, Result, VT);
9060 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9061 static bool isX86LogicalCmp(SDValue Op) {
9062 unsigned Opc = Op.getNode()->getOpcode();
9063 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9064 Opc == X86ISD::SAHF)
9066 if (Op.getResNo() == 1 &&
9067 (Opc == X86ISD::ADD ||
9068 Opc == X86ISD::SUB ||
9069 Opc == X86ISD::ADC ||
9070 Opc == X86ISD::SBB ||
9071 Opc == X86ISD::SMUL ||
9072 Opc == X86ISD::UMUL ||
9073 Opc == X86ISD::INC ||
9074 Opc == X86ISD::DEC ||
9075 Opc == X86ISD::OR ||
9076 Opc == X86ISD::XOR ||
9077 Opc == X86ISD::AND))
9080 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9086 static bool isZero(SDValue V) {
9087 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9088 return C && C->isNullValue();
9091 static bool isAllOnes(SDValue V) {
9092 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9093 return C && C->isAllOnesValue();
9096 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9097 if (V.getOpcode() != ISD::TRUNCATE)
9100 SDValue VOp0 = V.getOperand(0);
9101 unsigned InBits = VOp0.getValueSizeInBits();
9102 unsigned Bits = V.getValueSizeInBits();
9103 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9106 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9107 bool addTest = true;
9108 SDValue Cond = Op.getOperand(0);
9109 SDValue Op1 = Op.getOperand(1);
9110 SDValue Op2 = Op.getOperand(2);
9111 DebugLoc DL = Op.getDebugLoc();
9114 if (Cond.getOpcode() == ISD::SETCC) {
9115 SDValue NewCond = LowerSETCC(Cond, DAG);
9116 if (NewCond.getNode())
9120 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9121 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9122 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9123 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9124 if (Cond.getOpcode() == X86ISD::SETCC &&
9125 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9126 isZero(Cond.getOperand(1).getOperand(1))) {
9127 SDValue Cmp = Cond.getOperand(1);
9129 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9131 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9132 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9133 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9135 SDValue CmpOp0 = Cmp.getOperand(0);
9136 // Apply further optimizations for special cases
9137 // (select (x != 0), -1, 0) -> neg & sbb
9138 // (select (x == 0), 0, -1) -> neg & sbb
9139 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9140 if (YC->isNullValue() &&
9141 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9142 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9143 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9144 DAG.getConstant(0, CmpOp0.getValueType()),
9146 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9147 DAG.getConstant(X86::COND_B, MVT::i8),
9148 SDValue(Neg.getNode(), 1));
9152 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9153 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9154 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9156 SDValue Res = // Res = 0 or -1.
9157 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9158 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9160 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9161 Res = DAG.getNOT(DL, Res, Res.getValueType());
9163 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9164 if (N2C == 0 || !N2C->isNullValue())
9165 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9170 // Look past (and (setcc_carry (cmp ...)), 1).
9171 if (Cond.getOpcode() == ISD::AND &&
9172 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9173 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9174 if (C && C->getAPIntValue() == 1)
9175 Cond = Cond.getOperand(0);
9178 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9179 // setting operand in place of the X86ISD::SETCC.
9180 unsigned CondOpcode = Cond.getOpcode();
9181 if (CondOpcode == X86ISD::SETCC ||
9182 CondOpcode == X86ISD::SETCC_CARRY) {
9183 CC = Cond.getOperand(0);
9185 SDValue Cmp = Cond.getOperand(1);
9186 unsigned Opc = Cmp.getOpcode();
9187 EVT VT = Op.getValueType();
9189 bool IllegalFPCMov = false;
9190 if (VT.isFloatingPoint() && !VT.isVector() &&
9191 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9192 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9194 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9195 Opc == X86ISD::BT) { // FIXME
9199 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9200 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9201 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9202 Cond.getOperand(0).getValueType() != MVT::i8)) {
9203 SDValue LHS = Cond.getOperand(0);
9204 SDValue RHS = Cond.getOperand(1);
9208 switch (CondOpcode) {
9209 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9210 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9211 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9212 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9213 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9214 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9215 default: llvm_unreachable("unexpected overflowing operator");
9217 if (CondOpcode == ISD::UMULO)
9218 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9221 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9223 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9225 if (CondOpcode == ISD::UMULO)
9226 Cond = X86Op.getValue(2);
9228 Cond = X86Op.getValue(1);
9230 CC = DAG.getConstant(X86Cond, MVT::i8);
9235 // Look pass the truncate if the high bits are known zero.
9236 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9237 Cond = Cond.getOperand(0);
9239 // We know the result of AND is compared against zero. Try to match
9241 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9242 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9243 if (NewSetCC.getNode()) {
9244 CC = NewSetCC.getOperand(0);
9245 Cond = NewSetCC.getOperand(1);
9252 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9253 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9256 // a < b ? -1 : 0 -> RES = ~setcc_carry
9257 // a < b ? 0 : -1 -> RES = setcc_carry
9258 // a >= b ? -1 : 0 -> RES = setcc_carry
9259 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9260 if (Cond.getOpcode() == X86ISD::SUB) {
9261 Cond = ConvertCmpIfNecessary(Cond, DAG);
9262 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9264 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9265 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9266 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9267 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9268 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9269 return DAG.getNOT(DL, Res, Res.getValueType());
9274 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9275 // widen the cmov and push the truncate through. This avoids introducing a new
9276 // branch during isel and doesn't add any extensions.
9277 if (Op.getValueType() == MVT::i8 &&
9278 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9279 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9280 if (T1.getValueType() == T2.getValueType() &&
9281 // Blacklist CopyFromReg to avoid partial register stalls.
9282 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9283 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9284 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9285 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9289 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9290 // condition is true.
9291 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9292 SDValue Ops[] = { Op2, Op1, CC, Cond };
9293 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9296 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9297 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9298 // from the AND / OR.
9299 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9300 Opc = Op.getOpcode();
9301 if (Opc != ISD::OR && Opc != ISD::AND)
9303 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9304 Op.getOperand(0).hasOneUse() &&
9305 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9306 Op.getOperand(1).hasOneUse());
9309 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9310 // 1 and that the SETCC node has a single use.
9311 static bool isXor1OfSetCC(SDValue Op) {
9312 if (Op.getOpcode() != ISD::XOR)
9314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9315 if (N1C && N1C->getAPIntValue() == 1) {
9316 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9317 Op.getOperand(0).hasOneUse();
9322 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9323 bool addTest = true;
9324 SDValue Chain = Op.getOperand(0);
9325 SDValue Cond = Op.getOperand(1);
9326 SDValue Dest = Op.getOperand(2);
9327 DebugLoc dl = Op.getDebugLoc();
9329 bool Inverted = false;
9331 if (Cond.getOpcode() == ISD::SETCC) {
9332 // Check for setcc([su]{add,sub,mul}o == 0).
9333 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9334 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9335 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9336 Cond.getOperand(0).getResNo() == 1 &&
9337 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9338 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9339 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9340 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9341 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9342 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9344 Cond = Cond.getOperand(0);
9346 SDValue NewCond = LowerSETCC(Cond, DAG);
9347 if (NewCond.getNode())
9352 // FIXME: LowerXALUO doesn't handle these!!
9353 else if (Cond.getOpcode() == X86ISD::ADD ||
9354 Cond.getOpcode() == X86ISD::SUB ||
9355 Cond.getOpcode() == X86ISD::SMUL ||
9356 Cond.getOpcode() == X86ISD::UMUL)
9357 Cond = LowerXALUO(Cond, DAG);
9360 // Look pass (and (setcc_carry (cmp ...)), 1).
9361 if (Cond.getOpcode() == ISD::AND &&
9362 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9363 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9364 if (C && C->getAPIntValue() == 1)
9365 Cond = Cond.getOperand(0);
9368 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9369 // setting operand in place of the X86ISD::SETCC.
9370 unsigned CondOpcode = Cond.getOpcode();
9371 if (CondOpcode == X86ISD::SETCC ||
9372 CondOpcode == X86ISD::SETCC_CARRY) {
9373 CC = Cond.getOperand(0);
9375 SDValue Cmp = Cond.getOperand(1);
9376 unsigned Opc = Cmp.getOpcode();
9377 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9378 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9382 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9386 // These can only come from an arithmetic instruction with overflow,
9387 // e.g. SADDO, UADDO.
9388 Cond = Cond.getNode()->getOperand(1);
9394 CondOpcode = Cond.getOpcode();
9395 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9396 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9397 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9398 Cond.getOperand(0).getValueType() != MVT::i8)) {
9399 SDValue LHS = Cond.getOperand(0);
9400 SDValue RHS = Cond.getOperand(1);
9404 switch (CondOpcode) {
9405 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9406 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9407 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9408 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9409 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9410 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9411 default: llvm_unreachable("unexpected overflowing operator");
9414 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9415 if (CondOpcode == ISD::UMULO)
9416 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9419 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9421 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9423 if (CondOpcode == ISD::UMULO)
9424 Cond = X86Op.getValue(2);
9426 Cond = X86Op.getValue(1);
9428 CC = DAG.getConstant(X86Cond, MVT::i8);
9432 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9433 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9434 if (CondOpc == ISD::OR) {
9435 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9436 // two branches instead of an explicit OR instruction with a
9438 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9439 isX86LogicalCmp(Cmp)) {
9440 CC = Cond.getOperand(0).getOperand(0);
9441 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9442 Chain, Dest, CC, Cmp);
9443 CC = Cond.getOperand(1).getOperand(0);
9447 } else { // ISD::AND
9448 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9449 // two branches instead of an explicit AND instruction with a
9450 // separate test. However, we only do this if this block doesn't
9451 // have a fall-through edge, because this requires an explicit
9452 // jmp when the condition is false.
9453 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9454 isX86LogicalCmp(Cmp) &&
9455 Op.getNode()->hasOneUse()) {
9456 X86::CondCode CCode =
9457 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9458 CCode = X86::GetOppositeBranchCondition(CCode);
9459 CC = DAG.getConstant(CCode, MVT::i8);
9460 SDNode *User = *Op.getNode()->use_begin();
9461 // Look for an unconditional branch following this conditional branch.
9462 // We need this because we need to reverse the successors in order
9463 // to implement FCMP_OEQ.
9464 if (User->getOpcode() == ISD::BR) {
9465 SDValue FalseBB = User->getOperand(1);
9467 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9468 assert(NewBR == User);
9472 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9473 Chain, Dest, CC, Cmp);
9474 X86::CondCode CCode =
9475 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9476 CCode = X86::GetOppositeBranchCondition(CCode);
9477 CC = DAG.getConstant(CCode, MVT::i8);
9483 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9484 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9485 // It should be transformed during dag combiner except when the condition
9486 // is set by a arithmetics with overflow node.
9487 X86::CondCode CCode =
9488 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9489 CCode = X86::GetOppositeBranchCondition(CCode);
9490 CC = DAG.getConstant(CCode, MVT::i8);
9491 Cond = Cond.getOperand(0).getOperand(1);
9493 } else if (Cond.getOpcode() == ISD::SETCC &&
9494 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9495 // For FCMP_OEQ, we can emit
9496 // two branches instead of an explicit AND instruction with a
9497 // separate test. However, we only do this if this block doesn't
9498 // have a fall-through edge, because this requires an explicit
9499 // jmp when the condition is false.
9500 if (Op.getNode()->hasOneUse()) {
9501 SDNode *User = *Op.getNode()->use_begin();
9502 // Look for an unconditional branch following this conditional branch.
9503 // We need this because we need to reverse the successors in order
9504 // to implement FCMP_OEQ.
9505 if (User->getOpcode() == ISD::BR) {
9506 SDValue FalseBB = User->getOperand(1);
9508 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9509 assert(NewBR == User);
9513 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9514 Cond.getOperand(0), Cond.getOperand(1));
9515 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9516 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9517 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9518 Chain, Dest, CC, Cmp);
9519 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9524 } else if (Cond.getOpcode() == ISD::SETCC &&
9525 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9526 // For FCMP_UNE, we can emit
9527 // two branches instead of an explicit AND instruction with a
9528 // separate test. However, we only do this if this block doesn't
9529 // have a fall-through edge, because this requires an explicit
9530 // jmp when the condition is false.
9531 if (Op.getNode()->hasOneUse()) {
9532 SDNode *User = *Op.getNode()->use_begin();
9533 // Look for an unconditional branch following this conditional branch.
9534 // We need this because we need to reverse the successors in order
9535 // to implement FCMP_UNE.
9536 if (User->getOpcode() == ISD::BR) {
9537 SDValue FalseBB = User->getOperand(1);
9539 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9540 assert(NewBR == User);
9543 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9544 Cond.getOperand(0), Cond.getOperand(1));
9545 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9546 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9547 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9548 Chain, Dest, CC, Cmp);
9549 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9559 // Look pass the truncate if the high bits are known zero.
9560 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9561 Cond = Cond.getOperand(0);
9563 // We know the result of AND is compared against zero. Try to match
9565 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9566 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9567 if (NewSetCC.getNode()) {
9568 CC = NewSetCC.getOperand(0);
9569 Cond = NewSetCC.getOperand(1);
9576 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9577 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9579 Cond = ConvertCmpIfNecessary(Cond, DAG);
9580 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9581 Chain, Dest, CC, Cond);
9585 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9586 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9587 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9588 // that the guard pages used by the OS virtual memory manager are allocated in
9589 // correct sequence.
9591 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9592 SelectionDAG &DAG) const {
9593 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9594 getTargetMachine().Options.EnableSegmentedStacks) &&
9595 "This should be used only on Windows targets or when segmented stacks "
9597 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9598 DebugLoc dl = Op.getDebugLoc();
9601 SDValue Chain = Op.getOperand(0);
9602 SDValue Size = Op.getOperand(1);
9603 // FIXME: Ensure alignment here
9605 bool Is64Bit = Subtarget->is64Bit();
9606 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9608 if (getTargetMachine().Options.EnableSegmentedStacks) {
9609 MachineFunction &MF = DAG.getMachineFunction();
9610 MachineRegisterInfo &MRI = MF.getRegInfo();
9613 // The 64 bit implementation of segmented stacks needs to clobber both r10
9614 // r11. This makes it impossible to use it along with nested parameters.
9615 const Function *F = MF.getFunction();
9617 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9619 if (I->hasNestAttr())
9620 report_fatal_error("Cannot use segmented stacks with functions that "
9621 "have nested arguments.");
9624 const TargetRegisterClass *AddrRegClass =
9625 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9626 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9627 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9628 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9629 DAG.getRegister(Vreg, SPTy));
9630 SDValue Ops1[2] = { Value, Chain };
9631 return DAG.getMergeValues(Ops1, 2, dl);
9634 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9636 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9637 Flag = Chain.getValue(1);
9638 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9640 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9641 Flag = Chain.getValue(1);
9643 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9645 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9646 return DAG.getMergeValues(Ops1, 2, dl);
9650 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9651 MachineFunction &MF = DAG.getMachineFunction();
9652 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9654 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9655 DebugLoc DL = Op.getDebugLoc();
9657 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9658 // vastart just stores the address of the VarArgsFrameIndex slot into the
9659 // memory location argument.
9660 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9662 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9663 MachinePointerInfo(SV), false, false, 0);
9667 // gp_offset (0 - 6 * 8)
9668 // fp_offset (48 - 48 + 8 * 16)
9669 // overflow_arg_area (point to parameters coming in memory).
9671 SmallVector<SDValue, 8> MemOps;
9672 SDValue FIN = Op.getOperand(1);
9674 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9675 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9677 FIN, MachinePointerInfo(SV), false, false, 0);
9678 MemOps.push_back(Store);
9681 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9682 FIN, DAG.getIntPtrConstant(4));
9683 Store = DAG.getStore(Op.getOperand(0), DL,
9684 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9686 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9687 MemOps.push_back(Store);
9689 // Store ptr to overflow_arg_area
9690 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9691 FIN, DAG.getIntPtrConstant(4));
9692 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9694 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9695 MachinePointerInfo(SV, 8),
9697 MemOps.push_back(Store);
9699 // Store ptr to reg_save_area.
9700 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9701 FIN, DAG.getIntPtrConstant(8));
9702 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9704 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9705 MachinePointerInfo(SV, 16), false, false, 0);
9706 MemOps.push_back(Store);
9707 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9708 &MemOps[0], MemOps.size());
9711 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9712 assert(Subtarget->is64Bit() &&
9713 "LowerVAARG only handles 64-bit va_arg!");
9714 assert((Subtarget->isTargetLinux() ||
9715 Subtarget->isTargetDarwin()) &&
9716 "Unhandled target in LowerVAARG");
9717 assert(Op.getNode()->getNumOperands() == 4);
9718 SDValue Chain = Op.getOperand(0);
9719 SDValue SrcPtr = Op.getOperand(1);
9720 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9721 unsigned Align = Op.getConstantOperandVal(3);
9722 DebugLoc dl = Op.getDebugLoc();
9724 EVT ArgVT = Op.getNode()->getValueType(0);
9725 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9726 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9729 // Decide which area this value should be read from.
9730 // TODO: Implement the AMD64 ABI in its entirety. This simple
9731 // selection mechanism works only for the basic types.
9732 if (ArgVT == MVT::f80) {
9733 llvm_unreachable("va_arg for f80 not yet implemented");
9734 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9735 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9736 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9737 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9739 llvm_unreachable("Unhandled argument type in LowerVAARG");
9743 // Sanity Check: Make sure using fp_offset makes sense.
9744 assert(!getTargetMachine().Options.UseSoftFloat &&
9745 !(DAG.getMachineFunction()
9746 .getFunction()->getFnAttributes()
9747 .hasAttribute(Attributes::NoImplicitFloat)) &&
9748 Subtarget->hasSSE1());
9751 // Insert VAARG_64 node into the DAG
9752 // VAARG_64 returns two values: Variable Argument Address, Chain
9753 SmallVector<SDValue, 11> InstOps;
9754 InstOps.push_back(Chain);
9755 InstOps.push_back(SrcPtr);
9756 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9757 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9758 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9759 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9760 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9761 VTs, &InstOps[0], InstOps.size(),
9763 MachinePointerInfo(SV),
9768 Chain = VAARG.getValue(1);
9770 // Load the next argument and return it
9771 return DAG.getLoad(ArgVT, dl,
9774 MachinePointerInfo(),
9775 false, false, false, 0);
9778 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9779 SelectionDAG &DAG) {
9780 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9781 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9782 SDValue Chain = Op.getOperand(0);
9783 SDValue DstPtr = Op.getOperand(1);
9784 SDValue SrcPtr = Op.getOperand(2);
9785 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9786 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9787 DebugLoc DL = Op.getDebugLoc();
9789 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9790 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9792 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9795 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9796 // may or may not be a constant. Takes immediate version of shift as input.
9797 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9798 SDValue SrcOp, SDValue ShAmt,
9799 SelectionDAG &DAG) {
9800 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9802 if (isa<ConstantSDNode>(ShAmt)) {
9803 // Constant may be a TargetConstant. Use a regular constant.
9804 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9806 default: llvm_unreachable("Unknown target vector shift node");
9810 return DAG.getNode(Opc, dl, VT, SrcOp,
9811 DAG.getConstant(ShiftAmt, MVT::i32));
9815 // Change opcode to non-immediate version
9817 default: llvm_unreachable("Unknown target vector shift node");
9818 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9819 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9820 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9823 // Need to build a vector containing shift amount
9824 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9827 ShOps[1] = DAG.getConstant(0, MVT::i32);
9828 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9829 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9831 // The return type has to be a 128-bit type with the same element
9832 // type as the input type.
9833 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9834 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9836 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9837 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9840 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9841 DebugLoc dl = Op.getDebugLoc();
9842 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9844 default: return SDValue(); // Don't custom lower most intrinsics.
9845 // Comparison intrinsics.
9846 case Intrinsic::x86_sse_comieq_ss:
9847 case Intrinsic::x86_sse_comilt_ss:
9848 case Intrinsic::x86_sse_comile_ss:
9849 case Intrinsic::x86_sse_comigt_ss:
9850 case Intrinsic::x86_sse_comige_ss:
9851 case Intrinsic::x86_sse_comineq_ss:
9852 case Intrinsic::x86_sse_ucomieq_ss:
9853 case Intrinsic::x86_sse_ucomilt_ss:
9854 case Intrinsic::x86_sse_ucomile_ss:
9855 case Intrinsic::x86_sse_ucomigt_ss:
9856 case Intrinsic::x86_sse_ucomige_ss:
9857 case Intrinsic::x86_sse_ucomineq_ss:
9858 case Intrinsic::x86_sse2_comieq_sd:
9859 case Intrinsic::x86_sse2_comilt_sd:
9860 case Intrinsic::x86_sse2_comile_sd:
9861 case Intrinsic::x86_sse2_comigt_sd:
9862 case Intrinsic::x86_sse2_comige_sd:
9863 case Intrinsic::x86_sse2_comineq_sd:
9864 case Intrinsic::x86_sse2_ucomieq_sd:
9865 case Intrinsic::x86_sse2_ucomilt_sd:
9866 case Intrinsic::x86_sse2_ucomile_sd:
9867 case Intrinsic::x86_sse2_ucomigt_sd:
9868 case Intrinsic::x86_sse2_ucomige_sd:
9869 case Intrinsic::x86_sse2_ucomineq_sd: {
9873 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9874 case Intrinsic::x86_sse_comieq_ss:
9875 case Intrinsic::x86_sse2_comieq_sd:
9879 case Intrinsic::x86_sse_comilt_ss:
9880 case Intrinsic::x86_sse2_comilt_sd:
9884 case Intrinsic::x86_sse_comile_ss:
9885 case Intrinsic::x86_sse2_comile_sd:
9889 case Intrinsic::x86_sse_comigt_ss:
9890 case Intrinsic::x86_sse2_comigt_sd:
9894 case Intrinsic::x86_sse_comige_ss:
9895 case Intrinsic::x86_sse2_comige_sd:
9899 case Intrinsic::x86_sse_comineq_ss:
9900 case Intrinsic::x86_sse2_comineq_sd:
9904 case Intrinsic::x86_sse_ucomieq_ss:
9905 case Intrinsic::x86_sse2_ucomieq_sd:
9906 Opc = X86ISD::UCOMI;
9909 case Intrinsic::x86_sse_ucomilt_ss:
9910 case Intrinsic::x86_sse2_ucomilt_sd:
9911 Opc = X86ISD::UCOMI;
9914 case Intrinsic::x86_sse_ucomile_ss:
9915 case Intrinsic::x86_sse2_ucomile_sd:
9916 Opc = X86ISD::UCOMI;
9919 case Intrinsic::x86_sse_ucomigt_ss:
9920 case Intrinsic::x86_sse2_ucomigt_sd:
9921 Opc = X86ISD::UCOMI;
9924 case Intrinsic::x86_sse_ucomige_ss:
9925 case Intrinsic::x86_sse2_ucomige_sd:
9926 Opc = X86ISD::UCOMI;
9929 case Intrinsic::x86_sse_ucomineq_ss:
9930 case Intrinsic::x86_sse2_ucomineq_sd:
9931 Opc = X86ISD::UCOMI;
9936 SDValue LHS = Op.getOperand(1);
9937 SDValue RHS = Op.getOperand(2);
9938 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9939 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9940 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9941 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9942 DAG.getConstant(X86CC, MVT::i8), Cond);
9943 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9946 // Arithmetic intrinsics.
9947 case Intrinsic::x86_sse2_pmulu_dq:
9948 case Intrinsic::x86_avx2_pmulu_dq:
9949 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9950 Op.getOperand(1), Op.getOperand(2));
9952 // SSE3/AVX horizontal add/sub intrinsics
9953 case Intrinsic::x86_sse3_hadd_ps:
9954 case Intrinsic::x86_sse3_hadd_pd:
9955 case Intrinsic::x86_avx_hadd_ps_256:
9956 case Intrinsic::x86_avx_hadd_pd_256:
9957 case Intrinsic::x86_sse3_hsub_ps:
9958 case Intrinsic::x86_sse3_hsub_pd:
9959 case Intrinsic::x86_avx_hsub_ps_256:
9960 case Intrinsic::x86_avx_hsub_pd_256:
9961 case Intrinsic::x86_ssse3_phadd_w_128:
9962 case Intrinsic::x86_ssse3_phadd_d_128:
9963 case Intrinsic::x86_avx2_phadd_w:
9964 case Intrinsic::x86_avx2_phadd_d:
9965 case Intrinsic::x86_ssse3_phsub_w_128:
9966 case Intrinsic::x86_ssse3_phsub_d_128:
9967 case Intrinsic::x86_avx2_phsub_w:
9968 case Intrinsic::x86_avx2_phsub_d: {
9971 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9972 case Intrinsic::x86_sse3_hadd_ps:
9973 case Intrinsic::x86_sse3_hadd_pd:
9974 case Intrinsic::x86_avx_hadd_ps_256:
9975 case Intrinsic::x86_avx_hadd_pd_256:
9976 Opcode = X86ISD::FHADD;
9978 case Intrinsic::x86_sse3_hsub_ps:
9979 case Intrinsic::x86_sse3_hsub_pd:
9980 case Intrinsic::x86_avx_hsub_ps_256:
9981 case Intrinsic::x86_avx_hsub_pd_256:
9982 Opcode = X86ISD::FHSUB;
9984 case Intrinsic::x86_ssse3_phadd_w_128:
9985 case Intrinsic::x86_ssse3_phadd_d_128:
9986 case Intrinsic::x86_avx2_phadd_w:
9987 case Intrinsic::x86_avx2_phadd_d:
9988 Opcode = X86ISD::HADD;
9990 case Intrinsic::x86_ssse3_phsub_w_128:
9991 case Intrinsic::x86_ssse3_phsub_d_128:
9992 case Intrinsic::x86_avx2_phsub_w:
9993 case Intrinsic::x86_avx2_phsub_d:
9994 Opcode = X86ISD::HSUB;
9997 return DAG.getNode(Opcode, dl, Op.getValueType(),
9998 Op.getOperand(1), Op.getOperand(2));
10001 // AVX2 variable shift intrinsics
10002 case Intrinsic::x86_avx2_psllv_d:
10003 case Intrinsic::x86_avx2_psllv_q:
10004 case Intrinsic::x86_avx2_psllv_d_256:
10005 case Intrinsic::x86_avx2_psllv_q_256:
10006 case Intrinsic::x86_avx2_psrlv_d:
10007 case Intrinsic::x86_avx2_psrlv_q:
10008 case Intrinsic::x86_avx2_psrlv_d_256:
10009 case Intrinsic::x86_avx2_psrlv_q_256:
10010 case Intrinsic::x86_avx2_psrav_d:
10011 case Intrinsic::x86_avx2_psrav_d_256: {
10014 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10015 case Intrinsic::x86_avx2_psllv_d:
10016 case Intrinsic::x86_avx2_psllv_q:
10017 case Intrinsic::x86_avx2_psllv_d_256:
10018 case Intrinsic::x86_avx2_psllv_q_256:
10021 case Intrinsic::x86_avx2_psrlv_d:
10022 case Intrinsic::x86_avx2_psrlv_q:
10023 case Intrinsic::x86_avx2_psrlv_d_256:
10024 case Intrinsic::x86_avx2_psrlv_q_256:
10027 case Intrinsic::x86_avx2_psrav_d:
10028 case Intrinsic::x86_avx2_psrav_d_256:
10032 return DAG.getNode(Opcode, dl, Op.getValueType(),
10033 Op.getOperand(1), Op.getOperand(2));
10036 case Intrinsic::x86_ssse3_pshuf_b_128:
10037 case Intrinsic::x86_avx2_pshuf_b:
10038 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10039 Op.getOperand(1), Op.getOperand(2));
10041 case Intrinsic::x86_ssse3_psign_b_128:
10042 case Intrinsic::x86_ssse3_psign_w_128:
10043 case Intrinsic::x86_ssse3_psign_d_128:
10044 case Intrinsic::x86_avx2_psign_b:
10045 case Intrinsic::x86_avx2_psign_w:
10046 case Intrinsic::x86_avx2_psign_d:
10047 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10048 Op.getOperand(1), Op.getOperand(2));
10050 case Intrinsic::x86_sse41_insertps:
10051 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10052 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10054 case Intrinsic::x86_avx_vperm2f128_ps_256:
10055 case Intrinsic::x86_avx_vperm2f128_pd_256:
10056 case Intrinsic::x86_avx_vperm2f128_si_256:
10057 case Intrinsic::x86_avx2_vperm2i128:
10058 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10059 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10061 case Intrinsic::x86_avx2_permd:
10062 case Intrinsic::x86_avx2_permps:
10063 // Operands intentionally swapped. Mask is last operand to intrinsic,
10064 // but second operand for node/intruction.
10065 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10066 Op.getOperand(2), Op.getOperand(1));
10068 // ptest and testp intrinsics. The intrinsic these come from are designed to
10069 // return an integer value, not just an instruction so lower it to the ptest
10070 // or testp pattern and a setcc for the result.
10071 case Intrinsic::x86_sse41_ptestz:
10072 case Intrinsic::x86_sse41_ptestc:
10073 case Intrinsic::x86_sse41_ptestnzc:
10074 case Intrinsic::x86_avx_ptestz_256:
10075 case Intrinsic::x86_avx_ptestc_256:
10076 case Intrinsic::x86_avx_ptestnzc_256:
10077 case Intrinsic::x86_avx_vtestz_ps:
10078 case Intrinsic::x86_avx_vtestc_ps:
10079 case Intrinsic::x86_avx_vtestnzc_ps:
10080 case Intrinsic::x86_avx_vtestz_pd:
10081 case Intrinsic::x86_avx_vtestc_pd:
10082 case Intrinsic::x86_avx_vtestnzc_pd:
10083 case Intrinsic::x86_avx_vtestz_ps_256:
10084 case Intrinsic::x86_avx_vtestc_ps_256:
10085 case Intrinsic::x86_avx_vtestnzc_ps_256:
10086 case Intrinsic::x86_avx_vtestz_pd_256:
10087 case Intrinsic::x86_avx_vtestc_pd_256:
10088 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10089 bool IsTestPacked = false;
10092 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10093 case Intrinsic::x86_avx_vtestz_ps:
10094 case Intrinsic::x86_avx_vtestz_pd:
10095 case Intrinsic::x86_avx_vtestz_ps_256:
10096 case Intrinsic::x86_avx_vtestz_pd_256:
10097 IsTestPacked = true; // Fallthrough
10098 case Intrinsic::x86_sse41_ptestz:
10099 case Intrinsic::x86_avx_ptestz_256:
10101 X86CC = X86::COND_E;
10103 case Intrinsic::x86_avx_vtestc_ps:
10104 case Intrinsic::x86_avx_vtestc_pd:
10105 case Intrinsic::x86_avx_vtestc_ps_256:
10106 case Intrinsic::x86_avx_vtestc_pd_256:
10107 IsTestPacked = true; // Fallthrough
10108 case Intrinsic::x86_sse41_ptestc:
10109 case Intrinsic::x86_avx_ptestc_256:
10111 X86CC = X86::COND_B;
10113 case Intrinsic::x86_avx_vtestnzc_ps:
10114 case Intrinsic::x86_avx_vtestnzc_pd:
10115 case Intrinsic::x86_avx_vtestnzc_ps_256:
10116 case Intrinsic::x86_avx_vtestnzc_pd_256:
10117 IsTestPacked = true; // Fallthrough
10118 case Intrinsic::x86_sse41_ptestnzc:
10119 case Intrinsic::x86_avx_ptestnzc_256:
10121 X86CC = X86::COND_A;
10125 SDValue LHS = Op.getOperand(1);
10126 SDValue RHS = Op.getOperand(2);
10127 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10128 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10129 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10130 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10131 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10134 // SSE/AVX shift intrinsics
10135 case Intrinsic::x86_sse2_psll_w:
10136 case Intrinsic::x86_sse2_psll_d:
10137 case Intrinsic::x86_sse2_psll_q:
10138 case Intrinsic::x86_avx2_psll_w:
10139 case Intrinsic::x86_avx2_psll_d:
10140 case Intrinsic::x86_avx2_psll_q:
10141 case Intrinsic::x86_sse2_psrl_w:
10142 case Intrinsic::x86_sse2_psrl_d:
10143 case Intrinsic::x86_sse2_psrl_q:
10144 case Intrinsic::x86_avx2_psrl_w:
10145 case Intrinsic::x86_avx2_psrl_d:
10146 case Intrinsic::x86_avx2_psrl_q:
10147 case Intrinsic::x86_sse2_psra_w:
10148 case Intrinsic::x86_sse2_psra_d:
10149 case Intrinsic::x86_avx2_psra_w:
10150 case Intrinsic::x86_avx2_psra_d: {
10153 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10154 case Intrinsic::x86_sse2_psll_w:
10155 case Intrinsic::x86_sse2_psll_d:
10156 case Intrinsic::x86_sse2_psll_q:
10157 case Intrinsic::x86_avx2_psll_w:
10158 case Intrinsic::x86_avx2_psll_d:
10159 case Intrinsic::x86_avx2_psll_q:
10160 Opcode = X86ISD::VSHL;
10162 case Intrinsic::x86_sse2_psrl_w:
10163 case Intrinsic::x86_sse2_psrl_d:
10164 case Intrinsic::x86_sse2_psrl_q:
10165 case Intrinsic::x86_avx2_psrl_w:
10166 case Intrinsic::x86_avx2_psrl_d:
10167 case Intrinsic::x86_avx2_psrl_q:
10168 Opcode = X86ISD::VSRL;
10170 case Intrinsic::x86_sse2_psra_w:
10171 case Intrinsic::x86_sse2_psra_d:
10172 case Intrinsic::x86_avx2_psra_w:
10173 case Intrinsic::x86_avx2_psra_d:
10174 Opcode = X86ISD::VSRA;
10177 return DAG.getNode(Opcode, dl, Op.getValueType(),
10178 Op.getOperand(1), Op.getOperand(2));
10181 // SSE/AVX immediate shift intrinsics
10182 case Intrinsic::x86_sse2_pslli_w:
10183 case Intrinsic::x86_sse2_pslli_d:
10184 case Intrinsic::x86_sse2_pslli_q:
10185 case Intrinsic::x86_avx2_pslli_w:
10186 case Intrinsic::x86_avx2_pslli_d:
10187 case Intrinsic::x86_avx2_pslli_q:
10188 case Intrinsic::x86_sse2_psrli_w:
10189 case Intrinsic::x86_sse2_psrli_d:
10190 case Intrinsic::x86_sse2_psrli_q:
10191 case Intrinsic::x86_avx2_psrli_w:
10192 case Intrinsic::x86_avx2_psrli_d:
10193 case Intrinsic::x86_avx2_psrli_q:
10194 case Intrinsic::x86_sse2_psrai_w:
10195 case Intrinsic::x86_sse2_psrai_d:
10196 case Intrinsic::x86_avx2_psrai_w:
10197 case Intrinsic::x86_avx2_psrai_d: {
10200 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10201 case Intrinsic::x86_sse2_pslli_w:
10202 case Intrinsic::x86_sse2_pslli_d:
10203 case Intrinsic::x86_sse2_pslli_q:
10204 case Intrinsic::x86_avx2_pslli_w:
10205 case Intrinsic::x86_avx2_pslli_d:
10206 case Intrinsic::x86_avx2_pslli_q:
10207 Opcode = X86ISD::VSHLI;
10209 case Intrinsic::x86_sse2_psrli_w:
10210 case Intrinsic::x86_sse2_psrli_d:
10211 case Intrinsic::x86_sse2_psrli_q:
10212 case Intrinsic::x86_avx2_psrli_w:
10213 case Intrinsic::x86_avx2_psrli_d:
10214 case Intrinsic::x86_avx2_psrli_q:
10215 Opcode = X86ISD::VSRLI;
10217 case Intrinsic::x86_sse2_psrai_w:
10218 case Intrinsic::x86_sse2_psrai_d:
10219 case Intrinsic::x86_avx2_psrai_w:
10220 case Intrinsic::x86_avx2_psrai_d:
10221 Opcode = X86ISD::VSRAI;
10224 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10225 Op.getOperand(1), Op.getOperand(2), DAG);
10228 case Intrinsic::x86_sse42_pcmpistria128:
10229 case Intrinsic::x86_sse42_pcmpestria128:
10230 case Intrinsic::x86_sse42_pcmpistric128:
10231 case Intrinsic::x86_sse42_pcmpestric128:
10232 case Intrinsic::x86_sse42_pcmpistrio128:
10233 case Intrinsic::x86_sse42_pcmpestrio128:
10234 case Intrinsic::x86_sse42_pcmpistris128:
10235 case Intrinsic::x86_sse42_pcmpestris128:
10236 case Intrinsic::x86_sse42_pcmpistriz128:
10237 case Intrinsic::x86_sse42_pcmpestriz128: {
10241 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10242 case Intrinsic::x86_sse42_pcmpistria128:
10243 Opcode = X86ISD::PCMPISTRI;
10244 X86CC = X86::COND_A;
10246 case Intrinsic::x86_sse42_pcmpestria128:
10247 Opcode = X86ISD::PCMPESTRI;
10248 X86CC = X86::COND_A;
10250 case Intrinsic::x86_sse42_pcmpistric128:
10251 Opcode = X86ISD::PCMPISTRI;
10252 X86CC = X86::COND_B;
10254 case Intrinsic::x86_sse42_pcmpestric128:
10255 Opcode = X86ISD::PCMPESTRI;
10256 X86CC = X86::COND_B;
10258 case Intrinsic::x86_sse42_pcmpistrio128:
10259 Opcode = X86ISD::PCMPISTRI;
10260 X86CC = X86::COND_O;
10262 case Intrinsic::x86_sse42_pcmpestrio128:
10263 Opcode = X86ISD::PCMPESTRI;
10264 X86CC = X86::COND_O;
10266 case Intrinsic::x86_sse42_pcmpistris128:
10267 Opcode = X86ISD::PCMPISTRI;
10268 X86CC = X86::COND_S;
10270 case Intrinsic::x86_sse42_pcmpestris128:
10271 Opcode = X86ISD::PCMPESTRI;
10272 X86CC = X86::COND_S;
10274 case Intrinsic::x86_sse42_pcmpistriz128:
10275 Opcode = X86ISD::PCMPISTRI;
10276 X86CC = X86::COND_E;
10278 case Intrinsic::x86_sse42_pcmpestriz128:
10279 Opcode = X86ISD::PCMPESTRI;
10280 X86CC = X86::COND_E;
10283 SmallVector<SDValue, 5> NewOps;
10284 NewOps.append(Op->op_begin()+1, Op->op_end());
10285 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10286 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10287 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10288 DAG.getConstant(X86CC, MVT::i8),
10289 SDValue(PCMP.getNode(), 1));
10290 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10293 case Intrinsic::x86_sse42_pcmpistri128:
10294 case Intrinsic::x86_sse42_pcmpestri128: {
10296 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10297 Opcode = X86ISD::PCMPISTRI;
10299 Opcode = X86ISD::PCMPESTRI;
10301 SmallVector<SDValue, 5> NewOps;
10302 NewOps.append(Op->op_begin()+1, Op->op_end());
10303 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10304 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10306 case Intrinsic::x86_fma_vfmadd_ps:
10307 case Intrinsic::x86_fma_vfmadd_pd:
10308 case Intrinsic::x86_fma_vfmsub_ps:
10309 case Intrinsic::x86_fma_vfmsub_pd:
10310 case Intrinsic::x86_fma_vfnmadd_ps:
10311 case Intrinsic::x86_fma_vfnmadd_pd:
10312 case Intrinsic::x86_fma_vfnmsub_ps:
10313 case Intrinsic::x86_fma_vfnmsub_pd:
10314 case Intrinsic::x86_fma_vfmaddsub_ps:
10315 case Intrinsic::x86_fma_vfmaddsub_pd:
10316 case Intrinsic::x86_fma_vfmsubadd_ps:
10317 case Intrinsic::x86_fma_vfmsubadd_pd:
10318 case Intrinsic::x86_fma_vfmadd_ps_256:
10319 case Intrinsic::x86_fma_vfmadd_pd_256:
10320 case Intrinsic::x86_fma_vfmsub_ps_256:
10321 case Intrinsic::x86_fma_vfmsub_pd_256:
10322 case Intrinsic::x86_fma_vfnmadd_ps_256:
10323 case Intrinsic::x86_fma_vfnmadd_pd_256:
10324 case Intrinsic::x86_fma_vfnmsub_ps_256:
10325 case Intrinsic::x86_fma_vfnmsub_pd_256:
10326 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10327 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10328 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10329 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10332 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10333 case Intrinsic::x86_fma_vfmadd_ps:
10334 case Intrinsic::x86_fma_vfmadd_pd:
10335 case Intrinsic::x86_fma_vfmadd_ps_256:
10336 case Intrinsic::x86_fma_vfmadd_pd_256:
10337 Opc = X86ISD::FMADD;
10339 case Intrinsic::x86_fma_vfmsub_ps:
10340 case Intrinsic::x86_fma_vfmsub_pd:
10341 case Intrinsic::x86_fma_vfmsub_ps_256:
10342 case Intrinsic::x86_fma_vfmsub_pd_256:
10343 Opc = X86ISD::FMSUB;
10345 case Intrinsic::x86_fma_vfnmadd_ps:
10346 case Intrinsic::x86_fma_vfnmadd_pd:
10347 case Intrinsic::x86_fma_vfnmadd_ps_256:
10348 case Intrinsic::x86_fma_vfnmadd_pd_256:
10349 Opc = X86ISD::FNMADD;
10351 case Intrinsic::x86_fma_vfnmsub_ps:
10352 case Intrinsic::x86_fma_vfnmsub_pd:
10353 case Intrinsic::x86_fma_vfnmsub_ps_256:
10354 case Intrinsic::x86_fma_vfnmsub_pd_256:
10355 Opc = X86ISD::FNMSUB;
10357 case Intrinsic::x86_fma_vfmaddsub_ps:
10358 case Intrinsic::x86_fma_vfmaddsub_pd:
10359 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10360 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10361 Opc = X86ISD::FMADDSUB;
10363 case Intrinsic::x86_fma_vfmsubadd_ps:
10364 case Intrinsic::x86_fma_vfmsubadd_pd:
10365 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10366 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10367 Opc = X86ISD::FMSUBADD;
10371 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10372 Op.getOperand(2), Op.getOperand(3));
10377 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10378 DebugLoc dl = Op.getDebugLoc();
10379 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10381 default: return SDValue(); // Don't custom lower most intrinsics.
10383 // RDRAND intrinsics.
10384 case Intrinsic::x86_rdrand_16:
10385 case Intrinsic::x86_rdrand_32:
10386 case Intrinsic::x86_rdrand_64: {
10387 // Emit the node with the right value type.
10388 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10389 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10391 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10392 // return the value from Rand, which is always 0, casted to i32.
10393 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10394 DAG.getConstant(1, Op->getValueType(1)),
10395 DAG.getConstant(X86::COND_B, MVT::i32),
10396 SDValue(Result.getNode(), 1) };
10397 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10398 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10401 // Return { result, isValid, chain }.
10402 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10403 SDValue(Result.getNode(), 2));
10408 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10409 SelectionDAG &DAG) const {
10410 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10411 MFI->setReturnAddressIsTaken(true);
10413 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10414 DebugLoc dl = Op.getDebugLoc();
10417 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10419 DAG.getConstant(TD->getPointerSize(0),
10420 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10421 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10422 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10423 FrameAddr, Offset),
10424 MachinePointerInfo(), false, false, false, 0);
10427 // Just load the return address.
10428 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10429 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10430 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10433 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10434 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10435 MFI->setFrameAddressIsTaken(true);
10437 EVT VT = Op.getValueType();
10438 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10439 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10440 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10441 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10443 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10444 MachinePointerInfo(),
10445 false, false, false, 0);
10449 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10450 SelectionDAG &DAG) const {
10451 return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10454 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10455 SDValue Chain = Op.getOperand(0);
10456 SDValue Offset = Op.getOperand(1);
10457 SDValue Handler = Op.getOperand(2);
10458 DebugLoc dl = Op.getDebugLoc();
10460 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10461 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10463 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10465 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10466 DAG.getIntPtrConstant(TD->getPointerSize(0)));
10467 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10468 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10470 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10472 return DAG.getNode(X86ISD::EH_RETURN, dl,
10474 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10477 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10478 SelectionDAG &DAG) const {
10479 DebugLoc DL = Op.getDebugLoc();
10480 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10481 DAG.getVTList(MVT::i32, MVT::Other),
10482 Op.getOperand(0), Op.getOperand(1));
10485 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10486 SelectionDAG &DAG) const {
10487 DebugLoc DL = Op.getDebugLoc();
10488 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10489 Op.getOperand(0), Op.getOperand(1));
10492 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10493 return Op.getOperand(0);
10496 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10497 SelectionDAG &DAG) const {
10498 SDValue Root = Op.getOperand(0);
10499 SDValue Trmp = Op.getOperand(1); // trampoline
10500 SDValue FPtr = Op.getOperand(2); // nested function
10501 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10502 DebugLoc dl = Op.getDebugLoc();
10504 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10505 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10507 if (Subtarget->is64Bit()) {
10508 SDValue OutChains[6];
10510 // Large code-model.
10511 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10512 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10514 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10515 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10517 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10519 // Load the pointer to the nested function into R11.
10520 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10521 SDValue Addr = Trmp;
10522 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10523 Addr, MachinePointerInfo(TrmpAddr),
10526 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10527 DAG.getConstant(2, MVT::i64));
10528 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10529 MachinePointerInfo(TrmpAddr, 2),
10532 // Load the 'nest' parameter value into R10.
10533 // R10 is specified in X86CallingConv.td
10534 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10535 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10536 DAG.getConstant(10, MVT::i64));
10537 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10538 Addr, MachinePointerInfo(TrmpAddr, 10),
10541 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10542 DAG.getConstant(12, MVT::i64));
10543 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10544 MachinePointerInfo(TrmpAddr, 12),
10547 // Jump to the nested function.
10548 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10549 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10550 DAG.getConstant(20, MVT::i64));
10551 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10552 Addr, MachinePointerInfo(TrmpAddr, 20),
10555 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10557 DAG.getConstant(22, MVT::i64));
10558 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10559 MachinePointerInfo(TrmpAddr, 22),
10562 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10564 const Function *Func =
10565 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10566 CallingConv::ID CC = Func->getCallingConv();
10571 llvm_unreachable("Unsupported calling convention");
10572 case CallingConv::C:
10573 case CallingConv::X86_StdCall: {
10574 // Pass 'nest' parameter in ECX.
10575 // Must be kept in sync with X86CallingConv.td
10576 NestReg = X86::ECX;
10578 // Check that ECX wasn't needed by an 'inreg' parameter.
10579 FunctionType *FTy = Func->getFunctionType();
10580 const AttrListPtr &Attrs = Func->getAttributes();
10582 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10583 unsigned InRegCount = 0;
10586 for (FunctionType::param_iterator I = FTy->param_begin(),
10587 E = FTy->param_end(); I != E; ++I, ++Idx)
10588 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10589 // FIXME: should only count parameters that are lowered to integers.
10590 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10592 if (InRegCount > 2) {
10593 report_fatal_error("Nest register in use - reduce number of inreg"
10599 case CallingConv::X86_FastCall:
10600 case CallingConv::X86_ThisCall:
10601 case CallingConv::Fast:
10602 // Pass 'nest' parameter in EAX.
10603 // Must be kept in sync with X86CallingConv.td
10604 NestReg = X86::EAX;
10608 SDValue OutChains[4];
10609 SDValue Addr, Disp;
10611 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10612 DAG.getConstant(10, MVT::i32));
10613 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10615 // This is storing the opcode for MOV32ri.
10616 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10617 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10618 OutChains[0] = DAG.getStore(Root, dl,
10619 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10620 Trmp, MachinePointerInfo(TrmpAddr),
10623 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10624 DAG.getConstant(1, MVT::i32));
10625 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10626 MachinePointerInfo(TrmpAddr, 1),
10629 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10630 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10631 DAG.getConstant(5, MVT::i32));
10632 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10633 MachinePointerInfo(TrmpAddr, 5),
10636 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10637 DAG.getConstant(6, MVT::i32));
10638 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10639 MachinePointerInfo(TrmpAddr, 6),
10642 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10646 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10647 SelectionDAG &DAG) const {
10649 The rounding mode is in bits 11:10 of FPSR, and has the following
10651 00 Round to nearest
10656 FLT_ROUNDS, on the other hand, expects the following:
10663 To perform the conversion, we do:
10664 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10667 MachineFunction &MF = DAG.getMachineFunction();
10668 const TargetMachine &TM = MF.getTarget();
10669 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10670 unsigned StackAlignment = TFI.getStackAlignment();
10671 EVT VT = Op.getValueType();
10672 DebugLoc DL = Op.getDebugLoc();
10674 // Save FP Control Word to stack slot
10675 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10676 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10679 MachineMemOperand *MMO =
10680 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10681 MachineMemOperand::MOStore, 2, 2);
10683 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10684 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10685 DAG.getVTList(MVT::Other),
10686 Ops, 2, MVT::i16, MMO);
10688 // Load FP Control Word from stack slot
10689 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10690 MachinePointerInfo(), false, false, false, 0);
10692 // Transform as necessary
10694 DAG.getNode(ISD::SRL, DL, MVT::i16,
10695 DAG.getNode(ISD::AND, DL, MVT::i16,
10696 CWD, DAG.getConstant(0x800, MVT::i16)),
10697 DAG.getConstant(11, MVT::i8));
10699 DAG.getNode(ISD::SRL, DL, MVT::i16,
10700 DAG.getNode(ISD::AND, DL, MVT::i16,
10701 CWD, DAG.getConstant(0x400, MVT::i16)),
10702 DAG.getConstant(9, MVT::i8));
10705 DAG.getNode(ISD::AND, DL, MVT::i16,
10706 DAG.getNode(ISD::ADD, DL, MVT::i16,
10707 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10708 DAG.getConstant(1, MVT::i16)),
10709 DAG.getConstant(3, MVT::i16));
10712 return DAG.getNode((VT.getSizeInBits() < 16 ?
10713 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10716 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10717 EVT VT = Op.getValueType();
10719 unsigned NumBits = VT.getSizeInBits();
10720 DebugLoc dl = Op.getDebugLoc();
10722 Op = Op.getOperand(0);
10723 if (VT == MVT::i8) {
10724 // Zero extend to i32 since there is not an i8 bsr.
10726 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10729 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10730 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10731 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10733 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10736 DAG.getConstant(NumBits+NumBits-1, OpVT),
10737 DAG.getConstant(X86::COND_E, MVT::i8),
10740 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10742 // Finally xor with NumBits-1.
10743 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10746 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10750 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10751 EVT VT = Op.getValueType();
10753 unsigned NumBits = VT.getSizeInBits();
10754 DebugLoc dl = Op.getDebugLoc();
10756 Op = Op.getOperand(0);
10757 if (VT == MVT::i8) {
10758 // Zero extend to i32 since there is not an i8 bsr.
10760 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10763 // Issue a bsr (scan bits in reverse).
10764 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10765 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10767 // And xor with NumBits-1.
10768 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10771 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10775 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10776 EVT VT = Op.getValueType();
10777 unsigned NumBits = VT.getSizeInBits();
10778 DebugLoc dl = Op.getDebugLoc();
10779 Op = Op.getOperand(0);
10781 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10782 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10783 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10785 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10788 DAG.getConstant(NumBits, VT),
10789 DAG.getConstant(X86::COND_E, MVT::i8),
10792 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10795 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10796 // ones, and then concatenate the result back.
10797 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10798 EVT VT = Op.getValueType();
10800 assert(VT.is256BitVector() && VT.isInteger() &&
10801 "Unsupported value type for operation");
10803 unsigned NumElems = VT.getVectorNumElements();
10804 DebugLoc dl = Op.getDebugLoc();
10806 // Extract the LHS vectors
10807 SDValue LHS = Op.getOperand(0);
10808 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10809 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10811 // Extract the RHS vectors
10812 SDValue RHS = Op.getOperand(1);
10813 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10814 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10816 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10817 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10819 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10820 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10821 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10824 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10825 assert(Op.getValueType().is256BitVector() &&
10826 Op.getValueType().isInteger() &&
10827 "Only handle AVX 256-bit vector integer operation");
10828 return Lower256IntArith(Op, DAG);
10831 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10832 assert(Op.getValueType().is256BitVector() &&
10833 Op.getValueType().isInteger() &&
10834 "Only handle AVX 256-bit vector integer operation");
10835 return Lower256IntArith(Op, DAG);
10838 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10839 SelectionDAG &DAG) {
10840 EVT VT = Op.getValueType();
10842 // Decompose 256-bit ops into smaller 128-bit ops.
10843 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10844 return Lower256IntArith(Op, DAG);
10846 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10847 "Only know how to lower V2I64/V4I64 multiply");
10849 DebugLoc dl = Op.getDebugLoc();
10851 // Ahi = psrlqi(a, 32);
10852 // Bhi = psrlqi(b, 32);
10854 // AloBlo = pmuludq(a, b);
10855 // AloBhi = pmuludq(a, Bhi);
10856 // AhiBlo = pmuludq(Ahi, b);
10858 // AloBhi = psllqi(AloBhi, 32);
10859 // AhiBlo = psllqi(AhiBlo, 32);
10860 // return AloBlo + AloBhi + AhiBlo;
10862 SDValue A = Op.getOperand(0);
10863 SDValue B = Op.getOperand(1);
10865 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10867 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10868 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10870 // Bit cast to 32-bit vectors for MULUDQ
10871 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10872 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10873 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10874 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10875 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10877 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10878 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10879 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10881 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10882 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10884 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10885 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10888 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10890 EVT VT = Op.getValueType();
10891 DebugLoc dl = Op.getDebugLoc();
10892 SDValue R = Op.getOperand(0);
10893 SDValue Amt = Op.getOperand(1);
10894 LLVMContext *Context = DAG.getContext();
10896 if (!Subtarget->hasSSE2())
10899 // Optimize shl/srl/sra with constant shift amount.
10900 if (isSplatVector(Amt.getNode())) {
10901 SDValue SclrAmt = Amt->getOperand(0);
10902 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10903 uint64_t ShiftAmt = C->getZExtValue();
10905 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10906 (Subtarget->hasAVX2() &&
10907 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10908 if (Op.getOpcode() == ISD::SHL)
10909 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10910 DAG.getConstant(ShiftAmt, MVT::i32));
10911 if (Op.getOpcode() == ISD::SRL)
10912 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10913 DAG.getConstant(ShiftAmt, MVT::i32));
10914 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10915 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10916 DAG.getConstant(ShiftAmt, MVT::i32));
10919 if (VT == MVT::v16i8) {
10920 if (Op.getOpcode() == ISD::SHL) {
10921 // Make a large shift.
10922 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10923 DAG.getConstant(ShiftAmt, MVT::i32));
10924 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10925 // Zero out the rightmost bits.
10926 SmallVector<SDValue, 16> V(16,
10927 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10929 return DAG.getNode(ISD::AND, dl, VT, SHL,
10930 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10932 if (Op.getOpcode() == ISD::SRL) {
10933 // Make a large shift.
10934 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10935 DAG.getConstant(ShiftAmt, MVT::i32));
10936 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10937 // Zero out the leftmost bits.
10938 SmallVector<SDValue, 16> V(16,
10939 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10941 return DAG.getNode(ISD::AND, dl, VT, SRL,
10942 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10944 if (Op.getOpcode() == ISD::SRA) {
10945 if (ShiftAmt == 7) {
10946 // R s>> 7 === R s< 0
10947 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10948 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10951 // R s>> a === ((R u>> a) ^ m) - m
10952 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10953 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10955 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10956 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10957 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10960 llvm_unreachable("Unknown shift opcode.");
10963 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10964 if (Op.getOpcode() == ISD::SHL) {
10965 // Make a large shift.
10966 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10967 DAG.getConstant(ShiftAmt, MVT::i32));
10968 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10969 // Zero out the rightmost bits.
10970 SmallVector<SDValue, 32> V(32,
10971 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10973 return DAG.getNode(ISD::AND, dl, VT, SHL,
10974 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10976 if (Op.getOpcode() == ISD::SRL) {
10977 // Make a large shift.
10978 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10979 DAG.getConstant(ShiftAmt, MVT::i32));
10980 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10981 // Zero out the leftmost bits.
10982 SmallVector<SDValue, 32> V(32,
10983 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10985 return DAG.getNode(ISD::AND, dl, VT, SRL,
10986 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10988 if (Op.getOpcode() == ISD::SRA) {
10989 if (ShiftAmt == 7) {
10990 // R s>> 7 === R s< 0
10991 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10992 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10995 // R s>> a === ((R u>> a) ^ m) - m
10996 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10997 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10999 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11000 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11001 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11004 llvm_unreachable("Unknown shift opcode.");
11009 // Lower SHL with variable shift amount.
11010 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11011 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11012 DAG.getConstant(23, MVT::i32));
11014 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11015 Constant *C = ConstantDataVector::get(*Context, CV);
11016 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11017 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11018 MachinePointerInfo::getConstantPool(),
11019 false, false, false, 16);
11021 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11022 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11023 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11024 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11026 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11027 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11030 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11031 DAG.getConstant(5, MVT::i32));
11032 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11034 // Turn 'a' into a mask suitable for VSELECT
11035 SDValue VSelM = DAG.getConstant(0x80, VT);
11036 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11037 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11039 SDValue CM1 = DAG.getConstant(0x0f, VT);
11040 SDValue CM2 = DAG.getConstant(0x3f, VT);
11042 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11043 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11044 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11045 DAG.getConstant(4, MVT::i32), DAG);
11046 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11047 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11050 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11051 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11052 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11054 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11055 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11056 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11057 DAG.getConstant(2, MVT::i32), DAG);
11058 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11059 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11062 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11063 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11064 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11066 // return VSELECT(r, r+r, a);
11067 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11068 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11072 // Decompose 256-bit shifts into smaller 128-bit shifts.
11073 if (VT.is256BitVector()) {
11074 unsigned NumElems = VT.getVectorNumElements();
11075 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11076 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11078 // Extract the two vectors
11079 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11080 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11082 // Recreate the shift amount vectors
11083 SDValue Amt1, Amt2;
11084 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11085 // Constant shift amount
11086 SmallVector<SDValue, 4> Amt1Csts;
11087 SmallVector<SDValue, 4> Amt2Csts;
11088 for (unsigned i = 0; i != NumElems/2; ++i)
11089 Amt1Csts.push_back(Amt->getOperand(i));
11090 for (unsigned i = NumElems/2; i != NumElems; ++i)
11091 Amt2Csts.push_back(Amt->getOperand(i));
11093 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11094 &Amt1Csts[0], NumElems/2);
11095 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11096 &Amt2Csts[0], NumElems/2);
11098 // Variable shift amount
11099 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11100 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11103 // Issue new vector shifts for the smaller types
11104 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11105 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11107 // Concatenate the result back
11108 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11114 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11115 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11116 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11117 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11118 // has only one use.
11119 SDNode *N = Op.getNode();
11120 SDValue LHS = N->getOperand(0);
11121 SDValue RHS = N->getOperand(1);
11122 unsigned BaseOp = 0;
11124 DebugLoc DL = Op.getDebugLoc();
11125 switch (Op.getOpcode()) {
11126 default: llvm_unreachable("Unknown ovf instruction!");
11128 // A subtract of one will be selected as a INC. Note that INC doesn't
11129 // set CF, so we can't do this for UADDO.
11130 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11132 BaseOp = X86ISD::INC;
11133 Cond = X86::COND_O;
11136 BaseOp = X86ISD::ADD;
11137 Cond = X86::COND_O;
11140 BaseOp = X86ISD::ADD;
11141 Cond = X86::COND_B;
11144 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11145 // set CF, so we can't do this for USUBO.
11146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11148 BaseOp = X86ISD::DEC;
11149 Cond = X86::COND_O;
11152 BaseOp = X86ISD::SUB;
11153 Cond = X86::COND_O;
11156 BaseOp = X86ISD::SUB;
11157 Cond = X86::COND_B;
11160 BaseOp = X86ISD::SMUL;
11161 Cond = X86::COND_O;
11163 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11164 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11166 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11169 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11170 DAG.getConstant(X86::COND_O, MVT::i32),
11171 SDValue(Sum.getNode(), 2));
11173 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11177 // Also sets EFLAGS.
11178 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11179 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11182 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11183 DAG.getConstant(Cond, MVT::i32),
11184 SDValue(Sum.getNode(), 1));
11186 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11189 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11190 SelectionDAG &DAG) const {
11191 DebugLoc dl = Op.getDebugLoc();
11192 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11193 EVT VT = Op.getValueType();
11195 if (!Subtarget->hasSSE2() || !VT.isVector())
11198 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11199 ExtraVT.getScalarType().getSizeInBits();
11200 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11202 switch (VT.getSimpleVT().SimpleTy) {
11203 default: return SDValue();
11206 if (!Subtarget->hasAVX())
11208 if (!Subtarget->hasAVX2()) {
11209 // needs to be split
11210 unsigned NumElems = VT.getVectorNumElements();
11212 // Extract the LHS vectors
11213 SDValue LHS = Op.getOperand(0);
11214 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11215 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11217 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11218 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11220 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11221 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11222 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11224 SDValue Extra = DAG.getValueType(ExtraVT);
11226 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11227 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11229 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11234 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11235 Op.getOperand(0), ShAmt, DAG);
11236 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11242 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11243 SelectionDAG &DAG) {
11244 DebugLoc dl = Op.getDebugLoc();
11246 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11247 // There isn't any reason to disable it if the target processor supports it.
11248 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11249 SDValue Chain = Op.getOperand(0);
11250 SDValue Zero = DAG.getConstant(0, MVT::i32);
11252 DAG.getRegister(X86::ESP, MVT::i32), // Base
11253 DAG.getTargetConstant(1, MVT::i8), // Scale
11254 DAG.getRegister(0, MVT::i32), // Index
11255 DAG.getTargetConstant(0, MVT::i32), // Disp
11256 DAG.getRegister(0, MVT::i32), // Segment.
11261 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11262 array_lengthof(Ops));
11263 return SDValue(Res, 0);
11266 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11268 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11270 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11271 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11272 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11273 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11275 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11276 if (!Op1 && !Op2 && !Op3 && Op4)
11277 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11279 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11280 if (Op1 && !Op2 && !Op3 && !Op4)
11281 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11283 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11285 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11288 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11289 SelectionDAG &DAG) {
11290 DebugLoc dl = Op.getDebugLoc();
11291 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11292 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11293 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11294 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11296 // The only fence that needs an instruction is a sequentially-consistent
11297 // cross-thread fence.
11298 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11299 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11300 // no-sse2). There isn't any reason to disable it if the target processor
11302 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11303 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11305 SDValue Chain = Op.getOperand(0);
11306 SDValue Zero = DAG.getConstant(0, MVT::i32);
11308 DAG.getRegister(X86::ESP, MVT::i32), // Base
11309 DAG.getTargetConstant(1, MVT::i8), // Scale
11310 DAG.getRegister(0, MVT::i32), // Index
11311 DAG.getTargetConstant(0, MVT::i32), // Disp
11312 DAG.getRegister(0, MVT::i32), // Segment.
11317 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11318 array_lengthof(Ops));
11319 return SDValue(Res, 0);
11322 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11323 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11327 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11328 SelectionDAG &DAG) {
11329 EVT T = Op.getValueType();
11330 DebugLoc DL = Op.getDebugLoc();
11333 switch(T.getSimpleVT().SimpleTy) {
11334 default: llvm_unreachable("Invalid value type!");
11335 case MVT::i8: Reg = X86::AL; size = 1; break;
11336 case MVT::i16: Reg = X86::AX; size = 2; break;
11337 case MVT::i32: Reg = X86::EAX; size = 4; break;
11339 assert(Subtarget->is64Bit() && "Node not type legal!");
11340 Reg = X86::RAX; size = 8;
11343 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11344 Op.getOperand(2), SDValue());
11345 SDValue Ops[] = { cpIn.getValue(0),
11348 DAG.getTargetConstant(size, MVT::i8),
11349 cpIn.getValue(1) };
11350 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11351 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11352 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11355 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11359 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11360 SelectionDAG &DAG) {
11361 assert(Subtarget->is64Bit() && "Result not type legalized?");
11362 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11363 SDValue TheChain = Op.getOperand(0);
11364 DebugLoc dl = Op.getDebugLoc();
11365 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11366 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11367 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11369 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11370 DAG.getConstant(32, MVT::i8));
11372 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11375 return DAG.getMergeValues(Ops, 2, dl);
11378 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11379 EVT SrcVT = Op.getOperand(0).getValueType();
11380 EVT DstVT = Op.getValueType();
11381 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11382 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11383 assert((DstVT == MVT::i64 ||
11384 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11385 "Unexpected custom BITCAST");
11386 // i64 <=> MMX conversions are Legal.
11387 if (SrcVT==MVT::i64 && DstVT.isVector())
11389 if (DstVT==MVT::i64 && SrcVT.isVector())
11391 // MMX <=> MMX conversions are Legal.
11392 if (SrcVT.isVector() && DstVT.isVector())
11394 // All other conversions need to be expanded.
11398 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11399 SDNode *Node = Op.getNode();
11400 DebugLoc dl = Node->getDebugLoc();
11401 EVT T = Node->getValueType(0);
11402 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11403 DAG.getConstant(0, T), Node->getOperand(2));
11404 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11405 cast<AtomicSDNode>(Node)->getMemoryVT(),
11406 Node->getOperand(0),
11407 Node->getOperand(1), negOp,
11408 cast<AtomicSDNode>(Node)->getSrcValue(),
11409 cast<AtomicSDNode>(Node)->getAlignment(),
11410 cast<AtomicSDNode>(Node)->getOrdering(),
11411 cast<AtomicSDNode>(Node)->getSynchScope());
11414 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11415 SDNode *Node = Op.getNode();
11416 DebugLoc dl = Node->getDebugLoc();
11417 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11419 // Convert seq_cst store -> xchg
11420 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11421 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11422 // (The only way to get a 16-byte store is cmpxchg16b)
11423 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11424 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11425 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11426 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11427 cast<AtomicSDNode>(Node)->getMemoryVT(),
11428 Node->getOperand(0),
11429 Node->getOperand(1), Node->getOperand(2),
11430 cast<AtomicSDNode>(Node)->getMemOperand(),
11431 cast<AtomicSDNode>(Node)->getOrdering(),
11432 cast<AtomicSDNode>(Node)->getSynchScope());
11433 return Swap.getValue(1);
11435 // Other atomic stores have a simple pattern.
11439 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11440 EVT VT = Op.getNode()->getValueType(0);
11442 // Let legalize expand this if it isn't a legal type yet.
11443 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11446 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11449 bool ExtraOp = false;
11450 switch (Op.getOpcode()) {
11451 default: llvm_unreachable("Invalid code");
11452 case ISD::ADDC: Opc = X86ISD::ADD; break;
11453 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11454 case ISD::SUBC: Opc = X86ISD::SUB; break;
11455 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11459 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11461 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11462 Op.getOperand(1), Op.getOperand(2));
11465 /// LowerOperation - Provide custom lowering hooks for some operations.
11467 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11468 switch (Op.getOpcode()) {
11469 default: llvm_unreachable("Should not custom lower this!");
11470 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11471 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11472 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11473 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11474 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11475 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11476 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11477 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11478 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11479 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11480 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11481 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11482 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11483 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11484 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11485 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11486 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11487 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11488 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11489 case ISD::SHL_PARTS:
11490 case ISD::SRA_PARTS:
11491 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11492 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11493 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11494 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11495 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11496 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11497 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11498 case ISD::FABS: return LowerFABS(Op, DAG);
11499 case ISD::FNEG: return LowerFNEG(Op, DAG);
11500 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11501 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11502 case ISD::SETCC: return LowerSETCC(Op, DAG);
11503 case ISD::SELECT: return LowerSELECT(Op, DAG);
11504 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11505 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11506 case ISD::VASTART: return LowerVASTART(Op, DAG);
11507 case ISD::VAARG: return LowerVAARG(Op, DAG);
11508 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11509 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11510 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11511 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11512 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11513 case ISD::FRAME_TO_ARGS_OFFSET:
11514 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11515 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11516 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11517 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11518 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11519 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11520 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11521 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11522 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11523 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11524 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11525 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11528 case ISD::SHL: return LowerShift(Op, DAG);
11534 case ISD::UMULO: return LowerXALUO(Op, DAG);
11535 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11536 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11540 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11541 case ISD::ADD: return LowerADD(Op, DAG);
11542 case ISD::SUB: return LowerSUB(Op, DAG);
11546 static void ReplaceATOMIC_LOAD(SDNode *Node,
11547 SmallVectorImpl<SDValue> &Results,
11548 SelectionDAG &DAG) {
11549 DebugLoc dl = Node->getDebugLoc();
11550 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11552 // Convert wide load -> cmpxchg8b/cmpxchg16b
11553 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11554 // (The only way to get a 16-byte load is cmpxchg16b)
11555 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11556 SDValue Zero = DAG.getConstant(0, VT);
11557 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11558 Node->getOperand(0),
11559 Node->getOperand(1), Zero, Zero,
11560 cast<AtomicSDNode>(Node)->getMemOperand(),
11561 cast<AtomicSDNode>(Node)->getOrdering(),
11562 cast<AtomicSDNode>(Node)->getSynchScope());
11563 Results.push_back(Swap.getValue(0));
11564 Results.push_back(Swap.getValue(1));
11568 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11569 SelectionDAG &DAG, unsigned NewOp) {
11570 DebugLoc dl = Node->getDebugLoc();
11571 assert (Node->getValueType(0) == MVT::i64 &&
11572 "Only know how to expand i64 atomics");
11574 SDValue Chain = Node->getOperand(0);
11575 SDValue In1 = Node->getOperand(1);
11576 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11577 Node->getOperand(2), DAG.getIntPtrConstant(0));
11578 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11579 Node->getOperand(2), DAG.getIntPtrConstant(1));
11580 SDValue Ops[] = { Chain, In1, In2L, In2H };
11581 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11583 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11584 cast<MemSDNode>(Node)->getMemOperand());
11585 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11586 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11587 Results.push_back(Result.getValue(2));
11590 /// ReplaceNodeResults - Replace a node with an illegal result type
11591 /// with a new node built out of custom code.
11592 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11593 SmallVectorImpl<SDValue>&Results,
11594 SelectionDAG &DAG) const {
11595 DebugLoc dl = N->getDebugLoc();
11596 switch (N->getOpcode()) {
11598 llvm_unreachable("Do not know how to custom type legalize this operation!");
11599 case ISD::SIGN_EXTEND_INREG:
11604 // We don't want to expand or promote these.
11606 case ISD::FP_TO_SINT:
11607 case ISD::FP_TO_UINT: {
11608 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11610 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11613 std::pair<SDValue,SDValue> Vals =
11614 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11615 SDValue FIST = Vals.first, StackSlot = Vals.second;
11616 if (FIST.getNode() != 0) {
11617 EVT VT = N->getValueType(0);
11618 // Return a load from the stack slot.
11619 if (StackSlot.getNode() != 0)
11620 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11621 MachinePointerInfo(),
11622 false, false, false, 0));
11624 Results.push_back(FIST);
11628 case ISD::FP_ROUND: {
11629 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11630 Results.push_back(V);
11633 case ISD::READCYCLECOUNTER: {
11634 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11635 SDValue TheChain = N->getOperand(0);
11636 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11637 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11639 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11641 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11642 SDValue Ops[] = { eax, edx };
11643 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11644 Results.push_back(edx.getValue(1));
11647 case ISD::ATOMIC_CMP_SWAP: {
11648 EVT T = N->getValueType(0);
11649 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11650 bool Regs64bit = T == MVT::i128;
11651 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11652 SDValue cpInL, cpInH;
11653 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11654 DAG.getConstant(0, HalfT));
11655 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11656 DAG.getConstant(1, HalfT));
11657 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11658 Regs64bit ? X86::RAX : X86::EAX,
11660 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11661 Regs64bit ? X86::RDX : X86::EDX,
11662 cpInH, cpInL.getValue(1));
11663 SDValue swapInL, swapInH;
11664 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11665 DAG.getConstant(0, HalfT));
11666 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11667 DAG.getConstant(1, HalfT));
11668 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11669 Regs64bit ? X86::RBX : X86::EBX,
11670 swapInL, cpInH.getValue(1));
11671 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11672 Regs64bit ? X86::RCX : X86::ECX,
11673 swapInH, swapInL.getValue(1));
11674 SDValue Ops[] = { swapInH.getValue(0),
11676 swapInH.getValue(1) };
11677 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11678 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11679 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11680 X86ISD::LCMPXCHG8_DAG;
11681 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11683 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11684 Regs64bit ? X86::RAX : X86::EAX,
11685 HalfT, Result.getValue(1));
11686 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11687 Regs64bit ? X86::RDX : X86::EDX,
11688 HalfT, cpOutL.getValue(2));
11689 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11690 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11691 Results.push_back(cpOutH.getValue(1));
11694 case ISD::ATOMIC_LOAD_ADD:
11695 case ISD::ATOMIC_LOAD_AND:
11696 case ISD::ATOMIC_LOAD_NAND:
11697 case ISD::ATOMIC_LOAD_OR:
11698 case ISD::ATOMIC_LOAD_SUB:
11699 case ISD::ATOMIC_LOAD_XOR:
11700 case ISD::ATOMIC_LOAD_MAX:
11701 case ISD::ATOMIC_LOAD_MIN:
11702 case ISD::ATOMIC_LOAD_UMAX:
11703 case ISD::ATOMIC_LOAD_UMIN:
11704 case ISD::ATOMIC_SWAP: {
11706 switch (N->getOpcode()) {
11707 default: llvm_unreachable("Unexpected opcode");
11708 case ISD::ATOMIC_LOAD_ADD:
11709 Opc = X86ISD::ATOMADD64_DAG;
11711 case ISD::ATOMIC_LOAD_AND:
11712 Opc = X86ISD::ATOMAND64_DAG;
11714 case ISD::ATOMIC_LOAD_NAND:
11715 Opc = X86ISD::ATOMNAND64_DAG;
11717 case ISD::ATOMIC_LOAD_OR:
11718 Opc = X86ISD::ATOMOR64_DAG;
11720 case ISD::ATOMIC_LOAD_SUB:
11721 Opc = X86ISD::ATOMSUB64_DAG;
11723 case ISD::ATOMIC_LOAD_XOR:
11724 Opc = X86ISD::ATOMXOR64_DAG;
11726 case ISD::ATOMIC_LOAD_MAX:
11727 Opc = X86ISD::ATOMMAX64_DAG;
11729 case ISD::ATOMIC_LOAD_MIN:
11730 Opc = X86ISD::ATOMMIN64_DAG;
11732 case ISD::ATOMIC_LOAD_UMAX:
11733 Opc = X86ISD::ATOMUMAX64_DAG;
11735 case ISD::ATOMIC_LOAD_UMIN:
11736 Opc = X86ISD::ATOMUMIN64_DAG;
11738 case ISD::ATOMIC_SWAP:
11739 Opc = X86ISD::ATOMSWAP64_DAG;
11742 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11745 case ISD::ATOMIC_LOAD:
11746 ReplaceATOMIC_LOAD(N, Results, DAG);
11750 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11752 default: return NULL;
11753 case X86ISD::BSF: return "X86ISD::BSF";
11754 case X86ISD::BSR: return "X86ISD::BSR";
11755 case X86ISD::SHLD: return "X86ISD::SHLD";
11756 case X86ISD::SHRD: return "X86ISD::SHRD";
11757 case X86ISD::FAND: return "X86ISD::FAND";
11758 case X86ISD::FOR: return "X86ISD::FOR";
11759 case X86ISD::FXOR: return "X86ISD::FXOR";
11760 case X86ISD::FSRL: return "X86ISD::FSRL";
11761 case X86ISD::FILD: return "X86ISD::FILD";
11762 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11763 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11764 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11765 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11766 case X86ISD::FLD: return "X86ISD::FLD";
11767 case X86ISD::FST: return "X86ISD::FST";
11768 case X86ISD::CALL: return "X86ISD::CALL";
11769 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11770 case X86ISD::BT: return "X86ISD::BT";
11771 case X86ISD::CMP: return "X86ISD::CMP";
11772 case X86ISD::COMI: return "X86ISD::COMI";
11773 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11774 case X86ISD::SETCC: return "X86ISD::SETCC";
11775 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11776 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11777 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11778 case X86ISD::CMOV: return "X86ISD::CMOV";
11779 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11780 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11781 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11782 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11783 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11784 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11785 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11786 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11787 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11788 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11789 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11790 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11791 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11792 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11793 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11794 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11795 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11796 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11797 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11798 case X86ISD::HADD: return "X86ISD::HADD";
11799 case X86ISD::HSUB: return "X86ISD::HSUB";
11800 case X86ISD::FHADD: return "X86ISD::FHADD";
11801 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11802 case X86ISD::FMAX: return "X86ISD::FMAX";
11803 case X86ISD::FMIN: return "X86ISD::FMIN";
11804 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11805 case X86ISD::FMINC: return "X86ISD::FMINC";
11806 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11807 case X86ISD::FRCP: return "X86ISD::FRCP";
11808 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11809 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11810 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11811 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11812 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11813 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11814 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11815 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11816 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11817 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11818 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11819 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11820 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11821 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11822 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11823 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11824 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11825 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11826 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11827 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11828 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11829 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11830 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11831 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11832 case X86ISD::VSHL: return "X86ISD::VSHL";
11833 case X86ISD::VSRL: return "X86ISD::VSRL";
11834 case X86ISD::VSRA: return "X86ISD::VSRA";
11835 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11836 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11837 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11838 case X86ISD::CMPP: return "X86ISD::CMPP";
11839 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11840 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11841 case X86ISD::ADD: return "X86ISD::ADD";
11842 case X86ISD::SUB: return "X86ISD::SUB";
11843 case X86ISD::ADC: return "X86ISD::ADC";
11844 case X86ISD::SBB: return "X86ISD::SBB";
11845 case X86ISD::SMUL: return "X86ISD::SMUL";
11846 case X86ISD::UMUL: return "X86ISD::UMUL";
11847 case X86ISD::INC: return "X86ISD::INC";
11848 case X86ISD::DEC: return "X86ISD::DEC";
11849 case X86ISD::OR: return "X86ISD::OR";
11850 case X86ISD::XOR: return "X86ISD::XOR";
11851 case X86ISD::AND: return "X86ISD::AND";
11852 case X86ISD::ANDN: return "X86ISD::ANDN";
11853 case X86ISD::BLSI: return "X86ISD::BLSI";
11854 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11855 case X86ISD::BLSR: return "X86ISD::BLSR";
11856 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11857 case X86ISD::PTEST: return "X86ISD::PTEST";
11858 case X86ISD::TESTP: return "X86ISD::TESTP";
11859 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11860 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11861 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11862 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11863 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11864 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11865 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11866 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11867 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11868 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11869 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11870 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11871 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11872 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11873 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11874 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11875 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11876 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11877 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11878 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11879 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11880 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11881 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11882 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11883 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11884 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11885 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11886 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11887 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11888 case X86ISD::SAHF: return "X86ISD::SAHF";
11889 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11890 case X86ISD::FMADD: return "X86ISD::FMADD";
11891 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11892 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11893 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11894 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11895 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11899 // isLegalAddressingMode - Return true if the addressing mode represented
11900 // by AM is legal for this target, for a load/store of the specified type.
11901 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11903 // X86 supports extremely general addressing modes.
11904 CodeModel::Model M = getTargetMachine().getCodeModel();
11905 Reloc::Model R = getTargetMachine().getRelocationModel();
11907 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11908 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11913 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11915 // If a reference to this global requires an extra load, we can't fold it.
11916 if (isGlobalStubReference(GVFlags))
11919 // If BaseGV requires a register for the PIC base, we cannot also have a
11920 // BaseReg specified.
11921 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11924 // If lower 4G is not available, then we must use rip-relative addressing.
11925 if ((M != CodeModel::Small || R != Reloc::Static) &&
11926 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11930 switch (AM.Scale) {
11936 // These scales always work.
11941 // These scales are formed with basereg+scalereg. Only accept if there is
11946 default: // Other stuff never works.
11954 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11955 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11957 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11958 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11959 if (NumBits1 <= NumBits2)
11964 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11965 return Imm == (int32_t)Imm;
11968 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11969 // Can also use sub to handle negated immediates.
11970 return Imm == (int32_t)Imm;
11973 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11974 if (!VT1.isInteger() || !VT2.isInteger())
11976 unsigned NumBits1 = VT1.getSizeInBits();
11977 unsigned NumBits2 = VT2.getSizeInBits();
11978 if (NumBits1 <= NumBits2)
11983 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11984 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11985 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11988 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11989 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11990 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11993 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11994 // i16 instructions are longer (0x66 prefix) and potentially slower.
11995 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11998 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11999 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12000 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12001 /// are assumed to be legal.
12003 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12005 // Very little shuffling can be done for 64-bit vectors right now.
12006 if (VT.getSizeInBits() == 64)
12009 // FIXME: pshufb, blends, shifts.
12010 return (VT.getVectorNumElements() == 2 ||
12011 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12012 isMOVLMask(M, VT) ||
12013 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12014 isPSHUFDMask(M, VT) ||
12015 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12016 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12017 isPALIGNRMask(M, VT, Subtarget) ||
12018 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12019 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12020 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12021 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12025 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12027 unsigned NumElts = VT.getVectorNumElements();
12028 // FIXME: This collection of masks seems suspect.
12031 if (NumElts == 4 && VT.is128BitVector()) {
12032 return (isMOVLMask(Mask, VT) ||
12033 isCommutedMOVLMask(Mask, VT, true) ||
12034 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12035 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12040 //===----------------------------------------------------------------------===//
12041 // X86 Scheduler Hooks
12042 //===----------------------------------------------------------------------===//
12044 // private utility function
12046 // Get CMPXCHG opcode for the specified data type.
12047 static unsigned getCmpXChgOpcode(EVT VT) {
12048 switch (VT.getSimpleVT().SimpleTy) {
12049 case MVT::i8: return X86::LCMPXCHG8;
12050 case MVT::i16: return X86::LCMPXCHG16;
12051 case MVT::i32: return X86::LCMPXCHG32;
12052 case MVT::i64: return X86::LCMPXCHG64;
12056 llvm_unreachable("Invalid operand size!");
12059 // Get LOAD opcode for the specified data type.
12060 static unsigned getLoadOpcode(EVT VT) {
12061 switch (VT.getSimpleVT().SimpleTy) {
12062 case MVT::i8: return X86::MOV8rm;
12063 case MVT::i16: return X86::MOV16rm;
12064 case MVT::i32: return X86::MOV32rm;
12065 case MVT::i64: return X86::MOV64rm;
12069 llvm_unreachable("Invalid operand size!");
12072 // Get opcode of the non-atomic one from the specified atomic instruction.
12073 static unsigned getNonAtomicOpcode(unsigned Opc) {
12075 case X86::ATOMAND8: return X86::AND8rr;
12076 case X86::ATOMAND16: return X86::AND16rr;
12077 case X86::ATOMAND32: return X86::AND32rr;
12078 case X86::ATOMAND64: return X86::AND64rr;
12079 case X86::ATOMOR8: return X86::OR8rr;
12080 case X86::ATOMOR16: return X86::OR16rr;
12081 case X86::ATOMOR32: return X86::OR32rr;
12082 case X86::ATOMOR64: return X86::OR64rr;
12083 case X86::ATOMXOR8: return X86::XOR8rr;
12084 case X86::ATOMXOR16: return X86::XOR16rr;
12085 case X86::ATOMXOR32: return X86::XOR32rr;
12086 case X86::ATOMXOR64: return X86::XOR64rr;
12088 llvm_unreachable("Unhandled atomic-load-op opcode!");
12091 // Get opcode of the non-atomic one from the specified atomic instruction with
12093 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12094 unsigned &ExtraOpc) {
12096 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12097 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12098 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12099 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12100 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12101 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12102 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12103 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12104 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12105 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12106 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12107 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12108 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12109 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12110 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12111 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12112 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12113 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12114 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12115 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12117 llvm_unreachable("Unhandled atomic-load-op opcode!");
12120 // Get opcode of the non-atomic one from the specified atomic instruction for
12121 // 64-bit data type on 32-bit target.
12122 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12124 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12125 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12126 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12127 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12128 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12129 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12130 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12131 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12132 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12133 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12135 llvm_unreachable("Unhandled atomic-load-op opcode!");
12138 // Get opcode of the non-atomic one from the specified atomic instruction for
12139 // 64-bit data type on 32-bit target with extra opcode.
12140 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12142 unsigned &ExtraOpc) {
12144 case X86::ATOMNAND6432:
12145 ExtraOpc = X86::NOT32r;
12146 HiOpc = X86::AND32rr;
12147 return X86::AND32rr;
12149 llvm_unreachable("Unhandled atomic-load-op opcode!");
12152 // Get pseudo CMOV opcode from the specified data type.
12153 static unsigned getPseudoCMOVOpc(EVT VT) {
12154 switch (VT.getSimpleVT().SimpleTy) {
12155 case MVT::i8: return X86::CMOV_GR8;
12156 case MVT::i16: return X86::CMOV_GR16;
12157 case MVT::i32: return X86::CMOV_GR32;
12161 llvm_unreachable("Unknown CMOV opcode!");
12164 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12165 // They will be translated into a spin-loop or compare-exchange loop from
12168 // dst = atomic-fetch-op MI.addr, MI.val
12174 // EAX = LOAD MI.addr
12176 // t1 = OP MI.val, EAX
12177 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12182 MachineBasicBlock *
12183 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12184 MachineBasicBlock *MBB) const {
12185 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12186 DebugLoc DL = MI->getDebugLoc();
12188 MachineFunction *MF = MBB->getParent();
12189 MachineRegisterInfo &MRI = MF->getRegInfo();
12191 const BasicBlock *BB = MBB->getBasicBlock();
12192 MachineFunction::iterator I = MBB;
12195 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12196 "Unexpected number of operands");
12198 assert(MI->hasOneMemOperand() &&
12199 "Expected atomic-load-op to have one memoperand");
12201 // Memory Reference
12202 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12203 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12205 unsigned DstReg, SrcReg;
12206 unsigned MemOpndSlot;
12208 unsigned CurOp = 0;
12210 DstReg = MI->getOperand(CurOp++).getReg();
12211 MemOpndSlot = CurOp;
12212 CurOp += X86::AddrNumOperands;
12213 SrcReg = MI->getOperand(CurOp++).getReg();
12215 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12216 MVT::SimpleValueType VT = *RC->vt_begin();
12217 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12219 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12220 unsigned LOADOpc = getLoadOpcode(VT);
12222 // For the atomic load-arith operator, we generate
12225 // EAX = LOAD [MI.addr]
12227 // t1 = OP MI.val, EAX
12228 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12232 MachineBasicBlock *thisMBB = MBB;
12233 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12234 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12235 MF->insert(I, mainMBB);
12236 MF->insert(I, sinkMBB);
12238 MachineInstrBuilder MIB;
12240 // Transfer the remainder of BB and its successor edges to sinkMBB.
12241 sinkMBB->splice(sinkMBB->begin(), MBB,
12242 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12243 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12246 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12247 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12248 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12249 MIB.setMemRefs(MMOBegin, MMOEnd);
12251 thisMBB->addSuccessor(mainMBB);
12254 MachineBasicBlock *origMainMBB = mainMBB;
12255 mainMBB->addLiveIn(AccPhyReg);
12257 // Copy AccPhyReg as it is used more than once.
12258 unsigned AccReg = MRI.createVirtualRegister(RC);
12259 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12260 .addReg(AccPhyReg);
12262 unsigned t1 = MRI.createVirtualRegister(RC);
12263 unsigned Opc = MI->getOpcode();
12266 llvm_unreachable("Unhandled atomic-load-op opcode!");
12267 case X86::ATOMAND8:
12268 case X86::ATOMAND16:
12269 case X86::ATOMAND32:
12270 case X86::ATOMAND64:
12272 case X86::ATOMOR16:
12273 case X86::ATOMOR32:
12274 case X86::ATOMOR64:
12275 case X86::ATOMXOR8:
12276 case X86::ATOMXOR16:
12277 case X86::ATOMXOR32:
12278 case X86::ATOMXOR64: {
12279 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12280 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12284 case X86::ATOMNAND8:
12285 case X86::ATOMNAND16:
12286 case X86::ATOMNAND32:
12287 case X86::ATOMNAND64: {
12288 unsigned t2 = MRI.createVirtualRegister(RC);
12290 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12291 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12293 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12296 case X86::ATOMMAX8:
12297 case X86::ATOMMAX16:
12298 case X86::ATOMMAX32:
12299 case X86::ATOMMAX64:
12300 case X86::ATOMMIN8:
12301 case X86::ATOMMIN16:
12302 case X86::ATOMMIN32:
12303 case X86::ATOMMIN64:
12304 case X86::ATOMUMAX8:
12305 case X86::ATOMUMAX16:
12306 case X86::ATOMUMAX32:
12307 case X86::ATOMUMAX64:
12308 case X86::ATOMUMIN8:
12309 case X86::ATOMUMIN16:
12310 case X86::ATOMUMIN32:
12311 case X86::ATOMUMIN64: {
12313 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12315 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12319 if (Subtarget->hasCMov()) {
12320 if (VT != MVT::i8) {
12322 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12326 // Promote i8 to i32 to use CMOV32
12327 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12328 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12329 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12330 unsigned t2 = MRI.createVirtualRegister(RC32);
12332 unsigned Undef = MRI.createVirtualRegister(RC32);
12333 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12335 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12338 .addImm(X86::sub_8bit);
12339 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12342 .addImm(X86::sub_8bit);
12344 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12348 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12349 .addReg(t2, 0, X86::sub_8bit);
12352 // Use pseudo select and lower them.
12353 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12354 "Invalid atomic-load-op transformation!");
12355 unsigned SelOpc = getPseudoCMOVOpc(VT);
12356 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12357 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12358 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12359 .addReg(SrcReg).addReg(AccReg)
12361 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12367 // Copy AccPhyReg back from virtual register.
12368 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12371 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12372 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12373 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12375 MIB.setMemRefs(MMOBegin, MMOEnd);
12377 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12379 mainMBB->addSuccessor(origMainMBB);
12380 mainMBB->addSuccessor(sinkMBB);
12383 sinkMBB->addLiveIn(AccPhyReg);
12385 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12386 TII->get(TargetOpcode::COPY), DstReg)
12387 .addReg(AccPhyReg);
12389 MI->eraseFromParent();
12393 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12394 // instructions. They will be translated into a spin-loop or compare-exchange
12398 // dst = atomic-fetch-op MI.addr, MI.val
12404 // EAX = LOAD [MI.addr + 0]
12405 // EDX = LOAD [MI.addr + 4]
12407 // EBX = OP MI.val.lo, EAX
12408 // ECX = OP MI.val.hi, EDX
12409 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12414 MachineBasicBlock *
12415 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12416 MachineBasicBlock *MBB) const {
12417 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12418 DebugLoc DL = MI->getDebugLoc();
12420 MachineFunction *MF = MBB->getParent();
12421 MachineRegisterInfo &MRI = MF->getRegInfo();
12423 const BasicBlock *BB = MBB->getBasicBlock();
12424 MachineFunction::iterator I = MBB;
12427 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12428 "Unexpected number of operands");
12430 assert(MI->hasOneMemOperand() &&
12431 "Expected atomic-load-op32 to have one memoperand");
12433 // Memory Reference
12434 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12435 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12437 unsigned DstLoReg, DstHiReg;
12438 unsigned SrcLoReg, SrcHiReg;
12439 unsigned MemOpndSlot;
12441 unsigned CurOp = 0;
12443 DstLoReg = MI->getOperand(CurOp++).getReg();
12444 DstHiReg = MI->getOperand(CurOp++).getReg();
12445 MemOpndSlot = CurOp;
12446 CurOp += X86::AddrNumOperands;
12447 SrcLoReg = MI->getOperand(CurOp++).getReg();
12448 SrcHiReg = MI->getOperand(CurOp++).getReg();
12450 const TargetRegisterClass *RC = &X86::GR32RegClass;
12451 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12453 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12454 unsigned LOADOpc = X86::MOV32rm;
12456 // For the atomic load-arith operator, we generate
12459 // EAX = LOAD [MI.addr + 0]
12460 // EDX = LOAD [MI.addr + 4]
12462 // EBX = OP MI.vallo, EAX
12463 // ECX = OP MI.valhi, EDX
12464 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12468 MachineBasicBlock *thisMBB = MBB;
12469 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12470 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12471 MF->insert(I, mainMBB);
12472 MF->insert(I, sinkMBB);
12474 MachineInstrBuilder MIB;
12476 // Transfer the remainder of BB and its successor edges to sinkMBB.
12477 sinkMBB->splice(sinkMBB->begin(), MBB,
12478 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12479 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12483 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12484 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12485 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12486 MIB.setMemRefs(MMOBegin, MMOEnd);
12488 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12489 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12490 if (i == X86::AddrDisp)
12491 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12493 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12495 MIB.setMemRefs(MMOBegin, MMOEnd);
12497 thisMBB->addSuccessor(mainMBB);
12500 MachineBasicBlock *origMainMBB = mainMBB;
12501 mainMBB->addLiveIn(X86::EAX);
12502 mainMBB->addLiveIn(X86::EDX);
12504 // Copy EDX:EAX as they are used more than once.
12505 unsigned LoReg = MRI.createVirtualRegister(RC);
12506 unsigned HiReg = MRI.createVirtualRegister(RC);
12507 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12508 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12510 unsigned t1L = MRI.createVirtualRegister(RC);
12511 unsigned t1H = MRI.createVirtualRegister(RC);
12513 unsigned Opc = MI->getOpcode();
12516 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12517 case X86::ATOMAND6432:
12518 case X86::ATOMOR6432:
12519 case X86::ATOMXOR6432:
12520 case X86::ATOMADD6432:
12521 case X86::ATOMSUB6432: {
12523 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12524 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12525 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12528 case X86::ATOMNAND6432: {
12529 unsigned HiOpc, NOTOpc;
12530 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12531 unsigned t2L = MRI.createVirtualRegister(RC);
12532 unsigned t2H = MRI.createVirtualRegister(RC);
12533 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12534 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12535 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12536 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12539 case X86::ATOMMAX6432:
12540 case X86::ATOMMIN6432:
12541 case X86::ATOMUMAX6432:
12542 case X86::ATOMUMIN6432: {
12544 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12545 unsigned cL = MRI.createVirtualRegister(RC8);
12546 unsigned cH = MRI.createVirtualRegister(RC8);
12547 unsigned cL32 = MRI.createVirtualRegister(RC);
12548 unsigned cH32 = MRI.createVirtualRegister(RC);
12549 unsigned cc = MRI.createVirtualRegister(RC);
12550 // cl := cmp src_lo, lo
12551 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12552 .addReg(SrcLoReg).addReg(LoReg);
12553 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12554 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12555 // ch := cmp src_hi, hi
12556 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12557 .addReg(SrcHiReg).addReg(HiReg);
12558 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12559 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12560 // cc := if (src_hi == hi) ? cl : ch;
12561 if (Subtarget->hasCMov()) {
12562 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12563 .addReg(cH32).addReg(cL32);
12565 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12566 .addReg(cH32).addReg(cL32)
12567 .addImm(X86::COND_E);
12568 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12570 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12571 if (Subtarget->hasCMov()) {
12572 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12573 .addReg(SrcLoReg).addReg(LoReg);
12574 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12575 .addReg(SrcHiReg).addReg(HiReg);
12577 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12578 .addReg(SrcLoReg).addReg(LoReg)
12579 .addImm(X86::COND_NE);
12580 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12581 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12582 .addReg(SrcHiReg).addReg(HiReg)
12583 .addImm(X86::COND_NE);
12584 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12588 case X86::ATOMSWAP6432: {
12590 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12591 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12592 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12597 // Copy EDX:EAX back from HiReg:LoReg
12598 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12599 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12600 // Copy ECX:EBX from t1H:t1L
12601 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12602 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12604 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12605 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12606 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12607 MIB.setMemRefs(MMOBegin, MMOEnd);
12609 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12611 mainMBB->addSuccessor(origMainMBB);
12612 mainMBB->addSuccessor(sinkMBB);
12615 sinkMBB->addLiveIn(X86::EAX);
12616 sinkMBB->addLiveIn(X86::EDX);
12618 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12619 TII->get(TargetOpcode::COPY), DstLoReg)
12621 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12622 TII->get(TargetOpcode::COPY), DstHiReg)
12625 MI->eraseFromParent();
12629 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12630 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12631 // in the .td file.
12632 MachineBasicBlock *
12633 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12634 unsigned numArgs, bool memArg) const {
12635 assert(Subtarget->hasSSE42() &&
12636 "Target must have SSE4.2 or AVX features enabled");
12638 DebugLoc dl = MI->getDebugLoc();
12639 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12641 if (!Subtarget->hasAVX()) {
12643 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12645 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12648 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12650 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12653 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12654 for (unsigned i = 0; i < numArgs; ++i) {
12655 MachineOperand &Op = MI->getOperand(i+1);
12656 if (!(Op.isReg() && Op.isImplicit()))
12657 MIB.addOperand(Op);
12659 BuildMI(*BB, MI, dl,
12660 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12661 .addReg(X86::XMM0);
12663 MI->eraseFromParent();
12667 MachineBasicBlock *
12668 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12669 DebugLoc dl = MI->getDebugLoc();
12670 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12672 // Address into RAX/EAX, other two args into ECX, EDX.
12673 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12674 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12675 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12676 for (int i = 0; i < X86::AddrNumOperands; ++i)
12677 MIB.addOperand(MI->getOperand(i));
12679 unsigned ValOps = X86::AddrNumOperands;
12680 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12681 .addReg(MI->getOperand(ValOps).getReg());
12682 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12683 .addReg(MI->getOperand(ValOps+1).getReg());
12685 // The instruction doesn't actually take any operands though.
12686 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12688 MI->eraseFromParent(); // The pseudo is gone now.
12692 MachineBasicBlock *
12693 X86TargetLowering::EmitVAARG64WithCustomInserter(
12695 MachineBasicBlock *MBB) const {
12696 // Emit va_arg instruction on X86-64.
12698 // Operands to this pseudo-instruction:
12699 // 0 ) Output : destination address (reg)
12700 // 1-5) Input : va_list address (addr, i64mem)
12701 // 6 ) ArgSize : Size (in bytes) of vararg type
12702 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12703 // 8 ) Align : Alignment of type
12704 // 9 ) EFLAGS (implicit-def)
12706 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12707 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12709 unsigned DestReg = MI->getOperand(0).getReg();
12710 MachineOperand &Base = MI->getOperand(1);
12711 MachineOperand &Scale = MI->getOperand(2);
12712 MachineOperand &Index = MI->getOperand(3);
12713 MachineOperand &Disp = MI->getOperand(4);
12714 MachineOperand &Segment = MI->getOperand(5);
12715 unsigned ArgSize = MI->getOperand(6).getImm();
12716 unsigned ArgMode = MI->getOperand(7).getImm();
12717 unsigned Align = MI->getOperand(8).getImm();
12719 // Memory Reference
12720 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12721 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12722 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12724 // Machine Information
12725 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12726 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12727 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12728 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12729 DebugLoc DL = MI->getDebugLoc();
12731 // struct va_list {
12734 // i64 overflow_area (address)
12735 // i64 reg_save_area (address)
12737 // sizeof(va_list) = 24
12738 // alignment(va_list) = 8
12740 unsigned TotalNumIntRegs = 6;
12741 unsigned TotalNumXMMRegs = 8;
12742 bool UseGPOffset = (ArgMode == 1);
12743 bool UseFPOffset = (ArgMode == 2);
12744 unsigned MaxOffset = TotalNumIntRegs * 8 +
12745 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12747 /* Align ArgSize to a multiple of 8 */
12748 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12749 bool NeedsAlign = (Align > 8);
12751 MachineBasicBlock *thisMBB = MBB;
12752 MachineBasicBlock *overflowMBB;
12753 MachineBasicBlock *offsetMBB;
12754 MachineBasicBlock *endMBB;
12756 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12757 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12758 unsigned OffsetReg = 0;
12760 if (!UseGPOffset && !UseFPOffset) {
12761 // If we only pull from the overflow region, we don't create a branch.
12762 // We don't need to alter control flow.
12763 OffsetDestReg = 0; // unused
12764 OverflowDestReg = DestReg;
12767 overflowMBB = thisMBB;
12770 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12771 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12772 // If not, pull from overflow_area. (branch to overflowMBB)
12777 // offsetMBB overflowMBB
12782 // Registers for the PHI in endMBB
12783 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12784 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12786 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12787 MachineFunction *MF = MBB->getParent();
12788 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12789 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12790 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12792 MachineFunction::iterator MBBIter = MBB;
12795 // Insert the new basic blocks
12796 MF->insert(MBBIter, offsetMBB);
12797 MF->insert(MBBIter, overflowMBB);
12798 MF->insert(MBBIter, endMBB);
12800 // Transfer the remainder of MBB and its successor edges to endMBB.
12801 endMBB->splice(endMBB->begin(), thisMBB,
12802 llvm::next(MachineBasicBlock::iterator(MI)),
12804 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12806 // Make offsetMBB and overflowMBB successors of thisMBB
12807 thisMBB->addSuccessor(offsetMBB);
12808 thisMBB->addSuccessor(overflowMBB);
12810 // endMBB is a successor of both offsetMBB and overflowMBB
12811 offsetMBB->addSuccessor(endMBB);
12812 overflowMBB->addSuccessor(endMBB);
12814 // Load the offset value into a register
12815 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12816 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12820 .addDisp(Disp, UseFPOffset ? 4 : 0)
12821 .addOperand(Segment)
12822 .setMemRefs(MMOBegin, MMOEnd);
12824 // Check if there is enough room left to pull this argument.
12825 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12827 .addImm(MaxOffset + 8 - ArgSizeA8);
12829 // Branch to "overflowMBB" if offset >= max
12830 // Fall through to "offsetMBB" otherwise
12831 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12832 .addMBB(overflowMBB);
12835 // In offsetMBB, emit code to use the reg_save_area.
12837 assert(OffsetReg != 0);
12839 // Read the reg_save_area address.
12840 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12841 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12846 .addOperand(Segment)
12847 .setMemRefs(MMOBegin, MMOEnd);
12849 // Zero-extend the offset
12850 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12851 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12854 .addImm(X86::sub_32bit);
12856 // Add the offset to the reg_save_area to get the final address.
12857 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12858 .addReg(OffsetReg64)
12859 .addReg(RegSaveReg);
12861 // Compute the offset for the next argument
12862 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12863 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12865 .addImm(UseFPOffset ? 16 : 8);
12867 // Store it back into the va_list.
12868 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12872 .addDisp(Disp, UseFPOffset ? 4 : 0)
12873 .addOperand(Segment)
12874 .addReg(NextOffsetReg)
12875 .setMemRefs(MMOBegin, MMOEnd);
12878 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12883 // Emit code to use overflow area
12886 // Load the overflow_area address into a register.
12887 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12888 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12893 .addOperand(Segment)
12894 .setMemRefs(MMOBegin, MMOEnd);
12896 // If we need to align it, do so. Otherwise, just copy the address
12897 // to OverflowDestReg.
12899 // Align the overflow address
12900 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12901 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12903 // aligned_addr = (addr + (align-1)) & ~(align-1)
12904 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12905 .addReg(OverflowAddrReg)
12908 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12910 .addImm(~(uint64_t)(Align-1));
12912 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12913 .addReg(OverflowAddrReg);
12916 // Compute the next overflow address after this argument.
12917 // (the overflow address should be kept 8-byte aligned)
12918 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12919 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12920 .addReg(OverflowDestReg)
12921 .addImm(ArgSizeA8);
12923 // Store the new overflow address.
12924 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12929 .addOperand(Segment)
12930 .addReg(NextAddrReg)
12931 .setMemRefs(MMOBegin, MMOEnd);
12933 // If we branched, emit the PHI to the front of endMBB.
12935 BuildMI(*endMBB, endMBB->begin(), DL,
12936 TII->get(X86::PHI), DestReg)
12937 .addReg(OffsetDestReg).addMBB(offsetMBB)
12938 .addReg(OverflowDestReg).addMBB(overflowMBB);
12941 // Erase the pseudo instruction
12942 MI->eraseFromParent();
12947 MachineBasicBlock *
12948 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12950 MachineBasicBlock *MBB) const {
12951 // Emit code to save XMM registers to the stack. The ABI says that the
12952 // number of registers to save is given in %al, so it's theoretically
12953 // possible to do an indirect jump trick to avoid saving all of them,
12954 // however this code takes a simpler approach and just executes all
12955 // of the stores if %al is non-zero. It's less code, and it's probably
12956 // easier on the hardware branch predictor, and stores aren't all that
12957 // expensive anyway.
12959 // Create the new basic blocks. One block contains all the XMM stores,
12960 // and one block is the final destination regardless of whether any
12961 // stores were performed.
12962 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12963 MachineFunction *F = MBB->getParent();
12964 MachineFunction::iterator MBBIter = MBB;
12966 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12967 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12968 F->insert(MBBIter, XMMSaveMBB);
12969 F->insert(MBBIter, EndMBB);
12971 // Transfer the remainder of MBB and its successor edges to EndMBB.
12972 EndMBB->splice(EndMBB->begin(), MBB,
12973 llvm::next(MachineBasicBlock::iterator(MI)),
12975 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12977 // The original block will now fall through to the XMM save block.
12978 MBB->addSuccessor(XMMSaveMBB);
12979 // The XMMSaveMBB will fall through to the end block.
12980 XMMSaveMBB->addSuccessor(EndMBB);
12982 // Now add the instructions.
12983 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12984 DebugLoc DL = MI->getDebugLoc();
12986 unsigned CountReg = MI->getOperand(0).getReg();
12987 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12988 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12990 if (!Subtarget->isTargetWin64()) {
12991 // If %al is 0, branch around the XMM save block.
12992 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12993 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12994 MBB->addSuccessor(EndMBB);
12997 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12998 // In the XMM save block, save all the XMM argument registers.
12999 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13000 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13001 MachineMemOperand *MMO =
13002 F->getMachineMemOperand(
13003 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13004 MachineMemOperand::MOStore,
13005 /*Size=*/16, /*Align=*/16);
13006 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13007 .addFrameIndex(RegSaveFrameIndex)
13008 .addImm(/*Scale=*/1)
13009 .addReg(/*IndexReg=*/0)
13010 .addImm(/*Disp=*/Offset)
13011 .addReg(/*Segment=*/0)
13012 .addReg(MI->getOperand(i).getReg())
13013 .addMemOperand(MMO);
13016 MI->eraseFromParent(); // The pseudo instruction is gone now.
13021 // The EFLAGS operand of SelectItr might be missing a kill marker
13022 // because there were multiple uses of EFLAGS, and ISel didn't know
13023 // which to mark. Figure out whether SelectItr should have had a
13024 // kill marker, and set it if it should. Returns the correct kill
13026 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13027 MachineBasicBlock* BB,
13028 const TargetRegisterInfo* TRI) {
13029 // Scan forward through BB for a use/def of EFLAGS.
13030 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13031 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13032 const MachineInstr& mi = *miI;
13033 if (mi.readsRegister(X86::EFLAGS))
13035 if (mi.definesRegister(X86::EFLAGS))
13036 break; // Should have kill-flag - update below.
13039 // If we hit the end of the block, check whether EFLAGS is live into a
13041 if (miI == BB->end()) {
13042 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13043 sEnd = BB->succ_end();
13044 sItr != sEnd; ++sItr) {
13045 MachineBasicBlock* succ = *sItr;
13046 if (succ->isLiveIn(X86::EFLAGS))
13051 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13052 // out. SelectMI should have a kill flag on EFLAGS.
13053 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13057 MachineBasicBlock *
13058 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13059 MachineBasicBlock *BB) const {
13060 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13061 DebugLoc DL = MI->getDebugLoc();
13063 // To "insert" a SELECT_CC instruction, we actually have to insert the
13064 // diamond control-flow pattern. The incoming instruction knows the
13065 // destination vreg to set, the condition code register to branch on, the
13066 // true/false values to select between, and a branch opcode to use.
13067 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13068 MachineFunction::iterator It = BB;
13074 // cmpTY ccX, r1, r2
13076 // fallthrough --> copy0MBB
13077 MachineBasicBlock *thisMBB = BB;
13078 MachineFunction *F = BB->getParent();
13079 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13080 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13081 F->insert(It, copy0MBB);
13082 F->insert(It, sinkMBB);
13084 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13085 // live into the sink and copy blocks.
13086 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13087 if (!MI->killsRegister(X86::EFLAGS) &&
13088 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13089 copy0MBB->addLiveIn(X86::EFLAGS);
13090 sinkMBB->addLiveIn(X86::EFLAGS);
13093 // Transfer the remainder of BB and its successor edges to sinkMBB.
13094 sinkMBB->splice(sinkMBB->begin(), BB,
13095 llvm::next(MachineBasicBlock::iterator(MI)),
13097 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13099 // Add the true and fallthrough blocks as its successors.
13100 BB->addSuccessor(copy0MBB);
13101 BB->addSuccessor(sinkMBB);
13103 // Create the conditional branch instruction.
13105 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13106 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13109 // %FalseValue = ...
13110 // # fallthrough to sinkMBB
13111 copy0MBB->addSuccessor(sinkMBB);
13114 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13116 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13117 TII->get(X86::PHI), MI->getOperand(0).getReg())
13118 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13119 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13121 MI->eraseFromParent(); // The pseudo instruction is gone now.
13125 MachineBasicBlock *
13126 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13127 bool Is64Bit) const {
13128 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13129 DebugLoc DL = MI->getDebugLoc();
13130 MachineFunction *MF = BB->getParent();
13131 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13133 assert(getTargetMachine().Options.EnableSegmentedStacks);
13135 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13136 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13139 // ... [Till the alloca]
13140 // If stacklet is not large enough, jump to mallocMBB
13143 // Allocate by subtracting from RSP
13144 // Jump to continueMBB
13147 // Allocate by call to runtime
13151 // [rest of original BB]
13154 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13155 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13156 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13158 MachineRegisterInfo &MRI = MF->getRegInfo();
13159 const TargetRegisterClass *AddrRegClass =
13160 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13162 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13163 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13164 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13165 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13166 sizeVReg = MI->getOperand(1).getReg(),
13167 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13169 MachineFunction::iterator MBBIter = BB;
13172 MF->insert(MBBIter, bumpMBB);
13173 MF->insert(MBBIter, mallocMBB);
13174 MF->insert(MBBIter, continueMBB);
13176 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13177 (MachineBasicBlock::iterator(MI)), BB->end());
13178 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13180 // Add code to the main basic block to check if the stack limit has been hit,
13181 // and if so, jump to mallocMBB otherwise to bumpMBB.
13182 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13183 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13184 .addReg(tmpSPVReg).addReg(sizeVReg);
13185 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13186 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13187 .addReg(SPLimitVReg);
13188 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13190 // bumpMBB simply decreases the stack pointer, since we know the current
13191 // stacklet has enough space.
13192 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13193 .addReg(SPLimitVReg);
13194 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13195 .addReg(SPLimitVReg);
13196 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13198 // Calls into a routine in libgcc to allocate more space from the heap.
13199 const uint32_t *RegMask =
13200 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13202 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13204 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13205 .addExternalSymbol("__morestack_allocate_stack_space")
13206 .addRegMask(RegMask)
13207 .addReg(X86::RDI, RegState::Implicit)
13208 .addReg(X86::RAX, RegState::ImplicitDefine);
13210 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13212 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13213 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13214 .addExternalSymbol("__morestack_allocate_stack_space")
13215 .addRegMask(RegMask)
13216 .addReg(X86::EAX, RegState::ImplicitDefine);
13220 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13223 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13224 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13225 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13227 // Set up the CFG correctly.
13228 BB->addSuccessor(bumpMBB);
13229 BB->addSuccessor(mallocMBB);
13230 mallocMBB->addSuccessor(continueMBB);
13231 bumpMBB->addSuccessor(continueMBB);
13233 // Take care of the PHI nodes.
13234 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13235 MI->getOperand(0).getReg())
13236 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13237 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13239 // Delete the original pseudo instruction.
13240 MI->eraseFromParent();
13243 return continueMBB;
13246 MachineBasicBlock *
13247 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13248 MachineBasicBlock *BB) const {
13249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13250 DebugLoc DL = MI->getDebugLoc();
13252 assert(!Subtarget->isTargetEnvMacho());
13254 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13255 // non-trivial part is impdef of ESP.
13257 if (Subtarget->isTargetWin64()) {
13258 if (Subtarget->isTargetCygMing()) {
13259 // ___chkstk(Mingw64):
13260 // Clobbers R10, R11, RAX and EFLAGS.
13262 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13263 .addExternalSymbol("___chkstk")
13264 .addReg(X86::RAX, RegState::Implicit)
13265 .addReg(X86::RSP, RegState::Implicit)
13266 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13267 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13268 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13270 // __chkstk(MSVCRT): does not update stack pointer.
13271 // Clobbers R10, R11 and EFLAGS.
13272 // FIXME: RAX(allocated size) might be reused and not killed.
13273 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13274 .addExternalSymbol("__chkstk")
13275 .addReg(X86::RAX, RegState::Implicit)
13276 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13277 // RAX has the offset to subtracted from RSP.
13278 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13283 const char *StackProbeSymbol =
13284 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13286 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13287 .addExternalSymbol(StackProbeSymbol)
13288 .addReg(X86::EAX, RegState::Implicit)
13289 .addReg(X86::ESP, RegState::Implicit)
13290 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13291 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13292 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13295 MI->eraseFromParent(); // The pseudo instruction is gone now.
13299 MachineBasicBlock *
13300 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13301 MachineBasicBlock *BB) const {
13302 // This is pretty easy. We're taking the value that we received from
13303 // our load from the relocation, sticking it in either RDI (x86-64)
13304 // or EAX and doing an indirect call. The return value will then
13305 // be in the normal return register.
13306 const X86InstrInfo *TII
13307 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13308 DebugLoc DL = MI->getDebugLoc();
13309 MachineFunction *F = BB->getParent();
13311 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13312 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13314 // Get a register mask for the lowered call.
13315 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13316 // proper register mask.
13317 const uint32_t *RegMask =
13318 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13319 if (Subtarget->is64Bit()) {
13320 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13321 TII->get(X86::MOV64rm), X86::RDI)
13323 .addImm(0).addReg(0)
13324 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13325 MI->getOperand(3).getTargetFlags())
13327 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13328 addDirectMem(MIB, X86::RDI);
13329 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13330 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13331 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13332 TII->get(X86::MOV32rm), X86::EAX)
13334 .addImm(0).addReg(0)
13335 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13336 MI->getOperand(3).getTargetFlags())
13338 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13339 addDirectMem(MIB, X86::EAX);
13340 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13342 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13343 TII->get(X86::MOV32rm), X86::EAX)
13344 .addReg(TII->getGlobalBaseReg(F))
13345 .addImm(0).addReg(0)
13346 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13347 MI->getOperand(3).getTargetFlags())
13349 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13350 addDirectMem(MIB, X86::EAX);
13351 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13354 MI->eraseFromParent(); // The pseudo instruction is gone now.
13358 MachineBasicBlock *
13359 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13360 MachineBasicBlock *MBB) const {
13361 DebugLoc DL = MI->getDebugLoc();
13362 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13364 MachineFunction *MF = MBB->getParent();
13365 MachineRegisterInfo &MRI = MF->getRegInfo();
13367 const BasicBlock *BB = MBB->getBasicBlock();
13368 MachineFunction::iterator I = MBB;
13371 // Memory Reference
13372 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13373 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13376 unsigned MemOpndSlot = 0;
13378 unsigned CurOp = 0;
13380 DstReg = MI->getOperand(CurOp++).getReg();
13381 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13382 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13383 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13384 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13386 MemOpndSlot = CurOp;
13388 MVT PVT = getPointerTy();
13389 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13390 "Invalid Pointer Size!");
13392 // For v = setjmp(buf), we generate
13395 // buf[LabelOffset] = restoreMBB
13396 // SjLjSetup restoreMBB
13402 // v = phi(main, restore)
13407 MachineBasicBlock *thisMBB = MBB;
13408 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13409 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13410 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13411 MF->insert(I, mainMBB);
13412 MF->insert(I, sinkMBB);
13413 MF->push_back(restoreMBB);
13415 MachineInstrBuilder MIB;
13417 // Transfer the remainder of BB and its successor edges to sinkMBB.
13418 sinkMBB->splice(sinkMBB->begin(), MBB,
13419 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13420 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13423 unsigned PtrStoreOpc = 0;
13424 unsigned LabelReg = 0;
13425 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13426 Reloc::Model RM = getTargetMachine().getRelocationModel();
13427 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13428 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13430 // Prepare IP either in reg or imm.
13431 if (!UseImmLabel) {
13432 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13433 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13434 LabelReg = MRI.createVirtualRegister(PtrRC);
13435 if (Subtarget->is64Bit()) {
13436 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13440 .addMBB(restoreMBB)
13443 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13444 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13445 .addReg(XII->getGlobalBaseReg(MF))
13448 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13452 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13454 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13455 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13456 if (i == X86::AddrDisp)
13457 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13459 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13462 MIB.addReg(LabelReg);
13464 MIB.addMBB(restoreMBB);
13465 MIB.setMemRefs(MMOBegin, MMOEnd);
13467 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13468 .addMBB(restoreMBB);
13469 MIB.addRegMask(RegInfo->getNoPreservedMask());
13470 thisMBB->addSuccessor(mainMBB);
13471 thisMBB->addSuccessor(restoreMBB);
13475 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13476 mainMBB->addSuccessor(sinkMBB);
13479 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13480 TII->get(X86::PHI), DstReg)
13481 .addReg(mainDstReg).addMBB(mainMBB)
13482 .addReg(restoreDstReg).addMBB(restoreMBB);
13485 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13486 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13487 restoreMBB->addSuccessor(sinkMBB);
13489 MI->eraseFromParent();
13493 MachineBasicBlock *
13494 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13495 MachineBasicBlock *MBB) const {
13496 DebugLoc DL = MI->getDebugLoc();
13497 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13499 MachineFunction *MF = MBB->getParent();
13500 MachineRegisterInfo &MRI = MF->getRegInfo();
13502 // Memory Reference
13503 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13504 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13506 MVT PVT = getPointerTy();
13507 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13508 "Invalid Pointer Size!");
13510 const TargetRegisterClass *RC =
13511 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13512 unsigned Tmp = MRI.createVirtualRegister(RC);
13513 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13514 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13515 unsigned SP = RegInfo->getStackRegister();
13517 MachineInstrBuilder MIB;
13519 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13520 const int64_t SPOffset = 2 * PVT.getStoreSize();
13522 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13523 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13526 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13527 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13528 MIB.addOperand(MI->getOperand(i));
13529 MIB.setMemRefs(MMOBegin, MMOEnd);
13531 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13532 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13533 if (i == X86::AddrDisp)
13534 MIB.addDisp(MI->getOperand(i), LabelOffset);
13536 MIB.addOperand(MI->getOperand(i));
13538 MIB.setMemRefs(MMOBegin, MMOEnd);
13540 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13541 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13542 if (i == X86::AddrDisp)
13543 MIB.addDisp(MI->getOperand(i), SPOffset);
13545 MIB.addOperand(MI->getOperand(i));
13547 MIB.setMemRefs(MMOBegin, MMOEnd);
13549 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13551 MI->eraseFromParent();
13555 MachineBasicBlock *
13556 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13557 MachineBasicBlock *BB) const {
13558 switch (MI->getOpcode()) {
13559 default: llvm_unreachable("Unexpected instr type to insert");
13560 case X86::TAILJMPd64:
13561 case X86::TAILJMPr64:
13562 case X86::TAILJMPm64:
13563 llvm_unreachable("TAILJMP64 would not be touched here.");
13564 case X86::TCRETURNdi64:
13565 case X86::TCRETURNri64:
13566 case X86::TCRETURNmi64:
13568 case X86::WIN_ALLOCA:
13569 return EmitLoweredWinAlloca(MI, BB);
13570 case X86::SEG_ALLOCA_32:
13571 return EmitLoweredSegAlloca(MI, BB, false);
13572 case X86::SEG_ALLOCA_64:
13573 return EmitLoweredSegAlloca(MI, BB, true);
13574 case X86::TLSCall_32:
13575 case X86::TLSCall_64:
13576 return EmitLoweredTLSCall(MI, BB);
13577 case X86::CMOV_GR8:
13578 case X86::CMOV_FR32:
13579 case X86::CMOV_FR64:
13580 case X86::CMOV_V4F32:
13581 case X86::CMOV_V2F64:
13582 case X86::CMOV_V2I64:
13583 case X86::CMOV_V8F32:
13584 case X86::CMOV_V4F64:
13585 case X86::CMOV_V4I64:
13586 case X86::CMOV_GR16:
13587 case X86::CMOV_GR32:
13588 case X86::CMOV_RFP32:
13589 case X86::CMOV_RFP64:
13590 case X86::CMOV_RFP80:
13591 return EmitLoweredSelect(MI, BB);
13593 case X86::FP32_TO_INT16_IN_MEM:
13594 case X86::FP32_TO_INT32_IN_MEM:
13595 case X86::FP32_TO_INT64_IN_MEM:
13596 case X86::FP64_TO_INT16_IN_MEM:
13597 case X86::FP64_TO_INT32_IN_MEM:
13598 case X86::FP64_TO_INT64_IN_MEM:
13599 case X86::FP80_TO_INT16_IN_MEM:
13600 case X86::FP80_TO_INT32_IN_MEM:
13601 case X86::FP80_TO_INT64_IN_MEM: {
13602 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13603 DebugLoc DL = MI->getDebugLoc();
13605 // Change the floating point control register to use "round towards zero"
13606 // mode when truncating to an integer value.
13607 MachineFunction *F = BB->getParent();
13608 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13609 addFrameReference(BuildMI(*BB, MI, DL,
13610 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13612 // Load the old value of the high byte of the control word...
13614 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13615 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13618 // Set the high part to be round to zero...
13619 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13622 // Reload the modified control word now...
13623 addFrameReference(BuildMI(*BB, MI, DL,
13624 TII->get(X86::FLDCW16m)), CWFrameIdx);
13626 // Restore the memory image of control word to original value
13627 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13630 // Get the X86 opcode to use.
13632 switch (MI->getOpcode()) {
13633 default: llvm_unreachable("illegal opcode!");
13634 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13635 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13636 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13637 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13638 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13639 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13640 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13641 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13642 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13646 MachineOperand &Op = MI->getOperand(0);
13648 AM.BaseType = X86AddressMode::RegBase;
13649 AM.Base.Reg = Op.getReg();
13651 AM.BaseType = X86AddressMode::FrameIndexBase;
13652 AM.Base.FrameIndex = Op.getIndex();
13654 Op = MI->getOperand(1);
13656 AM.Scale = Op.getImm();
13657 Op = MI->getOperand(2);
13659 AM.IndexReg = Op.getImm();
13660 Op = MI->getOperand(3);
13661 if (Op.isGlobal()) {
13662 AM.GV = Op.getGlobal();
13664 AM.Disp = Op.getImm();
13666 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13667 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13669 // Reload the original control word now.
13670 addFrameReference(BuildMI(*BB, MI, DL,
13671 TII->get(X86::FLDCW16m)), CWFrameIdx);
13673 MI->eraseFromParent(); // The pseudo instruction is gone now.
13676 // String/text processing lowering.
13677 case X86::PCMPISTRM128REG:
13678 case X86::VPCMPISTRM128REG:
13679 case X86::PCMPISTRM128MEM:
13680 case X86::VPCMPISTRM128MEM:
13681 case X86::PCMPESTRM128REG:
13682 case X86::VPCMPESTRM128REG:
13683 case X86::PCMPESTRM128MEM:
13684 case X86::VPCMPESTRM128MEM: {
13687 switch (MI->getOpcode()) {
13688 default: llvm_unreachable("illegal opcode!");
13689 case X86::PCMPISTRM128REG:
13690 case X86::VPCMPISTRM128REG:
13691 NumArgs = 3; MemArg = false; break;
13692 case X86::PCMPISTRM128MEM:
13693 case X86::VPCMPISTRM128MEM:
13694 NumArgs = 3; MemArg = true; break;
13695 case X86::PCMPESTRM128REG:
13696 case X86::VPCMPESTRM128REG:
13697 NumArgs = 5; MemArg = false; break;
13698 case X86::PCMPESTRM128MEM:
13699 case X86::VPCMPESTRM128MEM:
13700 NumArgs = 5; MemArg = true; break;
13702 return EmitPCMP(MI, BB, NumArgs, MemArg);
13705 // Thread synchronization.
13707 return EmitMonitor(MI, BB);
13709 // Atomic Lowering.
13710 case X86::ATOMAND8:
13711 case X86::ATOMAND16:
13712 case X86::ATOMAND32:
13713 case X86::ATOMAND64:
13716 case X86::ATOMOR16:
13717 case X86::ATOMOR32:
13718 case X86::ATOMOR64:
13720 case X86::ATOMXOR16:
13721 case X86::ATOMXOR8:
13722 case X86::ATOMXOR32:
13723 case X86::ATOMXOR64:
13725 case X86::ATOMNAND8:
13726 case X86::ATOMNAND16:
13727 case X86::ATOMNAND32:
13728 case X86::ATOMNAND64:
13730 case X86::ATOMMAX8:
13731 case X86::ATOMMAX16:
13732 case X86::ATOMMAX32:
13733 case X86::ATOMMAX64:
13735 case X86::ATOMMIN8:
13736 case X86::ATOMMIN16:
13737 case X86::ATOMMIN32:
13738 case X86::ATOMMIN64:
13740 case X86::ATOMUMAX8:
13741 case X86::ATOMUMAX16:
13742 case X86::ATOMUMAX32:
13743 case X86::ATOMUMAX64:
13745 case X86::ATOMUMIN8:
13746 case X86::ATOMUMIN16:
13747 case X86::ATOMUMIN32:
13748 case X86::ATOMUMIN64:
13749 return EmitAtomicLoadArith(MI, BB);
13751 // This group does 64-bit operations on a 32-bit host.
13752 case X86::ATOMAND6432:
13753 case X86::ATOMOR6432:
13754 case X86::ATOMXOR6432:
13755 case X86::ATOMNAND6432:
13756 case X86::ATOMADD6432:
13757 case X86::ATOMSUB6432:
13758 case X86::ATOMMAX6432:
13759 case X86::ATOMMIN6432:
13760 case X86::ATOMUMAX6432:
13761 case X86::ATOMUMIN6432:
13762 case X86::ATOMSWAP6432:
13763 return EmitAtomicLoadArith6432(MI, BB);
13765 case X86::VASTART_SAVE_XMM_REGS:
13766 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13768 case X86::VAARG_64:
13769 return EmitVAARG64WithCustomInserter(MI, BB);
13771 case X86::EH_SjLj_SetJmp32:
13772 case X86::EH_SjLj_SetJmp64:
13773 return emitEHSjLjSetJmp(MI, BB);
13775 case X86::EH_SjLj_LongJmp32:
13776 case X86::EH_SjLj_LongJmp64:
13777 return emitEHSjLjLongJmp(MI, BB);
13781 //===----------------------------------------------------------------------===//
13782 // X86 Optimization Hooks
13783 //===----------------------------------------------------------------------===//
13785 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13788 const SelectionDAG &DAG,
13789 unsigned Depth) const {
13790 unsigned BitWidth = KnownZero.getBitWidth();
13791 unsigned Opc = Op.getOpcode();
13792 assert((Opc >= ISD::BUILTIN_OP_END ||
13793 Opc == ISD::INTRINSIC_WO_CHAIN ||
13794 Opc == ISD::INTRINSIC_W_CHAIN ||
13795 Opc == ISD::INTRINSIC_VOID) &&
13796 "Should use MaskedValueIsZero if you don't know whether Op"
13797 " is a target node!");
13799 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13813 // These nodes' second result is a boolean.
13814 if (Op.getResNo() == 0)
13817 case X86ISD::SETCC:
13818 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13820 case ISD::INTRINSIC_WO_CHAIN: {
13821 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13822 unsigned NumLoBits = 0;
13825 case Intrinsic::x86_sse_movmsk_ps:
13826 case Intrinsic::x86_avx_movmsk_ps_256:
13827 case Intrinsic::x86_sse2_movmsk_pd:
13828 case Intrinsic::x86_avx_movmsk_pd_256:
13829 case Intrinsic::x86_mmx_pmovmskb:
13830 case Intrinsic::x86_sse2_pmovmskb_128:
13831 case Intrinsic::x86_avx2_pmovmskb: {
13832 // High bits of movmskp{s|d}, pmovmskb are known zero.
13834 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13835 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13836 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13837 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13838 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13839 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13840 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13841 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13843 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13852 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13853 unsigned Depth) const {
13854 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13855 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13856 return Op.getValueType().getScalarType().getSizeInBits();
13862 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13863 /// node is a GlobalAddress + offset.
13864 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13865 const GlobalValue* &GA,
13866 int64_t &Offset) const {
13867 if (N->getOpcode() == X86ISD::Wrapper) {
13868 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13869 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13870 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13874 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13877 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13878 /// same as extracting the high 128-bit part of 256-bit vector and then
13879 /// inserting the result into the low part of a new 256-bit vector
13880 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13881 EVT VT = SVOp->getValueType(0);
13882 unsigned NumElems = VT.getVectorNumElements();
13884 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13885 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13886 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13887 SVOp->getMaskElt(j) >= 0)
13893 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13894 /// same as extracting the low 128-bit part of 256-bit vector and then
13895 /// inserting the result into the high part of a new 256-bit vector
13896 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13897 EVT VT = SVOp->getValueType(0);
13898 unsigned NumElems = VT.getVectorNumElements();
13900 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13901 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13902 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13903 SVOp->getMaskElt(j) >= 0)
13909 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13910 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13911 TargetLowering::DAGCombinerInfo &DCI,
13912 const X86Subtarget* Subtarget) {
13913 DebugLoc dl = N->getDebugLoc();
13914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13915 SDValue V1 = SVOp->getOperand(0);
13916 SDValue V2 = SVOp->getOperand(1);
13917 EVT VT = SVOp->getValueType(0);
13918 unsigned NumElems = VT.getVectorNumElements();
13920 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13921 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13925 // V UNDEF BUILD_VECTOR UNDEF
13927 // CONCAT_VECTOR CONCAT_VECTOR
13930 // RESULT: V + zero extended
13932 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13933 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13934 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13937 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13940 // To match the shuffle mask, the first half of the mask should
13941 // be exactly the first vector, and all the rest a splat with the
13942 // first element of the second one.
13943 for (unsigned i = 0; i != NumElems/2; ++i)
13944 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13945 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13948 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13949 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13950 if (Ld->hasNUsesOfValue(1, 0)) {
13951 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13952 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13954 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13956 Ld->getPointerInfo(),
13957 Ld->getAlignment(),
13958 false/*isVolatile*/, true/*ReadMem*/,
13959 false/*WriteMem*/);
13960 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13964 // Emit a zeroed vector and insert the desired subvector on its
13966 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13967 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13968 return DCI.CombineTo(N, InsV);
13971 //===--------------------------------------------------------------------===//
13972 // Combine some shuffles into subvector extracts and inserts:
13975 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13976 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13977 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13978 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13979 return DCI.CombineTo(N, InsV);
13982 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13983 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13984 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13985 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13986 return DCI.CombineTo(N, InsV);
13992 /// PerformShuffleCombine - Performs several different shuffle combines.
13993 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13994 TargetLowering::DAGCombinerInfo &DCI,
13995 const X86Subtarget *Subtarget) {
13996 DebugLoc dl = N->getDebugLoc();
13997 EVT VT = N->getValueType(0);
13999 // Don't create instructions with illegal types after legalize types has run.
14000 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14001 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14004 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14005 if (Subtarget->hasAVX() && VT.is256BitVector() &&
14006 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14007 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14009 // Only handle 128 wide vector from here on.
14010 if (!VT.is128BitVector())
14013 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14014 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14015 // consecutive, non-overlapping, and in the right order.
14016 SmallVector<SDValue, 16> Elts;
14017 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14018 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14020 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14024 /// PerformTruncateCombine - Converts truncate operation to
14025 /// a sequence of vector shuffle operations.
14026 /// It is possible when we truncate 256-bit vector to 128-bit vector
14027 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14028 TargetLowering::DAGCombinerInfo &DCI,
14029 const X86Subtarget *Subtarget) {
14030 if (!DCI.isBeforeLegalizeOps())
14033 if (!Subtarget->hasAVX())
14036 EVT VT = N->getValueType(0);
14037 SDValue Op = N->getOperand(0);
14038 EVT OpVT = Op.getValueType();
14039 DebugLoc dl = N->getDebugLoc();
14041 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14043 if (Subtarget->hasAVX2()) {
14044 // AVX2: v4i64 -> v4i32
14047 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14049 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14050 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14053 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14054 DAG.getIntPtrConstant(0));
14057 // AVX: v4i64 -> v4i32
14058 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14059 DAG.getIntPtrConstant(0));
14061 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14062 DAG.getIntPtrConstant(2));
14064 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14065 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14068 static const int ShufMask1[] = {0, 2, 0, 0};
14070 SDValue Undef = DAG.getUNDEF(VT);
14071 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14072 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14075 static const int ShufMask2[] = {0, 1, 4, 5};
14077 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14080 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14082 if (Subtarget->hasAVX2()) {
14083 // AVX2: v8i32 -> v8i16
14085 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14088 SmallVector<SDValue,32> pshufbMask;
14089 for (unsigned i = 0; i < 2; ++i) {
14090 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14091 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14092 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14093 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14094 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14095 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14096 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14097 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14098 for (unsigned j = 0; j < 8; ++j)
14099 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14101 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14102 &pshufbMask[0], 32);
14103 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14105 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14107 static const int ShufMask[] = {0, 2, -1, -1};
14108 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14111 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14112 DAG.getIntPtrConstant(0));
14114 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14117 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14118 DAG.getIntPtrConstant(0));
14120 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14121 DAG.getIntPtrConstant(4));
14123 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14124 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14127 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14128 -1, -1, -1, -1, -1, -1, -1, -1};
14130 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14131 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14132 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14134 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14135 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14138 static const int ShufMask2[] = {0, 1, 4, 5};
14140 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14141 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14147 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14148 /// specific shuffle of a load can be folded into a single element load.
14149 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14150 /// shuffles have been customed lowered so we need to handle those here.
14151 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14152 TargetLowering::DAGCombinerInfo &DCI) {
14153 if (DCI.isBeforeLegalizeOps())
14156 SDValue InVec = N->getOperand(0);
14157 SDValue EltNo = N->getOperand(1);
14159 if (!isa<ConstantSDNode>(EltNo))
14162 EVT VT = InVec.getValueType();
14164 bool HasShuffleIntoBitcast = false;
14165 if (InVec.getOpcode() == ISD::BITCAST) {
14166 // Don't duplicate a load with other uses.
14167 if (!InVec.hasOneUse())
14169 EVT BCVT = InVec.getOperand(0).getValueType();
14170 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14172 InVec = InVec.getOperand(0);
14173 HasShuffleIntoBitcast = true;
14176 if (!isTargetShuffle(InVec.getOpcode()))
14179 // Don't duplicate a load with other uses.
14180 if (!InVec.hasOneUse())
14183 SmallVector<int, 16> ShuffleMask;
14185 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14189 // Select the input vector, guarding against out of range extract vector.
14190 unsigned NumElems = VT.getVectorNumElements();
14191 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14192 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14193 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14194 : InVec.getOperand(1);
14196 // If inputs to shuffle are the same for both ops, then allow 2 uses
14197 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14199 if (LdNode.getOpcode() == ISD::BITCAST) {
14200 // Don't duplicate a load with other uses.
14201 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14204 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14205 LdNode = LdNode.getOperand(0);
14208 if (!ISD::isNormalLoad(LdNode.getNode()))
14211 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14213 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14216 if (HasShuffleIntoBitcast) {
14217 // If there's a bitcast before the shuffle, check if the load type and
14218 // alignment is valid.
14219 unsigned Align = LN0->getAlignment();
14220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14221 unsigned NewAlign = TLI.getDataLayout()->
14222 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14224 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14228 // All checks match so transform back to vector_shuffle so that DAG combiner
14229 // can finish the job
14230 DebugLoc dl = N->getDebugLoc();
14232 // Create shuffle node taking into account the case that its a unary shuffle
14233 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14234 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14235 InVec.getOperand(0), Shuffle,
14237 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14238 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14242 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14243 /// generation and convert it from being a bunch of shuffles and extracts
14244 /// to a simple store and scalar loads to extract the elements.
14245 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14246 TargetLowering::DAGCombinerInfo &DCI) {
14247 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14248 if (NewOp.getNode())
14251 SDValue InputVector = N->getOperand(0);
14253 // Only operate on vectors of 4 elements, where the alternative shuffling
14254 // gets to be more expensive.
14255 if (InputVector.getValueType() != MVT::v4i32)
14258 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14259 // single use which is a sign-extend or zero-extend, and all elements are
14261 SmallVector<SDNode *, 4> Uses;
14262 unsigned ExtractedElements = 0;
14263 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14264 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14265 if (UI.getUse().getResNo() != InputVector.getResNo())
14268 SDNode *Extract = *UI;
14269 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14272 if (Extract->getValueType(0) != MVT::i32)
14274 if (!Extract->hasOneUse())
14276 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14277 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14279 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14282 // Record which element was extracted.
14283 ExtractedElements |=
14284 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14286 Uses.push_back(Extract);
14289 // If not all the elements were used, this may not be worthwhile.
14290 if (ExtractedElements != 15)
14293 // Ok, we've now decided to do the transformation.
14294 DebugLoc dl = InputVector.getDebugLoc();
14296 // Store the value to a temporary stack slot.
14297 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14298 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14299 MachinePointerInfo(), false, false, 0);
14301 // Replace each use (extract) with a load of the appropriate element.
14302 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14303 UE = Uses.end(); UI != UE; ++UI) {
14304 SDNode *Extract = *UI;
14306 // cOMpute the element's address.
14307 SDValue Idx = Extract->getOperand(1);
14309 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14310 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14311 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14312 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14314 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14315 StackPtr, OffsetVal);
14317 // Load the scalar.
14318 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14319 ScalarAddr, MachinePointerInfo(),
14320 false, false, false, 0);
14322 // Replace the exact with the load.
14323 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14326 // The replacement was made in place; don't return anything.
14330 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14332 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14333 TargetLowering::DAGCombinerInfo &DCI,
14334 const X86Subtarget *Subtarget) {
14335 DebugLoc DL = N->getDebugLoc();
14336 SDValue Cond = N->getOperand(0);
14337 // Get the LHS/RHS of the select.
14338 SDValue LHS = N->getOperand(1);
14339 SDValue RHS = N->getOperand(2);
14340 EVT VT = LHS.getValueType();
14342 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14343 // instructions match the semantics of the common C idiom x<y?x:y but not
14344 // x<=y?x:y, because of how they handle negative zero (which can be
14345 // ignored in unsafe-math mode).
14346 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14347 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14348 (Subtarget->hasSSE2() ||
14349 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14350 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14352 unsigned Opcode = 0;
14353 // Check for x CC y ? x : y.
14354 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14355 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14359 // Converting this to a min would handle NaNs incorrectly, and swapping
14360 // the operands would cause it to handle comparisons between positive
14361 // and negative zero incorrectly.
14362 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14363 if (!DAG.getTarget().Options.UnsafeFPMath &&
14364 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14366 std::swap(LHS, RHS);
14368 Opcode = X86ISD::FMIN;
14371 // Converting this to a min would handle comparisons between positive
14372 // and negative zero incorrectly.
14373 if (!DAG.getTarget().Options.UnsafeFPMath &&
14374 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14376 Opcode = X86ISD::FMIN;
14379 // Converting this to a min would handle both negative zeros and NaNs
14380 // incorrectly, but we can swap the operands to fix both.
14381 std::swap(LHS, RHS);
14385 Opcode = X86ISD::FMIN;
14389 // Converting this to a max would handle comparisons between positive
14390 // and negative zero incorrectly.
14391 if (!DAG.getTarget().Options.UnsafeFPMath &&
14392 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14394 Opcode = X86ISD::FMAX;
14397 // Converting this to a max would handle NaNs incorrectly, and swapping
14398 // the operands would cause it to handle comparisons between positive
14399 // and negative zero incorrectly.
14400 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14401 if (!DAG.getTarget().Options.UnsafeFPMath &&
14402 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14404 std::swap(LHS, RHS);
14406 Opcode = X86ISD::FMAX;
14409 // Converting this to a max would handle both negative zeros and NaNs
14410 // incorrectly, but we can swap the operands to fix both.
14411 std::swap(LHS, RHS);
14415 Opcode = X86ISD::FMAX;
14418 // Check for x CC y ? y : x -- a min/max with reversed arms.
14419 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14420 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14424 // Converting this to a min would handle comparisons between positive
14425 // and negative zero incorrectly, and swapping the operands would
14426 // cause it to handle NaNs incorrectly.
14427 if (!DAG.getTarget().Options.UnsafeFPMath &&
14428 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14429 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14431 std::swap(LHS, RHS);
14433 Opcode = X86ISD::FMIN;
14436 // Converting this to a min would handle NaNs incorrectly.
14437 if (!DAG.getTarget().Options.UnsafeFPMath &&
14438 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14440 Opcode = X86ISD::FMIN;
14443 // Converting this to a min would handle both negative zeros and NaNs
14444 // incorrectly, but we can swap the operands to fix both.
14445 std::swap(LHS, RHS);
14449 Opcode = X86ISD::FMIN;
14453 // Converting this to a max would handle NaNs incorrectly.
14454 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14456 Opcode = X86ISD::FMAX;
14459 // Converting this to a max would handle comparisons between positive
14460 // and negative zero incorrectly, and swapping the operands would
14461 // cause it to handle NaNs incorrectly.
14462 if (!DAG.getTarget().Options.UnsafeFPMath &&
14463 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14464 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14466 std::swap(LHS, RHS);
14468 Opcode = X86ISD::FMAX;
14471 // Converting this to a max would handle both negative zeros and NaNs
14472 // incorrectly, but we can swap the operands to fix both.
14473 std::swap(LHS, RHS);
14477 Opcode = X86ISD::FMAX;
14483 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14486 // If this is a select between two integer constants, try to do some
14488 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14489 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14490 // Don't do this for crazy integer types.
14491 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14492 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14493 // so that TrueC (the true value) is larger than FalseC.
14494 bool NeedsCondInvert = false;
14496 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14497 // Efficiently invertible.
14498 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14499 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14500 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14501 NeedsCondInvert = true;
14502 std::swap(TrueC, FalseC);
14505 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14506 if (FalseC->getAPIntValue() == 0 &&
14507 TrueC->getAPIntValue().isPowerOf2()) {
14508 if (NeedsCondInvert) // Invert the condition if needed.
14509 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14510 DAG.getConstant(1, Cond.getValueType()));
14512 // Zero extend the condition if needed.
14513 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14515 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14516 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14517 DAG.getConstant(ShAmt, MVT::i8));
14520 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14521 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14522 if (NeedsCondInvert) // Invert the condition if needed.
14523 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14524 DAG.getConstant(1, Cond.getValueType()));
14526 // Zero extend the condition if needed.
14527 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14528 FalseC->getValueType(0), Cond);
14529 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14530 SDValue(FalseC, 0));
14533 // Optimize cases that will turn into an LEA instruction. This requires
14534 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14535 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14536 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14537 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14539 bool isFastMultiplier = false;
14541 switch ((unsigned char)Diff) {
14543 case 1: // result = add base, cond
14544 case 2: // result = lea base( , cond*2)
14545 case 3: // result = lea base(cond, cond*2)
14546 case 4: // result = lea base( , cond*4)
14547 case 5: // result = lea base(cond, cond*4)
14548 case 8: // result = lea base( , cond*8)
14549 case 9: // result = lea base(cond, cond*8)
14550 isFastMultiplier = true;
14555 if (isFastMultiplier) {
14556 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14557 if (NeedsCondInvert) // Invert the condition if needed.
14558 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14559 DAG.getConstant(1, Cond.getValueType()));
14561 // Zero extend the condition if needed.
14562 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14564 // Scale the condition by the difference.
14566 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14567 DAG.getConstant(Diff, Cond.getValueType()));
14569 // Add the base if non-zero.
14570 if (FalseC->getAPIntValue() != 0)
14571 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14572 SDValue(FalseC, 0));
14579 // Canonicalize max and min:
14580 // (x > y) ? x : y -> (x >= y) ? x : y
14581 // (x < y) ? x : y -> (x <= y) ? x : y
14582 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14583 // the need for an extra compare
14584 // against zero. e.g.
14585 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14587 // testl %edi, %edi
14589 // cmovgl %edi, %eax
14593 // cmovsl %eax, %edi
14594 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14595 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14596 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14597 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14602 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14603 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14604 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14605 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14610 // If we know that this node is legal then we know that it is going to be
14611 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14612 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14613 // to simplify previous instructions.
14614 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14615 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14616 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14617 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14619 // Don't optimize vector selects that map to mask-registers.
14623 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14624 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14626 APInt KnownZero, KnownOne;
14627 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14628 DCI.isBeforeLegalizeOps());
14629 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14630 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14631 DCI.CommitTargetLoweringOpt(TLO);
14637 // Check whether a boolean test is testing a boolean value generated by
14638 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14641 // Simplify the following patterns:
14642 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14643 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14644 // to (Op EFLAGS Cond)
14646 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14647 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14648 // to (Op EFLAGS !Cond)
14650 // where Op could be BRCOND or CMOV.
14652 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14653 // Quit if not CMP and SUB with its value result used.
14654 if (Cmp.getOpcode() != X86ISD::CMP &&
14655 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14658 // Quit if not used as a boolean value.
14659 if (CC != X86::COND_E && CC != X86::COND_NE)
14662 // Check CMP operands. One of them should be 0 or 1 and the other should be
14663 // an SetCC or extended from it.
14664 SDValue Op1 = Cmp.getOperand(0);
14665 SDValue Op2 = Cmp.getOperand(1);
14668 const ConstantSDNode* C = 0;
14669 bool needOppositeCond = (CC == X86::COND_E);
14671 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14673 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14675 else // Quit if all operands are not constants.
14678 if (C->getZExtValue() == 1)
14679 needOppositeCond = !needOppositeCond;
14680 else if (C->getZExtValue() != 0)
14681 // Quit if the constant is neither 0 or 1.
14684 // Skip 'zext' node.
14685 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14686 SetCC = SetCC.getOperand(0);
14688 switch (SetCC.getOpcode()) {
14689 case X86ISD::SETCC:
14690 // Set the condition code or opposite one if necessary.
14691 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14692 if (needOppositeCond)
14693 CC = X86::GetOppositeBranchCondition(CC);
14694 return SetCC.getOperand(1);
14695 case X86ISD::CMOV: {
14696 // Check whether false/true value has canonical one, i.e. 0 or 1.
14697 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14698 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14699 // Quit if true value is not a constant.
14702 // Quit if false value is not a constant.
14704 // A special case for rdrand, where 0 is set if false cond is found.
14705 SDValue Op = SetCC.getOperand(0);
14706 if (Op.getOpcode() != X86ISD::RDRAND)
14709 // Quit if false value is not the constant 0 or 1.
14710 bool FValIsFalse = true;
14711 if (FVal && FVal->getZExtValue() != 0) {
14712 if (FVal->getZExtValue() != 1)
14714 // If FVal is 1, opposite cond is needed.
14715 needOppositeCond = !needOppositeCond;
14716 FValIsFalse = false;
14718 // Quit if TVal is not the constant opposite of FVal.
14719 if (FValIsFalse && TVal->getZExtValue() != 1)
14721 if (!FValIsFalse && TVal->getZExtValue() != 0)
14723 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14724 if (needOppositeCond)
14725 CC = X86::GetOppositeBranchCondition(CC);
14726 return SetCC.getOperand(3);
14733 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14734 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14735 TargetLowering::DAGCombinerInfo &DCI,
14736 const X86Subtarget *Subtarget) {
14737 DebugLoc DL = N->getDebugLoc();
14739 // If the flag operand isn't dead, don't touch this CMOV.
14740 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14743 SDValue FalseOp = N->getOperand(0);
14744 SDValue TrueOp = N->getOperand(1);
14745 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14746 SDValue Cond = N->getOperand(3);
14748 if (CC == X86::COND_E || CC == X86::COND_NE) {
14749 switch (Cond.getOpcode()) {
14753 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14754 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14755 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14761 Flags = checkBoolTestSetCCCombine(Cond, CC);
14762 if (Flags.getNode() &&
14763 // Extra check as FCMOV only supports a subset of X86 cond.
14764 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14765 SDValue Ops[] = { FalseOp, TrueOp,
14766 DAG.getConstant(CC, MVT::i8), Flags };
14767 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14768 Ops, array_lengthof(Ops));
14771 // If this is a select between two integer constants, try to do some
14772 // optimizations. Note that the operands are ordered the opposite of SELECT
14774 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14775 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14776 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14777 // larger than FalseC (the false value).
14778 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14779 CC = X86::GetOppositeBranchCondition(CC);
14780 std::swap(TrueC, FalseC);
14781 std::swap(TrueOp, FalseOp);
14784 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14785 // This is efficient for any integer data type (including i8/i16) and
14787 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14788 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14789 DAG.getConstant(CC, MVT::i8), Cond);
14791 // Zero extend the condition if needed.
14792 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14794 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14795 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14796 DAG.getConstant(ShAmt, MVT::i8));
14797 if (N->getNumValues() == 2) // Dead flag value?
14798 return DCI.CombineTo(N, Cond, SDValue());
14802 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14803 // for any integer data type, including i8/i16.
14804 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14805 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14806 DAG.getConstant(CC, MVT::i8), Cond);
14808 // Zero extend the condition if needed.
14809 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14810 FalseC->getValueType(0), Cond);
14811 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14812 SDValue(FalseC, 0));
14814 if (N->getNumValues() == 2) // Dead flag value?
14815 return DCI.CombineTo(N, Cond, SDValue());
14819 // Optimize cases that will turn into an LEA instruction. This requires
14820 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14821 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14822 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14823 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14825 bool isFastMultiplier = false;
14827 switch ((unsigned char)Diff) {
14829 case 1: // result = add base, cond
14830 case 2: // result = lea base( , cond*2)
14831 case 3: // result = lea base(cond, cond*2)
14832 case 4: // result = lea base( , cond*4)
14833 case 5: // result = lea base(cond, cond*4)
14834 case 8: // result = lea base( , cond*8)
14835 case 9: // result = lea base(cond, cond*8)
14836 isFastMultiplier = true;
14841 if (isFastMultiplier) {
14842 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14843 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14844 DAG.getConstant(CC, MVT::i8), Cond);
14845 // Zero extend the condition if needed.
14846 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14848 // Scale the condition by the difference.
14850 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14851 DAG.getConstant(Diff, Cond.getValueType()));
14853 // Add the base if non-zero.
14854 if (FalseC->getAPIntValue() != 0)
14855 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14856 SDValue(FalseC, 0));
14857 if (N->getNumValues() == 2) // Dead flag value?
14858 return DCI.CombineTo(N, Cond, SDValue());
14865 // Handle these cases:
14866 // (select (x != c), e, c) -> select (x != c), e, x),
14867 // (select (x == c), c, e) -> select (x == c), x, e)
14868 // where the c is an integer constant, and the "select" is the combination
14869 // of CMOV and CMP.
14871 // The rationale for this change is that the conditional-move from a constant
14872 // needs two instructions, however, conditional-move from a register needs
14873 // only one instruction.
14875 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14876 // some instruction-combining opportunities. This opt needs to be
14877 // postponed as late as possible.
14879 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14880 // the DCI.xxxx conditions are provided to postpone the optimization as
14881 // late as possible.
14883 ConstantSDNode *CmpAgainst = 0;
14884 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14885 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14886 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14888 if (CC == X86::COND_NE &&
14889 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14890 CC = X86::GetOppositeBranchCondition(CC);
14891 std::swap(TrueOp, FalseOp);
14894 if (CC == X86::COND_E &&
14895 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14896 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14897 DAG.getConstant(CC, MVT::i8), Cond };
14898 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14899 array_lengthof(Ops));
14908 /// PerformMulCombine - Optimize a single multiply with constant into two
14909 /// in order to implement it with two cheaper instructions, e.g.
14910 /// LEA + SHL, LEA + LEA.
14911 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14912 TargetLowering::DAGCombinerInfo &DCI) {
14913 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14916 EVT VT = N->getValueType(0);
14917 if (VT != MVT::i64)
14920 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14923 uint64_t MulAmt = C->getZExtValue();
14924 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14927 uint64_t MulAmt1 = 0;
14928 uint64_t MulAmt2 = 0;
14929 if ((MulAmt % 9) == 0) {
14931 MulAmt2 = MulAmt / 9;
14932 } else if ((MulAmt % 5) == 0) {
14934 MulAmt2 = MulAmt / 5;
14935 } else if ((MulAmt % 3) == 0) {
14937 MulAmt2 = MulAmt / 3;
14940 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14941 DebugLoc DL = N->getDebugLoc();
14943 if (isPowerOf2_64(MulAmt2) &&
14944 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14945 // If second multiplifer is pow2, issue it first. We want the multiply by
14946 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14948 std::swap(MulAmt1, MulAmt2);
14951 if (isPowerOf2_64(MulAmt1))
14952 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14953 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14955 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14956 DAG.getConstant(MulAmt1, VT));
14958 if (isPowerOf2_64(MulAmt2))
14959 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14960 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14962 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14963 DAG.getConstant(MulAmt2, VT));
14965 // Do not add new nodes to DAG combiner worklist.
14966 DCI.CombineTo(N, NewMul, false);
14971 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14972 SDValue N0 = N->getOperand(0);
14973 SDValue N1 = N->getOperand(1);
14974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14975 EVT VT = N0.getValueType();
14977 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14978 // since the result of setcc_c is all zero's or all ones.
14979 if (VT.isInteger() && !VT.isVector() &&
14980 N1C && N0.getOpcode() == ISD::AND &&
14981 N0.getOperand(1).getOpcode() == ISD::Constant) {
14982 SDValue N00 = N0.getOperand(0);
14983 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14984 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14985 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14986 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14987 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14988 APInt ShAmt = N1C->getAPIntValue();
14989 Mask = Mask.shl(ShAmt);
14991 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14992 N00, DAG.getConstant(Mask, VT));
14997 // Hardware support for vector shifts is sparse which makes us scalarize the
14998 // vector operations in many cases. Also, on sandybridge ADD is faster than
15000 // (shl V, 1) -> add V,V
15001 if (isSplatVector(N1.getNode())) {
15002 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15003 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15004 // We shift all of the values by one. In many cases we do not have
15005 // hardware support for this operation. This is better expressed as an ADD
15007 if (N1C && (1 == N1C->getZExtValue())) {
15008 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15015 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15017 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15018 TargetLowering::DAGCombinerInfo &DCI,
15019 const X86Subtarget *Subtarget) {
15020 EVT VT = N->getValueType(0);
15021 if (N->getOpcode() == ISD::SHL) {
15022 SDValue V = PerformSHLCombine(N, DAG);
15023 if (V.getNode()) return V;
15026 // On X86 with SSE2 support, we can transform this to a vector shift if
15027 // all elements are shifted by the same amount. We can't do this in legalize
15028 // because the a constant vector is typically transformed to a constant pool
15029 // so we have no knowledge of the shift amount.
15030 if (!Subtarget->hasSSE2())
15033 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15034 (!Subtarget->hasAVX2() ||
15035 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15038 SDValue ShAmtOp = N->getOperand(1);
15039 EVT EltVT = VT.getVectorElementType();
15040 DebugLoc DL = N->getDebugLoc();
15041 SDValue BaseShAmt = SDValue();
15042 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15043 unsigned NumElts = VT.getVectorNumElements();
15045 for (; i != NumElts; ++i) {
15046 SDValue Arg = ShAmtOp.getOperand(i);
15047 if (Arg.getOpcode() == ISD::UNDEF) continue;
15051 // Handle the case where the build_vector is all undef
15052 // FIXME: Should DAG allow this?
15056 for (; i != NumElts; ++i) {
15057 SDValue Arg = ShAmtOp.getOperand(i);
15058 if (Arg.getOpcode() == ISD::UNDEF) continue;
15059 if (Arg != BaseShAmt) {
15063 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15064 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15065 SDValue InVec = ShAmtOp.getOperand(0);
15066 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15067 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15069 for (; i != NumElts; ++i) {
15070 SDValue Arg = InVec.getOperand(i);
15071 if (Arg.getOpcode() == ISD::UNDEF) continue;
15075 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15077 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15078 if (C->getZExtValue() == SplatIdx)
15079 BaseShAmt = InVec.getOperand(1);
15082 if (BaseShAmt.getNode() == 0) {
15083 // Don't create instructions with illegal types after legalize
15085 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15086 !DCI.isBeforeLegalize())
15089 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15090 DAG.getIntPtrConstant(0));
15095 // The shift amount is an i32.
15096 if (EltVT.bitsGT(MVT::i32))
15097 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15098 else if (EltVT.bitsLT(MVT::i32))
15099 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15101 // The shift amount is identical so we can do a vector shift.
15102 SDValue ValOp = N->getOperand(0);
15103 switch (N->getOpcode()) {
15105 llvm_unreachable("Unknown shift opcode!");
15107 switch (VT.getSimpleVT().SimpleTy) {
15108 default: return SDValue();
15115 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15118 switch (VT.getSimpleVT().SimpleTy) {
15119 default: return SDValue();
15124 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15127 switch (VT.getSimpleVT().SimpleTy) {
15128 default: return SDValue();
15135 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15141 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15142 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15143 // and friends. Likewise for OR -> CMPNEQSS.
15144 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15145 TargetLowering::DAGCombinerInfo &DCI,
15146 const X86Subtarget *Subtarget) {
15149 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15150 // we're requiring SSE2 for both.
15151 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15152 SDValue N0 = N->getOperand(0);
15153 SDValue N1 = N->getOperand(1);
15154 SDValue CMP0 = N0->getOperand(1);
15155 SDValue CMP1 = N1->getOperand(1);
15156 DebugLoc DL = N->getDebugLoc();
15158 // The SETCCs should both refer to the same CMP.
15159 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15162 SDValue CMP00 = CMP0->getOperand(0);
15163 SDValue CMP01 = CMP0->getOperand(1);
15164 EVT VT = CMP00.getValueType();
15166 if (VT == MVT::f32 || VT == MVT::f64) {
15167 bool ExpectingFlags = false;
15168 // Check for any users that want flags:
15169 for (SDNode::use_iterator UI = N->use_begin(),
15171 !ExpectingFlags && UI != UE; ++UI)
15172 switch (UI->getOpcode()) {
15177 ExpectingFlags = true;
15179 case ISD::CopyToReg:
15180 case ISD::SIGN_EXTEND:
15181 case ISD::ZERO_EXTEND:
15182 case ISD::ANY_EXTEND:
15186 if (!ExpectingFlags) {
15187 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15188 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15190 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15191 X86::CondCode tmp = cc0;
15196 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15197 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15198 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15199 X86ISD::NodeType NTOperator = is64BitFP ?
15200 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15201 // FIXME: need symbolic constants for these magic numbers.
15202 // See X86ATTInstPrinter.cpp:printSSECC().
15203 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15204 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15205 DAG.getConstant(x86cc, MVT::i8));
15206 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15208 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15209 DAG.getConstant(1, MVT::i32));
15210 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15211 return OneBitOfTruth;
15219 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15220 /// so it can be folded inside ANDNP.
15221 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15222 EVT VT = N->getValueType(0);
15224 // Match direct AllOnes for 128 and 256-bit vectors
15225 if (ISD::isBuildVectorAllOnes(N))
15228 // Look through a bit convert.
15229 if (N->getOpcode() == ISD::BITCAST)
15230 N = N->getOperand(0).getNode();
15232 // Sometimes the operand may come from a insert_subvector building a 256-bit
15234 if (VT.is256BitVector() &&
15235 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15236 SDValue V1 = N->getOperand(0);
15237 SDValue V2 = N->getOperand(1);
15239 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15240 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15241 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15242 ISD::isBuildVectorAllOnes(V2.getNode()))
15249 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15250 TargetLowering::DAGCombinerInfo &DCI,
15251 const X86Subtarget *Subtarget) {
15252 if (DCI.isBeforeLegalizeOps())
15255 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15259 EVT VT = N->getValueType(0);
15261 // Create ANDN, BLSI, and BLSR instructions
15262 // BLSI is X & (-X)
15263 // BLSR is X & (X-1)
15264 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15265 SDValue N0 = N->getOperand(0);
15266 SDValue N1 = N->getOperand(1);
15267 DebugLoc DL = N->getDebugLoc();
15269 // Check LHS for not
15270 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15271 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15272 // Check RHS for not
15273 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15274 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15276 // Check LHS for neg
15277 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15278 isZero(N0.getOperand(0)))
15279 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15281 // Check RHS for neg
15282 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15283 isZero(N1.getOperand(0)))
15284 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15286 // Check LHS for X-1
15287 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15288 isAllOnes(N0.getOperand(1)))
15289 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15291 // Check RHS for X-1
15292 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15293 isAllOnes(N1.getOperand(1)))
15294 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15299 // Want to form ANDNP nodes:
15300 // 1) In the hopes of then easily combining them with OR and AND nodes
15301 // to form PBLEND/PSIGN.
15302 // 2) To match ANDN packed intrinsics
15303 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15306 SDValue N0 = N->getOperand(0);
15307 SDValue N1 = N->getOperand(1);
15308 DebugLoc DL = N->getDebugLoc();
15310 // Check LHS for vnot
15311 if (N0.getOpcode() == ISD::XOR &&
15312 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15313 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15314 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15316 // Check RHS for vnot
15317 if (N1.getOpcode() == ISD::XOR &&
15318 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15319 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15320 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15325 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15326 TargetLowering::DAGCombinerInfo &DCI,
15327 const X86Subtarget *Subtarget) {
15328 if (DCI.isBeforeLegalizeOps())
15331 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15335 EVT VT = N->getValueType(0);
15337 SDValue N0 = N->getOperand(0);
15338 SDValue N1 = N->getOperand(1);
15340 // look for psign/blend
15341 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15342 if (!Subtarget->hasSSSE3() ||
15343 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15346 // Canonicalize pandn to RHS
15347 if (N0.getOpcode() == X86ISD::ANDNP)
15349 // or (and (m, y), (pandn m, x))
15350 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15351 SDValue Mask = N1.getOperand(0);
15352 SDValue X = N1.getOperand(1);
15354 if (N0.getOperand(0) == Mask)
15355 Y = N0.getOperand(1);
15356 if (N0.getOperand(1) == Mask)
15357 Y = N0.getOperand(0);
15359 // Check to see if the mask appeared in both the AND and ANDNP and
15363 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15364 // Look through mask bitcast.
15365 if (Mask.getOpcode() == ISD::BITCAST)
15366 Mask = Mask.getOperand(0);
15367 if (X.getOpcode() == ISD::BITCAST)
15368 X = X.getOperand(0);
15369 if (Y.getOpcode() == ISD::BITCAST)
15370 Y = Y.getOperand(0);
15372 EVT MaskVT = Mask.getValueType();
15374 // Validate that the Mask operand is a vector sra node.
15375 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15376 // there is no psrai.b
15377 if (Mask.getOpcode() != X86ISD::VSRAI)
15380 // Check that the SRA is all signbits.
15381 SDValue SraC = Mask.getOperand(1);
15382 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15383 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15384 if ((SraAmt + 1) != EltBits)
15387 DebugLoc DL = N->getDebugLoc();
15389 // Now we know we at least have a plendvb with the mask val. See if
15390 // we can form a psignb/w/d.
15391 // psign = x.type == y.type == mask.type && y = sub(0, x);
15392 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15393 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15394 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15395 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15396 "Unsupported VT for PSIGN");
15397 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15398 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15400 // PBLENDVB only available on SSE 4.1
15401 if (!Subtarget->hasSSE41())
15404 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15406 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15407 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15408 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15409 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15410 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15414 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15417 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15418 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15420 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15422 if (!N0.hasOneUse() || !N1.hasOneUse())
15425 SDValue ShAmt0 = N0.getOperand(1);
15426 if (ShAmt0.getValueType() != MVT::i8)
15428 SDValue ShAmt1 = N1.getOperand(1);
15429 if (ShAmt1.getValueType() != MVT::i8)
15431 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15432 ShAmt0 = ShAmt0.getOperand(0);
15433 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15434 ShAmt1 = ShAmt1.getOperand(0);
15436 DebugLoc DL = N->getDebugLoc();
15437 unsigned Opc = X86ISD::SHLD;
15438 SDValue Op0 = N0.getOperand(0);
15439 SDValue Op1 = N1.getOperand(0);
15440 if (ShAmt0.getOpcode() == ISD::SUB) {
15441 Opc = X86ISD::SHRD;
15442 std::swap(Op0, Op1);
15443 std::swap(ShAmt0, ShAmt1);
15446 unsigned Bits = VT.getSizeInBits();
15447 if (ShAmt1.getOpcode() == ISD::SUB) {
15448 SDValue Sum = ShAmt1.getOperand(0);
15449 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15450 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15451 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15452 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15453 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15454 return DAG.getNode(Opc, DL, VT,
15456 DAG.getNode(ISD::TRUNCATE, DL,
15459 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15460 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15462 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15463 return DAG.getNode(Opc, DL, VT,
15464 N0.getOperand(0), N1.getOperand(0),
15465 DAG.getNode(ISD::TRUNCATE, DL,
15472 // Generate NEG and CMOV for integer abs.
15473 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15474 EVT VT = N->getValueType(0);
15476 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15477 // 8-bit integer abs to NEG and CMOV.
15478 if (VT.isInteger() && VT.getSizeInBits() == 8)
15481 SDValue N0 = N->getOperand(0);
15482 SDValue N1 = N->getOperand(1);
15483 DebugLoc DL = N->getDebugLoc();
15485 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15486 // and change it to SUB and CMOV.
15487 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15488 N0.getOpcode() == ISD::ADD &&
15489 N0.getOperand(1) == N1 &&
15490 N1.getOpcode() == ISD::SRA &&
15491 N1.getOperand(0) == N0.getOperand(0))
15492 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15493 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15494 // Generate SUB & CMOV.
15495 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15496 DAG.getConstant(0, VT), N0.getOperand(0));
15498 SDValue Ops[] = { N0.getOperand(0), Neg,
15499 DAG.getConstant(X86::COND_GE, MVT::i8),
15500 SDValue(Neg.getNode(), 1) };
15501 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15502 Ops, array_lengthof(Ops));
15507 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15508 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15509 TargetLowering::DAGCombinerInfo &DCI,
15510 const X86Subtarget *Subtarget) {
15511 if (DCI.isBeforeLegalizeOps())
15514 if (Subtarget->hasCMov()) {
15515 SDValue RV = performIntegerAbsCombine(N, DAG);
15520 // Try forming BMI if it is available.
15521 if (!Subtarget->hasBMI())
15524 EVT VT = N->getValueType(0);
15526 if (VT != MVT::i32 && VT != MVT::i64)
15529 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15531 // Create BLSMSK instructions by finding X ^ (X-1)
15532 SDValue N0 = N->getOperand(0);
15533 SDValue N1 = N->getOperand(1);
15534 DebugLoc DL = N->getDebugLoc();
15536 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15537 isAllOnes(N0.getOperand(1)))
15538 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15540 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15541 isAllOnes(N1.getOperand(1)))
15542 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15547 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15548 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15549 TargetLowering::DAGCombinerInfo &DCI,
15550 const X86Subtarget *Subtarget) {
15551 LoadSDNode *Ld = cast<LoadSDNode>(N);
15552 EVT RegVT = Ld->getValueType(0);
15553 EVT MemVT = Ld->getMemoryVT();
15554 DebugLoc dl = Ld->getDebugLoc();
15555 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15557 ISD::LoadExtType Ext = Ld->getExtensionType();
15559 // If this is a vector EXT Load then attempt to optimize it using a
15560 // shuffle. We need SSSE3 shuffles.
15561 // TODO: It is possible to support ZExt by zeroing the undef values
15562 // during the shuffle phase or after the shuffle.
15563 if (RegVT.isVector() && RegVT.isInteger() &&
15564 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15565 assert(MemVT != RegVT && "Cannot extend to the same type");
15566 assert(MemVT.isVector() && "Must load a vector from memory");
15568 unsigned NumElems = RegVT.getVectorNumElements();
15569 unsigned RegSz = RegVT.getSizeInBits();
15570 unsigned MemSz = MemVT.getSizeInBits();
15571 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15573 // All sizes must be a power of two.
15574 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15577 // Attempt to load the original value using scalar loads.
15578 // Find the largest scalar type that divides the total loaded size.
15579 MVT SclrLoadTy = MVT::i8;
15580 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15581 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15582 MVT Tp = (MVT::SimpleValueType)tp;
15583 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15588 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15589 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15591 SclrLoadTy = MVT::f64;
15593 // Calculate the number of scalar loads that we need to perform
15594 // in order to load our vector from memory.
15595 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15597 // Represent our vector as a sequence of elements which are the
15598 // largest scalar that we can load.
15599 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15600 RegSz/SclrLoadTy.getSizeInBits());
15602 // Represent the data using the same element type that is stored in
15603 // memory. In practice, we ''widen'' MemVT.
15604 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15605 RegSz/MemVT.getScalarType().getSizeInBits());
15607 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15608 "Invalid vector type");
15610 // We can't shuffle using an illegal type.
15611 if (!TLI.isTypeLegal(WideVecVT))
15614 SmallVector<SDValue, 8> Chains;
15615 SDValue Ptr = Ld->getBasePtr();
15616 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15617 TLI.getPointerTy());
15618 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15620 for (unsigned i = 0; i < NumLoads; ++i) {
15621 // Perform a single load.
15622 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15623 Ptr, Ld->getPointerInfo(),
15624 Ld->isVolatile(), Ld->isNonTemporal(),
15625 Ld->isInvariant(), Ld->getAlignment());
15626 Chains.push_back(ScalarLoad.getValue(1));
15627 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15628 // another round of DAGCombining.
15630 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15632 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15633 ScalarLoad, DAG.getIntPtrConstant(i));
15635 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15638 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15641 // Bitcast the loaded value to a vector of the original element type, in
15642 // the size of the target vector type.
15643 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15644 unsigned SizeRatio = RegSz/MemSz;
15646 // Redistribute the loaded elements into the different locations.
15647 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15648 for (unsigned i = 0; i != NumElems; ++i)
15649 ShuffleVec[i*SizeRatio] = i;
15651 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15652 DAG.getUNDEF(WideVecVT),
15655 // Bitcast to the requested type.
15656 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15657 // Replace the original load with the new sequence
15658 // and return the new chain.
15659 return DCI.CombineTo(N, Shuff, TF, true);
15665 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15666 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15667 const X86Subtarget *Subtarget) {
15668 StoreSDNode *St = cast<StoreSDNode>(N);
15669 EVT VT = St->getValue().getValueType();
15670 EVT StVT = St->getMemoryVT();
15671 DebugLoc dl = St->getDebugLoc();
15672 SDValue StoredVal = St->getOperand(1);
15673 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15675 // If we are saving a concatenation of two XMM registers, perform two stores.
15676 // On Sandy Bridge, 256-bit memory operations are executed by two
15677 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15678 // memory operation.
15679 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15680 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15681 StoredVal.getNumOperands() == 2) {
15682 SDValue Value0 = StoredVal.getOperand(0);
15683 SDValue Value1 = StoredVal.getOperand(1);
15685 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15686 SDValue Ptr0 = St->getBasePtr();
15687 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15689 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15690 St->getPointerInfo(), St->isVolatile(),
15691 St->isNonTemporal(), St->getAlignment());
15692 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15693 St->getPointerInfo(), St->isVolatile(),
15694 St->isNonTemporal(), St->getAlignment());
15695 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15698 // Optimize trunc store (of multiple scalars) to shuffle and store.
15699 // First, pack all of the elements in one place. Next, store to memory
15700 // in fewer chunks.
15701 if (St->isTruncatingStore() && VT.isVector()) {
15702 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15703 unsigned NumElems = VT.getVectorNumElements();
15704 assert(StVT != VT && "Cannot truncate to the same type");
15705 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15706 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15708 // From, To sizes and ElemCount must be pow of two
15709 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15710 // We are going to use the original vector elt for storing.
15711 // Accumulated smaller vector elements must be a multiple of the store size.
15712 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15714 unsigned SizeRatio = FromSz / ToSz;
15716 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15718 // Create a type on which we perform the shuffle
15719 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15720 StVT.getScalarType(), NumElems*SizeRatio);
15722 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15724 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15725 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15726 for (unsigned i = 0; i != NumElems; ++i)
15727 ShuffleVec[i] = i * SizeRatio;
15729 // Can't shuffle using an illegal type.
15730 if (!TLI.isTypeLegal(WideVecVT))
15733 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15734 DAG.getUNDEF(WideVecVT),
15736 // At this point all of the data is stored at the bottom of the
15737 // register. We now need to save it to mem.
15739 // Find the largest store unit
15740 MVT StoreType = MVT::i8;
15741 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15742 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15743 MVT Tp = (MVT::SimpleValueType)tp;
15744 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15748 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15749 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15750 (64 <= NumElems * ToSz))
15751 StoreType = MVT::f64;
15753 // Bitcast the original vector into a vector of store-size units
15754 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15755 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15756 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15757 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15758 SmallVector<SDValue, 8> Chains;
15759 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15760 TLI.getPointerTy());
15761 SDValue Ptr = St->getBasePtr();
15763 // Perform one or more big stores into memory.
15764 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15765 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15766 StoreType, ShuffWide,
15767 DAG.getIntPtrConstant(i));
15768 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15769 St->getPointerInfo(), St->isVolatile(),
15770 St->isNonTemporal(), St->getAlignment());
15771 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15772 Chains.push_back(Ch);
15775 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15780 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15781 // the FP state in cases where an emms may be missing.
15782 // A preferable solution to the general problem is to figure out the right
15783 // places to insert EMMS. This qualifies as a quick hack.
15785 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15786 if (VT.getSizeInBits() != 64)
15789 const Function *F = DAG.getMachineFunction().getFunction();
15790 bool NoImplicitFloatOps = F->getFnAttributes().
15791 hasAttribute(Attributes::NoImplicitFloat);
15792 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15793 && Subtarget->hasSSE2();
15794 if ((VT.isVector() ||
15795 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15796 isa<LoadSDNode>(St->getValue()) &&
15797 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15798 St->getChain().hasOneUse() && !St->isVolatile()) {
15799 SDNode* LdVal = St->getValue().getNode();
15800 LoadSDNode *Ld = 0;
15801 int TokenFactorIndex = -1;
15802 SmallVector<SDValue, 8> Ops;
15803 SDNode* ChainVal = St->getChain().getNode();
15804 // Must be a store of a load. We currently handle two cases: the load
15805 // is a direct child, and it's under an intervening TokenFactor. It is
15806 // possible to dig deeper under nested TokenFactors.
15807 if (ChainVal == LdVal)
15808 Ld = cast<LoadSDNode>(St->getChain());
15809 else if (St->getValue().hasOneUse() &&
15810 ChainVal->getOpcode() == ISD::TokenFactor) {
15811 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15812 if (ChainVal->getOperand(i).getNode() == LdVal) {
15813 TokenFactorIndex = i;
15814 Ld = cast<LoadSDNode>(St->getValue());
15816 Ops.push_back(ChainVal->getOperand(i));
15820 if (!Ld || !ISD::isNormalLoad(Ld))
15823 // If this is not the MMX case, i.e. we are just turning i64 load/store
15824 // into f64 load/store, avoid the transformation if there are multiple
15825 // uses of the loaded value.
15826 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15829 DebugLoc LdDL = Ld->getDebugLoc();
15830 DebugLoc StDL = N->getDebugLoc();
15831 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15832 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15834 if (Subtarget->is64Bit() || F64IsLegal) {
15835 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15836 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15837 Ld->getPointerInfo(), Ld->isVolatile(),
15838 Ld->isNonTemporal(), Ld->isInvariant(),
15839 Ld->getAlignment());
15840 SDValue NewChain = NewLd.getValue(1);
15841 if (TokenFactorIndex != -1) {
15842 Ops.push_back(NewChain);
15843 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15846 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15847 St->getPointerInfo(),
15848 St->isVolatile(), St->isNonTemporal(),
15849 St->getAlignment());
15852 // Otherwise, lower to two pairs of 32-bit loads / stores.
15853 SDValue LoAddr = Ld->getBasePtr();
15854 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15855 DAG.getConstant(4, MVT::i32));
15857 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15858 Ld->getPointerInfo(),
15859 Ld->isVolatile(), Ld->isNonTemporal(),
15860 Ld->isInvariant(), Ld->getAlignment());
15861 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15862 Ld->getPointerInfo().getWithOffset(4),
15863 Ld->isVolatile(), Ld->isNonTemporal(),
15865 MinAlign(Ld->getAlignment(), 4));
15867 SDValue NewChain = LoLd.getValue(1);
15868 if (TokenFactorIndex != -1) {
15869 Ops.push_back(LoLd);
15870 Ops.push_back(HiLd);
15871 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15875 LoAddr = St->getBasePtr();
15876 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15877 DAG.getConstant(4, MVT::i32));
15879 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15880 St->getPointerInfo(),
15881 St->isVolatile(), St->isNonTemporal(),
15882 St->getAlignment());
15883 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15884 St->getPointerInfo().getWithOffset(4),
15886 St->isNonTemporal(),
15887 MinAlign(St->getAlignment(), 4));
15888 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15893 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15894 /// and return the operands for the horizontal operation in LHS and RHS. A
15895 /// horizontal operation performs the binary operation on successive elements
15896 /// of its first operand, then on successive elements of its second operand,
15897 /// returning the resulting values in a vector. For example, if
15898 /// A = < float a0, float a1, float a2, float a3 >
15900 /// B = < float b0, float b1, float b2, float b3 >
15901 /// then the result of doing a horizontal operation on A and B is
15902 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15903 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15904 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15905 /// set to A, RHS to B, and the routine returns 'true'.
15906 /// Note that the binary operation should have the property that if one of the
15907 /// operands is UNDEF then the result is UNDEF.
15908 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15909 // Look for the following pattern: if
15910 // A = < float a0, float a1, float a2, float a3 >
15911 // B = < float b0, float b1, float b2, float b3 >
15913 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15914 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15915 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15916 // which is A horizontal-op B.
15918 // At least one of the operands should be a vector shuffle.
15919 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15920 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15923 EVT VT = LHS.getValueType();
15925 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15926 "Unsupported vector type for horizontal add/sub");
15928 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15929 // operate independently on 128-bit lanes.
15930 unsigned NumElts = VT.getVectorNumElements();
15931 unsigned NumLanes = VT.getSizeInBits()/128;
15932 unsigned NumLaneElts = NumElts / NumLanes;
15933 assert((NumLaneElts % 2 == 0) &&
15934 "Vector type should have an even number of elements in each lane");
15935 unsigned HalfLaneElts = NumLaneElts/2;
15937 // View LHS in the form
15938 // LHS = VECTOR_SHUFFLE A, B, LMask
15939 // If LHS is not a shuffle then pretend it is the shuffle
15940 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15941 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15944 SmallVector<int, 16> LMask(NumElts);
15945 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15946 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15947 A = LHS.getOperand(0);
15948 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15949 B = LHS.getOperand(1);
15950 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15951 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15953 if (LHS.getOpcode() != ISD::UNDEF)
15955 for (unsigned i = 0; i != NumElts; ++i)
15959 // Likewise, view RHS in the form
15960 // RHS = VECTOR_SHUFFLE C, D, RMask
15962 SmallVector<int, 16> RMask(NumElts);
15963 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15964 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15965 C = RHS.getOperand(0);
15966 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15967 D = RHS.getOperand(1);
15968 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15969 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15971 if (RHS.getOpcode() != ISD::UNDEF)
15973 for (unsigned i = 0; i != NumElts; ++i)
15977 // Check that the shuffles are both shuffling the same vectors.
15978 if (!(A == C && B == D) && !(A == D && B == C))
15981 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15982 if (!A.getNode() && !B.getNode())
15985 // If A and B occur in reverse order in RHS, then "swap" them (which means
15986 // rewriting the mask).
15988 CommuteVectorShuffleMask(RMask, NumElts);
15990 // At this point LHS and RHS are equivalent to
15991 // LHS = VECTOR_SHUFFLE A, B, LMask
15992 // RHS = VECTOR_SHUFFLE A, B, RMask
15993 // Check that the masks correspond to performing a horizontal operation.
15994 for (unsigned i = 0; i != NumElts; ++i) {
15995 int LIdx = LMask[i], RIdx = RMask[i];
15997 // Ignore any UNDEF components.
15998 if (LIdx < 0 || RIdx < 0 ||
15999 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16000 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16003 // Check that successive elements are being operated on. If not, this is
16004 // not a horizontal operation.
16005 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16006 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16007 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16008 if (!(LIdx == Index && RIdx == Index + 1) &&
16009 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16013 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16014 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16018 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16019 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16020 const X86Subtarget *Subtarget) {
16021 EVT VT = N->getValueType(0);
16022 SDValue LHS = N->getOperand(0);
16023 SDValue RHS = N->getOperand(1);
16025 // Try to synthesize horizontal adds from adds of shuffles.
16026 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16027 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16028 isHorizontalBinOp(LHS, RHS, true))
16029 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16033 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16034 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16035 const X86Subtarget *Subtarget) {
16036 EVT VT = N->getValueType(0);
16037 SDValue LHS = N->getOperand(0);
16038 SDValue RHS = N->getOperand(1);
16040 // Try to synthesize horizontal subs from subs of shuffles.
16041 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16042 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16043 isHorizontalBinOp(LHS, RHS, false))
16044 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16048 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16049 /// X86ISD::FXOR nodes.
16050 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16051 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16052 // F[X]OR(0.0, x) -> x
16053 // F[X]OR(x, 0.0) -> x
16054 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16055 if (C->getValueAPF().isPosZero())
16056 return N->getOperand(1);
16057 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16058 if (C->getValueAPF().isPosZero())
16059 return N->getOperand(0);
16063 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16064 /// X86ISD::FMAX nodes.
16065 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16066 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16068 // Only perform optimizations if UnsafeMath is used.
16069 if (!DAG.getTarget().Options.UnsafeFPMath)
16072 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16073 // into FMINC and FMAXC, which are Commutative operations.
16074 unsigned NewOp = 0;
16075 switch (N->getOpcode()) {
16076 default: llvm_unreachable("unknown opcode");
16077 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16078 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16081 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16082 N->getOperand(0), N->getOperand(1));
16086 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16087 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16088 // FAND(0.0, x) -> 0.0
16089 // FAND(x, 0.0) -> 0.0
16090 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16091 if (C->getValueAPF().isPosZero())
16092 return N->getOperand(0);
16093 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16094 if (C->getValueAPF().isPosZero())
16095 return N->getOperand(1);
16099 static SDValue PerformBTCombine(SDNode *N,
16101 TargetLowering::DAGCombinerInfo &DCI) {
16102 // BT ignores high bits in the bit index operand.
16103 SDValue Op1 = N->getOperand(1);
16104 if (Op1.hasOneUse()) {
16105 unsigned BitWidth = Op1.getValueSizeInBits();
16106 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16107 APInt KnownZero, KnownOne;
16108 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16109 !DCI.isBeforeLegalizeOps());
16110 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16111 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16112 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16113 DCI.CommitTargetLoweringOpt(TLO);
16118 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16119 SDValue Op = N->getOperand(0);
16120 if (Op.getOpcode() == ISD::BITCAST)
16121 Op = Op.getOperand(0);
16122 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16123 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16124 VT.getVectorElementType().getSizeInBits() ==
16125 OpVT.getVectorElementType().getSizeInBits()) {
16126 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16131 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16132 TargetLowering::DAGCombinerInfo &DCI,
16133 const X86Subtarget *Subtarget) {
16134 if (!DCI.isBeforeLegalizeOps())
16137 if (!Subtarget->hasAVX())
16140 EVT VT = N->getValueType(0);
16141 SDValue Op = N->getOperand(0);
16142 EVT OpVT = Op.getValueType();
16143 DebugLoc dl = N->getDebugLoc();
16145 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16146 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16148 if (Subtarget->hasAVX2())
16149 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16151 // Optimize vectors in AVX mode
16152 // Sign extend v8i16 to v8i32 and
16155 // Divide input vector into two parts
16156 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16157 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16158 // concat the vectors to original VT
16160 unsigned NumElems = OpVT.getVectorNumElements();
16161 SDValue Undef = DAG.getUNDEF(OpVT);
16163 SmallVector<int,8> ShufMask1(NumElems, -1);
16164 for (unsigned i = 0; i != NumElems/2; ++i)
16167 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16169 SmallVector<int,8> ShufMask2(NumElems, -1);
16170 for (unsigned i = 0; i != NumElems/2; ++i)
16171 ShufMask2[i] = i + NumElems/2;
16173 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16175 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16176 VT.getVectorNumElements()/2);
16178 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16179 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16181 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16186 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16187 const X86Subtarget* Subtarget) {
16188 DebugLoc dl = N->getDebugLoc();
16189 EVT VT = N->getValueType(0);
16191 // Let legalize expand this if it isn't a legal type yet.
16192 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16195 EVT ScalarVT = VT.getScalarType();
16196 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16197 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16200 SDValue A = N->getOperand(0);
16201 SDValue B = N->getOperand(1);
16202 SDValue C = N->getOperand(2);
16204 bool NegA = (A.getOpcode() == ISD::FNEG);
16205 bool NegB = (B.getOpcode() == ISD::FNEG);
16206 bool NegC = (C.getOpcode() == ISD::FNEG);
16208 // Negative multiplication when NegA xor NegB
16209 bool NegMul = (NegA != NegB);
16211 A = A.getOperand(0);
16213 B = B.getOperand(0);
16215 C = C.getOperand(0);
16219 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16221 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16223 return DAG.getNode(Opcode, dl, VT, A, B, C);
16226 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16227 TargetLowering::DAGCombinerInfo &DCI,
16228 const X86Subtarget *Subtarget) {
16229 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16230 // (and (i32 x86isd::setcc_carry), 1)
16231 // This eliminates the zext. This transformation is necessary because
16232 // ISD::SETCC is always legalized to i8.
16233 DebugLoc dl = N->getDebugLoc();
16234 SDValue N0 = N->getOperand(0);
16235 EVT VT = N->getValueType(0);
16236 EVT OpVT = N0.getValueType();
16238 if (N0.getOpcode() == ISD::AND &&
16240 N0.getOperand(0).hasOneUse()) {
16241 SDValue N00 = N0.getOperand(0);
16242 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16244 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16245 if (!C || C->getZExtValue() != 1)
16247 return DAG.getNode(ISD::AND, dl, VT,
16248 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16249 N00.getOperand(0), N00.getOperand(1)),
16250 DAG.getConstant(1, VT));
16253 // Optimize vectors in AVX mode:
16256 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16257 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16258 // Concat upper and lower parts.
16261 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16262 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16263 // Concat upper and lower parts.
16265 if (!DCI.isBeforeLegalizeOps())
16268 if (!Subtarget->hasAVX())
16271 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16272 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16274 if (Subtarget->hasAVX2())
16275 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16277 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16278 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16279 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16281 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16282 VT.getVectorNumElements()/2);
16284 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16285 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16287 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16293 // Optimize x == -y --> x+y == 0
16294 // x != -y --> x+y != 0
16295 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16296 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16297 SDValue LHS = N->getOperand(0);
16298 SDValue RHS = N->getOperand(1);
16300 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16302 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16303 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16304 LHS.getValueType(), RHS, LHS.getOperand(1));
16305 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16306 addV, DAG.getConstant(0, addV.getValueType()), CC);
16308 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16309 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16310 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16311 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16312 RHS.getValueType(), LHS, RHS.getOperand(1));
16313 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16314 addV, DAG.getConstant(0, addV.getValueType()), CC);
16319 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16320 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16321 TargetLowering::DAGCombinerInfo &DCI,
16322 const X86Subtarget *Subtarget) {
16323 DebugLoc DL = N->getDebugLoc();
16324 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16325 SDValue EFLAGS = N->getOperand(1);
16327 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16328 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16330 if (CC == X86::COND_B)
16331 return DAG.getNode(ISD::AND, DL, MVT::i8,
16332 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16333 DAG.getConstant(CC, MVT::i8), EFLAGS),
16334 DAG.getConstant(1, MVT::i8));
16338 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16339 if (Flags.getNode()) {
16340 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16341 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16347 // Optimize branch condition evaluation.
16349 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16350 TargetLowering::DAGCombinerInfo &DCI,
16351 const X86Subtarget *Subtarget) {
16352 DebugLoc DL = N->getDebugLoc();
16353 SDValue Chain = N->getOperand(0);
16354 SDValue Dest = N->getOperand(1);
16355 SDValue EFLAGS = N->getOperand(3);
16356 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16360 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16361 if (Flags.getNode()) {
16362 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16363 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16370 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16371 SDValue Op0 = N->getOperand(0);
16372 EVT InVT = Op0->getValueType(0);
16374 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16375 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16376 DebugLoc dl = N->getDebugLoc();
16377 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16378 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16379 // Notice that we use SINT_TO_FP because we know that the high bits
16380 // are zero and SINT_TO_FP is better supported by the hardware.
16381 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16387 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16388 const X86TargetLowering *XTLI) {
16389 SDValue Op0 = N->getOperand(0);
16390 EVT InVT = Op0->getValueType(0);
16392 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16393 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16394 DebugLoc dl = N->getDebugLoc();
16395 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16396 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16397 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16400 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16401 // a 32-bit target where SSE doesn't support i64->FP operations.
16402 if (Op0.getOpcode() == ISD::LOAD) {
16403 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16404 EVT VT = Ld->getValueType(0);
16405 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16406 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16407 !XTLI->getSubtarget()->is64Bit() &&
16408 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16409 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16410 Ld->getChain(), Op0, DAG);
16411 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16418 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16419 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16420 X86TargetLowering::DAGCombinerInfo &DCI) {
16421 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16422 // the result is either zero or one (depending on the input carry bit).
16423 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16424 if (X86::isZeroNode(N->getOperand(0)) &&
16425 X86::isZeroNode(N->getOperand(1)) &&
16426 // We don't have a good way to replace an EFLAGS use, so only do this when
16428 SDValue(N, 1).use_empty()) {
16429 DebugLoc DL = N->getDebugLoc();
16430 EVT VT = N->getValueType(0);
16431 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16432 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16433 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16434 DAG.getConstant(X86::COND_B,MVT::i8),
16436 DAG.getConstant(1, VT));
16437 return DCI.CombineTo(N, Res1, CarryOut);
16443 // fold (add Y, (sete X, 0)) -> adc 0, Y
16444 // (add Y, (setne X, 0)) -> sbb -1, Y
16445 // (sub (sete X, 0), Y) -> sbb 0, Y
16446 // (sub (setne X, 0), Y) -> adc -1, Y
16447 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16448 DebugLoc DL = N->getDebugLoc();
16450 // Look through ZExts.
16451 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16452 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16455 SDValue SetCC = Ext.getOperand(0);
16456 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16459 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16460 if (CC != X86::COND_E && CC != X86::COND_NE)
16463 SDValue Cmp = SetCC.getOperand(1);
16464 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16465 !X86::isZeroNode(Cmp.getOperand(1)) ||
16466 !Cmp.getOperand(0).getValueType().isInteger())
16469 SDValue CmpOp0 = Cmp.getOperand(0);
16470 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16471 DAG.getConstant(1, CmpOp0.getValueType()));
16473 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16474 if (CC == X86::COND_NE)
16475 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16476 DL, OtherVal.getValueType(), OtherVal,
16477 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16478 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16479 DL, OtherVal.getValueType(), OtherVal,
16480 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16483 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16484 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16485 const X86Subtarget *Subtarget) {
16486 EVT VT = N->getValueType(0);
16487 SDValue Op0 = N->getOperand(0);
16488 SDValue Op1 = N->getOperand(1);
16490 // Try to synthesize horizontal adds from adds of shuffles.
16491 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16492 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16493 isHorizontalBinOp(Op0, Op1, true))
16494 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16496 return OptimizeConditionalInDecrement(N, DAG);
16499 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16500 const X86Subtarget *Subtarget) {
16501 SDValue Op0 = N->getOperand(0);
16502 SDValue Op1 = N->getOperand(1);
16504 // X86 can't encode an immediate LHS of a sub. See if we can push the
16505 // negation into a preceding instruction.
16506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16507 // If the RHS of the sub is a XOR with one use and a constant, invert the
16508 // immediate. Then add one to the LHS of the sub so we can turn
16509 // X-Y -> X+~Y+1, saving one register.
16510 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16511 isa<ConstantSDNode>(Op1.getOperand(1))) {
16512 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16513 EVT VT = Op0.getValueType();
16514 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16516 DAG.getConstant(~XorC, VT));
16517 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16518 DAG.getConstant(C->getAPIntValue()+1, VT));
16522 // Try to synthesize horizontal adds from adds of shuffles.
16523 EVT VT = N->getValueType(0);
16524 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16525 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16526 isHorizontalBinOp(Op0, Op1, true))
16527 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16529 return OptimizeConditionalInDecrement(N, DAG);
16532 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16533 DAGCombinerInfo &DCI) const {
16534 SelectionDAG &DAG = DCI.DAG;
16535 switch (N->getOpcode()) {
16537 case ISD::EXTRACT_VECTOR_ELT:
16538 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16540 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16541 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16542 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16543 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16544 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16545 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16548 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16549 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16550 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16551 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16552 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16553 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16554 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16555 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16556 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16557 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16559 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16561 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16562 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16563 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16564 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16565 case ISD::ANY_EXTEND:
16566 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16567 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16568 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16569 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16570 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16571 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16572 case X86ISD::SHUFP: // Handle all target specific shuffles
16573 case X86ISD::PALIGN:
16574 case X86ISD::UNPCKH:
16575 case X86ISD::UNPCKL:
16576 case X86ISD::MOVHLPS:
16577 case X86ISD::MOVLHPS:
16578 case X86ISD::PSHUFD:
16579 case X86ISD::PSHUFHW:
16580 case X86ISD::PSHUFLW:
16581 case X86ISD::MOVSS:
16582 case X86ISD::MOVSD:
16583 case X86ISD::VPERMILP:
16584 case X86ISD::VPERM2X128:
16585 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16586 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16592 /// isTypeDesirableForOp - Return true if the target has native support for
16593 /// the specified value type and it is 'desirable' to use the type for the
16594 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16595 /// instruction encodings are longer and some i16 instructions are slow.
16596 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16597 if (!isTypeLegal(VT))
16599 if (VT != MVT::i16)
16606 case ISD::SIGN_EXTEND:
16607 case ISD::ZERO_EXTEND:
16608 case ISD::ANY_EXTEND:
16621 /// IsDesirableToPromoteOp - This method query the target whether it is
16622 /// beneficial for dag combiner to promote the specified node. If true, it
16623 /// should return the desired promotion type by reference.
16624 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16625 EVT VT = Op.getValueType();
16626 if (VT != MVT::i16)
16629 bool Promote = false;
16630 bool Commute = false;
16631 switch (Op.getOpcode()) {
16634 LoadSDNode *LD = cast<LoadSDNode>(Op);
16635 // If the non-extending load has a single use and it's not live out, then it
16636 // might be folded.
16637 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16638 Op.hasOneUse()*/) {
16639 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16640 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16641 // The only case where we'd want to promote LOAD (rather then it being
16642 // promoted as an operand is when it's only use is liveout.
16643 if (UI->getOpcode() != ISD::CopyToReg)
16650 case ISD::SIGN_EXTEND:
16651 case ISD::ZERO_EXTEND:
16652 case ISD::ANY_EXTEND:
16657 SDValue N0 = Op.getOperand(0);
16658 // Look out for (store (shl (load), x)).
16659 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16672 SDValue N0 = Op.getOperand(0);
16673 SDValue N1 = Op.getOperand(1);
16674 if (!Commute && MayFoldLoad(N1))
16676 // Avoid disabling potential load folding opportunities.
16677 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16679 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16689 //===----------------------------------------------------------------------===//
16690 // X86 Inline Assembly Support
16691 //===----------------------------------------------------------------------===//
16694 // Helper to match a string separated by whitespace.
16695 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16696 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16698 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16699 StringRef piece(*args[i]);
16700 if (!s.startswith(piece)) // Check if the piece matches.
16703 s = s.substr(piece.size());
16704 StringRef::size_type pos = s.find_first_not_of(" \t");
16705 if (pos == 0) // We matched a prefix.
16713 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16716 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16717 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16719 std::string AsmStr = IA->getAsmString();
16721 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16722 if (!Ty || Ty->getBitWidth() % 16 != 0)
16725 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16726 SmallVector<StringRef, 4> AsmPieces;
16727 SplitString(AsmStr, AsmPieces, ";\n");
16729 switch (AsmPieces.size()) {
16730 default: return false;
16732 // FIXME: this should verify that we are targeting a 486 or better. If not,
16733 // we will turn this bswap into something that will be lowered to logical
16734 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16735 // lower so don't worry about this.
16737 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16738 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16739 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16740 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16741 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16742 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16743 // No need to check constraints, nothing other than the equivalent of
16744 // "=r,0" would be valid here.
16745 return IntrinsicLowering::LowerToByteSwap(CI);
16748 // rorw $$8, ${0:w} --> llvm.bswap.i16
16749 if (CI->getType()->isIntegerTy(16) &&
16750 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16751 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16752 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16754 const std::string &ConstraintsStr = IA->getConstraintString();
16755 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16756 std::sort(AsmPieces.begin(), AsmPieces.end());
16757 if (AsmPieces.size() == 4 &&
16758 AsmPieces[0] == "~{cc}" &&
16759 AsmPieces[1] == "~{dirflag}" &&
16760 AsmPieces[2] == "~{flags}" &&
16761 AsmPieces[3] == "~{fpsr}")
16762 return IntrinsicLowering::LowerToByteSwap(CI);
16766 if (CI->getType()->isIntegerTy(32) &&
16767 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16768 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16769 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16770 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16772 const std::string &ConstraintsStr = IA->getConstraintString();
16773 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16774 std::sort(AsmPieces.begin(), AsmPieces.end());
16775 if (AsmPieces.size() == 4 &&
16776 AsmPieces[0] == "~{cc}" &&
16777 AsmPieces[1] == "~{dirflag}" &&
16778 AsmPieces[2] == "~{flags}" &&
16779 AsmPieces[3] == "~{fpsr}")
16780 return IntrinsicLowering::LowerToByteSwap(CI);
16783 if (CI->getType()->isIntegerTy(64)) {
16784 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16785 if (Constraints.size() >= 2 &&
16786 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16787 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16788 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16789 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16790 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16791 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16792 return IntrinsicLowering::LowerToByteSwap(CI);
16802 /// getConstraintType - Given a constraint letter, return the type of
16803 /// constraint it is for this target.
16804 X86TargetLowering::ConstraintType
16805 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16806 if (Constraint.size() == 1) {
16807 switch (Constraint[0]) {
16818 return C_RegisterClass;
16842 return TargetLowering::getConstraintType(Constraint);
16845 /// Examine constraint type and operand type and determine a weight value.
16846 /// This object must already have been set up with the operand type
16847 /// and the current alternative constraint selected.
16848 TargetLowering::ConstraintWeight
16849 X86TargetLowering::getSingleConstraintMatchWeight(
16850 AsmOperandInfo &info, const char *constraint) const {
16851 ConstraintWeight weight = CW_Invalid;
16852 Value *CallOperandVal = info.CallOperandVal;
16853 // If we don't have a value, we can't do a match,
16854 // but allow it at the lowest weight.
16855 if (CallOperandVal == NULL)
16857 Type *type = CallOperandVal->getType();
16858 // Look at the constraint type.
16859 switch (*constraint) {
16861 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16872 if (CallOperandVal->getType()->isIntegerTy())
16873 weight = CW_SpecificReg;
16878 if (type->isFloatingPointTy())
16879 weight = CW_SpecificReg;
16882 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16883 weight = CW_SpecificReg;
16887 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16888 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16889 weight = CW_Register;
16892 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16893 if (C->getZExtValue() <= 31)
16894 weight = CW_Constant;
16898 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16899 if (C->getZExtValue() <= 63)
16900 weight = CW_Constant;
16904 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16905 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16906 weight = CW_Constant;
16910 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16911 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16912 weight = CW_Constant;
16916 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16917 if (C->getZExtValue() <= 3)
16918 weight = CW_Constant;
16922 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16923 if (C->getZExtValue() <= 0xff)
16924 weight = CW_Constant;
16929 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16930 weight = CW_Constant;
16934 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16935 if ((C->getSExtValue() >= -0x80000000LL) &&
16936 (C->getSExtValue() <= 0x7fffffffLL))
16937 weight = CW_Constant;
16941 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16942 if (C->getZExtValue() <= 0xffffffff)
16943 weight = CW_Constant;
16950 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16951 /// with another that has more specific requirements based on the type of the
16952 /// corresponding operand.
16953 const char *X86TargetLowering::
16954 LowerXConstraint(EVT ConstraintVT) const {
16955 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16956 // 'f' like normal targets.
16957 if (ConstraintVT.isFloatingPoint()) {
16958 if (Subtarget->hasSSE2())
16960 if (Subtarget->hasSSE1())
16964 return TargetLowering::LowerXConstraint(ConstraintVT);
16967 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16968 /// vector. If it is invalid, don't add anything to Ops.
16969 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16970 std::string &Constraint,
16971 std::vector<SDValue>&Ops,
16972 SelectionDAG &DAG) const {
16973 SDValue Result(0, 0);
16975 // Only support length 1 constraints for now.
16976 if (Constraint.length() > 1) return;
16978 char ConstraintLetter = Constraint[0];
16979 switch (ConstraintLetter) {
16982 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16983 if (C->getZExtValue() <= 31) {
16984 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16990 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16991 if (C->getZExtValue() <= 63) {
16992 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16998 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16999 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17000 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17007 if (C->getZExtValue() <= 255) {
17008 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17014 // 32-bit signed value
17015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17016 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17017 C->getSExtValue())) {
17018 // Widen to 64 bits here to get it sign extended.
17019 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17022 // FIXME gcc accepts some relocatable values here too, but only in certain
17023 // memory models; it's complicated.
17028 // 32-bit unsigned value
17029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17030 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17031 C->getZExtValue())) {
17032 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17036 // FIXME gcc accepts some relocatable values here too, but only in certain
17037 // memory models; it's complicated.
17041 // Literal immediates are always ok.
17042 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17043 // Widen to 64 bits here to get it sign extended.
17044 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17048 // In any sort of PIC mode addresses need to be computed at runtime by
17049 // adding in a register or some sort of table lookup. These can't
17050 // be used as immediates.
17051 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17054 // If we are in non-pic codegen mode, we allow the address of a global (with
17055 // an optional displacement) to be used with 'i'.
17056 GlobalAddressSDNode *GA = 0;
17057 int64_t Offset = 0;
17059 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17061 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17062 Offset += GA->getOffset();
17064 } else if (Op.getOpcode() == ISD::ADD) {
17065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17066 Offset += C->getZExtValue();
17067 Op = Op.getOperand(0);
17070 } else if (Op.getOpcode() == ISD::SUB) {
17071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17072 Offset += -C->getZExtValue();
17073 Op = Op.getOperand(0);
17078 // Otherwise, this isn't something we can handle, reject it.
17082 const GlobalValue *GV = GA->getGlobal();
17083 // If we require an extra load to get this address, as in PIC mode, we
17084 // can't accept it.
17085 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17086 getTargetMachine())))
17089 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17090 GA->getValueType(0), Offset);
17095 if (Result.getNode()) {
17096 Ops.push_back(Result);
17099 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17102 std::pair<unsigned, const TargetRegisterClass*>
17103 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17105 // First, see if this is a constraint that directly corresponds to an LLVM
17107 if (Constraint.size() == 1) {
17108 // GCC Constraint Letters
17109 switch (Constraint[0]) {
17111 // TODO: Slight differences here in allocation order and leaving
17112 // RIP in the class. Do they matter any more here than they do
17113 // in the normal allocation?
17114 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17115 if (Subtarget->is64Bit()) {
17116 if (VT == MVT::i32 || VT == MVT::f32)
17117 return std::make_pair(0U, &X86::GR32RegClass);
17118 if (VT == MVT::i16)
17119 return std::make_pair(0U, &X86::GR16RegClass);
17120 if (VT == MVT::i8 || VT == MVT::i1)
17121 return std::make_pair(0U, &X86::GR8RegClass);
17122 if (VT == MVT::i64 || VT == MVT::f64)
17123 return std::make_pair(0U, &X86::GR64RegClass);
17126 // 32-bit fallthrough
17127 case 'Q': // Q_REGS
17128 if (VT == MVT::i32 || VT == MVT::f32)
17129 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17130 if (VT == MVT::i16)
17131 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17132 if (VT == MVT::i8 || VT == MVT::i1)
17133 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17134 if (VT == MVT::i64)
17135 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17137 case 'r': // GENERAL_REGS
17138 case 'l': // INDEX_REGS
17139 if (VT == MVT::i8 || VT == MVT::i1)
17140 return std::make_pair(0U, &X86::GR8RegClass);
17141 if (VT == MVT::i16)
17142 return std::make_pair(0U, &X86::GR16RegClass);
17143 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17144 return std::make_pair(0U, &X86::GR32RegClass);
17145 return std::make_pair(0U, &X86::GR64RegClass);
17146 case 'R': // LEGACY_REGS
17147 if (VT == MVT::i8 || VT == MVT::i1)
17148 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17149 if (VT == MVT::i16)
17150 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17151 if (VT == MVT::i32 || !Subtarget->is64Bit())
17152 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17153 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17154 case 'f': // FP Stack registers.
17155 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17156 // value to the correct fpstack register class.
17157 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17158 return std::make_pair(0U, &X86::RFP32RegClass);
17159 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17160 return std::make_pair(0U, &X86::RFP64RegClass);
17161 return std::make_pair(0U, &X86::RFP80RegClass);
17162 case 'y': // MMX_REGS if MMX allowed.
17163 if (!Subtarget->hasMMX()) break;
17164 return std::make_pair(0U, &X86::VR64RegClass);
17165 case 'Y': // SSE_REGS if SSE2 allowed
17166 if (!Subtarget->hasSSE2()) break;
17168 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17169 if (!Subtarget->hasSSE1()) break;
17171 switch (VT.getSimpleVT().SimpleTy) {
17173 // Scalar SSE types.
17176 return std::make_pair(0U, &X86::FR32RegClass);
17179 return std::make_pair(0U, &X86::FR64RegClass);
17187 return std::make_pair(0U, &X86::VR128RegClass);
17195 return std::make_pair(0U, &X86::VR256RegClass);
17201 // Use the default implementation in TargetLowering to convert the register
17202 // constraint into a member of a register class.
17203 std::pair<unsigned, const TargetRegisterClass*> Res;
17204 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17206 // Not found as a standard register?
17207 if (Res.second == 0) {
17208 // Map st(0) -> st(7) -> ST0
17209 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17210 tolower(Constraint[1]) == 's' &&
17211 tolower(Constraint[2]) == 't' &&
17212 Constraint[3] == '(' &&
17213 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17214 Constraint[5] == ')' &&
17215 Constraint[6] == '}') {
17217 Res.first = X86::ST0+Constraint[4]-'0';
17218 Res.second = &X86::RFP80RegClass;
17222 // GCC allows "st(0)" to be called just plain "st".
17223 if (StringRef("{st}").equals_lower(Constraint)) {
17224 Res.first = X86::ST0;
17225 Res.second = &X86::RFP80RegClass;
17230 if (StringRef("{flags}").equals_lower(Constraint)) {
17231 Res.first = X86::EFLAGS;
17232 Res.second = &X86::CCRRegClass;
17236 // 'A' means EAX + EDX.
17237 if (Constraint == "A") {
17238 Res.first = X86::EAX;
17239 Res.second = &X86::GR32_ADRegClass;
17245 // Otherwise, check to see if this is a register class of the wrong value
17246 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17247 // turn into {ax},{dx}.
17248 if (Res.second->hasType(VT))
17249 return Res; // Correct type already, nothing to do.
17251 // All of the single-register GCC register classes map their values onto
17252 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17253 // really want an 8-bit or 32-bit register, map to the appropriate register
17254 // class and return the appropriate register.
17255 if (Res.second == &X86::GR16RegClass) {
17256 if (VT == MVT::i8) {
17257 unsigned DestReg = 0;
17258 switch (Res.first) {
17260 case X86::AX: DestReg = X86::AL; break;
17261 case X86::DX: DestReg = X86::DL; break;
17262 case X86::CX: DestReg = X86::CL; break;
17263 case X86::BX: DestReg = X86::BL; break;
17266 Res.first = DestReg;
17267 Res.second = &X86::GR8RegClass;
17269 } else if (VT == MVT::i32) {
17270 unsigned DestReg = 0;
17271 switch (Res.first) {
17273 case X86::AX: DestReg = X86::EAX; break;
17274 case X86::DX: DestReg = X86::EDX; break;
17275 case X86::CX: DestReg = X86::ECX; break;
17276 case X86::BX: DestReg = X86::EBX; break;
17277 case X86::SI: DestReg = X86::ESI; break;
17278 case X86::DI: DestReg = X86::EDI; break;
17279 case X86::BP: DestReg = X86::EBP; break;
17280 case X86::SP: DestReg = X86::ESP; break;
17283 Res.first = DestReg;
17284 Res.second = &X86::GR32RegClass;
17286 } else if (VT == MVT::i64) {
17287 unsigned DestReg = 0;
17288 switch (Res.first) {
17290 case X86::AX: DestReg = X86::RAX; break;
17291 case X86::DX: DestReg = X86::RDX; break;
17292 case X86::CX: DestReg = X86::RCX; break;
17293 case X86::BX: DestReg = X86::RBX; break;
17294 case X86::SI: DestReg = X86::RSI; break;
17295 case X86::DI: DestReg = X86::RDI; break;
17296 case X86::BP: DestReg = X86::RBP; break;
17297 case X86::SP: DestReg = X86::RSP; break;
17300 Res.first = DestReg;
17301 Res.second = &X86::GR64RegClass;
17304 } else if (Res.second == &X86::FR32RegClass ||
17305 Res.second == &X86::FR64RegClass ||
17306 Res.second == &X86::VR128RegClass) {
17307 // Handle references to XMM physical registers that got mapped into the
17308 // wrong class. This can happen with constraints like {xmm0} where the
17309 // target independent register mapper will just pick the first match it can
17310 // find, ignoring the required type.
17312 if (VT == MVT::f32 || VT == MVT::i32)
17313 Res.second = &X86::FR32RegClass;
17314 else if (VT == MVT::f64 || VT == MVT::i64)
17315 Res.second = &X86::FR64RegClass;
17316 else if (X86::VR128RegClass.hasType(VT))
17317 Res.second = &X86::VR128RegClass;
17318 else if (X86::VR256RegClass.hasType(VT))
17319 Res.second = &X86::VR256RegClass;