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);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
729 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
730 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
745 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
747 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
781 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
782 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
784 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
785 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
786 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
787 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
788 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
789 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
790 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
791 setTruncStoreAction((MVT::SimpleValueType)VT,
792 (MVT::SimpleValueType)InnerVT, Expand);
793 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
794 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
798 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
799 // with -msoft-float, disable use of MMX as well.
800 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
801 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
802 // No operations on x86mmx supported, everything uses intrinsics.
805 // MMX-sized vectors (other than x86mmx) are expected to be expanded
806 // into smaller operations.
807 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
808 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
809 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
810 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
811 setOperationAction(ISD::AND, MVT::v8i8, Expand);
812 setOperationAction(ISD::AND, MVT::v4i16, Expand);
813 setOperationAction(ISD::AND, MVT::v2i32, Expand);
814 setOperationAction(ISD::AND, MVT::v1i64, Expand);
815 setOperationAction(ISD::OR, MVT::v8i8, Expand);
816 setOperationAction(ISD::OR, MVT::v4i16, Expand);
817 setOperationAction(ISD::OR, MVT::v2i32, Expand);
818 setOperationAction(ISD::OR, MVT::v1i64, Expand);
819 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
820 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
821 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
822 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
823 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
825 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
826 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
827 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
828 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
829 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
830 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
831 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
832 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
833 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
834 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
835 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
837 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
838 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
841 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
842 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
843 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
844 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
845 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
846 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
847 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
848 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
849 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
854 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
855 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
858 // registers cannot be used even for integer operations.
859 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
860 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
861 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
862 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
865 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
866 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
867 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
868 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
869 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
870 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
871 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
872 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
874 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
875 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
876 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
877 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
878 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
879 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
880 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
882 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
883 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
884 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
885 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
887 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
893 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
894 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895 MVT VT = (MVT::SimpleValueType)i;
896 // Do not attempt to custom lower non-power-of-2 vectors
897 if (!isPowerOf2_32(VT.getVectorNumElements()))
899 // Do not attempt to custom lower non-128-bit vectors
900 if (!VT.is128BitVector())
902 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
907 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914 if (Subtarget->is64Bit()) {
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
919 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
920 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
921 MVT VT = (MVT::SimpleValueType)i;
923 // Do not attempt to promote non-128-bit vectors
924 if (!VT.is128BitVector())
927 setOperationAction(ISD::AND, VT, Promote);
928 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
929 setOperationAction(ISD::OR, VT, Promote);
930 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
931 setOperationAction(ISD::XOR, VT, Promote);
932 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
933 setOperationAction(ISD::LOAD, VT, Promote);
934 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
935 setOperationAction(ISD::SELECT, VT, Promote);
936 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
939 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941 // Custom lower v2i64 and v2f64 selects.
942 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
943 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
944 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
945 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
947 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
948 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
950 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
951 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
953 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
956 if (Subtarget->hasSSE41()) {
957 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
958 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
959 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
960 setOperationAction(ISD::FRINT, MVT::f32, Legal);
961 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
962 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
963 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
964 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
965 setOperationAction(ISD::FRINT, MVT::f64, Legal);
966 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
968 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
969 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
971 // FIXME: Do we need to handle scalar-to-vector here?
972 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
974 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
975 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
976 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
977 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
978 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
980 // i8 and i16 vectors are custom , because the source register and source
981 // source memory operand types are not the same width. f32 vectors are
982 // custom since the immediate controlling the insert encodes additional
984 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
994 // FIXME: these should be Legal but thats only for the case where
995 // the index is constant. For now custom expand to deal with that.
996 if (Subtarget->is64Bit()) {
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002 if (Subtarget->hasSSE2()) {
1003 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1004 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1006 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1007 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1009 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1010 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1012 if (Subtarget->hasAVX2()) {
1013 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1014 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1016 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1017 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1019 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1021 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1022 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1024 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1025 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1027 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1031 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1032 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1039 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1043 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1050 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1052 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1059 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1061 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1063 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1065 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1066 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1067 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1069 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1071 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1072 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1074 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1075 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1078 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1080 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1081 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1082 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1083 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1085 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1086 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1087 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1089 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1090 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1091 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1092 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1094 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1095 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1096 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1097 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1098 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1099 setOperationAction(ISD::FMA, MVT::f32, Custom);
1100 setOperationAction(ISD::FMA, MVT::f64, Custom);
1103 if (Subtarget->hasAVX2()) {
1104 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1105 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1106 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1107 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1109 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1110 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1111 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1112 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1114 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1115 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1116 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1117 // Don't lower v32i8 because there is no 128-bit byte mul
1119 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1121 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1122 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1124 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1125 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1127 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1129 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1130 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1131 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1132 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1134 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1135 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1136 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1137 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1139 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1140 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1141 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1142 // Don't lower v32i8 because there is no 128-bit byte mul
1144 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1145 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1147 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1148 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1150 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1153 // Custom lower several nodes for 256-bit types.
1154 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1155 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1156 MVT VT = (MVT::SimpleValueType)i;
1158 // Extract subvector is special because the value type
1159 // (result) is 128-bit but the source is 256-bit wide.
1160 if (VT.is128BitVector())
1161 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1163 // Do not attempt to custom lower other non-256-bit vectors
1164 if (!VT.is256BitVector())
1167 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1168 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1169 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1170 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1171 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1172 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1173 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1176 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1177 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1178 MVT VT = (MVT::SimpleValueType)i;
1180 // Do not attempt to promote non-256-bit vectors
1181 if (!VT.is256BitVector())
1184 setOperationAction(ISD::AND, VT, Promote);
1185 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1186 setOperationAction(ISD::OR, VT, Promote);
1187 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1188 setOperationAction(ISD::XOR, VT, Promote);
1189 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1190 setOperationAction(ISD::LOAD, VT, Promote);
1191 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1192 setOperationAction(ISD::SELECT, VT, Promote);
1193 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1197 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1198 // of this type with custom code.
1199 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1200 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1201 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1205 // We want to custom lower some of our intrinsics.
1206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1207 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1210 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1211 // handle type legalization for these operations here.
1213 // FIXME: We really should do custom legalization for addition and
1214 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1215 // than generic legalization for 64-bit multiplication-with-overflow, though.
1216 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1217 // Add/Sub/Mul with overflow operations are custom lowered.
1219 setOperationAction(ISD::SADDO, VT, Custom);
1220 setOperationAction(ISD::UADDO, VT, Custom);
1221 setOperationAction(ISD::SSUBO, VT, Custom);
1222 setOperationAction(ISD::USUBO, VT, Custom);
1223 setOperationAction(ISD::SMULO, VT, Custom);
1224 setOperationAction(ISD::UMULO, VT, Custom);
1227 // There are no 8-bit 3-address imul/mul instructions
1228 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1229 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1231 if (!Subtarget->is64Bit()) {
1232 // These libcalls are not available in 32-bit.
1233 setLibcallName(RTLIB::SHL_I128, 0);
1234 setLibcallName(RTLIB::SRL_I128, 0);
1235 setLibcallName(RTLIB::SRA_I128, 0);
1238 // We have target-specific dag combine patterns for the following nodes:
1239 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1240 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1241 setTargetDAGCombine(ISD::VSELECT);
1242 setTargetDAGCombine(ISD::SELECT);
1243 setTargetDAGCombine(ISD::SHL);
1244 setTargetDAGCombine(ISD::SRA);
1245 setTargetDAGCombine(ISD::SRL);
1246 setTargetDAGCombine(ISD::OR);
1247 setTargetDAGCombine(ISD::AND);
1248 setTargetDAGCombine(ISD::ADD);
1249 setTargetDAGCombine(ISD::FADD);
1250 setTargetDAGCombine(ISD::FSUB);
1251 setTargetDAGCombine(ISD::FMA);
1252 setTargetDAGCombine(ISD::SUB);
1253 setTargetDAGCombine(ISD::LOAD);
1254 setTargetDAGCombine(ISD::STORE);
1255 setTargetDAGCombine(ISD::ZERO_EXTEND);
1256 setTargetDAGCombine(ISD::ANY_EXTEND);
1257 setTargetDAGCombine(ISD::SIGN_EXTEND);
1258 setTargetDAGCombine(ISD::TRUNCATE);
1259 setTargetDAGCombine(ISD::UINT_TO_FP);
1260 setTargetDAGCombine(ISD::SINT_TO_FP);
1261 setTargetDAGCombine(ISD::SETCC);
1262 if (Subtarget->is64Bit())
1263 setTargetDAGCombine(ISD::MUL);
1264 setTargetDAGCombine(ISD::XOR);
1266 computeRegisterProperties();
1268 // On Darwin, -Os means optimize for size without hurting performance,
1269 // do not reduce the limit.
1270 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1271 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1272 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1273 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1274 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1275 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1276 setPrefLoopAlignment(4); // 2^4 bytes.
1277 benefitFromCodePlacementOpt = true;
1279 // Predictable cmov don't hurt on atom because it's in-order.
1280 predictableSelectIsExpensive = !Subtarget->isAtom();
1282 setPrefFunctionAlignment(4); // 2^4 bytes.
1286 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1287 if (!VT.isVector()) return MVT::i8;
1288 return VT.changeVectorElementTypeToInteger();
1292 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1293 /// the desired ByVal argument alignment.
1294 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1297 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1298 if (VTy->getBitWidth() == 128)
1300 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1301 unsigned EltAlign = 0;
1302 getMaxByValAlign(ATy->getElementType(), EltAlign);
1303 if (EltAlign > MaxAlign)
1304 MaxAlign = EltAlign;
1305 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1306 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1307 unsigned EltAlign = 0;
1308 getMaxByValAlign(STy->getElementType(i), EltAlign);
1309 if (EltAlign > MaxAlign)
1310 MaxAlign = EltAlign;
1317 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1318 /// function arguments in the caller parameter area. For X86, aggregates
1319 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1320 /// are at 4-byte boundaries.
1321 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1322 if (Subtarget->is64Bit()) {
1323 // Max of 8 and alignment of type.
1324 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1331 if (Subtarget->hasSSE1())
1332 getMaxByValAlign(Ty, Align);
1336 /// getOptimalMemOpType - Returns the target specific optimal type for load
1337 /// and store operations as a result of memset, memcpy, and memmove
1338 /// lowering. If DstAlign is zero that means it's safe to destination
1339 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1340 /// means there isn't a need to check it against alignment requirement,
1341 /// probably because the source does not need to be loaded. If
1342 /// 'IsZeroVal' is true, that means it's safe to return a
1343 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1344 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1345 /// constant so it does not need to be loaded.
1346 /// It returns EVT::Other if the type should be determined using generic
1347 /// target-independent logic.
1349 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1350 unsigned DstAlign, unsigned SrcAlign,
1353 MachineFunction &MF) const {
1354 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1355 // linux. This is because the stack realignment code can't handle certain
1356 // cases like PR2962. This should be removed when PR2962 is fixed.
1357 const Function *F = MF.getFunction();
1359 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1361 (Subtarget->isUnalignedMemAccessFast() ||
1362 ((DstAlign == 0 || DstAlign >= 16) &&
1363 (SrcAlign == 0 || SrcAlign >= 16))) &&
1364 Subtarget->getStackAlignment() >= 16) {
1365 if (Subtarget->getStackAlignment() >= 32) {
1366 if (Subtarget->hasAVX2())
1368 if (Subtarget->hasAVX())
1371 if (Subtarget->hasSSE2())
1373 if (Subtarget->hasSSE1())
1375 } else if (!MemcpyStrSrc && Size >= 8 &&
1376 !Subtarget->is64Bit() &&
1377 Subtarget->getStackAlignment() >= 8 &&
1378 Subtarget->hasSSE2()) {
1379 // Do not use f64 to lower memcpy if source is string constant. It's
1380 // better to use i32 to avoid the loads.
1384 if (Subtarget->is64Bit() && Size >= 8)
1389 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1390 /// current function. The returned value is a member of the
1391 /// MachineJumpTableInfo::JTEntryKind enum.
1392 unsigned X86TargetLowering::getJumpTableEncoding() const {
1393 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1395 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1396 Subtarget->isPICStyleGOT())
1397 return MachineJumpTableInfo::EK_Custom32;
1399 // Otherwise, use the normal jump table encoding heuristics.
1400 return TargetLowering::getJumpTableEncoding();
1404 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1405 const MachineBasicBlock *MBB,
1406 unsigned uid,MCContext &Ctx) const{
1407 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1408 Subtarget->isPICStyleGOT());
1409 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1411 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1412 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1415 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1417 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1418 SelectionDAG &DAG) const {
1419 if (!Subtarget->is64Bit())
1420 // This doesn't have DebugLoc associated with it, but is not really the
1421 // same as a Register.
1422 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1426 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1427 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1429 const MCExpr *X86TargetLowering::
1430 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1431 MCContext &Ctx) const {
1432 // X86-64 uses RIP relative addressing based on the jump table label.
1433 if (Subtarget->isPICStyleRIPRel())
1434 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1436 // Otherwise, the reference is relative to the PIC base.
1437 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1440 // FIXME: Why this routine is here? Move to RegInfo!
1441 std::pair<const TargetRegisterClass*, uint8_t>
1442 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1443 const TargetRegisterClass *RRC = 0;
1445 switch (VT.getSimpleVT().SimpleTy) {
1447 return TargetLowering::findRepresentativeClass(VT);
1448 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1449 RRC = Subtarget->is64Bit() ?
1450 (const TargetRegisterClass*)&X86::GR64RegClass :
1451 (const TargetRegisterClass*)&X86::GR32RegClass;
1454 RRC = &X86::VR64RegClass;
1456 case MVT::f32: case MVT::f64:
1457 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1458 case MVT::v4f32: case MVT::v2f64:
1459 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1461 RRC = &X86::VR128RegClass;
1464 return std::make_pair(RRC, Cost);
1467 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1468 unsigned &Offset) const {
1469 if (!Subtarget->isTargetLinux())
1472 if (Subtarget->is64Bit()) {
1473 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1475 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1488 //===----------------------------------------------------------------------===//
1489 // Return Value Calling Convention Implementation
1490 //===----------------------------------------------------------------------===//
1492 #include "X86GenCallingConv.inc"
1495 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1496 MachineFunction &MF, bool isVarArg,
1497 const SmallVectorImpl<ISD::OutputArg> &Outs,
1498 LLVMContext &Context) const {
1499 SmallVector<CCValAssign, 16> RVLocs;
1500 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1502 return CCInfo.CheckReturn(Outs, RetCC_X86);
1506 X86TargetLowering::LowerReturn(SDValue Chain,
1507 CallingConv::ID CallConv, bool isVarArg,
1508 const SmallVectorImpl<ISD::OutputArg> &Outs,
1509 const SmallVectorImpl<SDValue> &OutVals,
1510 DebugLoc dl, SelectionDAG &DAG) const {
1511 MachineFunction &MF = DAG.getMachineFunction();
1512 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1514 SmallVector<CCValAssign, 16> RVLocs;
1515 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1516 RVLocs, *DAG.getContext());
1517 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1519 // Add the regs to the liveout set for the function.
1520 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1521 for (unsigned i = 0; i != RVLocs.size(); ++i)
1522 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1523 MRI.addLiveOut(RVLocs[i].getLocReg());
1527 SmallVector<SDValue, 6> RetOps;
1528 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1529 // Operand #1 = Bytes To Pop
1530 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1533 // Copy the result values into the output registers.
1534 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1535 CCValAssign &VA = RVLocs[i];
1536 assert(VA.isRegLoc() && "Can only return in registers!");
1537 SDValue ValToCopy = OutVals[i];
1538 EVT ValVT = ValToCopy.getValueType();
1540 // Promote values to the appropriate types
1541 if (VA.getLocInfo() == CCValAssign::SExt)
1542 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1543 else if (VA.getLocInfo() == CCValAssign::ZExt)
1544 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1545 else if (VA.getLocInfo() == CCValAssign::AExt)
1546 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1547 else if (VA.getLocInfo() == CCValAssign::BCvt)
1548 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1550 // If this is x86-64, and we disabled SSE, we can't return FP values,
1551 // or SSE or MMX vectors.
1552 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1553 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1554 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1555 report_fatal_error("SSE register return with SSE disabled");
1557 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1558 // llvm-gcc has never done it right and no one has noticed, so this
1559 // should be OK for now.
1560 if (ValVT == MVT::f64 &&
1561 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1562 report_fatal_error("SSE2 register return with SSE2 disabled");
1564 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1565 // the RET instruction and handled by the FP Stackifier.
1566 if (VA.getLocReg() == X86::ST0 ||
1567 VA.getLocReg() == X86::ST1) {
1568 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1569 // change the value to the FP stack register class.
1570 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1571 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1572 RetOps.push_back(ValToCopy);
1573 // Don't emit a copytoreg.
1577 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1578 // which is returned in RAX / RDX.
1579 if (Subtarget->is64Bit()) {
1580 if (ValVT == MVT::x86mmx) {
1581 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1582 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1583 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1585 // If we don't have SSE2 available, convert to v4f32 so the generated
1586 // register is legal.
1587 if (!Subtarget->hasSSE2())
1588 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1593 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1594 Flag = Chain.getValue(1);
1597 // The x86-64 ABI for returning structs by value requires that we copy
1598 // the sret argument into %rax for the return. We saved the argument into
1599 // a virtual register in the entry block, so now we copy the value out
1601 if (Subtarget->is64Bit() &&
1602 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1603 MachineFunction &MF = DAG.getMachineFunction();
1604 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1605 unsigned Reg = FuncInfo->getSRetReturnReg();
1607 "SRetReturnReg should have been set in LowerFormalArguments().");
1608 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1610 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1611 Flag = Chain.getValue(1);
1613 // RAX now acts like a return value.
1614 MRI.addLiveOut(X86::RAX);
1617 RetOps[0] = Chain; // Update chain.
1619 // Add the flag if we have it.
1621 RetOps.push_back(Flag);
1623 return DAG.getNode(X86ISD::RET_FLAG, dl,
1624 MVT::Other, &RetOps[0], RetOps.size());
1627 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1628 if (N->getNumValues() != 1)
1630 if (!N->hasNUsesOfValue(1, 0))
1633 SDValue TCChain = Chain;
1634 SDNode *Copy = *N->use_begin();
1635 if (Copy->getOpcode() == ISD::CopyToReg) {
1636 // If the copy has a glue operand, we conservatively assume it isn't safe to
1637 // perform a tail call.
1638 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1640 TCChain = Copy->getOperand(0);
1641 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1644 bool HasRet = false;
1645 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1647 if (UI->getOpcode() != X86ISD::RET_FLAG)
1660 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1661 ISD::NodeType ExtendKind) const {
1663 // TODO: Is this also valid on 32-bit?
1664 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1665 ReturnMVT = MVT::i8;
1667 ReturnMVT = MVT::i32;
1669 EVT MinVT = getRegisterType(Context, ReturnMVT);
1670 return VT.bitsLT(MinVT) ? MinVT : VT;
1673 /// LowerCallResult - Lower the result values of a call into the
1674 /// appropriate copies out of appropriate physical registers.
1677 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1678 CallingConv::ID CallConv, bool isVarArg,
1679 const SmallVectorImpl<ISD::InputArg> &Ins,
1680 DebugLoc dl, SelectionDAG &DAG,
1681 SmallVectorImpl<SDValue> &InVals) const {
1683 // Assign locations to each value returned by this call.
1684 SmallVector<CCValAssign, 16> RVLocs;
1685 bool Is64Bit = Subtarget->is64Bit();
1686 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1687 getTargetMachine(), RVLocs, *DAG.getContext());
1688 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1690 // Copy all of the result registers out of their specified physreg.
1691 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1692 CCValAssign &VA = RVLocs[i];
1693 EVT CopyVT = VA.getValVT();
1695 // If this is x86-64, and we disabled SSE, we can't return FP values
1696 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1697 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1698 report_fatal_error("SSE register return with SSE disabled");
1703 // If this is a call to a function that returns an fp value on the floating
1704 // point stack, we must guarantee the value is popped from the stack, so
1705 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1706 // if the return value is not used. We use the FpPOP_RETVAL instruction
1708 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1709 // If we prefer to use the value in xmm registers, copy it out as f80 and
1710 // use a truncate to move it from fp stack reg to xmm reg.
1711 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1712 SDValue Ops[] = { Chain, InFlag };
1713 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1714 MVT::Other, MVT::Glue, Ops, 2), 1);
1715 Val = Chain.getValue(0);
1717 // Round the f80 to the right size, which also moves it to the appropriate
1719 if (CopyVT != VA.getValVT())
1720 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1721 // This truncation won't change the value.
1722 DAG.getIntPtrConstant(1));
1724 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1725 CopyVT, InFlag).getValue(1);
1726 Val = Chain.getValue(0);
1728 InFlag = Chain.getValue(2);
1729 InVals.push_back(Val);
1736 //===----------------------------------------------------------------------===//
1737 // C & StdCall & Fast Calling Convention implementation
1738 //===----------------------------------------------------------------------===//
1739 // StdCall calling convention seems to be standard for many Windows' API
1740 // routines and around. It differs from C calling convention just a little:
1741 // callee should clean up the stack, not caller. Symbols should be also
1742 // decorated in some fancy way :) It doesn't support any vector arguments.
1743 // For info on fast calling convention see Fast Calling Convention (tail call)
1744 // implementation LowerX86_32FastCCCallTo.
1746 /// CallIsStructReturn - Determines whether a call uses struct return
1748 enum StructReturnType {
1753 static StructReturnType
1754 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1756 return NotStructReturn;
1758 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1759 if (!Flags.isSRet())
1760 return NotStructReturn;
1761 if (Flags.isInReg())
1762 return RegStructReturn;
1763 return StackStructReturn;
1766 /// ArgsAreStructReturn - Determines whether a function uses struct
1767 /// return semantics.
1768 static StructReturnType
1769 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1771 return NotStructReturn;
1773 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1774 if (!Flags.isSRet())
1775 return NotStructReturn;
1776 if (Flags.isInReg())
1777 return RegStructReturn;
1778 return StackStructReturn;
1781 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1782 /// by "Src" to address "Dst" with size and alignment information specified by
1783 /// the specific parameter attribute. The copy will be passed as a byval
1784 /// function parameter.
1786 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1787 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1789 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1791 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1792 /*isVolatile*/false, /*AlwaysInline=*/true,
1793 MachinePointerInfo(), MachinePointerInfo());
1796 /// IsTailCallConvention - Return true if the calling convention is one that
1797 /// supports tail call optimization.
1798 static bool IsTailCallConvention(CallingConv::ID CC) {
1799 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1802 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1803 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1807 CallingConv::ID CalleeCC = CS.getCallingConv();
1808 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1814 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1815 /// a tailcall target by changing its ABI.
1816 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1817 bool GuaranteedTailCallOpt) {
1818 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1822 X86TargetLowering::LowerMemArgument(SDValue Chain,
1823 CallingConv::ID CallConv,
1824 const SmallVectorImpl<ISD::InputArg> &Ins,
1825 DebugLoc dl, SelectionDAG &DAG,
1826 const CCValAssign &VA,
1827 MachineFrameInfo *MFI,
1829 // Create the nodes corresponding to a load from this parameter slot.
1830 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1831 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1832 getTargetMachine().Options.GuaranteedTailCallOpt);
1833 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1836 // If value is passed by pointer we have address passed instead of the value
1838 if (VA.getLocInfo() == CCValAssign::Indirect)
1839 ValVT = VA.getLocVT();
1841 ValVT = VA.getValVT();
1843 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1844 // changed with more analysis.
1845 // In case of tail call optimization mark all arguments mutable. Since they
1846 // could be overwritten by lowering of arguments in case of a tail call.
1847 if (Flags.isByVal()) {
1848 unsigned Bytes = Flags.getByValSize();
1849 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1850 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1851 return DAG.getFrameIndex(FI, getPointerTy());
1853 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1854 VA.getLocMemOffset(), isImmutable);
1855 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1856 return DAG.getLoad(ValVT, dl, Chain, FIN,
1857 MachinePointerInfo::getFixedStack(FI),
1858 false, false, false, 0);
1863 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1864 CallingConv::ID CallConv,
1866 const SmallVectorImpl<ISD::InputArg> &Ins,
1869 SmallVectorImpl<SDValue> &InVals)
1871 MachineFunction &MF = DAG.getMachineFunction();
1872 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1874 const Function* Fn = MF.getFunction();
1875 if (Fn->hasExternalLinkage() &&
1876 Subtarget->isTargetCygMing() &&
1877 Fn->getName() == "main")
1878 FuncInfo->setForceFramePointer(true);
1880 MachineFrameInfo *MFI = MF.getFrameInfo();
1881 bool Is64Bit = Subtarget->is64Bit();
1882 bool IsWindows = Subtarget->isTargetWindows();
1883 bool IsWin64 = Subtarget->isTargetWin64();
1885 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1886 "Var args not supported with calling convention fastcc or ghc");
1888 // Assign locations to all of the incoming arguments.
1889 SmallVector<CCValAssign, 16> ArgLocs;
1890 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1891 ArgLocs, *DAG.getContext());
1893 // Allocate shadow area for Win64
1895 CCInfo.AllocateStack(32, 8);
1898 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1900 unsigned LastVal = ~0U;
1902 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1903 CCValAssign &VA = ArgLocs[i];
1904 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1906 assert(VA.getValNo() != LastVal &&
1907 "Don't support value assigned to multiple locs yet");
1909 LastVal = VA.getValNo();
1911 if (VA.isRegLoc()) {
1912 EVT RegVT = VA.getLocVT();
1913 const TargetRegisterClass *RC;
1914 if (RegVT == MVT::i32)
1915 RC = &X86::GR32RegClass;
1916 else if (Is64Bit && RegVT == MVT::i64)
1917 RC = &X86::GR64RegClass;
1918 else if (RegVT == MVT::f32)
1919 RC = &X86::FR32RegClass;
1920 else if (RegVT == MVT::f64)
1921 RC = &X86::FR64RegClass;
1922 else if (RegVT.is256BitVector())
1923 RC = &X86::VR256RegClass;
1924 else if (RegVT.is128BitVector())
1925 RC = &X86::VR128RegClass;
1926 else if (RegVT == MVT::x86mmx)
1927 RC = &X86::VR64RegClass;
1929 llvm_unreachable("Unknown argument type!");
1931 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1932 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1934 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1935 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1937 if (VA.getLocInfo() == CCValAssign::SExt)
1938 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1939 DAG.getValueType(VA.getValVT()));
1940 else if (VA.getLocInfo() == CCValAssign::ZExt)
1941 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1942 DAG.getValueType(VA.getValVT()));
1943 else if (VA.getLocInfo() == CCValAssign::BCvt)
1944 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1946 if (VA.isExtInLoc()) {
1947 // Handle MMX values passed in XMM regs.
1948 if (RegVT.isVector()) {
1949 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1952 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1955 assert(VA.isMemLoc());
1956 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1959 // If value is passed via pointer - do a load.
1960 if (VA.getLocInfo() == CCValAssign::Indirect)
1961 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1962 MachinePointerInfo(), false, false, false, 0);
1964 InVals.push_back(ArgValue);
1967 // The x86-64 ABI for returning structs by value requires that we copy
1968 // the sret argument into %rax for the return. Save the argument into
1969 // a virtual register so that we can access it from the return points.
1970 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1971 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1972 unsigned Reg = FuncInfo->getSRetReturnReg();
1974 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1975 FuncInfo->setSRetReturnReg(Reg);
1977 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1978 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1981 unsigned StackSize = CCInfo.getNextStackOffset();
1982 // Align stack specially for tail calls.
1983 if (FuncIsMadeTailCallSafe(CallConv,
1984 MF.getTarget().Options.GuaranteedTailCallOpt))
1985 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1987 // If the function takes variable number of arguments, make a frame index for
1988 // the start of the first vararg value... for expansion of llvm.va_start.
1990 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1991 CallConv != CallingConv::X86_ThisCall)) {
1992 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1995 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1997 // FIXME: We should really autogenerate these arrays
1998 static const uint16_t GPR64ArgRegsWin64[] = {
1999 X86::RCX, X86::RDX, X86::R8, X86::R9
2001 static const uint16_t GPR64ArgRegs64Bit[] = {
2002 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2004 static const uint16_t XMMArgRegs64Bit[] = {
2005 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2006 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2008 const uint16_t *GPR64ArgRegs;
2009 unsigned NumXMMRegs = 0;
2012 // The XMM registers which might contain var arg parameters are shadowed
2013 // in their paired GPR. So we only need to save the GPR to their home
2015 TotalNumIntRegs = 4;
2016 GPR64ArgRegs = GPR64ArgRegsWin64;
2018 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2019 GPR64ArgRegs = GPR64ArgRegs64Bit;
2021 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2024 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2027 bool NoImplicitFloatOps = Fn->getFnAttributes().
2028 hasAttribute(Attributes::NoImplicitFloat);
2029 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2030 "SSE register cannot be used when SSE is disabled!");
2031 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2032 NoImplicitFloatOps) &&
2033 "SSE register cannot be used when SSE is disabled!");
2034 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2035 !Subtarget->hasSSE1())
2036 // Kernel mode asks for SSE to be disabled, so don't push them
2038 TotalNumXMMRegs = 0;
2041 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2042 // Get to the caller-allocated home save location. Add 8 to account
2043 // for the return address.
2044 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2045 FuncInfo->setRegSaveFrameIndex(
2046 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2047 // Fixup to set vararg frame on shadow area (4 x i64).
2049 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2051 // For X86-64, if there are vararg parameters that are passed via
2052 // registers, then we must store them to their spots on the stack so
2053 // they may be loaded by deferencing the result of va_next.
2054 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2055 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2056 FuncInfo->setRegSaveFrameIndex(
2057 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2061 // Store the integer parameter registers.
2062 SmallVector<SDValue, 8> MemOps;
2063 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2065 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2066 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2067 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2068 DAG.getIntPtrConstant(Offset));
2069 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2070 &X86::GR64RegClass);
2071 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2073 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2074 MachinePointerInfo::getFixedStack(
2075 FuncInfo->getRegSaveFrameIndex(), Offset),
2077 MemOps.push_back(Store);
2081 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2082 // Now store the XMM (fp + vector) parameter registers.
2083 SmallVector<SDValue, 11> SaveXMMOps;
2084 SaveXMMOps.push_back(Chain);
2086 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2087 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2088 SaveXMMOps.push_back(ALVal);
2090 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2091 FuncInfo->getRegSaveFrameIndex()));
2092 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2093 FuncInfo->getVarArgsFPOffset()));
2095 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2096 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2097 &X86::VR128RegClass);
2098 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2099 SaveXMMOps.push_back(Val);
2101 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2103 &SaveXMMOps[0], SaveXMMOps.size()));
2106 if (!MemOps.empty())
2107 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2108 &MemOps[0], MemOps.size());
2112 // Some CCs need callee pop.
2113 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2114 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2115 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2117 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2118 // If this is an sret function, the return should pop the hidden pointer.
2119 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2120 argsAreStructReturn(Ins) == StackStructReturn)
2121 FuncInfo->setBytesToPopOnReturn(4);
2125 // RegSaveFrameIndex is X86-64 only.
2126 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2127 if (CallConv == CallingConv::X86_FastCall ||
2128 CallConv == CallingConv::X86_ThisCall)
2129 // fastcc functions can't have varargs.
2130 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2133 FuncInfo->setArgumentStackSize(StackSize);
2139 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2140 SDValue StackPtr, SDValue Arg,
2141 DebugLoc dl, SelectionDAG &DAG,
2142 const CCValAssign &VA,
2143 ISD::ArgFlagsTy Flags) const {
2144 unsigned LocMemOffset = VA.getLocMemOffset();
2145 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2146 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2147 if (Flags.isByVal())
2148 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2150 return DAG.getStore(Chain, dl, Arg, PtrOff,
2151 MachinePointerInfo::getStack(LocMemOffset),
2155 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2156 /// optimization is performed and it is required.
2158 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2159 SDValue &OutRetAddr, SDValue Chain,
2160 bool IsTailCall, bool Is64Bit,
2161 int FPDiff, DebugLoc dl) const {
2162 // Adjust the Return address stack slot.
2163 EVT VT = getPointerTy();
2164 OutRetAddr = getReturnAddressFrameIndex(DAG);
2166 // Load the "old" Return address.
2167 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2168 false, false, false, 0);
2169 return SDValue(OutRetAddr.getNode(), 1);
2172 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2173 /// optimization is performed and it is required (FPDiff!=0).
2175 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2176 SDValue Chain, SDValue RetAddrFrIdx,
2177 bool Is64Bit, int FPDiff, DebugLoc dl) {
2178 // Store the return address to the appropriate stack slot.
2179 if (!FPDiff) return Chain;
2180 // Calculate the new stack slot for the return address.
2181 int SlotSize = Is64Bit ? 8 : 4;
2182 int NewReturnAddrFI =
2183 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2184 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2185 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2186 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2187 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2193 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2194 SmallVectorImpl<SDValue> &InVals) const {
2195 SelectionDAG &DAG = CLI.DAG;
2196 DebugLoc &dl = CLI.DL;
2197 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2198 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2199 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2200 SDValue Chain = CLI.Chain;
2201 SDValue Callee = CLI.Callee;
2202 CallingConv::ID CallConv = CLI.CallConv;
2203 bool &isTailCall = CLI.IsTailCall;
2204 bool isVarArg = CLI.IsVarArg;
2206 MachineFunction &MF = DAG.getMachineFunction();
2207 bool Is64Bit = Subtarget->is64Bit();
2208 bool IsWin64 = Subtarget->isTargetWin64();
2209 bool IsWindows = Subtarget->isTargetWindows();
2210 StructReturnType SR = callIsStructReturn(Outs);
2211 bool IsSibcall = false;
2213 if (MF.getTarget().Options.DisableTailCalls)
2217 // Check if it's really possible to do a tail call.
2218 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2219 isVarArg, SR != NotStructReturn,
2220 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2221 Outs, OutVals, Ins, DAG);
2223 // Sibcalls are automatically detected tailcalls which do not require
2225 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2232 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2233 "Var args not supported with calling convention fastcc or ghc");
2235 // Analyze operands of the call, assigning locations to each operand.
2236 SmallVector<CCValAssign, 16> ArgLocs;
2237 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2238 ArgLocs, *DAG.getContext());
2240 // Allocate shadow area for Win64
2242 CCInfo.AllocateStack(32, 8);
2245 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2247 // Get a count of how many bytes are to be pushed on the stack.
2248 unsigned NumBytes = CCInfo.getNextStackOffset();
2250 // This is a sibcall. The memory operands are available in caller's
2251 // own caller's stack.
2253 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2254 IsTailCallConvention(CallConv))
2255 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2258 if (isTailCall && !IsSibcall) {
2259 // Lower arguments at fp - stackoffset + fpdiff.
2260 unsigned NumBytesCallerPushed =
2261 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2262 FPDiff = NumBytesCallerPushed - NumBytes;
2264 // Set the delta of movement of the returnaddr stackslot.
2265 // But only set if delta is greater than previous delta.
2266 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2267 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2271 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2273 SDValue RetAddrFrIdx;
2274 // Load return address for tail calls.
2275 if (isTailCall && FPDiff)
2276 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2277 Is64Bit, FPDiff, dl);
2279 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2280 SmallVector<SDValue, 8> MemOpChains;
2283 // Walk the register/memloc assignments, inserting copies/loads. In the case
2284 // of tail call optimization arguments are handle later.
2285 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2286 CCValAssign &VA = ArgLocs[i];
2287 EVT RegVT = VA.getLocVT();
2288 SDValue Arg = OutVals[i];
2289 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2290 bool isByVal = Flags.isByVal();
2292 // Promote the value if needed.
2293 switch (VA.getLocInfo()) {
2294 default: llvm_unreachable("Unknown loc info!");
2295 case CCValAssign::Full: break;
2296 case CCValAssign::SExt:
2297 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2299 case CCValAssign::ZExt:
2300 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2302 case CCValAssign::AExt:
2303 if (RegVT.is128BitVector()) {
2304 // Special case: passing MMX values in XMM registers.
2305 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2306 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2307 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2309 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2311 case CCValAssign::BCvt:
2312 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2314 case CCValAssign::Indirect: {
2315 // Store the argument.
2316 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2317 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2318 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2319 MachinePointerInfo::getFixedStack(FI),
2326 if (VA.isRegLoc()) {
2327 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2328 if (isVarArg && IsWin64) {
2329 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2330 // shadow reg if callee is a varargs function.
2331 unsigned ShadowReg = 0;
2332 switch (VA.getLocReg()) {
2333 case X86::XMM0: ShadowReg = X86::RCX; break;
2334 case X86::XMM1: ShadowReg = X86::RDX; break;
2335 case X86::XMM2: ShadowReg = X86::R8; break;
2336 case X86::XMM3: ShadowReg = X86::R9; break;
2339 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2341 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2342 assert(VA.isMemLoc());
2343 if (StackPtr.getNode() == 0)
2344 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2345 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2346 dl, DAG, VA, Flags));
2350 if (!MemOpChains.empty())
2351 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2352 &MemOpChains[0], MemOpChains.size());
2354 if (Subtarget->isPICStyleGOT()) {
2355 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2358 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2359 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2361 // If we are tail calling and generating PIC/GOT style code load the
2362 // address of the callee into ECX. The value in ecx is used as target of
2363 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2364 // for tail calls on PIC/GOT architectures. Normally we would just put the
2365 // address of GOT into ebx and then call target@PLT. But for tail calls
2366 // ebx would be restored (since ebx is callee saved) before jumping to the
2369 // Note: The actual moving to ECX is done further down.
2370 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2371 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2372 !G->getGlobal()->hasProtectedVisibility())
2373 Callee = LowerGlobalAddress(Callee, DAG);
2374 else if (isa<ExternalSymbolSDNode>(Callee))
2375 Callee = LowerExternalSymbol(Callee, DAG);
2379 if (Is64Bit && isVarArg && !IsWin64) {
2380 // From AMD64 ABI document:
2381 // For calls that may call functions that use varargs or stdargs
2382 // (prototype-less calls or calls to functions containing ellipsis (...) in
2383 // the declaration) %al is used as hidden argument to specify the number
2384 // of SSE registers used. The contents of %al do not need to match exactly
2385 // the number of registers, but must be an ubound on the number of SSE
2386 // registers used and is in the range 0 - 8 inclusive.
2388 // Count the number of XMM registers allocated.
2389 static const uint16_t XMMArgRegs[] = {
2390 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2391 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2393 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2394 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2395 && "SSE registers cannot be used when SSE is disabled");
2397 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2398 DAG.getConstant(NumXMMRegs, MVT::i8)));
2401 // For tail calls lower the arguments to the 'real' stack slot.
2403 // Force all the incoming stack arguments to be loaded from the stack
2404 // before any new outgoing arguments are stored to the stack, because the
2405 // outgoing stack slots may alias the incoming argument stack slots, and
2406 // the alias isn't otherwise explicit. This is slightly more conservative
2407 // than necessary, because it means that each store effectively depends
2408 // on every argument instead of just those arguments it would clobber.
2409 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2411 SmallVector<SDValue, 8> MemOpChains2;
2414 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416 CCValAssign &VA = ArgLocs[i];
2419 assert(VA.isMemLoc());
2420 SDValue Arg = OutVals[i];
2421 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2422 // Create frame index.
2423 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2424 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2425 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2426 FIN = DAG.getFrameIndex(FI, getPointerTy());
2428 if (Flags.isByVal()) {
2429 // Copy relative to framepointer.
2430 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2431 if (StackPtr.getNode() == 0)
2432 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2434 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2436 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2440 // Store relative to framepointer.
2441 MemOpChains2.push_back(
2442 DAG.getStore(ArgChain, dl, Arg, FIN,
2443 MachinePointerInfo::getFixedStack(FI),
2449 if (!MemOpChains2.empty())
2450 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2451 &MemOpChains2[0], MemOpChains2.size());
2453 // Store the return address to the appropriate stack slot.
2454 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2458 // Build a sequence of copy-to-reg nodes chained together with token chain
2459 // and flag operands which copy the outgoing args into registers.
2461 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2462 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2463 RegsToPass[i].second, InFlag);
2464 InFlag = Chain.getValue(1);
2467 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2468 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2469 // In the 64-bit large code model, we have to make all calls
2470 // through a register, since the call instruction's 32-bit
2471 // pc-relative offset may not be large enough to hold the whole
2473 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2474 // If the callee is a GlobalAddress node (quite common, every direct call
2475 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2478 // We should use extra load for direct calls to dllimported functions in
2480 const GlobalValue *GV = G->getGlobal();
2481 if (!GV->hasDLLImportLinkage()) {
2482 unsigned char OpFlags = 0;
2483 bool ExtraLoad = false;
2484 unsigned WrapperKind = ISD::DELETED_NODE;
2486 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2487 // external symbols most go through the PLT in PIC mode. If the symbol
2488 // has hidden or protected visibility, or if it is static or local, then
2489 // we don't need to use the PLT - we can directly call it.
2490 if (Subtarget->isTargetELF() &&
2491 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2492 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2493 OpFlags = X86II::MO_PLT;
2494 } else if (Subtarget->isPICStyleStubAny() &&
2495 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2496 (!Subtarget->getTargetTriple().isMacOSX() ||
2497 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2498 // PC-relative references to external symbols should go through $stub,
2499 // unless we're building with the leopard linker or later, which
2500 // automatically synthesizes these stubs.
2501 OpFlags = X86II::MO_DARWIN_STUB;
2502 } else if (Subtarget->isPICStyleRIPRel() &&
2503 isa<Function>(GV) &&
2504 cast<Function>(GV)->getFnAttributes().
2505 hasAttribute(Attributes::NonLazyBind)) {
2506 // If the function is marked as non-lazy, generate an indirect call
2507 // which loads from the GOT directly. This avoids runtime overhead
2508 // at the cost of eager binding (and one extra byte of encoding).
2509 OpFlags = X86II::MO_GOTPCREL;
2510 WrapperKind = X86ISD::WrapperRIP;
2514 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2515 G->getOffset(), OpFlags);
2517 // Add a wrapper if needed.
2518 if (WrapperKind != ISD::DELETED_NODE)
2519 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2520 // Add extra indirection if needed.
2522 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2523 MachinePointerInfo::getGOT(),
2524 false, false, false, 0);
2526 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2527 unsigned char OpFlags = 0;
2529 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2530 // external symbols should go through the PLT.
2531 if (Subtarget->isTargetELF() &&
2532 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2533 OpFlags = X86II::MO_PLT;
2534 } else if (Subtarget->isPICStyleStubAny() &&
2535 (!Subtarget->getTargetTriple().isMacOSX() ||
2536 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537 // PC-relative references to external symbols should go through $stub,
2538 // unless we're building with the leopard linker or later, which
2539 // automatically synthesizes these stubs.
2540 OpFlags = X86II::MO_DARWIN_STUB;
2543 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2547 // Returns a chain & a flag for retval copy to use.
2548 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2549 SmallVector<SDValue, 8> Ops;
2551 if (!IsSibcall && isTailCall) {
2552 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2553 DAG.getIntPtrConstant(0, true), InFlag);
2554 InFlag = Chain.getValue(1);
2557 Ops.push_back(Chain);
2558 Ops.push_back(Callee);
2561 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2563 // Add argument registers to the end of the list so that they are known live
2565 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2566 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2567 RegsToPass[i].second.getValueType()));
2569 // Add a register mask operand representing the call-preserved registers.
2570 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2571 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2572 assert(Mask && "Missing call preserved mask for calling convention");
2573 Ops.push_back(DAG.getRegisterMask(Mask));
2575 if (InFlag.getNode())
2576 Ops.push_back(InFlag);
2580 //// If this is the first return lowered for this function, add the regs
2581 //// to the liveout set for the function.
2582 // This isn't right, although it's probably harmless on x86; liveouts
2583 // should be computed from returns not tail calls. Consider a void
2584 // function making a tail call to a function returning int.
2585 return DAG.getNode(X86ISD::TC_RETURN, dl,
2586 NodeTys, &Ops[0], Ops.size());
2589 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2590 InFlag = Chain.getValue(1);
2592 // Create the CALLSEQ_END node.
2593 unsigned NumBytesForCalleeToPush;
2594 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2595 getTargetMachine().Options.GuaranteedTailCallOpt))
2596 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2597 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2598 SR == StackStructReturn)
2599 // If this is a call to a struct-return function, the callee
2600 // pops the hidden struct pointer, so we have to push it back.
2601 // This is common for Darwin/X86, Linux & Mingw32 targets.
2602 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2603 NumBytesForCalleeToPush = 4;
2605 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2607 // Returns a flag for retval copy to use.
2609 Chain = DAG.getCALLSEQ_END(Chain,
2610 DAG.getIntPtrConstant(NumBytes, true),
2611 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2614 InFlag = Chain.getValue(1);
2617 // Handle result values, copying them out of physregs into vregs that we
2619 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2620 Ins, dl, DAG, InVals);
2624 //===----------------------------------------------------------------------===//
2625 // Fast Calling Convention (tail call) implementation
2626 //===----------------------------------------------------------------------===//
2628 // Like std call, callee cleans arguments, convention except that ECX is
2629 // reserved for storing the tail called function address. Only 2 registers are
2630 // free for argument passing (inreg). Tail call optimization is performed
2632 // * tailcallopt is enabled
2633 // * caller/callee are fastcc
2634 // On X86_64 architecture with GOT-style position independent code only local
2635 // (within module) calls are supported at the moment.
2636 // To keep the stack aligned according to platform abi the function
2637 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2638 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2639 // If a tail called function callee has more arguments than the caller the
2640 // caller needs to make sure that there is room to move the RETADDR to. This is
2641 // achieved by reserving an area the size of the argument delta right after the
2642 // original REtADDR, but before the saved framepointer or the spilled registers
2643 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2655 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2656 /// for a 16 byte align requirement.
2658 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2659 SelectionDAG& DAG) const {
2660 MachineFunction &MF = DAG.getMachineFunction();
2661 const TargetMachine &TM = MF.getTarget();
2662 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2663 unsigned StackAlignment = TFI.getStackAlignment();
2664 uint64_t AlignMask = StackAlignment - 1;
2665 int64_t Offset = StackSize;
2666 uint64_t SlotSize = TD->getPointerSize(0);
2667 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2668 // Number smaller than 12 so just add the difference.
2669 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2671 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2672 Offset = ((~AlignMask) & Offset) + StackAlignment +
2673 (StackAlignment-SlotSize);
2678 /// MatchingStackOffset - Return true if the given stack call argument is
2679 /// already available in the same position (relatively) of the caller's
2680 /// incoming argument stack.
2682 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2683 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2684 const X86InstrInfo *TII) {
2685 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2687 if (Arg.getOpcode() == ISD::CopyFromReg) {
2688 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2689 if (!TargetRegisterInfo::isVirtualRegister(VR))
2691 MachineInstr *Def = MRI->getVRegDef(VR);
2694 if (!Flags.isByVal()) {
2695 if (!TII->isLoadFromStackSlot(Def, FI))
2698 unsigned Opcode = Def->getOpcode();
2699 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2700 Def->getOperand(1).isFI()) {
2701 FI = Def->getOperand(1).getIndex();
2702 Bytes = Flags.getByValSize();
2706 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2707 if (Flags.isByVal())
2708 // ByVal argument is passed in as a pointer but it's now being
2709 // dereferenced. e.g.
2710 // define @foo(%struct.X* %A) {
2711 // tail call @bar(%struct.X* byval %A)
2714 SDValue Ptr = Ld->getBasePtr();
2715 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2718 FI = FINode->getIndex();
2719 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2720 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2721 FI = FINode->getIndex();
2722 Bytes = Flags.getByValSize();
2726 assert(FI != INT_MAX);
2727 if (!MFI->isFixedObjectIndex(FI))
2729 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2733 /// for tail call optimization. Targets which want to do tail call
2734 /// optimization should implement this function.
2736 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2737 CallingConv::ID CalleeCC,
2739 bool isCalleeStructRet,
2740 bool isCallerStructRet,
2742 const SmallVectorImpl<ISD::OutputArg> &Outs,
2743 const SmallVectorImpl<SDValue> &OutVals,
2744 const SmallVectorImpl<ISD::InputArg> &Ins,
2745 SelectionDAG& DAG) const {
2746 if (!IsTailCallConvention(CalleeCC) &&
2747 CalleeCC != CallingConv::C)
2750 // If -tailcallopt is specified, make fastcc functions tail-callable.
2751 const MachineFunction &MF = DAG.getMachineFunction();
2752 const Function *CallerF = DAG.getMachineFunction().getFunction();
2754 // If the function return type is x86_fp80 and the callee return type is not,
2755 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2756 // perform a tailcall optimization here.
2757 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2760 CallingConv::ID CallerCC = CallerF->getCallingConv();
2761 bool CCMatch = CallerCC == CalleeCC;
2763 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2764 if (IsTailCallConvention(CalleeCC) && CCMatch)
2769 // Look for obvious safe cases to perform tail call optimization that do not
2770 // require ABI changes. This is what gcc calls sibcall.
2772 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2773 // emit a special epilogue.
2774 if (RegInfo->needsStackRealignment(MF))
2777 // Also avoid sibcall optimization if either caller or callee uses struct
2778 // return semantics.
2779 if (isCalleeStructRet || isCallerStructRet)
2782 // An stdcall caller is expected to clean up its arguments; the callee
2783 // isn't going to do that.
2784 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2787 // Do not sibcall optimize vararg calls unless all arguments are passed via
2789 if (isVarArg && !Outs.empty()) {
2791 // Optimizing for varargs on Win64 is unlikely to be safe without
2792 // additional testing.
2793 if (Subtarget->isTargetWin64())
2796 SmallVector<CCValAssign, 16> ArgLocs;
2797 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2798 getTargetMachine(), ArgLocs, *DAG.getContext());
2800 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2801 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2802 if (!ArgLocs[i].isRegLoc())
2806 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2807 // stack. Therefore, if it's not used by the call it is not safe to optimize
2808 // this into a sibcall.
2809 bool Unused = false;
2810 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2817 SmallVector<CCValAssign, 16> RVLocs;
2818 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2819 getTargetMachine(), RVLocs, *DAG.getContext());
2820 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2821 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2822 CCValAssign &VA = RVLocs[i];
2823 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2828 // If the calling conventions do not match, then we'd better make sure the
2829 // results are returned in the same way as what the caller expects.
2831 SmallVector<CCValAssign, 16> RVLocs1;
2832 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2833 getTargetMachine(), RVLocs1, *DAG.getContext());
2834 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2836 SmallVector<CCValAssign, 16> RVLocs2;
2837 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2838 getTargetMachine(), RVLocs2, *DAG.getContext());
2839 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2841 if (RVLocs1.size() != RVLocs2.size())
2843 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2844 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2846 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2848 if (RVLocs1[i].isRegLoc()) {
2849 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2852 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2858 // If the callee takes no arguments then go on to check the results of the
2860 if (!Outs.empty()) {
2861 // Check if stack adjustment is needed. For now, do not do this if any
2862 // argument is passed on the stack.
2863 SmallVector<CCValAssign, 16> ArgLocs;
2864 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2865 getTargetMachine(), ArgLocs, *DAG.getContext());
2867 // Allocate shadow area for Win64
2868 if (Subtarget->isTargetWin64()) {
2869 CCInfo.AllocateStack(32, 8);
2872 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2873 if (CCInfo.getNextStackOffset()) {
2874 MachineFunction &MF = DAG.getMachineFunction();
2875 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2878 // Check if the arguments are already laid out in the right way as
2879 // the caller's fixed stack objects.
2880 MachineFrameInfo *MFI = MF.getFrameInfo();
2881 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2882 const X86InstrInfo *TII =
2883 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2884 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2885 CCValAssign &VA = ArgLocs[i];
2886 SDValue Arg = OutVals[i];
2887 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2888 if (VA.getLocInfo() == CCValAssign::Indirect)
2890 if (!VA.isRegLoc()) {
2891 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2898 // If the tailcall address may be in a register, then make sure it's
2899 // possible to register allocate for it. In 32-bit, the call address can
2900 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2901 // callee-saved registers are restored. These happen to be the same
2902 // registers used to pass 'inreg' arguments so watch out for those.
2903 if (!Subtarget->is64Bit() &&
2904 !isa<GlobalAddressSDNode>(Callee) &&
2905 !isa<ExternalSymbolSDNode>(Callee)) {
2906 unsigned NumInRegs = 0;
2907 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2908 CCValAssign &VA = ArgLocs[i];
2911 unsigned Reg = VA.getLocReg();
2914 case X86::EAX: case X86::EDX: case X86::ECX:
2915 if (++NumInRegs == 3)
2927 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2928 const TargetLibraryInfo *libInfo) const {
2929 return X86::createFastISel(funcInfo, libInfo);
2933 //===----------------------------------------------------------------------===//
2934 // Other Lowering Hooks
2935 //===----------------------------------------------------------------------===//
2937 static bool MayFoldLoad(SDValue Op) {
2938 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2941 static bool MayFoldIntoStore(SDValue Op) {
2942 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2945 static bool isTargetShuffle(unsigned Opcode) {
2947 default: return false;
2948 case X86ISD::PSHUFD:
2949 case X86ISD::PSHUFHW:
2950 case X86ISD::PSHUFLW:
2952 case X86ISD::PALIGN:
2953 case X86ISD::MOVLHPS:
2954 case X86ISD::MOVLHPD:
2955 case X86ISD::MOVHLPS:
2956 case X86ISD::MOVLPS:
2957 case X86ISD::MOVLPD:
2958 case X86ISD::MOVSHDUP:
2959 case X86ISD::MOVSLDUP:
2960 case X86ISD::MOVDDUP:
2963 case X86ISD::UNPCKL:
2964 case X86ISD::UNPCKH:
2965 case X86ISD::VPERMILP:
2966 case X86ISD::VPERM2X128:
2967 case X86ISD::VPERMI:
2972 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2973 SDValue V1, SelectionDAG &DAG) {
2975 default: llvm_unreachable("Unknown x86 shuffle node");
2976 case X86ISD::MOVSHDUP:
2977 case X86ISD::MOVSLDUP:
2978 case X86ISD::MOVDDUP:
2979 return DAG.getNode(Opc, dl, VT, V1);
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984 SDValue V1, unsigned TargetMask,
2985 SelectionDAG &DAG) {
2987 default: llvm_unreachable("Unknown x86 shuffle node");
2988 case X86ISD::PSHUFD:
2989 case X86ISD::PSHUFHW:
2990 case X86ISD::PSHUFLW:
2991 case X86ISD::VPERMILP:
2992 case X86ISD::VPERMI:
2993 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2997 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2998 SDValue V1, SDValue V2, unsigned TargetMask,
2999 SelectionDAG &DAG) {
3001 default: llvm_unreachable("Unknown x86 shuffle node");
3002 case X86ISD::PALIGN:
3004 case X86ISD::VPERM2X128:
3005 return DAG.getNode(Opc, dl, VT, V1, V2,
3006 DAG.getConstant(TargetMask, MVT::i8));
3010 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3011 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3013 default: llvm_unreachable("Unknown x86 shuffle node");
3014 case X86ISD::MOVLHPS:
3015 case X86ISD::MOVLHPD:
3016 case X86ISD::MOVHLPS:
3017 case X86ISD::MOVLPS:
3018 case X86ISD::MOVLPD:
3021 case X86ISD::UNPCKL:
3022 case X86ISD::UNPCKH:
3023 return DAG.getNode(Opc, dl, VT, V1, V2);
3027 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3028 MachineFunction &MF = DAG.getMachineFunction();
3029 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3030 int ReturnAddrIndex = FuncInfo->getRAIndex();
3032 if (ReturnAddrIndex == 0) {
3033 // Set up a frame object for the return address.
3034 uint64_t SlotSize = TD->getPointerSize(0);
3035 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3037 FuncInfo->setRAIndex(ReturnAddrIndex);
3040 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3044 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3045 bool hasSymbolicDisplacement) {
3046 // Offset should fit into 32 bit immediate field.
3047 if (!isInt<32>(Offset))
3050 // If we don't have a symbolic displacement - we don't have any extra
3052 if (!hasSymbolicDisplacement)
3055 // FIXME: Some tweaks might be needed for medium code model.
3056 if (M != CodeModel::Small && M != CodeModel::Kernel)
3059 // For small code model we assume that latest object is 16MB before end of 31
3060 // bits boundary. We may also accept pretty large negative constants knowing
3061 // that all objects are in the positive half of address space.
3062 if (M == CodeModel::Small && Offset < 16*1024*1024)
3065 // For kernel code model we know that all object resist in the negative half
3066 // of 32bits address space. We may not accept negative offsets, since they may
3067 // be just off and we may accept pretty large positive ones.
3068 if (M == CodeModel::Kernel && Offset > 0)
3074 /// isCalleePop - Determines whether the callee is required to pop its
3075 /// own arguments. Callee pop is necessary to support tail calls.
3076 bool X86::isCalleePop(CallingConv::ID CallingConv,
3077 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3081 switch (CallingConv) {
3084 case CallingConv::X86_StdCall:
3086 case CallingConv::X86_FastCall:
3088 case CallingConv::X86_ThisCall:
3090 case CallingConv::Fast:
3092 case CallingConv::GHC:
3097 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3098 /// specific condition code, returning the condition code and the LHS/RHS of the
3099 /// comparison to make.
3100 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3101 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3103 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3104 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3105 // X > -1 -> X == 0, jump !sign.
3106 RHS = DAG.getConstant(0, RHS.getValueType());
3107 return X86::COND_NS;
3109 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3110 // X < 0 -> X == 0, jump on sign.
3113 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3115 RHS = DAG.getConstant(0, RHS.getValueType());
3116 return X86::COND_LE;
3120 switch (SetCCOpcode) {
3121 default: llvm_unreachable("Invalid integer condition!");
3122 case ISD::SETEQ: return X86::COND_E;
3123 case ISD::SETGT: return X86::COND_G;
3124 case ISD::SETGE: return X86::COND_GE;
3125 case ISD::SETLT: return X86::COND_L;
3126 case ISD::SETLE: return X86::COND_LE;
3127 case ISD::SETNE: return X86::COND_NE;
3128 case ISD::SETULT: return X86::COND_B;
3129 case ISD::SETUGT: return X86::COND_A;
3130 case ISD::SETULE: return X86::COND_BE;
3131 case ISD::SETUGE: return X86::COND_AE;
3135 // First determine if it is required or is profitable to flip the operands.
3137 // If LHS is a foldable load, but RHS is not, flip the condition.
3138 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3139 !ISD::isNON_EXTLoad(RHS.getNode())) {
3140 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3141 std::swap(LHS, RHS);
3144 switch (SetCCOpcode) {
3150 std::swap(LHS, RHS);
3154 // On a floating point condition, the flags are set as follows:
3156 // 0 | 0 | 0 | X > Y
3157 // 0 | 0 | 1 | X < Y
3158 // 1 | 0 | 0 | X == Y
3159 // 1 | 1 | 1 | unordered
3160 switch (SetCCOpcode) {
3161 default: llvm_unreachable("Condcode should be pre-legalized away");
3163 case ISD::SETEQ: return X86::COND_E;
3164 case ISD::SETOLT: // flipped
3166 case ISD::SETGT: return X86::COND_A;
3167 case ISD::SETOLE: // flipped
3169 case ISD::SETGE: return X86::COND_AE;
3170 case ISD::SETUGT: // flipped
3172 case ISD::SETLT: return X86::COND_B;
3173 case ISD::SETUGE: // flipped
3175 case ISD::SETLE: return X86::COND_BE;
3177 case ISD::SETNE: return X86::COND_NE;
3178 case ISD::SETUO: return X86::COND_P;
3179 case ISD::SETO: return X86::COND_NP;
3181 case ISD::SETUNE: return X86::COND_INVALID;
3185 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3186 /// code. Current x86 isa includes the following FP cmov instructions:
3187 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3188 static bool hasFPCMov(unsigned X86CC) {
3204 /// isFPImmLegal - Returns true if the target can instruction select the
3205 /// specified FP immediate natively. If false, the legalizer will
3206 /// materialize the FP immediate as a load from a constant pool.
3207 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3208 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3209 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3215 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3216 /// the specified range (L, H].
3217 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3218 return (Val < 0) || (Val >= Low && Val < Hi);
3221 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3222 /// specified value.
3223 static bool isUndefOrEqual(int Val, int CmpVal) {
3224 if (Val < 0 || Val == CmpVal)
3229 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3230 /// from position Pos and ending in Pos+Size, falls within the specified
3231 /// sequential range (L, L+Pos]. or is undef.
3232 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3233 unsigned Pos, unsigned Size, int Low) {
3234 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3235 if (!isUndefOrEqual(Mask[i], Low))
3240 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3241 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3242 /// the second operand.
3243 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3244 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3245 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3246 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3247 return (Mask[0] < 2 && Mask[1] < 2);
3251 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3252 /// is suitable for input to PSHUFHW.
3253 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3254 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3257 // Lower quadword copied in order or undef.
3258 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3261 // Upper quadword shuffled.
3262 for (unsigned i = 4; i != 8; ++i)
3263 if (!isUndefOrInRange(Mask[i], 4, 8))
3266 if (VT == MVT::v16i16) {
3267 // Lower quadword copied in order or undef.
3268 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3271 // Upper quadword shuffled.
3272 for (unsigned i = 12; i != 16; ++i)
3273 if (!isUndefOrInRange(Mask[i], 12, 16))
3280 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3281 /// is suitable for input to PSHUFLW.
3282 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3283 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3286 // Upper quadword copied in order.
3287 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3290 // Lower quadword shuffled.
3291 for (unsigned i = 0; i != 4; ++i)
3292 if (!isUndefOrInRange(Mask[i], 0, 4))
3295 if (VT == MVT::v16i16) {
3296 // Upper quadword copied in order.
3297 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3300 // Lower quadword shuffled.
3301 for (unsigned i = 8; i != 12; ++i)
3302 if (!isUndefOrInRange(Mask[i], 8, 12))
3309 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3310 /// is suitable for input to PALIGNR.
3311 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3312 const X86Subtarget *Subtarget) {
3313 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3314 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3317 unsigned NumElts = VT.getVectorNumElements();
3318 unsigned NumLanes = VT.getSizeInBits()/128;
3319 unsigned NumLaneElts = NumElts/NumLanes;
3321 // Do not handle 64-bit element shuffles with palignr.
3322 if (NumLaneElts == 2)
3325 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3327 for (i = 0; i != NumLaneElts; ++i) {
3332 // Lane is all undef, go to next lane
3333 if (i == NumLaneElts)
3336 int Start = Mask[i+l];
3338 // Make sure its in this lane in one of the sources
3339 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3340 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3343 // If not lane 0, then we must match lane 0
3344 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3347 // Correct second source to be contiguous with first source
3348 if (Start >= (int)NumElts)
3349 Start -= NumElts - NumLaneElts;
3351 // Make sure we're shifting in the right direction.
3352 if (Start <= (int)(i+l))
3357 // Check the rest of the elements to see if they are consecutive.
3358 for (++i; i != NumLaneElts; ++i) {
3359 int Idx = Mask[i+l];
3361 // Make sure its in this lane
3362 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3363 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3366 // If not lane 0, then we must match lane 0
3367 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3370 if (Idx >= (int)NumElts)
3371 Idx -= NumElts - NumLaneElts;
3373 if (!isUndefOrEqual(Idx, Start+i))
3382 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3383 /// the two vector operands have swapped position.
3384 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3385 unsigned NumElems) {
3386 for (unsigned i = 0; i != NumElems; ++i) {
3390 else if (idx < (int)NumElems)
3391 Mask[i] = idx + NumElems;
3393 Mask[i] = idx - NumElems;
3397 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3398 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3399 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3400 /// reverse of what x86 shuffles want.
3401 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3402 bool Commuted = false) {
3403 if (!HasAVX && VT.getSizeInBits() == 256)
3406 unsigned NumElems = VT.getVectorNumElements();
3407 unsigned NumLanes = VT.getSizeInBits()/128;
3408 unsigned NumLaneElems = NumElems/NumLanes;
3410 if (NumLaneElems != 2 && NumLaneElems != 4)
3413 // VSHUFPSY divides the resulting vector into 4 chunks.
3414 // The sources are also splitted into 4 chunks, and each destination
3415 // chunk must come from a different source chunk.
3417 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3418 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3420 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3421 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3423 // VSHUFPDY divides the resulting vector into 4 chunks.
3424 // The sources are also splitted into 4 chunks, and each destination
3425 // chunk must come from a different source chunk.
3427 // SRC1 => X3 X2 X1 X0
3428 // SRC2 => Y3 Y2 Y1 Y0
3430 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3432 unsigned HalfLaneElems = NumLaneElems/2;
3433 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3434 for (unsigned i = 0; i != NumLaneElems; ++i) {
3435 int Idx = Mask[i+l];
3436 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3437 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3439 // For VSHUFPSY, the mask of the second half must be the same as the
3440 // first but with the appropriate offsets. This works in the same way as
3441 // VPERMILPS works with masks.
3442 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3444 if (!isUndefOrEqual(Idx, Mask[i]+l))
3452 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3453 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3454 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3455 if (!VT.is128BitVector())
3458 unsigned NumElems = VT.getVectorNumElements();
3463 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3464 return isUndefOrEqual(Mask[0], 6) &&
3465 isUndefOrEqual(Mask[1], 7) &&
3466 isUndefOrEqual(Mask[2], 2) &&
3467 isUndefOrEqual(Mask[3], 3);
3470 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3471 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3473 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3474 if (!VT.is128BitVector())
3477 unsigned NumElems = VT.getVectorNumElements();
3482 return isUndefOrEqual(Mask[0], 2) &&
3483 isUndefOrEqual(Mask[1], 3) &&
3484 isUndefOrEqual(Mask[2], 2) &&
3485 isUndefOrEqual(Mask[3], 3);
3488 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3490 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3491 if (!VT.is128BitVector())
3494 unsigned NumElems = VT.getVectorNumElements();
3496 if (NumElems != 2 && NumElems != 4)
3499 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3500 if (!isUndefOrEqual(Mask[i], i + NumElems))
3503 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3504 if (!isUndefOrEqual(Mask[i], i))
3510 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3511 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3512 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3513 if (!VT.is128BitVector())
3516 unsigned NumElems = VT.getVectorNumElements();
3518 if (NumElems != 2 && NumElems != 4)
3521 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3522 if (!isUndefOrEqual(Mask[i], i))
3525 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3526 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3533 // Some special combinations that can be optimized.
3536 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3537 SelectionDAG &DAG) {
3538 EVT VT = SVOp->getValueType(0);
3539 DebugLoc dl = SVOp->getDebugLoc();
3541 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3544 ArrayRef<int> Mask = SVOp->getMask();
3546 // These are the special masks that may be optimized.
3547 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3548 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3549 bool MatchEvenMask = true;
3550 bool MatchOddMask = true;
3551 for (int i=0; i<8; ++i) {
3552 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3553 MatchEvenMask = false;
3554 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3555 MatchOddMask = false;
3558 if (!MatchEvenMask && !MatchOddMask)
3561 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3563 SDValue Op0 = SVOp->getOperand(0);
3564 SDValue Op1 = SVOp->getOperand(1);
3566 if (MatchEvenMask) {
3567 // Shift the second operand right to 32 bits.
3568 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3569 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3571 // Shift the first operand left to 32 bits.
3572 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3573 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3575 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3576 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3579 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3580 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3581 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3582 bool HasAVX2, bool V2IsSplat = false) {
3583 unsigned NumElts = VT.getVectorNumElements();
3585 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3586 "Unsupported vector type for unpckh");
3588 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3589 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3592 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3593 // independently on 128-bit lanes.
3594 unsigned NumLanes = VT.getSizeInBits()/128;
3595 unsigned NumLaneElts = NumElts/NumLanes;
3597 for (unsigned l = 0; l != NumLanes; ++l) {
3598 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3599 i != (l+1)*NumLaneElts;
3602 int BitI1 = Mask[i+1];
3603 if (!isUndefOrEqual(BitI, j))
3606 if (!isUndefOrEqual(BitI1, NumElts))
3609 if (!isUndefOrEqual(BitI1, j + NumElts))
3618 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3619 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3620 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3621 bool HasAVX2, bool V2IsSplat = false) {
3622 unsigned NumElts = VT.getVectorNumElements();
3624 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3625 "Unsupported vector type for unpckh");
3627 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3628 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3631 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3632 // independently on 128-bit lanes.
3633 unsigned NumLanes = VT.getSizeInBits()/128;
3634 unsigned NumLaneElts = NumElts/NumLanes;
3636 for (unsigned l = 0; l != NumLanes; ++l) {
3637 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3638 i != (l+1)*NumLaneElts; i += 2, ++j) {
3640 int BitI1 = Mask[i+1];
3641 if (!isUndefOrEqual(BitI, j))
3644 if (isUndefOrEqual(BitI1, NumElts))
3647 if (!isUndefOrEqual(BitI1, j+NumElts))
3655 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3656 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3658 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3660 unsigned NumElts = VT.getVectorNumElements();
3662 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3663 "Unsupported vector type for unpckh");
3665 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3666 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3669 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3670 // FIXME: Need a better way to get rid of this, there's no latency difference
3671 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3672 // the former later. We should also remove the "_undef" special mask.
3673 if (NumElts == 4 && VT.getSizeInBits() == 256)
3676 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3677 // independently on 128-bit lanes.
3678 unsigned NumLanes = VT.getSizeInBits()/128;
3679 unsigned NumLaneElts = NumElts/NumLanes;
3681 for (unsigned l = 0; l != NumLanes; ++l) {
3682 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3683 i != (l+1)*NumLaneElts;
3686 int BitI1 = Mask[i+1];
3688 if (!isUndefOrEqual(BitI, j))
3690 if (!isUndefOrEqual(BitI1, j))
3698 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3699 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3701 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3702 unsigned NumElts = VT.getVectorNumElements();
3704 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3705 "Unsupported vector type for unpckh");
3707 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3708 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3711 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3712 // independently on 128-bit lanes.
3713 unsigned NumLanes = VT.getSizeInBits()/128;
3714 unsigned NumLaneElts = NumElts/NumLanes;
3716 for (unsigned l = 0; l != NumLanes; ++l) {
3717 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3718 i != (l+1)*NumLaneElts; i += 2, ++j) {
3720 int BitI1 = Mask[i+1];
3721 if (!isUndefOrEqual(BitI, j))
3723 if (!isUndefOrEqual(BitI1, j))
3730 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3731 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3732 /// MOVSD, and MOVD, i.e. setting the lowest element.
3733 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3734 if (VT.getVectorElementType().getSizeInBits() < 32)
3736 if (!VT.is128BitVector())
3739 unsigned NumElts = VT.getVectorNumElements();
3741 if (!isUndefOrEqual(Mask[0], NumElts))
3744 for (unsigned i = 1; i != NumElts; ++i)
3745 if (!isUndefOrEqual(Mask[i], i))
3751 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3752 /// as permutations between 128-bit chunks or halves. As an example: this
3754 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3755 /// The first half comes from the second half of V1 and the second half from the
3756 /// the second half of V2.
3757 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3758 if (!HasAVX || !VT.is256BitVector())
3761 // The shuffle result is divided into half A and half B. In total the two
3762 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3763 // B must come from C, D, E or F.
3764 unsigned HalfSize = VT.getVectorNumElements()/2;
3765 bool MatchA = false, MatchB = false;
3767 // Check if A comes from one of C, D, E, F.
3768 for (unsigned Half = 0; Half != 4; ++Half) {
3769 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3775 // Check if B comes from one of C, D, E, F.
3776 for (unsigned Half = 0; Half != 4; ++Half) {
3777 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3783 return MatchA && MatchB;
3786 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3787 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3788 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3789 EVT VT = SVOp->getValueType(0);
3791 unsigned HalfSize = VT.getVectorNumElements()/2;
3793 unsigned FstHalf = 0, SndHalf = 0;
3794 for (unsigned i = 0; i < HalfSize; ++i) {
3795 if (SVOp->getMaskElt(i) > 0) {
3796 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3800 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3801 if (SVOp->getMaskElt(i) > 0) {
3802 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3807 return (FstHalf | (SndHalf << 4));
3810 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3811 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3812 /// Note that VPERMIL mask matching is different depending whether theunderlying
3813 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3814 /// to the same elements of the low, but to the higher half of the source.
3815 /// In VPERMILPD the two lanes could be shuffled independently of each other
3816 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3817 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3821 unsigned NumElts = VT.getVectorNumElements();
3822 // Only match 256-bit with 32/64-bit types
3823 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3826 unsigned NumLanes = VT.getSizeInBits()/128;
3827 unsigned LaneSize = NumElts/NumLanes;
3828 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3829 for (unsigned i = 0; i != LaneSize; ++i) {
3830 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3832 if (NumElts != 8 || l == 0)
3834 // VPERMILPS handling
3837 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3845 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3846 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3847 /// element of vector 2 and the other elements to come from vector 1 in order.
3848 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3849 bool V2IsSplat = false, bool V2IsUndef = false) {
3850 if (!VT.is128BitVector())
3853 unsigned NumOps = VT.getVectorNumElements();
3854 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3857 if (!isUndefOrEqual(Mask[0], 0))
3860 for (unsigned i = 1; i != NumOps; ++i)
3861 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3862 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3863 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3869 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3870 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3871 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3872 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3873 const X86Subtarget *Subtarget) {
3874 if (!Subtarget->hasSSE3())
3877 unsigned NumElems = VT.getVectorNumElements();
3879 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3880 (VT.getSizeInBits() == 256 && NumElems != 8))
3883 // "i+1" is the value the indexed mask element must have
3884 for (unsigned i = 0; i != NumElems; i += 2)
3885 if (!isUndefOrEqual(Mask[i], i+1) ||
3886 !isUndefOrEqual(Mask[i+1], i+1))
3892 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3894 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3895 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3896 const X86Subtarget *Subtarget) {
3897 if (!Subtarget->hasSSE3())
3900 unsigned NumElems = VT.getVectorNumElements();
3902 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3903 (VT.getSizeInBits() == 256 && NumElems != 8))
3906 // "i" is the value the indexed mask element must have
3907 for (unsigned i = 0; i != NumElems; i += 2)
3908 if (!isUndefOrEqual(Mask[i], i) ||
3909 !isUndefOrEqual(Mask[i+1], i))
3915 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3916 /// specifies a shuffle of elements that is suitable for input to 256-bit
3917 /// version of MOVDDUP.
3918 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3919 if (!HasAVX || !VT.is256BitVector())
3922 unsigned NumElts = VT.getVectorNumElements();
3926 for (unsigned i = 0; i != NumElts/2; ++i)
3927 if (!isUndefOrEqual(Mask[i], 0))
3929 for (unsigned i = NumElts/2; i != NumElts; ++i)
3930 if (!isUndefOrEqual(Mask[i], NumElts/2))
3935 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to 128-bit
3937 /// version of MOVDDUP.
3938 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3939 if (!VT.is128BitVector())
3942 unsigned e = VT.getVectorNumElements() / 2;
3943 for (unsigned i = 0; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[i], i))
3946 for (unsigned i = 0; i != e; ++i)
3947 if (!isUndefOrEqual(Mask[e+i], i))
3952 /// isVEXTRACTF128Index - Return true if the specified
3953 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3954 /// suitable for input to VEXTRACTF128.
3955 bool X86::isVEXTRACTF128Index(SDNode *N) {
3956 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3959 // The index should be aligned on a 128-bit boundary.
3961 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3963 unsigned VL = N->getValueType(0).getVectorNumElements();
3964 unsigned VBits = N->getValueType(0).getSizeInBits();
3965 unsigned ElSize = VBits / VL;
3966 bool Result = (Index * ElSize) % 128 == 0;
3971 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3972 /// operand specifies a subvector insert that is suitable for input to
3974 bool X86::isVINSERTF128Index(SDNode *N) {
3975 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3978 // The index should be aligned on a 128-bit boundary.
3980 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3982 unsigned VL = N->getValueType(0).getVectorNumElements();
3983 unsigned VBits = N->getValueType(0).getSizeInBits();
3984 unsigned ElSize = VBits / VL;
3985 bool Result = (Index * ElSize) % 128 == 0;
3990 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3991 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3992 /// Handles 128-bit and 256-bit.
3993 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3994 EVT VT = N->getValueType(0);
3996 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3997 "Unsupported vector type for PSHUF/SHUFP");
3999 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4000 // independently on 128-bit lanes.
4001 unsigned NumElts = VT.getVectorNumElements();
4002 unsigned NumLanes = VT.getSizeInBits()/128;
4003 unsigned NumLaneElts = NumElts/NumLanes;
4005 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4006 "Only supports 2 or 4 elements per lane");
4008 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4010 for (unsigned i = 0; i != NumElts; ++i) {
4011 int Elt = N->getMaskElt(i);
4012 if (Elt < 0) continue;
4013 Elt &= NumLaneElts - 1;
4014 unsigned ShAmt = (i << Shift) % 8;
4015 Mask |= Elt << ShAmt;
4021 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4022 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4023 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4024 EVT VT = N->getValueType(0);
4026 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4027 "Unsupported vector type for PSHUFHW");
4029 unsigned NumElts = VT.getVectorNumElements();
4032 for (unsigned l = 0; l != NumElts; l += 8) {
4033 // 8 nodes per lane, but we only care about the last 4.
4034 for (unsigned i = 0; i < 4; ++i) {
4035 int Elt = N->getMaskElt(l+i+4);
4036 if (Elt < 0) continue;
4037 Elt &= 0x3; // only 2-bits.
4038 Mask |= Elt << (i * 2);
4045 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4046 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4047 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4048 EVT VT = N->getValueType(0);
4050 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4051 "Unsupported vector type for PSHUFHW");
4053 unsigned NumElts = VT.getVectorNumElements();
4056 for (unsigned l = 0; l != NumElts; l += 8) {
4057 // 8 nodes per lane, but we only care about the first 4.
4058 for (unsigned i = 0; i < 4; ++i) {
4059 int Elt = N->getMaskElt(l+i);
4060 if (Elt < 0) continue;
4061 Elt &= 0x3; // only 2-bits
4062 Mask |= Elt << (i * 2);
4069 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4070 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4071 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4072 EVT VT = SVOp->getValueType(0);
4073 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4075 unsigned NumElts = VT.getVectorNumElements();
4076 unsigned NumLanes = VT.getSizeInBits()/128;
4077 unsigned NumLaneElts = NumElts/NumLanes;
4081 for (i = 0; i != NumElts; ++i) {
4082 Val = SVOp->getMaskElt(i);
4086 if (Val >= (int)NumElts)
4087 Val -= NumElts - NumLaneElts;
4089 assert(Val - i > 0 && "PALIGNR imm should be positive");
4090 return (Val - i) * EltSize;
4093 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4094 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4096 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4097 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4098 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4101 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4103 EVT VecVT = N->getOperand(0).getValueType();
4104 EVT ElVT = VecVT.getVectorElementType();
4106 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4107 return Index / NumElemsPerChunk;
4110 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4111 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4113 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4114 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4115 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4118 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4120 EVT VecVT = N->getValueType(0);
4121 EVT ElVT = VecVT.getVectorElementType();
4123 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4124 return Index / NumElemsPerChunk;
4127 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4128 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4129 /// Handles 256-bit.
4130 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4131 EVT VT = N->getValueType(0);
4133 unsigned NumElts = VT.getVectorNumElements();
4135 assert((VT.is256BitVector() && NumElts == 4) &&
4136 "Unsupported vector type for VPERMQ/VPERMPD");
4139 for (unsigned i = 0; i != NumElts; ++i) {
4140 int Elt = N->getMaskElt(i);
4143 Mask |= Elt << (i*2);
4148 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4150 bool X86::isZeroNode(SDValue Elt) {
4151 return ((isa<ConstantSDNode>(Elt) &&
4152 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4153 (isa<ConstantFPSDNode>(Elt) &&
4154 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4157 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4158 /// their permute mask.
4159 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4160 SelectionDAG &DAG) {
4161 EVT VT = SVOp->getValueType(0);
4162 unsigned NumElems = VT.getVectorNumElements();
4163 SmallVector<int, 8> MaskVec;
4165 for (unsigned i = 0; i != NumElems; ++i) {
4166 int Idx = SVOp->getMaskElt(i);
4168 if (Idx < (int)NumElems)
4173 MaskVec.push_back(Idx);
4175 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4176 SVOp->getOperand(0), &MaskVec[0]);
4179 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4180 /// match movhlps. The lower half elements should come from upper half of
4181 /// V1 (and in order), and the upper half elements should come from the upper
4182 /// half of V2 (and in order).
4183 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4184 if (!VT.is128BitVector())
4186 if (VT.getVectorNumElements() != 4)
4188 for (unsigned i = 0, e = 2; i != e; ++i)
4189 if (!isUndefOrEqual(Mask[i], i+2))
4191 for (unsigned i = 2; i != 4; ++i)
4192 if (!isUndefOrEqual(Mask[i], i+4))
4197 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4198 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4200 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4201 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4203 N = N->getOperand(0).getNode();
4204 if (!ISD::isNON_EXTLoad(N))
4207 *LD = cast<LoadSDNode>(N);
4211 // Test whether the given value is a vector value which will be legalized
4213 static bool WillBeConstantPoolLoad(SDNode *N) {
4214 if (N->getOpcode() != ISD::BUILD_VECTOR)
4217 // Check for any non-constant elements.
4218 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4219 switch (N->getOperand(i).getNode()->getOpcode()) {
4221 case ISD::ConstantFP:
4228 // Vectors of all-zeros and all-ones are materialized with special
4229 // instructions rather than being loaded.
4230 return !ISD::isBuildVectorAllZeros(N) &&
4231 !ISD::isBuildVectorAllOnes(N);
4234 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4235 /// match movlp{s|d}. The lower half elements should come from lower half of
4236 /// V1 (and in order), and the upper half elements should come from the upper
4237 /// half of V2 (and in order). And since V1 will become the source of the
4238 /// MOVLP, it must be either a vector load or a scalar load to vector.
4239 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4240 ArrayRef<int> Mask, EVT VT) {
4241 if (!VT.is128BitVector())
4244 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4246 // Is V2 is a vector load, don't do this transformation. We will try to use
4247 // load folding shufps op.
4248 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4251 unsigned NumElems = VT.getVectorNumElements();
4253 if (NumElems != 2 && NumElems != 4)
4255 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4256 if (!isUndefOrEqual(Mask[i], i))
4258 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4259 if (!isUndefOrEqual(Mask[i], i+NumElems))
4264 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4266 static bool isSplatVector(SDNode *N) {
4267 if (N->getOpcode() != ISD::BUILD_VECTOR)
4270 SDValue SplatValue = N->getOperand(0);
4271 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4272 if (N->getOperand(i) != SplatValue)
4277 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4278 /// to an zero vector.
4279 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4280 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4281 SDValue V1 = N->getOperand(0);
4282 SDValue V2 = N->getOperand(1);
4283 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4284 for (unsigned i = 0; i != NumElems; ++i) {
4285 int Idx = N->getMaskElt(i);
4286 if (Idx >= (int)NumElems) {
4287 unsigned Opc = V2.getOpcode();
4288 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4290 if (Opc != ISD::BUILD_VECTOR ||
4291 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4293 } else if (Idx >= 0) {
4294 unsigned Opc = V1.getOpcode();
4295 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4297 if (Opc != ISD::BUILD_VECTOR ||
4298 !X86::isZeroNode(V1.getOperand(Idx)))
4305 /// getZeroVector - Returns a vector of specified type with all zero elements.
4307 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4308 SelectionDAG &DAG, DebugLoc dl) {
4309 assert(VT.isVector() && "Expected a vector type");
4310 unsigned Size = VT.getSizeInBits();
4312 // Always build SSE zero vectors as <4 x i32> bitcasted
4313 // to their dest type. This ensures they get CSE'd.
4315 if (Size == 128) { // SSE
4316 if (Subtarget->hasSSE2()) { // SSE2
4317 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4318 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4320 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4321 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4323 } else if (Size == 256) { // AVX
4324 if (Subtarget->hasAVX2()) { // AVX2
4325 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4326 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4327 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4329 // 256-bit logic and arithmetic instructions in AVX are all
4330 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4331 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4332 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4333 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4336 llvm_unreachable("Unexpected vector type");
4338 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4341 /// getOnesVector - Returns a vector of specified type with all bits set.
4342 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4343 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4344 /// Then bitcast to their original type, ensuring they get CSE'd.
4345 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4347 assert(VT.isVector() && "Expected a vector type");
4348 unsigned Size = VT.getSizeInBits();
4350 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4353 if (HasAVX2) { // AVX2
4354 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4355 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4357 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4358 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4360 } else if (Size == 128) {
4361 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4363 llvm_unreachable("Unexpected vector type");
4365 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4368 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4369 /// that point to V2 points to its first element.
4370 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4371 for (unsigned i = 0; i != NumElems; ++i) {
4372 if (Mask[i] > (int)NumElems) {
4378 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4379 /// operation of specified width.
4380 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4382 unsigned NumElems = VT.getVectorNumElements();
4383 SmallVector<int, 8> Mask;
4384 Mask.push_back(NumElems);
4385 for (unsigned i = 1; i != NumElems; ++i)
4387 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4390 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4391 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4393 unsigned NumElems = VT.getVectorNumElements();
4394 SmallVector<int, 8> Mask;
4395 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4397 Mask.push_back(i + NumElems);
4399 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4402 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4403 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4405 unsigned NumElems = VT.getVectorNumElements();
4406 SmallVector<int, 8> Mask;
4407 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4408 Mask.push_back(i + Half);
4409 Mask.push_back(i + NumElems + Half);
4411 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4414 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4415 // a generic shuffle instruction because the target has no such instructions.
4416 // Generate shuffles which repeat i16 and i8 several times until they can be
4417 // represented by v4f32 and then be manipulated by target suported shuffles.
4418 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4419 EVT VT = V.getValueType();
4420 int NumElems = VT.getVectorNumElements();
4421 DebugLoc dl = V.getDebugLoc();
4423 while (NumElems > 4) {
4424 if (EltNo < NumElems/2) {
4425 V = getUnpackl(DAG, dl, VT, V, V);
4427 V = getUnpackh(DAG, dl, VT, V, V);
4428 EltNo -= NumElems/2;
4435 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4436 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4437 EVT VT = V.getValueType();
4438 DebugLoc dl = V.getDebugLoc();
4439 unsigned Size = VT.getSizeInBits();
4442 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4443 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4444 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4446 } else if (Size == 256) {
4447 // To use VPERMILPS to splat scalars, the second half of indicies must
4448 // refer to the higher part, which is a duplication of the lower one,
4449 // because VPERMILPS can only handle in-lane permutations.
4450 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4451 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4453 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4454 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4457 llvm_unreachable("Vector size not supported");
4459 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4462 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4463 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4464 EVT SrcVT = SV->getValueType(0);
4465 SDValue V1 = SV->getOperand(0);
4466 DebugLoc dl = SV->getDebugLoc();
4468 int EltNo = SV->getSplatIndex();
4469 int NumElems = SrcVT.getVectorNumElements();
4470 unsigned Size = SrcVT.getSizeInBits();
4472 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4473 "Unknown how to promote splat for type");
4475 // Extract the 128-bit part containing the splat element and update
4476 // the splat element index when it refers to the higher register.
4478 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4479 if (EltNo >= NumElems/2)
4480 EltNo -= NumElems/2;
4483 // All i16 and i8 vector types can't be used directly by a generic shuffle
4484 // instruction because the target has no such instruction. Generate shuffles
4485 // which repeat i16 and i8 several times until they fit in i32, and then can
4486 // be manipulated by target suported shuffles.
4487 EVT EltVT = SrcVT.getVectorElementType();
4488 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4489 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4491 // Recreate the 256-bit vector and place the same 128-bit vector
4492 // into the low and high part. This is necessary because we want
4493 // to use VPERM* to shuffle the vectors
4495 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4498 return getLegalSplat(DAG, V1, EltNo);
4501 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4502 /// vector of zero or undef vector. This produces a shuffle where the low
4503 /// element of V2 is swizzled into the zero/undef vector, landing at element
4504 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4505 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4507 const X86Subtarget *Subtarget,
4508 SelectionDAG &DAG) {
4509 EVT VT = V2.getValueType();
4511 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4512 unsigned NumElems = VT.getVectorNumElements();
4513 SmallVector<int, 16> MaskVec;
4514 for (unsigned i = 0; i != NumElems; ++i)
4515 // If this is the insertion idx, put the low elt of V2 here.
4516 MaskVec.push_back(i == Idx ? NumElems : i);
4517 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4520 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4521 /// target specific opcode. Returns true if the Mask could be calculated.
4522 /// Sets IsUnary to true if only uses one source.
4523 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4524 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4525 unsigned NumElems = VT.getVectorNumElements();
4529 switch(N->getOpcode()) {
4531 ImmN = N->getOperand(N->getNumOperands()-1);
4532 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4534 case X86ISD::UNPCKH:
4535 DecodeUNPCKHMask(VT, Mask);
4537 case X86ISD::UNPCKL:
4538 DecodeUNPCKLMask(VT, Mask);
4540 case X86ISD::MOVHLPS:
4541 DecodeMOVHLPSMask(NumElems, Mask);
4543 case X86ISD::MOVLHPS:
4544 DecodeMOVLHPSMask(NumElems, Mask);
4546 case X86ISD::PSHUFD:
4547 case X86ISD::VPERMILP:
4548 ImmN = N->getOperand(N->getNumOperands()-1);
4549 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552 case X86ISD::PSHUFHW:
4553 ImmN = N->getOperand(N->getNumOperands()-1);
4554 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4557 case X86ISD::PSHUFLW:
4558 ImmN = N->getOperand(N->getNumOperands()-1);
4559 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4562 case X86ISD::VPERMI:
4563 ImmN = N->getOperand(N->getNumOperands()-1);
4564 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568 case X86ISD::MOVSD: {
4569 // The index 0 always comes from the first element of the second source,
4570 // this is why MOVSS and MOVSD are used in the first place. The other
4571 // elements come from the other positions of the first source vector
4572 Mask.push_back(NumElems);
4573 for (unsigned i = 1; i != NumElems; ++i) {
4578 case X86ISD::VPERM2X128:
4579 ImmN = N->getOperand(N->getNumOperands()-1);
4580 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581 if (Mask.empty()) return false;
4583 case X86ISD::MOVDDUP:
4584 case X86ISD::MOVLHPD:
4585 case X86ISD::MOVLPD:
4586 case X86ISD::MOVLPS:
4587 case X86ISD::MOVSHDUP:
4588 case X86ISD::MOVSLDUP:
4589 case X86ISD::PALIGN:
4590 // Not yet implemented
4592 default: llvm_unreachable("unknown target shuffle node");
4598 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4599 /// element of the result of the vector shuffle.
4600 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4603 return SDValue(); // Limit search depth.
4605 SDValue V = SDValue(N, 0);
4606 EVT VT = V.getValueType();
4607 unsigned Opcode = V.getOpcode();
4609 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4610 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4611 int Elt = SV->getMaskElt(Index);
4614 return DAG.getUNDEF(VT.getVectorElementType());
4616 unsigned NumElems = VT.getVectorNumElements();
4617 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4618 : SV->getOperand(1);
4619 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4622 // Recurse into target specific vector shuffles to find scalars.
4623 if (isTargetShuffle(Opcode)) {
4624 MVT ShufVT = V.getValueType().getSimpleVT();
4625 unsigned NumElems = ShufVT.getVectorNumElements();
4626 SmallVector<int, 16> ShuffleMask;
4630 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4633 int Elt = ShuffleMask[Index];
4635 return DAG.getUNDEF(ShufVT.getVectorElementType());
4637 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4639 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4643 // Actual nodes that may contain scalar elements
4644 if (Opcode == ISD::BITCAST) {
4645 V = V.getOperand(0);
4646 EVT SrcVT = V.getValueType();
4647 unsigned NumElems = VT.getVectorNumElements();
4649 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4653 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4654 return (Index == 0) ? V.getOperand(0)
4655 : DAG.getUNDEF(VT.getVectorElementType());
4657 if (V.getOpcode() == ISD::BUILD_VECTOR)
4658 return V.getOperand(Index);
4663 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4664 /// shuffle operation which come from a consecutively from a zero. The
4665 /// search can start in two different directions, from left or right.
4667 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4668 bool ZerosFromLeft, SelectionDAG &DAG) {
4670 for (i = 0; i != NumElems; ++i) {
4671 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4672 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4673 if (!(Elt.getNode() &&
4674 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4681 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4682 /// correspond consecutively to elements from one of the vector operands,
4683 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4685 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4686 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4687 unsigned NumElems, unsigned &OpNum) {
4688 bool SeenV1 = false;
4689 bool SeenV2 = false;
4691 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4692 int Idx = SVOp->getMaskElt(i);
4693 // Ignore undef indicies
4697 if (Idx < (int)NumElems)
4702 // Only accept consecutive elements from the same vector
4703 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4707 OpNum = SeenV1 ? 0 : 1;
4711 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4712 /// logical left shift of a vector.
4713 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4714 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4715 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4716 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4717 false /* check zeros from right */, DAG);
4723 // Considering the elements in the mask that are not consecutive zeros,
4724 // check if they consecutively come from only one of the source vectors.
4726 // V1 = {X, A, B, C} 0
4728 // vector_shuffle V1, V2 <1, 2, 3, X>
4730 if (!isShuffleMaskConsecutive(SVOp,
4731 0, // Mask Start Index
4732 NumElems-NumZeros, // Mask End Index(exclusive)
4733 NumZeros, // Where to start looking in the src vector
4734 NumElems, // Number of elements in vector
4735 OpSrc)) // Which source operand ?
4740 ShVal = SVOp->getOperand(OpSrc);
4744 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4745 /// logical left shift of a vector.
4746 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4747 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4748 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4749 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4750 true /* check zeros from left */, DAG);
4756 // Considering the elements in the mask that are not consecutive zeros,
4757 // check if they consecutively come from only one of the source vectors.
4759 // 0 { A, B, X, X } = V2
4761 // vector_shuffle V1, V2 <X, X, 4, 5>
4763 if (!isShuffleMaskConsecutive(SVOp,
4764 NumZeros, // Mask Start Index
4765 NumElems, // Mask End Index(exclusive)
4766 0, // Where to start looking in the src vector
4767 NumElems, // Number of elements in vector
4768 OpSrc)) // Which source operand ?
4773 ShVal = SVOp->getOperand(OpSrc);
4777 /// isVectorShift - Returns true if the shuffle can be implemented as a
4778 /// logical left or right shift of a vector.
4779 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4780 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4781 // Although the logic below support any bitwidth size, there are no
4782 // shift instructions which handle more than 128-bit vectors.
4783 if (!SVOp->getValueType(0).is128BitVector())
4786 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4787 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4793 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4795 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4796 unsigned NumNonZero, unsigned NumZero,
4798 const X86Subtarget* Subtarget,
4799 const TargetLowering &TLI) {
4803 DebugLoc dl = Op.getDebugLoc();
4806 for (unsigned i = 0; i < 16; ++i) {
4807 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4808 if (ThisIsNonZero && First) {
4810 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4812 V = DAG.getUNDEF(MVT::v8i16);
4817 SDValue ThisElt(0, 0), LastElt(0, 0);
4818 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4819 if (LastIsNonZero) {
4820 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4821 MVT::i16, Op.getOperand(i-1));
4823 if (ThisIsNonZero) {
4824 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4825 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4826 ThisElt, DAG.getConstant(8, MVT::i8));
4828 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4832 if (ThisElt.getNode())
4833 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4834 DAG.getIntPtrConstant(i/2));
4838 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4841 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4843 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4844 unsigned NumNonZero, unsigned NumZero,
4846 const X86Subtarget* Subtarget,
4847 const TargetLowering &TLI) {
4851 DebugLoc dl = Op.getDebugLoc();
4854 for (unsigned i = 0; i < 8; ++i) {
4855 bool isNonZero = (NonZeros & (1 << i)) != 0;
4859 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4861 V = DAG.getUNDEF(MVT::v8i16);
4864 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4865 MVT::v8i16, V, Op.getOperand(i),
4866 DAG.getIntPtrConstant(i));
4873 /// getVShift - Return a vector logical shift node.
4875 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4876 unsigned NumBits, SelectionDAG &DAG,
4877 const TargetLowering &TLI, DebugLoc dl) {
4878 assert(VT.is128BitVector() && "Unknown type for VShift");
4879 EVT ShVT = MVT::v2i64;
4880 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4881 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4882 return DAG.getNode(ISD::BITCAST, dl, VT,
4883 DAG.getNode(Opc, dl, ShVT, SrcOp,
4884 DAG.getConstant(NumBits,
4885 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4889 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4890 SelectionDAG &DAG) const {
4892 // Check if the scalar load can be widened into a vector load. And if
4893 // the address is "base + cst" see if the cst can be "absorbed" into
4894 // the shuffle mask.
4895 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4896 SDValue Ptr = LD->getBasePtr();
4897 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4899 EVT PVT = LD->getValueType(0);
4900 if (PVT != MVT::i32 && PVT != MVT::f32)
4905 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4906 FI = FINode->getIndex();
4908 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4909 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4910 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4911 Offset = Ptr.getConstantOperandVal(1);
4912 Ptr = Ptr.getOperand(0);
4917 // FIXME: 256-bit vector instructions don't require a strict alignment,
4918 // improve this code to support it better.
4919 unsigned RequiredAlign = VT.getSizeInBits()/8;
4920 SDValue Chain = LD->getChain();
4921 // Make sure the stack object alignment is at least 16 or 32.
4922 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4923 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4924 if (MFI->isFixedObjectIndex(FI)) {
4925 // Can't change the alignment. FIXME: It's possible to compute
4926 // the exact stack offset and reference FI + adjust offset instead.
4927 // If someone *really* cares about this. That's the way to implement it.
4930 MFI->setObjectAlignment(FI, RequiredAlign);
4934 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4935 // Ptr + (Offset & ~15).
4938 if ((Offset % RequiredAlign) & 3)
4940 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4942 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4943 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4945 int EltNo = (Offset - StartOffset) >> 2;
4946 unsigned NumElems = VT.getVectorNumElements();
4948 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4949 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4950 LD->getPointerInfo().getWithOffset(StartOffset),
4951 false, false, false, 0);
4953 SmallVector<int, 8> Mask;
4954 for (unsigned i = 0; i != NumElems; ++i)
4955 Mask.push_back(EltNo);
4957 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4963 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4964 /// vector of type 'VT', see if the elements can be replaced by a single large
4965 /// load which has the same value as a build_vector whose operands are 'elts'.
4967 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4969 /// FIXME: we'd also like to handle the case where the last elements are zero
4970 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4971 /// There's even a handy isZeroNode for that purpose.
4972 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4973 DebugLoc &DL, SelectionDAG &DAG) {
4974 EVT EltVT = VT.getVectorElementType();
4975 unsigned NumElems = Elts.size();
4977 LoadSDNode *LDBase = NULL;
4978 unsigned LastLoadedElt = -1U;
4980 // For each element in the initializer, see if we've found a load or an undef.
4981 // If we don't find an initial load element, or later load elements are
4982 // non-consecutive, bail out.
4983 for (unsigned i = 0; i < NumElems; ++i) {
4984 SDValue Elt = Elts[i];
4986 if (!Elt.getNode() ||
4987 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4990 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4992 LDBase = cast<LoadSDNode>(Elt.getNode());
4996 if (Elt.getOpcode() == ISD::UNDEF)
4999 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5000 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5005 // If we have found an entire vector of loads and undefs, then return a large
5006 // load of the entire vector width starting at the base pointer. If we found
5007 // consecutive loads for the low half, generate a vzext_load node.
5008 if (LastLoadedElt == NumElems - 1) {
5009 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5010 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5011 LDBase->getPointerInfo(),
5012 LDBase->isVolatile(), LDBase->isNonTemporal(),
5013 LDBase->isInvariant(), 0);
5014 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5015 LDBase->getPointerInfo(),
5016 LDBase->isVolatile(), LDBase->isNonTemporal(),
5017 LDBase->isInvariant(), LDBase->getAlignment());
5019 if (NumElems == 4 && LastLoadedElt == 1 &&
5020 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5021 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5022 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5024 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5025 LDBase->getPointerInfo(),
5026 LDBase->getAlignment(),
5027 false/*isVolatile*/, true/*ReadMem*/,
5030 // Make sure the newly-created LOAD is in the same position as LDBase in
5031 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5032 // update uses of LDBase's output chain to use the TokenFactor.
5033 if (LDBase->hasAnyUseOfValue(1)) {
5034 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5035 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5036 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5037 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5038 SDValue(ResNode.getNode(), 1));
5041 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5046 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5047 /// to generate a splat value for the following cases:
5048 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5049 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5050 /// a scalar load, or a constant.
5051 /// The VBROADCAST node is returned when a pattern is found,
5052 /// or SDValue() otherwise.
5054 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5055 if (!Subtarget->hasAVX())
5058 EVT VT = Op.getValueType();
5059 DebugLoc dl = Op.getDebugLoc();
5061 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5062 "Unsupported vector type for broadcast.");
5067 switch (Op.getOpcode()) {
5069 // Unknown pattern found.
5072 case ISD::BUILD_VECTOR: {
5073 // The BUILD_VECTOR node must be a splat.
5074 if (!isSplatVector(Op.getNode()))
5077 Ld = Op.getOperand(0);
5078 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5079 Ld.getOpcode() == ISD::ConstantFP);
5081 // The suspected load node has several users. Make sure that all
5082 // of its users are from the BUILD_VECTOR node.
5083 // Constants may have multiple users.
5084 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5089 case ISD::VECTOR_SHUFFLE: {
5090 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5092 // Shuffles must have a splat mask where the first element is
5094 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5097 SDValue Sc = Op.getOperand(0);
5098 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5099 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5101 if (!Subtarget->hasAVX2())
5104 // Use the register form of the broadcast instruction available on AVX2.
5105 if (VT.is256BitVector())
5106 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5107 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5110 Ld = Sc.getOperand(0);
5111 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5112 Ld.getOpcode() == ISD::ConstantFP);
5114 // The scalar_to_vector node and the suspected
5115 // load node must have exactly one user.
5116 // Constants may have multiple users.
5117 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5123 bool Is256 = VT.is256BitVector();
5125 // Handle the broadcasting a single constant scalar from the constant pool
5126 // into a vector. On Sandybridge it is still better to load a constant vector
5127 // from the constant pool and not to broadcast it from a scalar.
5128 if (ConstSplatVal && Subtarget->hasAVX2()) {
5129 EVT CVT = Ld.getValueType();
5130 assert(!CVT.isVector() && "Must not broadcast a vector type");
5131 unsigned ScalarSize = CVT.getSizeInBits();
5133 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5134 const Constant *C = 0;
5135 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5136 C = CI->getConstantIntValue();
5137 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5138 C = CF->getConstantFPValue();
5140 assert(C && "Invalid constant type");
5142 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5143 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5144 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5145 MachinePointerInfo::getConstantPool(),
5146 false, false, false, Alignment);
5148 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5152 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5153 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5155 // Handle AVX2 in-register broadcasts.
5156 if (!IsLoad && Subtarget->hasAVX2() &&
5157 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5158 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5160 // The scalar source must be a normal load.
5164 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5165 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5167 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5168 // double since there is no vbroadcastsd xmm
5169 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5170 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5171 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5174 // Unsupported broadcast.
5179 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5180 EVT VT = Op.getValueType();
5182 // Skip if insert_vec_elt is not supported.
5183 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5186 DebugLoc DL = Op.getDebugLoc();
5187 unsigned NumElems = Op.getNumOperands();
5191 SmallVector<unsigned, 4> InsertIndices;
5192 SmallVector<int, 8> Mask(NumElems, -1);
5194 for (unsigned i = 0; i != NumElems; ++i) {
5195 unsigned Opc = Op.getOperand(i).getOpcode();
5197 if (Opc == ISD::UNDEF)
5200 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5201 // Quit if more than 1 elements need inserting.
5202 if (InsertIndices.size() > 1)
5205 InsertIndices.push_back(i);
5209 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5210 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5212 // Quit if extracted from vector of different type.
5213 if (ExtractedFromVec.getValueType() != VT)
5216 // Quit if non-constant index.
5217 if (!isa<ConstantSDNode>(ExtIdx))
5220 if (VecIn1.getNode() == 0)
5221 VecIn1 = ExtractedFromVec;
5222 else if (VecIn1 != ExtractedFromVec) {
5223 if (VecIn2.getNode() == 0)
5224 VecIn2 = ExtractedFromVec;
5225 else if (VecIn2 != ExtractedFromVec)
5226 // Quit if more than 2 vectors to shuffle
5230 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5232 if (ExtractedFromVec == VecIn1)
5234 else if (ExtractedFromVec == VecIn2)
5235 Mask[i] = Idx + NumElems;
5238 if (VecIn1.getNode() == 0)
5241 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5242 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5243 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5244 unsigned Idx = InsertIndices[i];
5245 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5246 DAG.getIntPtrConstant(Idx));
5253 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5254 DebugLoc dl = Op.getDebugLoc();
5256 EVT VT = Op.getValueType();
5257 EVT ExtVT = VT.getVectorElementType();
5258 unsigned NumElems = Op.getNumOperands();
5260 // Vectors containing all zeros can be matched by pxor and xorps later
5261 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5262 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5263 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5264 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5267 return getZeroVector(VT, Subtarget, DAG, dl);
5270 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5271 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5272 // vpcmpeqd on 256-bit vectors.
5273 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5274 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5277 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5280 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5281 if (Broadcast.getNode())
5284 unsigned EVTBits = ExtVT.getSizeInBits();
5286 unsigned NumZero = 0;
5287 unsigned NumNonZero = 0;
5288 unsigned NonZeros = 0;
5289 bool IsAllConstants = true;
5290 SmallSet<SDValue, 8> Values;
5291 for (unsigned i = 0; i < NumElems; ++i) {
5292 SDValue Elt = Op.getOperand(i);
5293 if (Elt.getOpcode() == ISD::UNDEF)
5296 if (Elt.getOpcode() != ISD::Constant &&
5297 Elt.getOpcode() != ISD::ConstantFP)
5298 IsAllConstants = false;
5299 if (X86::isZeroNode(Elt))
5302 NonZeros |= (1 << i);
5307 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5308 if (NumNonZero == 0)
5309 return DAG.getUNDEF(VT);
5311 // Special case for single non-zero, non-undef, element.
5312 if (NumNonZero == 1) {
5313 unsigned Idx = CountTrailingZeros_32(NonZeros);
5314 SDValue Item = Op.getOperand(Idx);
5316 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5317 // the value are obviously zero, truncate the value to i32 and do the
5318 // insertion that way. Only do this if the value is non-constant or if the
5319 // value is a constant being inserted into element 0. It is cheaper to do
5320 // a constant pool load than it is to do a movd + shuffle.
5321 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5322 (!IsAllConstants || Idx == 0)) {
5323 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5325 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5326 EVT VecVT = MVT::v4i32;
5327 unsigned VecElts = 4;
5329 // Truncate the value (which may itself be a constant) to i32, and
5330 // convert it to a vector with movd (S2V+shuffle to zero extend).
5331 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5332 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5333 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5335 // Now we have our 32-bit value zero extended in the low element of
5336 // a vector. If Idx != 0, swizzle it into place.
5338 SmallVector<int, 4> Mask;
5339 Mask.push_back(Idx);
5340 for (unsigned i = 1; i != VecElts; ++i)
5342 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5345 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5349 // If we have a constant or non-constant insertion into the low element of
5350 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5351 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5352 // depending on what the source datatype is.
5355 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5357 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5358 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5359 if (VT.is256BitVector()) {
5360 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5361 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5362 Item, DAG.getIntPtrConstant(0));
5364 assert(VT.is128BitVector() && "Expected an SSE value type!");
5365 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5366 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5367 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5370 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5371 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5372 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5373 if (VT.is256BitVector()) {
5374 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5375 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5377 assert(VT.is128BitVector() && "Expected an SSE value type!");
5378 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5380 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5384 // Is it a vector logical left shift?
5385 if (NumElems == 2 && Idx == 1 &&
5386 X86::isZeroNode(Op.getOperand(0)) &&
5387 !X86::isZeroNode(Op.getOperand(1))) {
5388 unsigned NumBits = VT.getSizeInBits();
5389 return getVShift(true, VT,
5390 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5391 VT, Op.getOperand(1)),
5392 NumBits/2, DAG, *this, dl);
5395 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5398 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5399 // is a non-constant being inserted into an element other than the low one,
5400 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5401 // movd/movss) to move this into the low element, then shuffle it into
5403 if (EVTBits == 32) {
5404 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5406 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5407 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5408 SmallVector<int, 8> MaskVec;
5409 for (unsigned i = 0; i != NumElems; ++i)
5410 MaskVec.push_back(i == Idx ? 0 : 1);
5411 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5415 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5416 if (Values.size() == 1) {
5417 if (EVTBits == 32) {
5418 // Instead of a shuffle like this:
5419 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5420 // Check if it's possible to issue this instead.
5421 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5422 unsigned Idx = CountTrailingZeros_32(NonZeros);
5423 SDValue Item = Op.getOperand(Idx);
5424 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5425 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5430 // A vector full of immediates; various special cases are already
5431 // handled, so this is best done with a single constant-pool load.
5435 // For AVX-length vectors, build the individual 128-bit pieces and use
5436 // shuffles to put them in place.
5437 if (VT.is256BitVector()) {
5438 SmallVector<SDValue, 32> V;
5439 for (unsigned i = 0; i != NumElems; ++i)
5440 V.push_back(Op.getOperand(i));
5442 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5444 // Build both the lower and upper subvector.
5445 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5446 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5449 // Recreate the wider vector with the lower and upper part.
5450 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5453 // Let legalizer expand 2-wide build_vectors.
5454 if (EVTBits == 64) {
5455 if (NumNonZero == 1) {
5456 // One half is zero or undef.
5457 unsigned Idx = CountTrailingZeros_32(NonZeros);
5458 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5459 Op.getOperand(Idx));
5460 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5465 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5466 if (EVTBits == 8 && NumElems == 16) {
5467 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5469 if (V.getNode()) return V;
5472 if (EVTBits == 16 && NumElems == 8) {
5473 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5475 if (V.getNode()) return V;
5478 // If element VT is == 32 bits, turn it into a number of shuffles.
5479 SmallVector<SDValue, 8> V(NumElems);
5480 if (NumElems == 4 && NumZero > 0) {
5481 for (unsigned i = 0; i < 4; ++i) {
5482 bool isZero = !(NonZeros & (1 << i));
5484 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5486 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5489 for (unsigned i = 0; i < 2; ++i) {
5490 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5493 V[i] = V[i*2]; // Must be a zero vector.
5496 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5499 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5502 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5507 bool Reverse1 = (NonZeros & 0x3) == 2;
5508 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5512 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5513 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5515 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5518 if (Values.size() > 1 && VT.is128BitVector()) {
5519 // Check for a build vector of consecutive loads.
5520 for (unsigned i = 0; i < NumElems; ++i)
5521 V[i] = Op.getOperand(i);
5523 // Check for elements which are consecutive loads.
5524 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5528 // Check for a build vector from mostly shuffle plus few inserting.
5529 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5533 // For SSE 4.1, use insertps to put the high elements into the low element.
5534 if (getSubtarget()->hasSSE41()) {
5536 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5537 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5539 Result = DAG.getUNDEF(VT);
5541 for (unsigned i = 1; i < NumElems; ++i) {
5542 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5543 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5544 Op.getOperand(i), DAG.getIntPtrConstant(i));
5549 // Otherwise, expand into a number of unpckl*, start by extending each of
5550 // our (non-undef) elements to the full vector width with the element in the
5551 // bottom slot of the vector (which generates no code for SSE).
5552 for (unsigned i = 0; i < NumElems; ++i) {
5553 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5554 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5556 V[i] = DAG.getUNDEF(VT);
5559 // Next, we iteratively mix elements, e.g. for v4f32:
5560 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5561 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5562 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5563 unsigned EltStride = NumElems >> 1;
5564 while (EltStride != 0) {
5565 for (unsigned i = 0; i < EltStride; ++i) {
5566 // If V[i+EltStride] is undef and this is the first round of mixing,
5567 // then it is safe to just drop this shuffle: V[i] is already in the
5568 // right place, the one element (since it's the first round) being
5569 // inserted as undef can be dropped. This isn't safe for successive
5570 // rounds because they will permute elements within both vectors.
5571 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5572 EltStride == NumElems/2)
5575 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5584 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5585 // to create 256-bit vectors from two other 128-bit ones.
5586 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5587 DebugLoc dl = Op.getDebugLoc();
5588 EVT ResVT = Op.getValueType();
5590 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5592 SDValue V1 = Op.getOperand(0);
5593 SDValue V2 = Op.getOperand(1);
5594 unsigned NumElems = ResVT.getVectorNumElements();
5596 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5599 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5600 assert(Op.getNumOperands() == 2);
5602 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5603 // from two other 128-bit ones.
5604 return LowerAVXCONCAT_VECTORS(Op, DAG);
5607 // Try to lower a shuffle node into a simple blend instruction.
5609 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5610 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5611 SDValue V1 = SVOp->getOperand(0);
5612 SDValue V2 = SVOp->getOperand(1);
5613 DebugLoc dl = SVOp->getDebugLoc();
5614 MVT VT = SVOp->getValueType(0).getSimpleVT();
5615 unsigned NumElems = VT.getVectorNumElements();
5617 if (!Subtarget->hasSSE41())
5623 switch (VT.SimpleTy) {
5624 default: return SDValue();
5626 ISDNo = X86ISD::BLENDPW;
5631 ISDNo = X86ISD::BLENDPS;
5636 ISDNo = X86ISD::BLENDPD;
5641 if (!Subtarget->hasAVX())
5643 ISDNo = X86ISD::BLENDPS;
5648 if (!Subtarget->hasAVX())
5650 ISDNo = X86ISD::BLENDPD;
5654 assert(ISDNo && "Invalid Op Number");
5656 unsigned MaskVals = 0;
5658 for (unsigned i = 0; i != NumElems; ++i) {
5659 int EltIdx = SVOp->getMaskElt(i);
5660 if (EltIdx == (int)i || EltIdx < 0)
5662 else if (EltIdx == (int)(i + NumElems))
5663 continue; // Bit is set to zero;
5668 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5669 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5670 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5671 DAG.getConstant(MaskVals, MVT::i32));
5672 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5675 // v8i16 shuffles - Prefer shuffles in the following order:
5676 // 1. [all] pshuflw, pshufhw, optional move
5677 // 2. [ssse3] 1 x pshufb
5678 // 3. [ssse3] 2 x pshufb + 1 x por
5679 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5681 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5682 SelectionDAG &DAG) {
5683 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5684 SDValue V1 = SVOp->getOperand(0);
5685 SDValue V2 = SVOp->getOperand(1);
5686 DebugLoc dl = SVOp->getDebugLoc();
5687 SmallVector<int, 8> MaskVals;
5689 // Determine if more than 1 of the words in each of the low and high quadwords
5690 // of the result come from the same quadword of one of the two inputs. Undef
5691 // mask values count as coming from any quadword, for better codegen.
5692 unsigned LoQuad[] = { 0, 0, 0, 0 };
5693 unsigned HiQuad[] = { 0, 0, 0, 0 };
5694 std::bitset<4> InputQuads;
5695 for (unsigned i = 0; i < 8; ++i) {
5696 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5697 int EltIdx = SVOp->getMaskElt(i);
5698 MaskVals.push_back(EltIdx);
5707 InputQuads.set(EltIdx / 4);
5710 int BestLoQuad = -1;
5711 unsigned MaxQuad = 1;
5712 for (unsigned i = 0; i < 4; ++i) {
5713 if (LoQuad[i] > MaxQuad) {
5715 MaxQuad = LoQuad[i];
5719 int BestHiQuad = -1;
5721 for (unsigned i = 0; i < 4; ++i) {
5722 if (HiQuad[i] > MaxQuad) {
5724 MaxQuad = HiQuad[i];
5728 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5729 // of the two input vectors, shuffle them into one input vector so only a
5730 // single pshufb instruction is necessary. If There are more than 2 input
5731 // quads, disable the next transformation since it does not help SSSE3.
5732 bool V1Used = InputQuads[0] || InputQuads[1];
5733 bool V2Used = InputQuads[2] || InputQuads[3];
5734 if (Subtarget->hasSSSE3()) {
5735 if (InputQuads.count() == 2 && V1Used && V2Used) {
5736 BestLoQuad = InputQuads[0] ? 0 : 1;
5737 BestHiQuad = InputQuads[2] ? 2 : 3;
5739 if (InputQuads.count() > 2) {
5745 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5746 // the shuffle mask. If a quad is scored as -1, that means that it contains
5747 // words from all 4 input quadwords.
5749 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5751 BestLoQuad < 0 ? 0 : BestLoQuad,
5752 BestHiQuad < 0 ? 1 : BestHiQuad
5754 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5755 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5756 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5757 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5759 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5760 // source words for the shuffle, to aid later transformations.
5761 bool AllWordsInNewV = true;
5762 bool InOrder[2] = { true, true };
5763 for (unsigned i = 0; i != 8; ++i) {
5764 int idx = MaskVals[i];
5766 InOrder[i/4] = false;
5767 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5769 AllWordsInNewV = false;
5773 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5774 if (AllWordsInNewV) {
5775 for (int i = 0; i != 8; ++i) {
5776 int idx = MaskVals[i];
5779 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5780 if ((idx != i) && idx < 4)
5782 if ((idx != i) && idx > 3)
5791 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5792 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5793 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5794 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5795 unsigned TargetMask = 0;
5796 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5797 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5798 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5799 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5800 getShufflePSHUFLWImmediate(SVOp);
5801 V1 = NewV.getOperand(0);
5802 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5806 // If we have SSSE3, and all words of the result are from 1 input vector,
5807 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5808 // is present, fall back to case 4.
5809 if (Subtarget->hasSSSE3()) {
5810 SmallVector<SDValue,16> pshufbMask;
5812 // If we have elements from both input vectors, set the high bit of the
5813 // shuffle mask element to zero out elements that come from V2 in the V1
5814 // mask, and elements that come from V1 in the V2 mask, so that the two
5815 // results can be OR'd together.
5816 bool TwoInputs = V1Used && V2Used;
5817 for (unsigned i = 0; i != 8; ++i) {
5818 int EltIdx = MaskVals[i] * 2;
5819 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5820 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5821 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5822 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5824 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5825 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5826 DAG.getNode(ISD::BUILD_VECTOR, dl,
5827 MVT::v16i8, &pshufbMask[0], 16));
5829 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5831 // Calculate the shuffle mask for the second input, shuffle it, and
5832 // OR it with the first shuffled input.
5834 for (unsigned i = 0; i != 8; ++i) {
5835 int EltIdx = MaskVals[i] * 2;
5836 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5837 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5838 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5839 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5841 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5842 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5843 DAG.getNode(ISD::BUILD_VECTOR, dl,
5844 MVT::v16i8, &pshufbMask[0], 16));
5845 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5846 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5849 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5850 // and update MaskVals with new element order.
5851 std::bitset<8> InOrder;
5852 if (BestLoQuad >= 0) {
5853 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5854 for (int i = 0; i != 4; ++i) {
5855 int idx = MaskVals[i];
5858 } else if ((idx / 4) == BestLoQuad) {
5863 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5866 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5867 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5868 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5870 getShufflePSHUFLWImmediate(SVOp), DAG);
5874 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5875 // and update MaskVals with the new element order.
5876 if (BestHiQuad >= 0) {
5877 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5878 for (unsigned i = 4; i != 8; ++i) {
5879 int idx = MaskVals[i];
5882 } else if ((idx / 4) == BestHiQuad) {
5883 MaskV[i] = (idx & 3) + 4;
5887 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5890 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5892 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5894 getShufflePSHUFHWImmediate(SVOp), DAG);
5898 // In case BestHi & BestLo were both -1, which means each quadword has a word
5899 // from each of the four input quadwords, calculate the InOrder bitvector now
5900 // before falling through to the insert/extract cleanup.
5901 if (BestLoQuad == -1 && BestHiQuad == -1) {
5903 for (int i = 0; i != 8; ++i)
5904 if (MaskVals[i] < 0 || MaskVals[i] == i)
5908 // The other elements are put in the right place using pextrw and pinsrw.
5909 for (unsigned i = 0; i != 8; ++i) {
5912 int EltIdx = MaskVals[i];
5915 SDValue ExtOp = (EltIdx < 8) ?
5916 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5917 DAG.getIntPtrConstant(EltIdx)) :
5918 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5919 DAG.getIntPtrConstant(EltIdx - 8));
5920 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5921 DAG.getIntPtrConstant(i));
5926 // v16i8 shuffles - Prefer shuffles in the following order:
5927 // 1. [ssse3] 1 x pshufb
5928 // 2. [ssse3] 2 x pshufb + 1 x por
5929 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5931 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5933 const X86TargetLowering &TLI) {
5934 SDValue V1 = SVOp->getOperand(0);
5935 SDValue V2 = SVOp->getOperand(1);
5936 DebugLoc dl = SVOp->getDebugLoc();
5937 ArrayRef<int> MaskVals = SVOp->getMask();
5939 // If we have SSSE3, case 1 is generated when all result bytes come from
5940 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5941 // present, fall back to case 3.
5943 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5944 if (TLI.getSubtarget()->hasSSSE3()) {
5945 SmallVector<SDValue,16> pshufbMask;
5947 // If all result elements are from one input vector, then only translate
5948 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5950 // Otherwise, we have elements from both input vectors, and must zero out
5951 // elements that come from V2 in the first mask, and V1 in the second mask
5952 // so that we can OR them together.
5953 for (unsigned i = 0; i != 16; ++i) {
5954 int EltIdx = MaskVals[i];
5955 if (EltIdx < 0 || EltIdx >= 16)
5957 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5959 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5960 DAG.getNode(ISD::BUILD_VECTOR, dl,
5961 MVT::v16i8, &pshufbMask[0], 16));
5963 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5964 // the 2nd operand if it's undefined or zero.
5965 if (V2.getOpcode() == ISD::UNDEF ||
5966 ISD::isBuildVectorAllZeros(V2.getNode()))
5969 // Calculate the shuffle mask for the second input, shuffle it, and
5970 // OR it with the first shuffled input.
5972 for (unsigned i = 0; i != 16; ++i) {
5973 int EltIdx = MaskVals[i];
5974 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5975 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5977 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5978 DAG.getNode(ISD::BUILD_VECTOR, dl,
5979 MVT::v16i8, &pshufbMask[0], 16));
5980 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5983 // No SSSE3 - Calculate in place words and then fix all out of place words
5984 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5985 // the 16 different words that comprise the two doublequadword input vectors.
5986 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5987 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5989 for (int i = 0; i != 8; ++i) {
5990 int Elt0 = MaskVals[i*2];
5991 int Elt1 = MaskVals[i*2+1];
5993 // This word of the result is all undef, skip it.
5994 if (Elt0 < 0 && Elt1 < 0)
5997 // This word of the result is already in the correct place, skip it.
5998 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6001 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6002 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6005 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6006 // using a single extract together, load it and store it.
6007 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6008 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6009 DAG.getIntPtrConstant(Elt1 / 2));
6010 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6011 DAG.getIntPtrConstant(i));
6015 // If Elt1 is defined, extract it from the appropriate source. If the
6016 // source byte is not also odd, shift the extracted word left 8 bits
6017 // otherwise clear the bottom 8 bits if we need to do an or.
6019 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6020 DAG.getIntPtrConstant(Elt1 / 2));
6021 if ((Elt1 & 1) == 0)
6022 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6024 TLI.getShiftAmountTy(InsElt.getValueType())));
6026 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6027 DAG.getConstant(0xFF00, MVT::i16));
6029 // If Elt0 is defined, extract it from the appropriate source. If the
6030 // source byte is not also even, shift the extracted word right 8 bits. If
6031 // Elt1 was also defined, OR the extracted values together before
6032 // inserting them in the result.
6034 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6035 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6036 if ((Elt0 & 1) != 0)
6037 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6039 TLI.getShiftAmountTy(InsElt0.getValueType())));
6041 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6042 DAG.getConstant(0x00FF, MVT::i16));
6043 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6046 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6047 DAG.getIntPtrConstant(i));
6049 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6052 // v32i8 shuffles - Translate to VPSHUFB if possible.
6054 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6055 const X86Subtarget *Subtarget,
6056 SelectionDAG &DAG) {
6057 EVT VT = SVOp->getValueType(0);
6058 SDValue V1 = SVOp->getOperand(0);
6059 SDValue V2 = SVOp->getOperand(1);
6060 DebugLoc dl = SVOp->getDebugLoc();
6061 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6063 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6064 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6065 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6067 // VPSHUFB may be generated if
6068 // (1) one of input vector is undefined or zeroinitializer.
6069 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6070 // And (2) the mask indexes don't cross the 128-bit lane.
6071 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6072 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6075 if (V1IsAllZero && !V2IsAllZero) {
6076 CommuteVectorShuffleMask(MaskVals, 32);
6079 SmallVector<SDValue, 32> pshufbMask;
6080 for (unsigned i = 0; i != 32; i++) {
6081 int EltIdx = MaskVals[i];
6082 if (EltIdx < 0 || EltIdx >= 32)
6085 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6086 // Cross lane is not allowed.
6090 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6092 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6093 DAG.getNode(ISD::BUILD_VECTOR, dl,
6094 MVT::v32i8, &pshufbMask[0], 32));
6097 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6098 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6099 /// done when every pair / quad of shuffle mask elements point to elements in
6100 /// the right sequence. e.g.
6101 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6103 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6104 SelectionDAG &DAG, DebugLoc dl) {
6105 MVT VT = SVOp->getValueType(0).getSimpleVT();
6106 unsigned NumElems = VT.getVectorNumElements();
6109 switch (VT.SimpleTy) {
6110 default: llvm_unreachable("Unexpected!");
6111 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6112 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6113 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6114 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6115 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6116 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6119 SmallVector<int, 8> MaskVec;
6120 for (unsigned i = 0; i != NumElems; i += Scale) {
6122 for (unsigned j = 0; j != Scale; ++j) {
6123 int EltIdx = SVOp->getMaskElt(i+j);
6127 StartIdx = (EltIdx / Scale);
6128 if (EltIdx != (int)(StartIdx*Scale + j))
6131 MaskVec.push_back(StartIdx);
6134 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6135 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6136 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6139 /// getVZextMovL - Return a zero-extending vector move low node.
6141 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6142 SDValue SrcOp, SelectionDAG &DAG,
6143 const X86Subtarget *Subtarget, DebugLoc dl) {
6144 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6145 LoadSDNode *LD = NULL;
6146 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6147 LD = dyn_cast<LoadSDNode>(SrcOp);
6149 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6151 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6152 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6153 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6154 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6155 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6157 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6158 return DAG.getNode(ISD::BITCAST, dl, VT,
6159 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6160 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6168 return DAG.getNode(ISD::BITCAST, dl, VT,
6169 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6170 DAG.getNode(ISD::BITCAST, dl,
6174 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6175 /// which could not be matched by any known target speficic shuffle
6177 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6179 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6180 if (NewOp.getNode())
6183 EVT VT = SVOp->getValueType(0);
6185 unsigned NumElems = VT.getVectorNumElements();
6186 unsigned NumLaneElems = NumElems / 2;
6188 DebugLoc dl = SVOp->getDebugLoc();
6189 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6190 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6193 SmallVector<int, 16> Mask;
6194 for (unsigned l = 0; l < 2; ++l) {
6195 // Build a shuffle mask for the output, discovering on the fly which
6196 // input vectors to use as shuffle operands (recorded in InputUsed).
6197 // If building a suitable shuffle vector proves too hard, then bail
6198 // out with UseBuildVector set.
6199 bool UseBuildVector = false;
6200 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6201 unsigned LaneStart = l * NumLaneElems;
6202 for (unsigned i = 0; i != NumLaneElems; ++i) {
6203 // The mask element. This indexes into the input.
6204 int Idx = SVOp->getMaskElt(i+LaneStart);
6206 // the mask element does not index into any input vector.
6211 // The input vector this mask element indexes into.
6212 int Input = Idx / NumLaneElems;
6214 // Turn the index into an offset from the start of the input vector.
6215 Idx -= Input * NumLaneElems;
6217 // Find or create a shuffle vector operand to hold this input.
6219 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6220 if (InputUsed[OpNo] == Input)
6221 // This input vector is already an operand.
6223 if (InputUsed[OpNo] < 0) {
6224 // Create a new operand for this input vector.
6225 InputUsed[OpNo] = Input;
6230 if (OpNo >= array_lengthof(InputUsed)) {
6231 // More than two input vectors used! Give up on trying to create a
6232 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6233 UseBuildVector = true;
6237 // Add the mask index for the new shuffle vector.
6238 Mask.push_back(Idx + OpNo * NumLaneElems);
6241 if (UseBuildVector) {
6242 SmallVector<SDValue, 16> SVOps;
6243 for (unsigned i = 0; i != NumLaneElems; ++i) {
6244 // The mask element. This indexes into the input.
6245 int Idx = SVOp->getMaskElt(i+LaneStart);
6247 SVOps.push_back(DAG.getUNDEF(EltVT));
6251 // The input vector this mask element indexes into.
6252 int Input = Idx / NumElems;
6254 // Turn the index into an offset from the start of the input vector.
6255 Idx -= Input * NumElems;
6257 // Extract the vector element by hand.
6258 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6259 SVOp->getOperand(Input),
6260 DAG.getIntPtrConstant(Idx)));
6263 // Construct the output using a BUILD_VECTOR.
6264 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6266 } else if (InputUsed[0] < 0) {
6267 // No input vectors were used! The result is undefined.
6268 Output[l] = DAG.getUNDEF(NVT);
6270 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6271 (InputUsed[0] % 2) * NumLaneElems,
6273 // If only one input was used, use an undefined vector for the other.
6274 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6275 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6276 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6277 // At least one input vector was used. Create a new shuffle vector.
6278 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6284 // Concatenate the result back
6285 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6288 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6289 /// 4 elements, and match them with several different shuffle types.
6291 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6292 SDValue V1 = SVOp->getOperand(0);
6293 SDValue V2 = SVOp->getOperand(1);
6294 DebugLoc dl = SVOp->getDebugLoc();
6295 EVT VT = SVOp->getValueType(0);
6297 assert(VT.is128BitVector() && "Unsupported vector size");
6299 std::pair<int, int> Locs[4];
6300 int Mask1[] = { -1, -1, -1, -1 };
6301 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6305 for (unsigned i = 0; i != 4; ++i) {
6306 int Idx = PermMask[i];
6308 Locs[i] = std::make_pair(-1, -1);
6310 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6312 Locs[i] = std::make_pair(0, NumLo);
6316 Locs[i] = std::make_pair(1, NumHi);
6318 Mask1[2+NumHi] = Idx;
6324 if (NumLo <= 2 && NumHi <= 2) {
6325 // If no more than two elements come from either vector. This can be
6326 // implemented with two shuffles. First shuffle gather the elements.
6327 // The second shuffle, which takes the first shuffle as both of its
6328 // vector operands, put the elements into the right order.
6329 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6331 int Mask2[] = { -1, -1, -1, -1 };
6333 for (unsigned i = 0; i != 4; ++i)
6334 if (Locs[i].first != -1) {
6335 unsigned Idx = (i < 2) ? 0 : 4;
6336 Idx += Locs[i].first * 2 + Locs[i].second;
6340 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6343 if (NumLo == 3 || NumHi == 3) {
6344 // Otherwise, we must have three elements from one vector, call it X, and
6345 // one element from the other, call it Y. First, use a shufps to build an
6346 // intermediate vector with the one element from Y and the element from X
6347 // that will be in the same half in the final destination (the indexes don't
6348 // matter). Then, use a shufps to build the final vector, taking the half
6349 // containing the element from Y from the intermediate, and the other half
6352 // Normalize it so the 3 elements come from V1.
6353 CommuteVectorShuffleMask(PermMask, 4);
6357 // Find the element from V2.
6359 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6360 int Val = PermMask[HiIndex];
6367 Mask1[0] = PermMask[HiIndex];
6369 Mask1[2] = PermMask[HiIndex^1];
6371 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6374 Mask1[0] = PermMask[0];
6375 Mask1[1] = PermMask[1];
6376 Mask1[2] = HiIndex & 1 ? 6 : 4;
6377 Mask1[3] = HiIndex & 1 ? 4 : 6;
6378 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6381 Mask1[0] = HiIndex & 1 ? 2 : 0;
6382 Mask1[1] = HiIndex & 1 ? 0 : 2;
6383 Mask1[2] = PermMask[2];
6384 Mask1[3] = PermMask[3];
6389 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6392 // Break it into (shuffle shuffle_hi, shuffle_lo).
6393 int LoMask[] = { -1, -1, -1, -1 };
6394 int HiMask[] = { -1, -1, -1, -1 };
6396 int *MaskPtr = LoMask;
6397 unsigned MaskIdx = 0;
6400 for (unsigned i = 0; i != 4; ++i) {
6407 int Idx = PermMask[i];
6409 Locs[i] = std::make_pair(-1, -1);
6410 } else if (Idx < 4) {
6411 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6412 MaskPtr[LoIdx] = Idx;
6415 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6416 MaskPtr[HiIdx] = Idx;
6421 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6422 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6423 int MaskOps[] = { -1, -1, -1, -1 };
6424 for (unsigned i = 0; i != 4; ++i)
6425 if (Locs[i].first != -1)
6426 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6427 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6430 static bool MayFoldVectorLoad(SDValue V) {
6431 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6432 V = V.getOperand(0);
6433 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6434 V = V.getOperand(0);
6435 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6436 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6437 // BUILD_VECTOR (load), undef
6438 V = V.getOperand(0);
6444 // FIXME: the version above should always be used. Since there's
6445 // a bug where several vector shuffles can't be folded because the
6446 // DAG is not updated during lowering and a node claims to have two
6447 // uses while it only has one, use this version, and let isel match
6448 // another instruction if the load really happens to have more than
6449 // one use. Remove this version after this bug get fixed.
6450 // rdar://8434668, PR8156
6451 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6452 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6453 V = V.getOperand(0);
6454 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6455 V = V.getOperand(0);
6456 if (ISD::isNormalLoad(V.getNode()))
6462 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6463 EVT VT = Op.getValueType();
6465 // Canonizalize to v2f64.
6466 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6467 return DAG.getNode(ISD::BITCAST, dl, VT,
6468 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6473 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6475 SDValue V1 = Op.getOperand(0);
6476 SDValue V2 = Op.getOperand(1);
6477 EVT VT = Op.getValueType();
6479 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6481 if (HasSSE2 && VT == MVT::v2f64)
6482 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6484 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6485 return DAG.getNode(ISD::BITCAST, dl, VT,
6486 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6487 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6488 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6492 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6493 SDValue V1 = Op.getOperand(0);
6494 SDValue V2 = Op.getOperand(1);
6495 EVT VT = Op.getValueType();
6497 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6498 "unsupported shuffle type");
6500 if (V2.getOpcode() == ISD::UNDEF)
6504 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6508 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6509 SDValue V1 = Op.getOperand(0);
6510 SDValue V2 = Op.getOperand(1);
6511 EVT VT = Op.getValueType();
6512 unsigned NumElems = VT.getVectorNumElements();
6514 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6515 // operand of these instructions is only memory, so check if there's a
6516 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6518 bool CanFoldLoad = false;
6520 // Trivial case, when V2 comes from a load.
6521 if (MayFoldVectorLoad(V2))
6524 // When V1 is a load, it can be folded later into a store in isel, example:
6525 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6527 // (MOVLPSmr addr:$src1, VR128:$src2)
6528 // So, recognize this potential and also use MOVLPS or MOVLPD
6529 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6534 if (HasSSE2 && NumElems == 2)
6535 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6538 // If we don't care about the second element, proceed to use movss.
6539 if (SVOp->getMaskElt(1) != -1)
6540 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6543 // movl and movlp will both match v2i64, but v2i64 is never matched by
6544 // movl earlier because we make it strict to avoid messing with the movlp load
6545 // folding logic (see the code above getMOVLP call). Match it here then,
6546 // this is horrible, but will stay like this until we move all shuffle
6547 // matching to x86 specific nodes. Note that for the 1st condition all
6548 // types are matched with movsd.
6550 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6551 // as to remove this logic from here, as much as possible
6552 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6553 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6554 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6557 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6559 // Invert the operand order and use SHUFPS to match it.
6560 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6561 getShuffleSHUFImmediate(SVOp), DAG);
6565 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6566 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6567 EVT VT = Op.getValueType();
6568 DebugLoc dl = Op.getDebugLoc();
6569 SDValue V1 = Op.getOperand(0);
6570 SDValue V2 = Op.getOperand(1);
6572 if (isZeroShuffle(SVOp))
6573 return getZeroVector(VT, Subtarget, DAG, dl);
6575 // Handle splat operations
6576 if (SVOp->isSplat()) {
6577 unsigned NumElem = VT.getVectorNumElements();
6578 int Size = VT.getSizeInBits();
6580 // Use vbroadcast whenever the splat comes from a foldable load
6581 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6582 if (Broadcast.getNode())
6585 // Handle splats by matching through known shuffle masks
6586 if ((Size == 128 && NumElem <= 4) ||
6587 (Size == 256 && NumElem < 8))
6590 // All remaning splats are promoted to target supported vector shuffles.
6591 return PromoteSplat(SVOp, DAG);
6594 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6596 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6597 VT == MVT::v16i16 || VT == MVT::v32i8) {
6598 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6599 if (NewOp.getNode())
6600 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6601 } else if ((VT == MVT::v4i32 ||
6602 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6603 // FIXME: Figure out a cleaner way to do this.
6604 // Try to make use of movq to zero out the top part.
6605 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6606 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6607 if (NewOp.getNode()) {
6608 EVT NewVT = NewOp.getValueType();
6609 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6610 NewVT, true, false))
6611 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6612 DAG, Subtarget, dl);
6614 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6615 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6616 if (NewOp.getNode()) {
6617 EVT NewVT = NewOp.getValueType();
6618 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6619 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6620 DAG, Subtarget, dl);
6628 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6629 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6630 SDValue V1 = Op.getOperand(0);
6631 SDValue V2 = Op.getOperand(1);
6632 EVT VT = Op.getValueType();
6633 DebugLoc dl = Op.getDebugLoc();
6634 unsigned NumElems = VT.getVectorNumElements();
6635 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6636 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6637 bool V1IsSplat = false;
6638 bool V2IsSplat = false;
6639 bool HasSSE2 = Subtarget->hasSSE2();
6640 bool HasAVX = Subtarget->hasAVX();
6641 bool HasAVX2 = Subtarget->hasAVX2();
6642 MachineFunction &MF = DAG.getMachineFunction();
6643 bool OptForSize = MF.getFunction()->getFnAttributes().
6644 hasAttribute(Attributes::OptimizeForSize);
6646 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6648 if (V1IsUndef && V2IsUndef)
6649 return DAG.getUNDEF(VT);
6651 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6653 // Vector shuffle lowering takes 3 steps:
6655 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6656 // narrowing and commutation of operands should be handled.
6657 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6659 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6660 // so the shuffle can be broken into other shuffles and the legalizer can
6661 // try the lowering again.
6663 // The general idea is that no vector_shuffle operation should be left to
6664 // be matched during isel, all of them must be converted to a target specific
6667 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6668 // narrowing and commutation of operands should be handled. The actual code
6669 // doesn't include all of those, work in progress...
6670 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6671 if (NewOp.getNode())
6674 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6676 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6677 // unpckh_undef). Only use pshufd if speed is more important than size.
6678 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6679 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6680 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6681 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6683 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6684 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6685 return getMOVDDup(Op, dl, V1, DAG);
6687 if (isMOVHLPS_v_undef_Mask(M, VT))
6688 return getMOVHighToLow(Op, dl, DAG);
6690 // Use to match splats
6691 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6692 (VT == MVT::v2f64 || VT == MVT::v2i64))
6693 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6695 if (isPSHUFDMask(M, VT)) {
6696 // The actual implementation will match the mask in the if above and then
6697 // during isel it can match several different instructions, not only pshufd
6698 // as its name says, sad but true, emulate the behavior for now...
6699 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6700 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6702 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6704 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6705 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6707 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6708 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6710 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6714 // Check if this can be converted into a logical shift.
6715 bool isLeft = false;
6718 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6719 if (isShift && ShVal.hasOneUse()) {
6720 // If the shifted value has multiple uses, it may be cheaper to use
6721 // v_set0 + movlhps or movhlps, etc.
6722 EVT EltVT = VT.getVectorElementType();
6723 ShAmt *= EltVT.getSizeInBits();
6724 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6727 if (isMOVLMask(M, VT)) {
6728 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6729 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6730 if (!isMOVLPMask(M, VT)) {
6731 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6732 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6734 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6735 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6739 // FIXME: fold these into legal mask.
6740 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6741 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6743 if (isMOVHLPSMask(M, VT))
6744 return getMOVHighToLow(Op, dl, DAG);
6746 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6747 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6749 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6750 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6752 if (isMOVLPMask(M, VT))
6753 return getMOVLP(Op, dl, DAG, HasSSE2);
6755 if (ShouldXformToMOVHLPS(M, VT) ||
6756 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6757 return CommuteVectorShuffle(SVOp, DAG);
6760 // No better options. Use a vshldq / vsrldq.
6761 EVT EltVT = VT.getVectorElementType();
6762 ShAmt *= EltVT.getSizeInBits();
6763 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6766 bool Commuted = false;
6767 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6768 // 1,1,1,1 -> v8i16 though.
6769 V1IsSplat = isSplatVector(V1.getNode());
6770 V2IsSplat = isSplatVector(V2.getNode());
6772 // Canonicalize the splat or undef, if present, to be on the RHS.
6773 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6774 CommuteVectorShuffleMask(M, NumElems);
6776 std::swap(V1IsSplat, V2IsSplat);
6780 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6781 // Shuffling low element of v1 into undef, just return v1.
6784 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6785 // the instruction selector will not match, so get a canonical MOVL with
6786 // swapped operands to undo the commute.
6787 return getMOVL(DAG, dl, VT, V2, V1);
6790 if (isUNPCKLMask(M, VT, HasAVX2))
6791 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6793 if (isUNPCKHMask(M, VT, HasAVX2))
6794 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6797 // Normalize mask so all entries that point to V2 points to its first
6798 // element then try to match unpck{h|l} again. If match, return a
6799 // new vector_shuffle with the corrected mask.p
6800 SmallVector<int, 8> NewMask(M.begin(), M.end());
6801 NormalizeMask(NewMask, NumElems);
6802 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6803 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6804 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6805 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6809 // Commute is back and try unpck* again.
6810 // FIXME: this seems wrong.
6811 CommuteVectorShuffleMask(M, NumElems);
6813 std::swap(V1IsSplat, V2IsSplat);
6816 if (isUNPCKLMask(M, VT, HasAVX2))
6817 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6819 if (isUNPCKHMask(M, VT, HasAVX2))
6820 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6823 // Normalize the node to match x86 shuffle ops if needed
6824 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6825 return CommuteVectorShuffle(SVOp, DAG);
6827 // The checks below are all present in isShuffleMaskLegal, but they are
6828 // inlined here right now to enable us to directly emit target specific
6829 // nodes, and remove one by one until they don't return Op anymore.
6831 if (isPALIGNRMask(M, VT, Subtarget))
6832 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6833 getShufflePALIGNRImmediate(SVOp),
6836 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6837 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6838 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6839 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6842 if (isPSHUFHWMask(M, VT, HasAVX2))
6843 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6844 getShufflePSHUFHWImmediate(SVOp),
6847 if (isPSHUFLWMask(M, VT, HasAVX2))
6848 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6849 getShufflePSHUFLWImmediate(SVOp),
6852 if (isSHUFPMask(M, VT, HasAVX))
6853 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6854 getShuffleSHUFImmediate(SVOp), DAG);
6856 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6857 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6858 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6859 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6861 //===--------------------------------------------------------------------===//
6862 // Generate target specific nodes for 128 or 256-bit shuffles only
6863 // supported in the AVX instruction set.
6866 // Handle VMOVDDUPY permutations
6867 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6868 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6870 // Handle VPERMILPS/D* permutations
6871 if (isVPERMILPMask(M, VT, HasAVX)) {
6872 if (HasAVX2 && VT == MVT::v8i32)
6873 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6874 getShuffleSHUFImmediate(SVOp), DAG);
6875 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6876 getShuffleSHUFImmediate(SVOp), DAG);
6879 // Handle VPERM2F128/VPERM2I128 permutations
6880 if (isVPERM2X128Mask(M, VT, HasAVX))
6881 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6882 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6884 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6885 if (BlendOp.getNode())
6888 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6889 SmallVector<SDValue, 8> permclMask;
6890 for (unsigned i = 0; i != 8; ++i) {
6891 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6893 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6895 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6896 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6897 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6900 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6901 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6902 getShuffleCLImmediate(SVOp), DAG);
6905 //===--------------------------------------------------------------------===//
6906 // Since no target specific shuffle was selected for this generic one,
6907 // lower it into other known shuffles. FIXME: this isn't true yet, but
6908 // this is the plan.
6911 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6912 if (VT == MVT::v8i16) {
6913 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6914 if (NewOp.getNode())
6918 if (VT == MVT::v16i8) {
6919 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6920 if (NewOp.getNode())
6924 if (VT == MVT::v32i8) {
6925 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6926 if (NewOp.getNode())
6930 // Handle all 128-bit wide vectors with 4 elements, and match them with
6931 // several different shuffle types.
6932 if (NumElems == 4 && VT.is128BitVector())
6933 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6935 // Handle general 256-bit shuffles
6936 if (VT.is256BitVector())
6937 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6943 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6944 SelectionDAG &DAG) const {
6945 EVT VT = Op.getValueType();
6946 DebugLoc dl = Op.getDebugLoc();
6948 if (!Op.getOperand(0).getValueType().is128BitVector())
6951 if (VT.getSizeInBits() == 8) {
6952 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6953 Op.getOperand(0), Op.getOperand(1));
6954 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6955 DAG.getValueType(VT));
6956 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6959 if (VT.getSizeInBits() == 16) {
6960 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6961 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6963 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6964 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6965 DAG.getNode(ISD::BITCAST, dl,
6969 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6970 Op.getOperand(0), Op.getOperand(1));
6971 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6972 DAG.getValueType(VT));
6973 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6976 if (VT == MVT::f32) {
6977 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6978 // the result back to FR32 register. It's only worth matching if the
6979 // result has a single use which is a store or a bitcast to i32. And in
6980 // the case of a store, it's not worth it if the index is a constant 0,
6981 // because a MOVSSmr can be used instead, which is smaller and faster.
6982 if (!Op.hasOneUse())
6984 SDNode *User = *Op.getNode()->use_begin();
6985 if ((User->getOpcode() != ISD::STORE ||
6986 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6987 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6988 (User->getOpcode() != ISD::BITCAST ||
6989 User->getValueType(0) != MVT::i32))
6991 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6992 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6995 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6998 if (VT == MVT::i32 || VT == MVT::i64) {
6999 // ExtractPS/pextrq works with constant index.
7000 if (isa<ConstantSDNode>(Op.getOperand(1)))
7008 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7009 SelectionDAG &DAG) const {
7010 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7013 SDValue Vec = Op.getOperand(0);
7014 EVT VecVT = Vec.getValueType();
7016 // If this is a 256-bit vector result, first extract the 128-bit vector and
7017 // then extract the element from the 128-bit vector.
7018 if (VecVT.is256BitVector()) {
7019 DebugLoc dl = Op.getNode()->getDebugLoc();
7020 unsigned NumElems = VecVT.getVectorNumElements();
7021 SDValue Idx = Op.getOperand(1);
7022 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7024 // Get the 128-bit vector.
7025 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7027 if (IdxVal >= NumElems/2)
7028 IdxVal -= NumElems/2;
7029 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7030 DAG.getConstant(IdxVal, MVT::i32));
7033 assert(VecVT.is128BitVector() && "Unexpected vector length");
7035 if (Subtarget->hasSSE41()) {
7036 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7041 EVT VT = Op.getValueType();
7042 DebugLoc dl = Op.getDebugLoc();
7043 // TODO: handle v16i8.
7044 if (VT.getSizeInBits() == 16) {
7045 SDValue Vec = Op.getOperand(0);
7046 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7049 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7050 DAG.getNode(ISD::BITCAST, dl,
7053 // Transform it so it match pextrw which produces a 32-bit result.
7054 EVT EltVT = MVT::i32;
7055 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7056 Op.getOperand(0), Op.getOperand(1));
7057 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7058 DAG.getValueType(VT));
7059 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7062 if (VT.getSizeInBits() == 32) {
7063 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7067 // SHUFPS the element to the lowest double word, then movss.
7068 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7069 EVT VVT = Op.getOperand(0).getValueType();
7070 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7071 DAG.getUNDEF(VVT), Mask);
7072 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7073 DAG.getIntPtrConstant(0));
7076 if (VT.getSizeInBits() == 64) {
7077 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7078 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7079 // to match extract_elt for f64.
7080 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7084 // UNPCKHPD the element to the lowest double word, then movsd.
7085 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7086 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7087 int Mask[2] = { 1, -1 };
7088 EVT VVT = Op.getOperand(0).getValueType();
7089 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7090 DAG.getUNDEF(VVT), Mask);
7091 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7092 DAG.getIntPtrConstant(0));
7099 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7100 SelectionDAG &DAG) const {
7101 EVT VT = Op.getValueType();
7102 EVT EltVT = VT.getVectorElementType();
7103 DebugLoc dl = Op.getDebugLoc();
7105 SDValue N0 = Op.getOperand(0);
7106 SDValue N1 = Op.getOperand(1);
7107 SDValue N2 = Op.getOperand(2);
7109 if (!VT.is128BitVector())
7112 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7113 isa<ConstantSDNode>(N2)) {
7115 if (VT == MVT::v8i16)
7116 Opc = X86ISD::PINSRW;
7117 else if (VT == MVT::v16i8)
7118 Opc = X86ISD::PINSRB;
7120 Opc = X86ISD::PINSRB;
7122 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7124 if (N1.getValueType() != MVT::i32)
7125 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7126 if (N2.getValueType() != MVT::i32)
7127 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7128 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7131 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7132 // Bits [7:6] of the constant are the source select. This will always be
7133 // zero here. The DAG Combiner may combine an extract_elt index into these
7134 // bits. For example (insert (extract, 3), 2) could be matched by putting
7135 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7136 // Bits [5:4] of the constant are the destination select. This is the
7137 // value of the incoming immediate.
7138 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7139 // combine either bitwise AND or insert of float 0.0 to set these bits.
7140 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7141 // Create this as a scalar to vector..
7142 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7143 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7146 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7147 // PINSR* works with constant index.
7154 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7155 EVT VT = Op.getValueType();
7156 EVT EltVT = VT.getVectorElementType();
7158 DebugLoc dl = Op.getDebugLoc();
7159 SDValue N0 = Op.getOperand(0);
7160 SDValue N1 = Op.getOperand(1);
7161 SDValue N2 = Op.getOperand(2);
7163 // If this is a 256-bit vector result, first extract the 128-bit vector,
7164 // insert the element into the extracted half and then place it back.
7165 if (VT.is256BitVector()) {
7166 if (!isa<ConstantSDNode>(N2))
7169 // Get the desired 128-bit vector half.
7170 unsigned NumElems = VT.getVectorNumElements();
7171 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7172 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7174 // Insert the element into the desired half.
7175 bool Upper = IdxVal >= NumElems/2;
7176 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7177 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7179 // Insert the changed part back to the 256-bit vector
7180 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7183 if (Subtarget->hasSSE41())
7184 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7186 if (EltVT == MVT::i8)
7189 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7190 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7191 // as its second argument.
7192 if (N1.getValueType() != MVT::i32)
7193 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7194 if (N2.getValueType() != MVT::i32)
7195 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7196 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7201 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7202 LLVMContext *Context = DAG.getContext();
7203 DebugLoc dl = Op.getDebugLoc();
7204 EVT OpVT = Op.getValueType();
7206 // If this is a 256-bit vector result, first insert into a 128-bit
7207 // vector and then insert into the 256-bit vector.
7208 if (!OpVT.is128BitVector()) {
7209 // Insert into a 128-bit vector.
7210 EVT VT128 = EVT::getVectorVT(*Context,
7211 OpVT.getVectorElementType(),
7212 OpVT.getVectorNumElements() / 2);
7214 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7216 // Insert the 128-bit vector.
7217 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7220 if (OpVT == MVT::v1i64 &&
7221 Op.getOperand(0).getValueType() == MVT::i64)
7222 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7224 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7225 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7226 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7227 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7230 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7231 // a simple subregister reference or explicit instructions to grab
7232 // upper bits of a vector.
7233 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7234 SelectionDAG &DAG) {
7235 if (Subtarget->hasAVX()) {
7236 DebugLoc dl = Op.getNode()->getDebugLoc();
7237 SDValue Vec = Op.getNode()->getOperand(0);
7238 SDValue Idx = Op.getNode()->getOperand(1);
7240 if (Op.getNode()->getValueType(0).is128BitVector() &&
7241 Vec.getNode()->getValueType(0).is256BitVector() &&
7242 isa<ConstantSDNode>(Idx)) {
7243 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7244 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7250 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7251 // simple superregister reference or explicit instructions to insert
7252 // the upper bits of a vector.
7253 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7254 SelectionDAG &DAG) {
7255 if (Subtarget->hasAVX()) {
7256 DebugLoc dl = Op.getNode()->getDebugLoc();
7257 SDValue Vec = Op.getNode()->getOperand(0);
7258 SDValue SubVec = Op.getNode()->getOperand(1);
7259 SDValue Idx = Op.getNode()->getOperand(2);
7261 if (Op.getNode()->getValueType(0).is256BitVector() &&
7262 SubVec.getNode()->getValueType(0).is128BitVector() &&
7263 isa<ConstantSDNode>(Idx)) {
7264 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7265 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7271 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7272 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7273 // one of the above mentioned nodes. It has to be wrapped because otherwise
7274 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7275 // be used to form addressing mode. These wrapped nodes will be selected
7278 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7279 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7281 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7283 unsigned char OpFlag = 0;
7284 unsigned WrapperKind = X86ISD::Wrapper;
7285 CodeModel::Model M = getTargetMachine().getCodeModel();
7287 if (Subtarget->isPICStyleRIPRel() &&
7288 (M == CodeModel::Small || M == CodeModel::Kernel))
7289 WrapperKind = X86ISD::WrapperRIP;
7290 else if (Subtarget->isPICStyleGOT())
7291 OpFlag = X86II::MO_GOTOFF;
7292 else if (Subtarget->isPICStyleStubPIC())
7293 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7295 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7297 CP->getOffset(), OpFlag);
7298 DebugLoc DL = CP->getDebugLoc();
7299 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7300 // With PIC, the address is actually $g + Offset.
7302 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7303 DAG.getNode(X86ISD::GlobalBaseReg,
7304 DebugLoc(), getPointerTy()),
7311 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7312 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7314 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7316 unsigned char OpFlag = 0;
7317 unsigned WrapperKind = X86ISD::Wrapper;
7318 CodeModel::Model M = getTargetMachine().getCodeModel();
7320 if (Subtarget->isPICStyleRIPRel() &&
7321 (M == CodeModel::Small || M == CodeModel::Kernel))
7322 WrapperKind = X86ISD::WrapperRIP;
7323 else if (Subtarget->isPICStyleGOT())
7324 OpFlag = X86II::MO_GOTOFF;
7325 else if (Subtarget->isPICStyleStubPIC())
7326 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7328 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7330 DebugLoc DL = JT->getDebugLoc();
7331 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7333 // With PIC, the address is actually $g + Offset.
7335 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7336 DAG.getNode(X86ISD::GlobalBaseReg,
7337 DebugLoc(), getPointerTy()),
7344 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7345 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7347 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7349 unsigned char OpFlag = 0;
7350 unsigned WrapperKind = X86ISD::Wrapper;
7351 CodeModel::Model M = getTargetMachine().getCodeModel();
7353 if (Subtarget->isPICStyleRIPRel() &&
7354 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7355 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7356 OpFlag = X86II::MO_GOTPCREL;
7357 WrapperKind = X86ISD::WrapperRIP;
7358 } else if (Subtarget->isPICStyleGOT()) {
7359 OpFlag = X86II::MO_GOT;
7360 } else if (Subtarget->isPICStyleStubPIC()) {
7361 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7362 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7363 OpFlag = X86II::MO_DARWIN_NONLAZY;
7366 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7368 DebugLoc DL = Op.getDebugLoc();
7369 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7372 // With PIC, the address is actually $g + Offset.
7373 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7374 !Subtarget->is64Bit()) {
7375 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7376 DAG.getNode(X86ISD::GlobalBaseReg,
7377 DebugLoc(), getPointerTy()),
7381 // For symbols that require a load from a stub to get the address, emit the
7383 if (isGlobalStubReference(OpFlag))
7384 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7385 MachinePointerInfo::getGOT(), false, false, false, 0);
7391 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7392 // Create the TargetBlockAddressAddress node.
7393 unsigned char OpFlags =
7394 Subtarget->ClassifyBlockAddressReference();
7395 CodeModel::Model M = getTargetMachine().getCodeModel();
7396 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7397 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7398 DebugLoc dl = Op.getDebugLoc();
7399 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7402 if (Subtarget->isPICStyleRIPRel() &&
7403 (M == CodeModel::Small || M == CodeModel::Kernel))
7404 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7406 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7408 // With PIC, the address is actually $g + Offset.
7409 if (isGlobalRelativeToPICBase(OpFlags)) {
7410 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7411 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7419 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7421 SelectionDAG &DAG) const {
7422 // Create the TargetGlobalAddress node, folding in the constant
7423 // offset if it is legal.
7424 unsigned char OpFlags =
7425 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7426 CodeModel::Model M = getTargetMachine().getCodeModel();
7428 if (OpFlags == X86II::MO_NO_FLAG &&
7429 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7430 // A direct static reference to a global.
7431 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7434 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7437 if (Subtarget->isPICStyleRIPRel() &&
7438 (M == CodeModel::Small || M == CodeModel::Kernel))
7439 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7441 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7443 // With PIC, the address is actually $g + Offset.
7444 if (isGlobalRelativeToPICBase(OpFlags)) {
7445 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7446 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7450 // For globals that require a load from a stub to get the address, emit the
7452 if (isGlobalStubReference(OpFlags))
7453 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7454 MachinePointerInfo::getGOT(), false, false, false, 0);
7456 // If there was a non-zero offset that we didn't fold, create an explicit
7459 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7460 DAG.getConstant(Offset, getPointerTy()));
7466 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7467 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7468 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7469 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7473 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7474 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7475 unsigned char OperandFlags, bool LocalDynamic = false) {
7476 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7477 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7478 DebugLoc dl = GA->getDebugLoc();
7479 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7480 GA->getValueType(0),
7484 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7488 SDValue Ops[] = { Chain, TGA, *InFlag };
7489 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7491 SDValue Ops[] = { Chain, TGA };
7492 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7495 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7496 MFI->setAdjustsStack(true);
7498 SDValue Flag = Chain.getValue(1);
7499 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7502 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7504 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7507 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7508 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7509 DAG.getNode(X86ISD::GlobalBaseReg,
7510 DebugLoc(), PtrVT), InFlag);
7511 InFlag = Chain.getValue(1);
7513 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7516 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7518 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7520 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7521 X86::RAX, X86II::MO_TLSGD);
7524 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7528 DebugLoc dl = GA->getDebugLoc();
7530 // Get the start address of the TLS block for this module.
7531 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7532 .getInfo<X86MachineFunctionInfo>();
7533 MFI->incNumLocalDynamicTLSAccesses();
7537 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7538 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7541 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7542 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7543 InFlag = Chain.getValue(1);
7544 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7545 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7548 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7552 unsigned char OperandFlags = X86II::MO_DTPOFF;
7553 unsigned WrapperKind = X86ISD::Wrapper;
7554 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7555 GA->getValueType(0),
7556 GA->getOffset(), OperandFlags);
7557 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7559 // Add x@dtpoff with the base.
7560 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7563 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7564 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7565 const EVT PtrVT, TLSModel::Model model,
7566 bool is64Bit, bool isPIC) {
7567 DebugLoc dl = GA->getDebugLoc();
7569 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7570 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7571 is64Bit ? 257 : 256));
7573 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7574 DAG.getIntPtrConstant(0),
7575 MachinePointerInfo(Ptr),
7576 false, false, false, 0);
7578 unsigned char OperandFlags = 0;
7579 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7581 unsigned WrapperKind = X86ISD::Wrapper;
7582 if (model == TLSModel::LocalExec) {
7583 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7584 } else if (model == TLSModel::InitialExec) {
7586 OperandFlags = X86II::MO_GOTTPOFF;
7587 WrapperKind = X86ISD::WrapperRIP;
7589 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7592 llvm_unreachable("Unexpected model");
7595 // emit "addl x@ntpoff,%eax" (local exec)
7596 // or "addl x@indntpoff,%eax" (initial exec)
7597 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7598 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7599 GA->getValueType(0),
7600 GA->getOffset(), OperandFlags);
7601 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7603 if (model == TLSModel::InitialExec) {
7604 if (isPIC && !is64Bit) {
7605 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7606 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7610 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7611 MachinePointerInfo::getGOT(), false, false, false,
7615 // The address of the thread local variable is the add of the thread
7616 // pointer with the offset of the variable.
7617 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7621 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7623 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7624 const GlobalValue *GV = GA->getGlobal();
7626 if (Subtarget->isTargetELF()) {
7627 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7630 case TLSModel::GeneralDynamic:
7631 if (Subtarget->is64Bit())
7632 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7633 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7634 case TLSModel::LocalDynamic:
7635 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7636 Subtarget->is64Bit());
7637 case TLSModel::InitialExec:
7638 case TLSModel::LocalExec:
7639 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7640 Subtarget->is64Bit(),
7641 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7643 llvm_unreachable("Unknown TLS model.");
7646 if (Subtarget->isTargetDarwin()) {
7647 // Darwin only has one model of TLS. Lower to that.
7648 unsigned char OpFlag = 0;
7649 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7650 X86ISD::WrapperRIP : X86ISD::Wrapper;
7652 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7654 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7655 !Subtarget->is64Bit();
7657 OpFlag = X86II::MO_TLVP_PIC_BASE;
7659 OpFlag = X86II::MO_TLVP;
7660 DebugLoc DL = Op.getDebugLoc();
7661 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7662 GA->getValueType(0),
7663 GA->getOffset(), OpFlag);
7664 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7666 // With PIC32, the address is actually $g + Offset.
7668 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7669 DAG.getNode(X86ISD::GlobalBaseReg,
7670 DebugLoc(), getPointerTy()),
7673 // Lowering the machine isd will make sure everything is in the right
7675 SDValue Chain = DAG.getEntryNode();
7676 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7677 SDValue Args[] = { Chain, Offset };
7678 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7680 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7681 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7682 MFI->setAdjustsStack(true);
7684 // And our return value (tls address) is in the standard call return value
7686 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7687 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7691 if (Subtarget->isTargetWindows()) {
7692 // Just use the implicit TLS architecture
7693 // Need to generate someting similar to:
7694 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7696 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7697 // mov rcx, qword [rdx+rcx*8]
7698 // mov eax, .tls$:tlsvar
7699 // [rax+rcx] contains the address
7700 // Windows 64bit: gs:0x58
7701 // Windows 32bit: fs:__tls_array
7703 // If GV is an alias then use the aliasee for determining
7704 // thread-localness.
7705 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7706 GV = GA->resolveAliasedGlobal(false);
7707 DebugLoc dl = GA->getDebugLoc();
7708 SDValue Chain = DAG.getEntryNode();
7710 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7711 // %gs:0x58 (64-bit).
7712 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7713 ? Type::getInt8PtrTy(*DAG.getContext(),
7715 : Type::getInt32PtrTy(*DAG.getContext(),
7718 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7719 Subtarget->is64Bit()
7720 ? DAG.getIntPtrConstant(0x58)
7721 : DAG.getExternalSymbol("_tls_array",
7723 MachinePointerInfo(Ptr),
7724 false, false, false, 0);
7726 // Load the _tls_index variable
7727 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7728 if (Subtarget->is64Bit())
7729 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7730 IDX, MachinePointerInfo(), MVT::i32,
7733 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7734 false, false, false, 0);
7736 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7738 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7740 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7741 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7742 false, false, false, 0);
7744 // Get the offset of start of .tls section
7745 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7746 GA->getValueType(0),
7747 GA->getOffset(), X86II::MO_SECREL);
7748 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7750 // The address of the thread local variable is the add of the thread
7751 // pointer with the offset of the variable.
7752 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7755 llvm_unreachable("TLS not implemented for this target.");
7759 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7760 /// and take a 2 x i32 value to shift plus a shift amount.
7761 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7762 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7763 EVT VT = Op.getValueType();
7764 unsigned VTBits = VT.getSizeInBits();
7765 DebugLoc dl = Op.getDebugLoc();
7766 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7767 SDValue ShOpLo = Op.getOperand(0);
7768 SDValue ShOpHi = Op.getOperand(1);
7769 SDValue ShAmt = Op.getOperand(2);
7770 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7771 DAG.getConstant(VTBits - 1, MVT::i8))
7772 : DAG.getConstant(0, VT);
7775 if (Op.getOpcode() == ISD::SHL_PARTS) {
7776 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7777 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7779 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7780 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7783 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7784 DAG.getConstant(VTBits, MVT::i8));
7785 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7786 AndNode, DAG.getConstant(0, MVT::i8));
7789 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7790 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7791 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7793 if (Op.getOpcode() == ISD::SHL_PARTS) {
7794 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7795 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7797 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7798 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7801 SDValue Ops[2] = { Lo, Hi };
7802 return DAG.getMergeValues(Ops, 2, dl);
7805 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7806 SelectionDAG &DAG) const {
7807 EVT SrcVT = Op.getOperand(0).getValueType();
7809 if (SrcVT.isVector())
7812 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7813 "Unknown SINT_TO_FP to lower!");
7815 // These are really Legal; return the operand so the caller accepts it as
7817 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7819 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7820 Subtarget->is64Bit()) {
7824 DebugLoc dl = Op.getDebugLoc();
7825 unsigned Size = SrcVT.getSizeInBits()/8;
7826 MachineFunction &MF = DAG.getMachineFunction();
7827 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7828 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7829 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7831 MachinePointerInfo::getFixedStack(SSFI),
7833 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7836 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7838 SelectionDAG &DAG) const {
7840 DebugLoc DL = Op.getDebugLoc();
7842 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7844 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7846 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7848 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7850 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7851 MachineMemOperand *MMO;
7853 int SSFI = FI->getIndex();
7855 DAG.getMachineFunction()
7856 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7857 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7859 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7860 StackSlot = StackSlot.getOperand(1);
7862 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7863 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7865 Tys, Ops, array_lengthof(Ops),
7869 Chain = Result.getValue(1);
7870 SDValue InFlag = Result.getValue(2);
7872 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7873 // shouldn't be necessary except that RFP cannot be live across
7874 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7875 MachineFunction &MF = DAG.getMachineFunction();
7876 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7877 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7878 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7879 Tys = DAG.getVTList(MVT::Other);
7881 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7883 MachineMemOperand *MMO =
7884 DAG.getMachineFunction()
7885 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7886 MachineMemOperand::MOStore, SSFISize, SSFISize);
7888 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7889 Ops, array_lengthof(Ops),
7890 Op.getValueType(), MMO);
7891 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7892 MachinePointerInfo::getFixedStack(SSFI),
7893 false, false, false, 0);
7899 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7900 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7901 SelectionDAG &DAG) const {
7902 // This algorithm is not obvious. Here it is what we're trying to output:
7905 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7906 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7910 pshufd $0x4e, %xmm0, %xmm1
7915 DebugLoc dl = Op.getDebugLoc();
7916 LLVMContext *Context = DAG.getContext();
7918 // Build some magic constants.
7919 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7920 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7921 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7923 SmallVector<Constant*,2> CV1;
7925 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7927 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7928 Constant *C1 = ConstantVector::get(CV1);
7929 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7931 // Load the 64-bit value into an XMM register.
7932 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7934 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7935 MachinePointerInfo::getConstantPool(),
7936 false, false, false, 16);
7937 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7938 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7941 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7942 MachinePointerInfo::getConstantPool(),
7943 false, false, false, 16);
7944 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7945 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7948 if (Subtarget->hasSSE3()) {
7949 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7950 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7952 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7953 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7955 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7956 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7960 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7961 DAG.getIntPtrConstant(0));
7964 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7965 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7966 SelectionDAG &DAG) const {
7967 DebugLoc dl = Op.getDebugLoc();
7968 // FP constant to bias correct the final result.
7969 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7972 // Load the 32-bit value into an XMM register.
7973 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7976 // Zero out the upper parts of the register.
7977 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7979 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7980 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7981 DAG.getIntPtrConstant(0));
7983 // Or the load with the bias.
7984 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7985 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7986 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7988 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7989 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7990 MVT::v2f64, Bias)));
7991 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7992 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7993 DAG.getIntPtrConstant(0));
7995 // Subtract the bias.
7996 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7998 // Handle final rounding.
7999 EVT DestVT = Op.getValueType();
8001 if (DestVT.bitsLT(MVT::f64))
8002 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8003 DAG.getIntPtrConstant(0));
8004 if (DestVT.bitsGT(MVT::f64))
8005 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8007 // Handle final rounding.
8011 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8012 SelectionDAG &DAG) const {
8013 SDValue N0 = Op.getOperand(0);
8014 DebugLoc dl = Op.getDebugLoc();
8016 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8017 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8018 // the optimization here.
8019 if (DAG.SignBitIsZero(N0))
8020 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8022 EVT SrcVT = N0.getValueType();
8023 EVT DstVT = Op.getValueType();
8024 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8025 return LowerUINT_TO_FP_i64(Op, DAG);
8026 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8027 return LowerUINT_TO_FP_i32(Op, DAG);
8028 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8031 // Make a 64-bit buffer, and use it to build an FILD.
8032 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8033 if (SrcVT == MVT::i32) {
8034 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8035 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8036 getPointerTy(), StackSlot, WordOff);
8037 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8038 StackSlot, MachinePointerInfo(),
8040 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8041 OffsetSlot, MachinePointerInfo(),
8043 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8047 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8048 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8049 StackSlot, MachinePointerInfo(),
8051 // For i64 source, we need to add the appropriate power of 2 if the input
8052 // was negative. This is the same as the optimization in
8053 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8054 // we must be careful to do the computation in x87 extended precision, not
8055 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8056 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8057 MachineMemOperand *MMO =
8058 DAG.getMachineFunction()
8059 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8060 MachineMemOperand::MOLoad, 8, 8);
8062 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8063 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8064 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8067 APInt FF(32, 0x5F800000ULL);
8069 // Check whether the sign bit is set.
8070 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8071 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8074 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8075 SDValue FudgePtr = DAG.getConstantPool(
8076 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8079 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8080 SDValue Zero = DAG.getIntPtrConstant(0);
8081 SDValue Four = DAG.getIntPtrConstant(4);
8082 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8084 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8086 // Load the value out, extending it from f32 to f80.
8087 // FIXME: Avoid the extend by constructing the right constant pool?
8088 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8089 FudgePtr, MachinePointerInfo::getConstantPool(),
8090 MVT::f32, false, false, 4);
8091 // Extend everything to 80 bits to force it to be done on x87.
8092 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8093 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8096 std::pair<SDValue,SDValue> X86TargetLowering::
8097 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8098 DebugLoc DL = Op.getDebugLoc();
8100 EVT DstTy = Op.getValueType();
8102 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8103 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8107 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8108 DstTy.getSimpleVT() >= MVT::i16 &&
8109 "Unknown FP_TO_INT to lower!");
8111 // These are really Legal.
8112 if (DstTy == MVT::i32 &&
8113 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8114 return std::make_pair(SDValue(), SDValue());
8115 if (Subtarget->is64Bit() &&
8116 DstTy == MVT::i64 &&
8117 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8118 return std::make_pair(SDValue(), SDValue());
8120 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8121 // stack slot, or into the FTOL runtime function.
8122 MachineFunction &MF = DAG.getMachineFunction();
8123 unsigned MemSize = DstTy.getSizeInBits()/8;
8124 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8125 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8128 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8129 Opc = X86ISD::WIN_FTOL;
8131 switch (DstTy.getSimpleVT().SimpleTy) {
8132 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8133 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8134 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8135 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8138 SDValue Chain = DAG.getEntryNode();
8139 SDValue Value = Op.getOperand(0);
8140 EVT TheVT = Op.getOperand(0).getValueType();
8141 // FIXME This causes a redundant load/store if the SSE-class value is already
8142 // in memory, such as if it is on the callstack.
8143 if (isScalarFPTypeInSSEReg(TheVT)) {
8144 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8145 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8146 MachinePointerInfo::getFixedStack(SSFI),
8148 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8150 Chain, StackSlot, DAG.getValueType(TheVT)
8153 MachineMemOperand *MMO =
8154 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8155 MachineMemOperand::MOLoad, MemSize, MemSize);
8156 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8158 Chain = Value.getValue(1);
8159 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8160 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8163 MachineMemOperand *MMO =
8164 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8165 MachineMemOperand::MOStore, MemSize, MemSize);
8167 if (Opc != X86ISD::WIN_FTOL) {
8168 // Build the FP_TO_INT*_IN_MEM
8169 SDValue Ops[] = { Chain, Value, StackSlot };
8170 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8171 Ops, 3, DstTy, MMO);
8172 return std::make_pair(FIST, StackSlot);
8174 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8175 DAG.getVTList(MVT::Other, MVT::Glue),
8177 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8178 MVT::i32, ftol.getValue(1));
8179 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8180 MVT::i32, eax.getValue(2));
8181 SDValue Ops[] = { eax, edx };
8182 SDValue pair = IsReplace
8183 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8184 : DAG.getMergeValues(Ops, 2, DL);
8185 return std::make_pair(pair, SDValue());
8189 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8190 DebugLoc DL = Op.getDebugLoc();
8191 EVT VT = Op.getValueType();
8192 EVT SVT = Op.getOperand(0).getValueType();
8194 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8195 VT.getVectorNumElements() != SVT.getVectorNumElements())
8198 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8200 unsigned NumElems = VT.getVectorNumElements();
8201 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8204 SDValue In = Op.getOperand(0);
8205 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8206 // Prepare truncation shuffle mask
8207 for (unsigned i = 0; i != NumElems; ++i)
8209 SDValue V = DAG.getVectorShuffle(NVT, DL,
8210 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8211 DAG.getUNDEF(NVT), &MaskVec[0]);
8212 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8213 DAG.getIntPtrConstant(0));
8216 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8217 SelectionDAG &DAG) const {
8218 if (Op.getValueType().isVector()) {
8219 if (Op.getValueType() == MVT::v8i16)
8220 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8221 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8222 MVT::v8i32, Op.getOperand(0)));
8226 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8227 /*IsSigned=*/ true, /*IsReplace=*/ false);
8228 SDValue FIST = Vals.first, StackSlot = Vals.second;
8229 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8230 if (FIST.getNode() == 0) return Op;
8232 if (StackSlot.getNode())
8234 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8235 FIST, StackSlot, MachinePointerInfo(),
8236 false, false, false, 0);
8238 // The node is the result.
8242 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8243 SelectionDAG &DAG) const {
8244 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8245 /*IsSigned=*/ false, /*IsReplace=*/ false);
8246 SDValue FIST = Vals.first, StackSlot = Vals.second;
8247 assert(FIST.getNode() && "Unexpected failure");
8249 if (StackSlot.getNode())
8251 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8252 FIST, StackSlot, MachinePointerInfo(),
8253 false, false, false, 0);
8255 // The node is the result.
8259 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8260 SelectionDAG &DAG) const {
8261 DebugLoc DL = Op.getDebugLoc();
8262 EVT VT = Op.getValueType();
8263 SDValue In = Op.getOperand(0);
8264 EVT SVT = In.getValueType();
8266 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8268 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8269 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8270 In, DAG.getUNDEF(SVT)));
8273 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8274 LLVMContext *Context = DAG.getContext();
8275 DebugLoc dl = Op.getDebugLoc();
8276 EVT VT = Op.getValueType();
8278 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8279 if (VT.isVector()) {
8280 EltVT = VT.getVectorElementType();
8281 NumElts = VT.getVectorNumElements();
8284 if (EltVT == MVT::f64)
8285 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8287 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8288 C = ConstantVector::getSplat(NumElts, C);
8289 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8290 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8291 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8292 MachinePointerInfo::getConstantPool(),
8293 false, false, false, Alignment);
8294 if (VT.isVector()) {
8295 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8296 return DAG.getNode(ISD::BITCAST, dl, VT,
8297 DAG.getNode(ISD::AND, dl, ANDVT,
8298 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8300 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8302 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8305 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8306 LLVMContext *Context = DAG.getContext();
8307 DebugLoc dl = Op.getDebugLoc();
8308 EVT VT = Op.getValueType();
8310 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8311 if (VT.isVector()) {
8312 EltVT = VT.getVectorElementType();
8313 NumElts = VT.getVectorNumElements();
8316 if (EltVT == MVT::f64)
8317 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8319 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8320 C = ConstantVector::getSplat(NumElts, C);
8321 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8322 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8323 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8324 MachinePointerInfo::getConstantPool(),
8325 false, false, false, Alignment);
8326 if (VT.isVector()) {
8327 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8328 return DAG.getNode(ISD::BITCAST, dl, VT,
8329 DAG.getNode(ISD::XOR, dl, XORVT,
8330 DAG.getNode(ISD::BITCAST, dl, XORVT,
8332 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8335 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8338 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8339 LLVMContext *Context = DAG.getContext();
8340 SDValue Op0 = Op.getOperand(0);
8341 SDValue Op1 = Op.getOperand(1);
8342 DebugLoc dl = Op.getDebugLoc();
8343 EVT VT = Op.getValueType();
8344 EVT SrcVT = Op1.getValueType();
8346 // If second operand is smaller, extend it first.
8347 if (SrcVT.bitsLT(VT)) {
8348 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8351 // And if it is bigger, shrink it first.
8352 if (SrcVT.bitsGT(VT)) {
8353 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8357 // At this point the operands and the result should have the same
8358 // type, and that won't be f80 since that is not custom lowered.
8360 // First get the sign bit of second operand.
8361 SmallVector<Constant*,4> CV;
8362 if (SrcVT == MVT::f64) {
8363 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8364 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8366 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8367 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8368 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8369 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8371 Constant *C = ConstantVector::get(CV);
8372 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8373 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8374 MachinePointerInfo::getConstantPool(),
8375 false, false, false, 16);
8376 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8378 // Shift sign bit right or left if the two operands have different types.
8379 if (SrcVT.bitsGT(VT)) {
8380 // Op0 is MVT::f32, Op1 is MVT::f64.
8381 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8382 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8383 DAG.getConstant(32, MVT::i32));
8384 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8385 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8386 DAG.getIntPtrConstant(0));
8389 // Clear first operand sign bit.
8391 if (VT == MVT::f64) {
8392 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8393 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8395 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8396 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8397 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8398 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8400 C = ConstantVector::get(CV);
8401 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8402 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8403 MachinePointerInfo::getConstantPool(),
8404 false, false, false, 16);
8405 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8407 // Or the value with the sign bit.
8408 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8411 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8412 SDValue N0 = Op.getOperand(0);
8413 DebugLoc dl = Op.getDebugLoc();
8414 EVT VT = Op.getValueType();
8416 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8417 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8418 DAG.getConstant(1, VT));
8419 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8422 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8424 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8425 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8427 if (!Subtarget->hasSSE41())
8430 if (!Op->hasOneUse())
8433 SDNode *N = Op.getNode();
8434 DebugLoc DL = N->getDebugLoc();
8436 SmallVector<SDValue, 8> Opnds;
8437 DenseMap<SDValue, unsigned> VecInMap;
8438 EVT VT = MVT::Other;
8440 // Recognize a special case where a vector is casted into wide integer to
8442 Opnds.push_back(N->getOperand(0));
8443 Opnds.push_back(N->getOperand(1));
8445 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8446 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8447 // BFS traverse all OR'd operands.
8448 if (I->getOpcode() == ISD::OR) {
8449 Opnds.push_back(I->getOperand(0));
8450 Opnds.push_back(I->getOperand(1));
8451 // Re-evaluate the number of nodes to be traversed.
8452 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8456 // Quit if a non-EXTRACT_VECTOR_ELT
8457 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8460 // Quit if without a constant index.
8461 SDValue Idx = I->getOperand(1);
8462 if (!isa<ConstantSDNode>(Idx))
8465 SDValue ExtractedFromVec = I->getOperand(0);
8466 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8467 if (M == VecInMap.end()) {
8468 VT = ExtractedFromVec.getValueType();
8469 // Quit if not 128/256-bit vector.
8470 if (!VT.is128BitVector() && !VT.is256BitVector())
8472 // Quit if not the same type.
8473 if (VecInMap.begin() != VecInMap.end() &&
8474 VT != VecInMap.begin()->first.getValueType())
8476 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8478 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8481 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8482 "Not extracted from 128-/256-bit vector.");
8484 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8485 SmallVector<SDValue, 8> VecIns;
8487 for (DenseMap<SDValue, unsigned>::const_iterator
8488 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8489 // Quit if not all elements are used.
8490 if (I->second != FullMask)
8492 VecIns.push_back(I->first);
8495 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8497 // Cast all vectors into TestVT for PTEST.
8498 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8499 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8501 // If more than one full vectors are evaluated, OR them first before PTEST.
8502 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8503 // Each iteration will OR 2 nodes and append the result until there is only
8504 // 1 node left, i.e. the final OR'd value of all vectors.
8505 SDValue LHS = VecIns[Slot];
8506 SDValue RHS = VecIns[Slot + 1];
8507 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8510 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8511 VecIns.back(), VecIns.back());
8514 /// Emit nodes that will be selected as "test Op0,Op0", or something
8516 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8517 SelectionDAG &DAG) const {
8518 DebugLoc dl = Op.getDebugLoc();
8520 // CF and OF aren't always set the way we want. Determine which
8521 // of these we need.
8522 bool NeedCF = false;
8523 bool NeedOF = false;
8526 case X86::COND_A: case X86::COND_AE:
8527 case X86::COND_B: case X86::COND_BE:
8530 case X86::COND_G: case X86::COND_GE:
8531 case X86::COND_L: case X86::COND_LE:
8532 case X86::COND_O: case X86::COND_NO:
8537 // See if we can use the EFLAGS value from the operand instead of
8538 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8539 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8540 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8541 // Emit a CMP with 0, which is the TEST pattern.
8542 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8543 DAG.getConstant(0, Op.getValueType()));
8545 unsigned Opcode = 0;
8546 unsigned NumOperands = 0;
8548 // Truncate operations may prevent the merge of the SETCC instruction
8549 // and the arithmetic intruction before it. Attempt to truncate the operands
8550 // of the arithmetic instruction and use a reduced bit-width instruction.
8551 bool NeedTruncation = false;
8552 SDValue ArithOp = Op;
8553 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8554 SDValue Arith = Op->getOperand(0);
8555 // Both the trunc and the arithmetic op need to have one user each.
8556 if (Arith->hasOneUse())
8557 switch (Arith.getOpcode()) {
8564 NeedTruncation = true;
8570 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8571 // which may be the result of a CAST. We use the variable 'Op', which is the
8572 // non-casted variable when we check for possible users.
8573 switch (ArithOp.getOpcode()) {
8575 // Due to an isel shortcoming, be conservative if this add is likely to be
8576 // selected as part of a load-modify-store instruction. When the root node
8577 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8578 // uses of other nodes in the match, such as the ADD in this case. This
8579 // leads to the ADD being left around and reselected, with the result being
8580 // two adds in the output. Alas, even if none our users are stores, that
8581 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8582 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8583 // climbing the DAG back to the root, and it doesn't seem to be worth the
8585 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8586 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8587 if (UI->getOpcode() != ISD::CopyToReg &&
8588 UI->getOpcode() != ISD::SETCC &&
8589 UI->getOpcode() != ISD::STORE)
8592 if (ConstantSDNode *C =
8593 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8594 // An add of one will be selected as an INC.
8595 if (C->getAPIntValue() == 1) {
8596 Opcode = X86ISD::INC;
8601 // An add of negative one (subtract of one) will be selected as a DEC.
8602 if (C->getAPIntValue().isAllOnesValue()) {
8603 Opcode = X86ISD::DEC;
8609 // Otherwise use a regular EFLAGS-setting add.
8610 Opcode = X86ISD::ADD;
8614 // If the primary and result isn't used, don't bother using X86ISD::AND,
8615 // because a TEST instruction will be better.
8616 bool NonFlagUse = false;
8617 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8618 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8620 unsigned UOpNo = UI.getOperandNo();
8621 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8622 // Look pass truncate.
8623 UOpNo = User->use_begin().getOperandNo();
8624 User = *User->use_begin();
8627 if (User->getOpcode() != ISD::BRCOND &&
8628 User->getOpcode() != ISD::SETCC &&
8629 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8642 // Due to the ISEL shortcoming noted above, be conservative if this op is
8643 // likely to be selected as part of a load-modify-store instruction.
8644 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8645 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8646 if (UI->getOpcode() == ISD::STORE)
8649 // Otherwise use a regular EFLAGS-setting instruction.
8650 switch (ArithOp.getOpcode()) {
8651 default: llvm_unreachable("unexpected operator!");
8652 case ISD::SUB: Opcode = X86ISD::SUB; break;
8653 case ISD::XOR: Opcode = X86ISD::XOR; break;
8654 case ISD::AND: Opcode = X86ISD::AND; break;
8656 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8657 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8658 if (EFLAGS.getNode())
8661 Opcode = X86ISD::OR;
8675 return SDValue(Op.getNode(), 1);
8681 // If we found that truncation is beneficial, perform the truncation and
8683 if (NeedTruncation) {
8684 EVT VT = Op.getValueType();
8685 SDValue WideVal = Op->getOperand(0);
8686 EVT WideVT = WideVal.getValueType();
8687 unsigned ConvertedOp = 0;
8688 // Use a target machine opcode to prevent further DAGCombine
8689 // optimizations that may separate the arithmetic operations
8690 // from the setcc node.
8691 switch (WideVal.getOpcode()) {
8693 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8694 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8695 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8696 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8697 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8702 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8703 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8704 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8705 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8711 // Emit a CMP with 0, which is the TEST pattern.
8712 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8713 DAG.getConstant(0, Op.getValueType()));
8715 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8716 SmallVector<SDValue, 4> Ops;
8717 for (unsigned i = 0; i != NumOperands; ++i)
8718 Ops.push_back(Op.getOperand(i));
8720 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8721 DAG.ReplaceAllUsesWith(Op, New);
8722 return SDValue(New.getNode(), 1);
8725 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8727 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8728 SelectionDAG &DAG) const {
8729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8730 if (C->getAPIntValue() == 0)
8731 return EmitTest(Op0, X86CC, DAG);
8733 DebugLoc dl = Op0.getDebugLoc();
8734 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8735 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8736 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8737 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8738 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8740 return SDValue(Sub.getNode(), 1);
8742 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8745 /// Convert a comparison if required by the subtarget.
8746 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8747 SelectionDAG &DAG) const {
8748 // If the subtarget does not support the FUCOMI instruction, floating-point
8749 // comparisons have to be converted.
8750 if (Subtarget->hasCMov() ||
8751 Cmp.getOpcode() != X86ISD::CMP ||
8752 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8753 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8756 // The instruction selector will select an FUCOM instruction instead of
8757 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8758 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8759 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8760 DebugLoc dl = Cmp.getDebugLoc();
8761 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8762 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8763 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8764 DAG.getConstant(8, MVT::i8));
8765 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8766 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8769 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8770 /// if it's possible.
8771 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8772 DebugLoc dl, SelectionDAG &DAG) const {
8773 SDValue Op0 = And.getOperand(0);
8774 SDValue Op1 = And.getOperand(1);
8775 if (Op0.getOpcode() == ISD::TRUNCATE)
8776 Op0 = Op0.getOperand(0);
8777 if (Op1.getOpcode() == ISD::TRUNCATE)
8778 Op1 = Op1.getOperand(0);
8781 if (Op1.getOpcode() == ISD::SHL)
8782 std::swap(Op0, Op1);
8783 if (Op0.getOpcode() == ISD::SHL) {
8784 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8785 if (And00C->getZExtValue() == 1) {
8786 // If we looked past a truncate, check that it's only truncating away
8788 unsigned BitWidth = Op0.getValueSizeInBits();
8789 unsigned AndBitWidth = And.getValueSizeInBits();
8790 if (BitWidth > AndBitWidth) {
8792 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8793 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8797 RHS = Op0.getOperand(1);
8799 } else if (Op1.getOpcode() == ISD::Constant) {
8800 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8801 uint64_t AndRHSVal = AndRHS->getZExtValue();
8802 SDValue AndLHS = Op0;
8804 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8805 LHS = AndLHS.getOperand(0);
8806 RHS = AndLHS.getOperand(1);
8809 // Use BT if the immediate can't be encoded in a TEST instruction.
8810 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8812 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8816 if (LHS.getNode()) {
8817 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8818 // instruction. Since the shift amount is in-range-or-undefined, we know
8819 // that doing a bittest on the i32 value is ok. We extend to i32 because
8820 // the encoding for the i16 version is larger than the i32 version.
8821 // Also promote i16 to i32 for performance / code size reason.
8822 if (LHS.getValueType() == MVT::i8 ||
8823 LHS.getValueType() == MVT::i16)
8824 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8826 // If the operand types disagree, extend the shift amount to match. Since
8827 // BT ignores high bits (like shifts) we can use anyextend.
8828 if (LHS.getValueType() != RHS.getValueType())
8829 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8831 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8832 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8833 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8834 DAG.getConstant(Cond, MVT::i8), BT);
8840 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8842 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8844 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8845 SDValue Op0 = Op.getOperand(0);
8846 SDValue Op1 = Op.getOperand(1);
8847 DebugLoc dl = Op.getDebugLoc();
8848 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8850 // Optimize to BT if possible.
8851 // Lower (X & (1 << N)) == 0 to BT(X, N).
8852 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8853 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8854 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8855 Op1.getOpcode() == ISD::Constant &&
8856 cast<ConstantSDNode>(Op1)->isNullValue() &&
8857 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8858 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8859 if (NewSetCC.getNode())
8863 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8865 if (Op1.getOpcode() == ISD::Constant &&
8866 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8867 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8868 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8870 // If the input is a setcc, then reuse the input setcc or use a new one with
8871 // the inverted condition.
8872 if (Op0.getOpcode() == X86ISD::SETCC) {
8873 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8874 bool Invert = (CC == ISD::SETNE) ^
8875 cast<ConstantSDNode>(Op1)->isNullValue();
8876 if (!Invert) return Op0;
8878 CCode = X86::GetOppositeBranchCondition(CCode);
8879 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8880 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8884 bool isFP = Op1.getValueType().isFloatingPoint();
8885 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8886 if (X86CC == X86::COND_INVALID)
8889 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8890 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8891 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8892 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8895 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8896 // ones, and then concatenate the result back.
8897 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8898 EVT VT = Op.getValueType();
8900 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8901 "Unsupported value type for operation");
8903 unsigned NumElems = VT.getVectorNumElements();
8904 DebugLoc dl = Op.getDebugLoc();
8905 SDValue CC = Op.getOperand(2);
8907 // Extract the LHS vectors
8908 SDValue LHS = Op.getOperand(0);
8909 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8910 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8912 // Extract the RHS vectors
8913 SDValue RHS = Op.getOperand(1);
8914 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8915 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8917 // Issue the operation on the smaller types and concatenate the result back
8918 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8919 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8920 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8921 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8922 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8926 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8928 SDValue Op0 = Op.getOperand(0);
8929 SDValue Op1 = Op.getOperand(1);
8930 SDValue CC = Op.getOperand(2);
8931 EVT VT = Op.getValueType();
8932 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8933 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8934 DebugLoc dl = Op.getDebugLoc();
8938 EVT EltVT = Op0.getValueType().getVectorElementType();
8939 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8945 // SSE Condition code mapping:
8954 switch (SetCCOpcode) {
8955 default: llvm_unreachable("Unexpected SETCC condition");
8957 case ISD::SETEQ: SSECC = 0; break;
8959 case ISD::SETGT: Swap = true; // Fallthrough
8961 case ISD::SETOLT: SSECC = 1; break;
8963 case ISD::SETGE: Swap = true; // Fallthrough
8965 case ISD::SETOLE: SSECC = 2; break;
8966 case ISD::SETUO: SSECC = 3; break;
8968 case ISD::SETNE: SSECC = 4; break;
8969 case ISD::SETULE: Swap = true; // Fallthrough
8970 case ISD::SETUGE: SSECC = 5; break;
8971 case ISD::SETULT: Swap = true; // Fallthrough
8972 case ISD::SETUGT: SSECC = 6; break;
8973 case ISD::SETO: SSECC = 7; break;
8975 case ISD::SETONE: SSECC = 8; break;
8978 std::swap(Op0, Op1);
8980 // In the two special cases we can't handle, emit two comparisons.
8983 unsigned CombineOpc;
8984 if (SetCCOpcode == ISD::SETUEQ) {
8985 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8987 assert(SetCCOpcode == ISD::SETONE);
8988 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8991 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8992 DAG.getConstant(CC0, MVT::i8));
8993 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8994 DAG.getConstant(CC1, MVT::i8));
8995 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8997 // Handle all other FP comparisons here.
8998 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8999 DAG.getConstant(SSECC, MVT::i8));
9002 // Break 256-bit integer vector compare into smaller ones.
9003 if (VT.is256BitVector() && !Subtarget->hasAVX2())
9004 return Lower256IntVSETCC(Op, DAG);
9006 // We are handling one of the integer comparisons here. Since SSE only has
9007 // GT and EQ comparisons for integer, swapping operands and multiple
9008 // operations may be required for some comparisons.
9010 bool Swap = false, Invert = false, FlipSigns = false;
9012 switch (SetCCOpcode) {
9013 default: llvm_unreachable("Unexpected SETCC condition");
9014 case ISD::SETNE: Invert = true;
9015 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9016 case ISD::SETLT: Swap = true;
9017 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9018 case ISD::SETGE: Swap = true;
9019 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9020 case ISD::SETULT: Swap = true;
9021 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9022 case ISD::SETUGE: Swap = true;
9023 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9026 std::swap(Op0, Op1);
9028 // Check that the operation in question is available (most are plain SSE2,
9029 // but PCMPGTQ and PCMPEQQ have different requirements).
9030 if (VT == MVT::v2i64) {
9031 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9033 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9037 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9038 // bits of the inputs before performing those operations.
9040 EVT EltVT = VT.getVectorElementType();
9041 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9043 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9044 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9046 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9047 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9050 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9052 // If the logical-not of the result is required, perform that now.
9054 Result = DAG.getNOT(dl, Result, VT);
9059 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9060 static bool isX86LogicalCmp(SDValue Op) {
9061 unsigned Opc = Op.getNode()->getOpcode();
9062 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9063 Opc == X86ISD::SAHF)
9065 if (Op.getResNo() == 1 &&
9066 (Opc == X86ISD::ADD ||
9067 Opc == X86ISD::SUB ||
9068 Opc == X86ISD::ADC ||
9069 Opc == X86ISD::SBB ||
9070 Opc == X86ISD::SMUL ||
9071 Opc == X86ISD::UMUL ||
9072 Opc == X86ISD::INC ||
9073 Opc == X86ISD::DEC ||
9074 Opc == X86ISD::OR ||
9075 Opc == X86ISD::XOR ||
9076 Opc == X86ISD::AND))
9079 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9085 static bool isZero(SDValue V) {
9086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9087 return C && C->isNullValue();
9090 static bool isAllOnes(SDValue V) {
9091 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9092 return C && C->isAllOnesValue();
9095 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9096 if (V.getOpcode() != ISD::TRUNCATE)
9099 SDValue VOp0 = V.getOperand(0);
9100 unsigned InBits = VOp0.getValueSizeInBits();
9101 unsigned Bits = V.getValueSizeInBits();
9102 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9105 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9106 bool addTest = true;
9107 SDValue Cond = Op.getOperand(0);
9108 SDValue Op1 = Op.getOperand(1);
9109 SDValue Op2 = Op.getOperand(2);
9110 DebugLoc DL = Op.getDebugLoc();
9113 if (Cond.getOpcode() == ISD::SETCC) {
9114 SDValue NewCond = LowerSETCC(Cond, DAG);
9115 if (NewCond.getNode())
9119 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9120 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9121 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9122 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9123 if (Cond.getOpcode() == X86ISD::SETCC &&
9124 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9125 isZero(Cond.getOperand(1).getOperand(1))) {
9126 SDValue Cmp = Cond.getOperand(1);
9128 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9130 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9131 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9132 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9134 SDValue CmpOp0 = Cmp.getOperand(0);
9135 // Apply further optimizations for special cases
9136 // (select (x != 0), -1, 0) -> neg & sbb
9137 // (select (x == 0), 0, -1) -> neg & sbb
9138 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9139 if (YC->isNullValue() &&
9140 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9141 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9142 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9143 DAG.getConstant(0, CmpOp0.getValueType()),
9145 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9146 DAG.getConstant(X86::COND_B, MVT::i8),
9147 SDValue(Neg.getNode(), 1));
9151 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9152 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9153 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9155 SDValue Res = // Res = 0 or -1.
9156 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9157 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9159 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9160 Res = DAG.getNOT(DL, Res, Res.getValueType());
9162 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9163 if (N2C == 0 || !N2C->isNullValue())
9164 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9169 // Look past (and (setcc_carry (cmp ...)), 1).
9170 if (Cond.getOpcode() == ISD::AND &&
9171 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9172 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9173 if (C && C->getAPIntValue() == 1)
9174 Cond = Cond.getOperand(0);
9177 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9178 // setting operand in place of the X86ISD::SETCC.
9179 unsigned CondOpcode = Cond.getOpcode();
9180 if (CondOpcode == X86ISD::SETCC ||
9181 CondOpcode == X86ISD::SETCC_CARRY) {
9182 CC = Cond.getOperand(0);
9184 SDValue Cmp = Cond.getOperand(1);
9185 unsigned Opc = Cmp.getOpcode();
9186 EVT VT = Op.getValueType();
9188 bool IllegalFPCMov = false;
9189 if (VT.isFloatingPoint() && !VT.isVector() &&
9190 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9191 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9193 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9194 Opc == X86ISD::BT) { // FIXME
9198 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9199 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9200 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9201 Cond.getOperand(0).getValueType() != MVT::i8)) {
9202 SDValue LHS = Cond.getOperand(0);
9203 SDValue RHS = Cond.getOperand(1);
9207 switch (CondOpcode) {
9208 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9209 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9210 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9211 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9212 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9213 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9214 default: llvm_unreachable("unexpected overflowing operator");
9216 if (CondOpcode == ISD::UMULO)
9217 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9220 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9222 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9224 if (CondOpcode == ISD::UMULO)
9225 Cond = X86Op.getValue(2);
9227 Cond = X86Op.getValue(1);
9229 CC = DAG.getConstant(X86Cond, MVT::i8);
9234 // Look pass the truncate if the high bits are known zero.
9235 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9236 Cond = Cond.getOperand(0);
9238 // We know the result of AND is compared against zero. Try to match
9240 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9241 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9242 if (NewSetCC.getNode()) {
9243 CC = NewSetCC.getOperand(0);
9244 Cond = NewSetCC.getOperand(1);
9251 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9252 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9255 // a < b ? -1 : 0 -> RES = ~setcc_carry
9256 // a < b ? 0 : -1 -> RES = setcc_carry
9257 // a >= b ? -1 : 0 -> RES = setcc_carry
9258 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9259 if (Cond.getOpcode() == X86ISD::SUB) {
9260 Cond = ConvertCmpIfNecessary(Cond, DAG);
9261 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9263 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9264 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9265 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9266 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9267 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9268 return DAG.getNOT(DL, Res, Res.getValueType());
9273 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9274 // widen the cmov and push the truncate through. This avoids introducing a new
9275 // branch during isel and doesn't add any extensions.
9276 if (Op.getValueType() == MVT::i8 &&
9277 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9278 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9279 if (T1.getValueType() == T2.getValueType() &&
9280 // Blacklist CopyFromReg to avoid partial register stalls.
9281 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9282 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9283 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9284 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9288 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9289 // condition is true.
9290 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9291 SDValue Ops[] = { Op2, Op1, CC, Cond };
9292 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9295 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9296 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9297 // from the AND / OR.
9298 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9299 Opc = Op.getOpcode();
9300 if (Opc != ISD::OR && Opc != ISD::AND)
9302 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9303 Op.getOperand(0).hasOneUse() &&
9304 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9305 Op.getOperand(1).hasOneUse());
9308 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9309 // 1 and that the SETCC node has a single use.
9310 static bool isXor1OfSetCC(SDValue Op) {
9311 if (Op.getOpcode() != ISD::XOR)
9313 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9314 if (N1C && N1C->getAPIntValue() == 1) {
9315 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9316 Op.getOperand(0).hasOneUse();
9321 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9322 bool addTest = true;
9323 SDValue Chain = Op.getOperand(0);
9324 SDValue Cond = Op.getOperand(1);
9325 SDValue Dest = Op.getOperand(2);
9326 DebugLoc dl = Op.getDebugLoc();
9328 bool Inverted = false;
9330 if (Cond.getOpcode() == ISD::SETCC) {
9331 // Check for setcc([su]{add,sub,mul}o == 0).
9332 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9333 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9334 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9335 Cond.getOperand(0).getResNo() == 1 &&
9336 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9337 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9338 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9339 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9340 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9341 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9343 Cond = Cond.getOperand(0);
9345 SDValue NewCond = LowerSETCC(Cond, DAG);
9346 if (NewCond.getNode())
9351 // FIXME: LowerXALUO doesn't handle these!!
9352 else if (Cond.getOpcode() == X86ISD::ADD ||
9353 Cond.getOpcode() == X86ISD::SUB ||
9354 Cond.getOpcode() == X86ISD::SMUL ||
9355 Cond.getOpcode() == X86ISD::UMUL)
9356 Cond = LowerXALUO(Cond, DAG);
9359 // Look pass (and (setcc_carry (cmp ...)), 1).
9360 if (Cond.getOpcode() == ISD::AND &&
9361 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9362 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9363 if (C && C->getAPIntValue() == 1)
9364 Cond = Cond.getOperand(0);
9367 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9368 // setting operand in place of the X86ISD::SETCC.
9369 unsigned CondOpcode = Cond.getOpcode();
9370 if (CondOpcode == X86ISD::SETCC ||
9371 CondOpcode == X86ISD::SETCC_CARRY) {
9372 CC = Cond.getOperand(0);
9374 SDValue Cmp = Cond.getOperand(1);
9375 unsigned Opc = Cmp.getOpcode();
9376 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9377 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9381 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9385 // These can only come from an arithmetic instruction with overflow,
9386 // e.g. SADDO, UADDO.
9387 Cond = Cond.getNode()->getOperand(1);
9393 CondOpcode = Cond.getOpcode();
9394 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9395 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9396 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9397 Cond.getOperand(0).getValueType() != MVT::i8)) {
9398 SDValue LHS = Cond.getOperand(0);
9399 SDValue RHS = Cond.getOperand(1);
9403 switch (CondOpcode) {
9404 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9405 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9406 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9407 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9408 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9409 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9410 default: llvm_unreachable("unexpected overflowing operator");
9413 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9414 if (CondOpcode == ISD::UMULO)
9415 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9418 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9420 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9422 if (CondOpcode == ISD::UMULO)
9423 Cond = X86Op.getValue(2);
9425 Cond = X86Op.getValue(1);
9427 CC = DAG.getConstant(X86Cond, MVT::i8);
9431 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9432 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9433 if (CondOpc == ISD::OR) {
9434 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9435 // two branches instead of an explicit OR instruction with a
9437 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9438 isX86LogicalCmp(Cmp)) {
9439 CC = Cond.getOperand(0).getOperand(0);
9440 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9441 Chain, Dest, CC, Cmp);
9442 CC = Cond.getOperand(1).getOperand(0);
9446 } else { // ISD::AND
9447 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9448 // two branches instead of an explicit AND instruction with a
9449 // separate test. However, we only do this if this block doesn't
9450 // have a fall-through edge, because this requires an explicit
9451 // jmp when the condition is false.
9452 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9453 isX86LogicalCmp(Cmp) &&
9454 Op.getNode()->hasOneUse()) {
9455 X86::CondCode CCode =
9456 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9457 CCode = X86::GetOppositeBranchCondition(CCode);
9458 CC = DAG.getConstant(CCode, MVT::i8);
9459 SDNode *User = *Op.getNode()->use_begin();
9460 // Look for an unconditional branch following this conditional branch.
9461 // We need this because we need to reverse the successors in order
9462 // to implement FCMP_OEQ.
9463 if (User->getOpcode() == ISD::BR) {
9464 SDValue FalseBB = User->getOperand(1);
9466 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9467 assert(NewBR == User);
9471 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9472 Chain, Dest, CC, Cmp);
9473 X86::CondCode CCode =
9474 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9475 CCode = X86::GetOppositeBranchCondition(CCode);
9476 CC = DAG.getConstant(CCode, MVT::i8);
9482 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9483 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9484 // It should be transformed during dag combiner except when the condition
9485 // is set by a arithmetics with overflow node.
9486 X86::CondCode CCode =
9487 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9488 CCode = X86::GetOppositeBranchCondition(CCode);
9489 CC = DAG.getConstant(CCode, MVT::i8);
9490 Cond = Cond.getOperand(0).getOperand(1);
9492 } else if (Cond.getOpcode() == ISD::SETCC &&
9493 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9494 // For FCMP_OEQ, we can emit
9495 // two branches instead of an explicit AND instruction with a
9496 // separate test. However, we only do this if this block doesn't
9497 // have a fall-through edge, because this requires an explicit
9498 // jmp when the condition is false.
9499 if (Op.getNode()->hasOneUse()) {
9500 SDNode *User = *Op.getNode()->use_begin();
9501 // Look for an unconditional branch following this conditional branch.
9502 // We need this because we need to reverse the successors in order
9503 // to implement FCMP_OEQ.
9504 if (User->getOpcode() == ISD::BR) {
9505 SDValue FalseBB = User->getOperand(1);
9507 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9508 assert(NewBR == User);
9512 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9513 Cond.getOperand(0), Cond.getOperand(1));
9514 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9515 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9516 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9517 Chain, Dest, CC, Cmp);
9518 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9523 } else if (Cond.getOpcode() == ISD::SETCC &&
9524 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9525 // For FCMP_UNE, we can emit
9526 // two branches instead of an explicit AND instruction with a
9527 // separate test. However, we only do this if this block doesn't
9528 // have a fall-through edge, because this requires an explicit
9529 // jmp when the condition is false.
9530 if (Op.getNode()->hasOneUse()) {
9531 SDNode *User = *Op.getNode()->use_begin();
9532 // Look for an unconditional branch following this conditional branch.
9533 // We need this because we need to reverse the successors in order
9534 // to implement FCMP_UNE.
9535 if (User->getOpcode() == ISD::BR) {
9536 SDValue FalseBB = User->getOperand(1);
9538 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9539 assert(NewBR == User);
9542 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9543 Cond.getOperand(0), Cond.getOperand(1));
9544 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9545 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9546 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9547 Chain, Dest, CC, Cmp);
9548 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9558 // Look pass the truncate if the high bits are known zero.
9559 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9560 Cond = Cond.getOperand(0);
9562 // We know the result of AND is compared against zero. Try to match
9564 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9565 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9566 if (NewSetCC.getNode()) {
9567 CC = NewSetCC.getOperand(0);
9568 Cond = NewSetCC.getOperand(1);
9575 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9576 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9578 Cond = ConvertCmpIfNecessary(Cond, DAG);
9579 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9580 Chain, Dest, CC, Cond);
9584 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9585 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9586 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9587 // that the guard pages used by the OS virtual memory manager are allocated in
9588 // correct sequence.
9590 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9591 SelectionDAG &DAG) const {
9592 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9593 getTargetMachine().Options.EnableSegmentedStacks) &&
9594 "This should be used only on Windows targets or when segmented stacks "
9596 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9597 DebugLoc dl = Op.getDebugLoc();
9600 SDValue Chain = Op.getOperand(0);
9601 SDValue Size = Op.getOperand(1);
9602 // FIXME: Ensure alignment here
9604 bool Is64Bit = Subtarget->is64Bit();
9605 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9607 if (getTargetMachine().Options.EnableSegmentedStacks) {
9608 MachineFunction &MF = DAG.getMachineFunction();
9609 MachineRegisterInfo &MRI = MF.getRegInfo();
9612 // The 64 bit implementation of segmented stacks needs to clobber both r10
9613 // r11. This makes it impossible to use it along with nested parameters.
9614 const Function *F = MF.getFunction();
9616 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9618 if (I->hasNestAttr())
9619 report_fatal_error("Cannot use segmented stacks with functions that "
9620 "have nested arguments.");
9623 const TargetRegisterClass *AddrRegClass =
9624 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9625 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9626 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9627 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9628 DAG.getRegister(Vreg, SPTy));
9629 SDValue Ops1[2] = { Value, Chain };
9630 return DAG.getMergeValues(Ops1, 2, dl);
9633 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9635 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9636 Flag = Chain.getValue(1);
9637 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9639 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9640 Flag = Chain.getValue(1);
9642 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9644 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9645 return DAG.getMergeValues(Ops1, 2, dl);
9649 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9650 MachineFunction &MF = DAG.getMachineFunction();
9651 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9653 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9654 DebugLoc DL = Op.getDebugLoc();
9656 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9657 // vastart just stores the address of the VarArgsFrameIndex slot into the
9658 // memory location argument.
9659 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9661 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9662 MachinePointerInfo(SV), false, false, 0);
9666 // gp_offset (0 - 6 * 8)
9667 // fp_offset (48 - 48 + 8 * 16)
9668 // overflow_arg_area (point to parameters coming in memory).
9670 SmallVector<SDValue, 8> MemOps;
9671 SDValue FIN = Op.getOperand(1);
9673 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9674 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9676 FIN, MachinePointerInfo(SV), false, false, 0);
9677 MemOps.push_back(Store);
9680 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9681 FIN, DAG.getIntPtrConstant(4));
9682 Store = DAG.getStore(Op.getOperand(0), DL,
9683 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9685 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9686 MemOps.push_back(Store);
9688 // Store ptr to overflow_arg_area
9689 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9690 FIN, DAG.getIntPtrConstant(4));
9691 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9693 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9694 MachinePointerInfo(SV, 8),
9696 MemOps.push_back(Store);
9698 // Store ptr to reg_save_area.
9699 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9700 FIN, DAG.getIntPtrConstant(8));
9701 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9703 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9704 MachinePointerInfo(SV, 16), false, false, 0);
9705 MemOps.push_back(Store);
9706 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9707 &MemOps[0], MemOps.size());
9710 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9711 assert(Subtarget->is64Bit() &&
9712 "LowerVAARG only handles 64-bit va_arg!");
9713 assert((Subtarget->isTargetLinux() ||
9714 Subtarget->isTargetDarwin()) &&
9715 "Unhandled target in LowerVAARG");
9716 assert(Op.getNode()->getNumOperands() == 4);
9717 SDValue Chain = Op.getOperand(0);
9718 SDValue SrcPtr = Op.getOperand(1);
9719 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9720 unsigned Align = Op.getConstantOperandVal(3);
9721 DebugLoc dl = Op.getDebugLoc();
9723 EVT ArgVT = Op.getNode()->getValueType(0);
9724 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9725 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9728 // Decide which area this value should be read from.
9729 // TODO: Implement the AMD64 ABI in its entirety. This simple
9730 // selection mechanism works only for the basic types.
9731 if (ArgVT == MVT::f80) {
9732 llvm_unreachable("va_arg for f80 not yet implemented");
9733 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9734 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9735 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9736 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9738 llvm_unreachable("Unhandled argument type in LowerVAARG");
9742 // Sanity Check: Make sure using fp_offset makes sense.
9743 assert(!getTargetMachine().Options.UseSoftFloat &&
9744 !(DAG.getMachineFunction()
9745 .getFunction()->getFnAttributes()
9746 .hasAttribute(Attributes::NoImplicitFloat)) &&
9747 Subtarget->hasSSE1());
9750 // Insert VAARG_64 node into the DAG
9751 // VAARG_64 returns two values: Variable Argument Address, Chain
9752 SmallVector<SDValue, 11> InstOps;
9753 InstOps.push_back(Chain);
9754 InstOps.push_back(SrcPtr);
9755 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9756 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9757 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9758 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9759 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9760 VTs, &InstOps[0], InstOps.size(),
9762 MachinePointerInfo(SV),
9767 Chain = VAARG.getValue(1);
9769 // Load the next argument and return it
9770 return DAG.getLoad(ArgVT, dl,
9773 MachinePointerInfo(),
9774 false, false, false, 0);
9777 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9778 SelectionDAG &DAG) {
9779 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9780 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9781 SDValue Chain = Op.getOperand(0);
9782 SDValue DstPtr = Op.getOperand(1);
9783 SDValue SrcPtr = Op.getOperand(2);
9784 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9785 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9786 DebugLoc DL = Op.getDebugLoc();
9788 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9789 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9791 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9794 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9795 // may or may not be a constant. Takes immediate version of shift as input.
9796 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9797 SDValue SrcOp, SDValue ShAmt,
9798 SelectionDAG &DAG) {
9799 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9801 if (isa<ConstantSDNode>(ShAmt)) {
9802 // Constant may be a TargetConstant. Use a regular constant.
9803 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9805 default: llvm_unreachable("Unknown target vector shift node");
9809 return DAG.getNode(Opc, dl, VT, SrcOp,
9810 DAG.getConstant(ShiftAmt, MVT::i32));
9814 // Change opcode to non-immediate version
9816 default: llvm_unreachable("Unknown target vector shift node");
9817 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9818 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9819 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9822 // Need to build a vector containing shift amount
9823 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9826 ShOps[1] = DAG.getConstant(0, MVT::i32);
9827 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9828 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9830 // The return type has to be a 128-bit type with the same element
9831 // type as the input type.
9832 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9833 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9835 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9836 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9839 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9840 DebugLoc dl = Op.getDebugLoc();
9841 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9843 default: return SDValue(); // Don't custom lower most intrinsics.
9844 // Comparison intrinsics.
9845 case Intrinsic::x86_sse_comieq_ss:
9846 case Intrinsic::x86_sse_comilt_ss:
9847 case Intrinsic::x86_sse_comile_ss:
9848 case Intrinsic::x86_sse_comigt_ss:
9849 case Intrinsic::x86_sse_comige_ss:
9850 case Intrinsic::x86_sse_comineq_ss:
9851 case Intrinsic::x86_sse_ucomieq_ss:
9852 case Intrinsic::x86_sse_ucomilt_ss:
9853 case Intrinsic::x86_sse_ucomile_ss:
9854 case Intrinsic::x86_sse_ucomigt_ss:
9855 case Intrinsic::x86_sse_ucomige_ss:
9856 case Intrinsic::x86_sse_ucomineq_ss:
9857 case Intrinsic::x86_sse2_comieq_sd:
9858 case Intrinsic::x86_sse2_comilt_sd:
9859 case Intrinsic::x86_sse2_comile_sd:
9860 case Intrinsic::x86_sse2_comigt_sd:
9861 case Intrinsic::x86_sse2_comige_sd:
9862 case Intrinsic::x86_sse2_comineq_sd:
9863 case Intrinsic::x86_sse2_ucomieq_sd:
9864 case Intrinsic::x86_sse2_ucomilt_sd:
9865 case Intrinsic::x86_sse2_ucomile_sd:
9866 case Intrinsic::x86_sse2_ucomigt_sd:
9867 case Intrinsic::x86_sse2_ucomige_sd:
9868 case Intrinsic::x86_sse2_ucomineq_sd: {
9872 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9873 case Intrinsic::x86_sse_comieq_ss:
9874 case Intrinsic::x86_sse2_comieq_sd:
9878 case Intrinsic::x86_sse_comilt_ss:
9879 case Intrinsic::x86_sse2_comilt_sd:
9883 case Intrinsic::x86_sse_comile_ss:
9884 case Intrinsic::x86_sse2_comile_sd:
9888 case Intrinsic::x86_sse_comigt_ss:
9889 case Intrinsic::x86_sse2_comigt_sd:
9893 case Intrinsic::x86_sse_comige_ss:
9894 case Intrinsic::x86_sse2_comige_sd:
9898 case Intrinsic::x86_sse_comineq_ss:
9899 case Intrinsic::x86_sse2_comineq_sd:
9903 case Intrinsic::x86_sse_ucomieq_ss:
9904 case Intrinsic::x86_sse2_ucomieq_sd:
9905 Opc = X86ISD::UCOMI;
9908 case Intrinsic::x86_sse_ucomilt_ss:
9909 case Intrinsic::x86_sse2_ucomilt_sd:
9910 Opc = X86ISD::UCOMI;
9913 case Intrinsic::x86_sse_ucomile_ss:
9914 case Intrinsic::x86_sse2_ucomile_sd:
9915 Opc = X86ISD::UCOMI;
9918 case Intrinsic::x86_sse_ucomigt_ss:
9919 case Intrinsic::x86_sse2_ucomigt_sd:
9920 Opc = X86ISD::UCOMI;
9923 case Intrinsic::x86_sse_ucomige_ss:
9924 case Intrinsic::x86_sse2_ucomige_sd:
9925 Opc = X86ISD::UCOMI;
9928 case Intrinsic::x86_sse_ucomineq_ss:
9929 case Intrinsic::x86_sse2_ucomineq_sd:
9930 Opc = X86ISD::UCOMI;
9935 SDValue LHS = Op.getOperand(1);
9936 SDValue RHS = Op.getOperand(2);
9937 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9938 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9939 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9940 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9941 DAG.getConstant(X86CC, MVT::i8), Cond);
9942 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9945 // Arithmetic intrinsics.
9946 case Intrinsic::x86_sse2_pmulu_dq:
9947 case Intrinsic::x86_avx2_pmulu_dq:
9948 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9949 Op.getOperand(1), Op.getOperand(2));
9951 // SSE3/AVX horizontal add/sub intrinsics
9952 case Intrinsic::x86_sse3_hadd_ps:
9953 case Intrinsic::x86_sse3_hadd_pd:
9954 case Intrinsic::x86_avx_hadd_ps_256:
9955 case Intrinsic::x86_avx_hadd_pd_256:
9956 case Intrinsic::x86_sse3_hsub_ps:
9957 case Intrinsic::x86_sse3_hsub_pd:
9958 case Intrinsic::x86_avx_hsub_ps_256:
9959 case Intrinsic::x86_avx_hsub_pd_256:
9960 case Intrinsic::x86_ssse3_phadd_w_128:
9961 case Intrinsic::x86_ssse3_phadd_d_128:
9962 case Intrinsic::x86_avx2_phadd_w:
9963 case Intrinsic::x86_avx2_phadd_d:
9964 case Intrinsic::x86_ssse3_phsub_w_128:
9965 case Intrinsic::x86_ssse3_phsub_d_128:
9966 case Intrinsic::x86_avx2_phsub_w:
9967 case Intrinsic::x86_avx2_phsub_d: {
9970 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9971 case Intrinsic::x86_sse3_hadd_ps:
9972 case Intrinsic::x86_sse3_hadd_pd:
9973 case Intrinsic::x86_avx_hadd_ps_256:
9974 case Intrinsic::x86_avx_hadd_pd_256:
9975 Opcode = X86ISD::FHADD;
9977 case Intrinsic::x86_sse3_hsub_ps:
9978 case Intrinsic::x86_sse3_hsub_pd:
9979 case Intrinsic::x86_avx_hsub_ps_256:
9980 case Intrinsic::x86_avx_hsub_pd_256:
9981 Opcode = X86ISD::FHSUB;
9983 case Intrinsic::x86_ssse3_phadd_w_128:
9984 case Intrinsic::x86_ssse3_phadd_d_128:
9985 case Intrinsic::x86_avx2_phadd_w:
9986 case Intrinsic::x86_avx2_phadd_d:
9987 Opcode = X86ISD::HADD;
9989 case Intrinsic::x86_ssse3_phsub_w_128:
9990 case Intrinsic::x86_ssse3_phsub_d_128:
9991 case Intrinsic::x86_avx2_phsub_w:
9992 case Intrinsic::x86_avx2_phsub_d:
9993 Opcode = X86ISD::HSUB;
9996 return DAG.getNode(Opcode, dl, Op.getValueType(),
9997 Op.getOperand(1), Op.getOperand(2));
10000 // AVX2 variable shift intrinsics
10001 case Intrinsic::x86_avx2_psllv_d:
10002 case Intrinsic::x86_avx2_psllv_q:
10003 case Intrinsic::x86_avx2_psllv_d_256:
10004 case Intrinsic::x86_avx2_psllv_q_256:
10005 case Intrinsic::x86_avx2_psrlv_d:
10006 case Intrinsic::x86_avx2_psrlv_q:
10007 case Intrinsic::x86_avx2_psrlv_d_256:
10008 case Intrinsic::x86_avx2_psrlv_q_256:
10009 case Intrinsic::x86_avx2_psrav_d:
10010 case Intrinsic::x86_avx2_psrav_d_256: {
10013 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10014 case Intrinsic::x86_avx2_psllv_d:
10015 case Intrinsic::x86_avx2_psllv_q:
10016 case Intrinsic::x86_avx2_psllv_d_256:
10017 case Intrinsic::x86_avx2_psllv_q_256:
10020 case Intrinsic::x86_avx2_psrlv_d:
10021 case Intrinsic::x86_avx2_psrlv_q:
10022 case Intrinsic::x86_avx2_psrlv_d_256:
10023 case Intrinsic::x86_avx2_psrlv_q_256:
10026 case Intrinsic::x86_avx2_psrav_d:
10027 case Intrinsic::x86_avx2_psrav_d_256:
10031 return DAG.getNode(Opcode, dl, Op.getValueType(),
10032 Op.getOperand(1), Op.getOperand(2));
10035 case Intrinsic::x86_ssse3_pshuf_b_128:
10036 case Intrinsic::x86_avx2_pshuf_b:
10037 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10038 Op.getOperand(1), Op.getOperand(2));
10040 case Intrinsic::x86_ssse3_psign_b_128:
10041 case Intrinsic::x86_ssse3_psign_w_128:
10042 case Intrinsic::x86_ssse3_psign_d_128:
10043 case Intrinsic::x86_avx2_psign_b:
10044 case Intrinsic::x86_avx2_psign_w:
10045 case Intrinsic::x86_avx2_psign_d:
10046 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10047 Op.getOperand(1), Op.getOperand(2));
10049 case Intrinsic::x86_sse41_insertps:
10050 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10051 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10053 case Intrinsic::x86_avx_vperm2f128_ps_256:
10054 case Intrinsic::x86_avx_vperm2f128_pd_256:
10055 case Intrinsic::x86_avx_vperm2f128_si_256:
10056 case Intrinsic::x86_avx2_vperm2i128:
10057 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10058 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10060 case Intrinsic::x86_avx2_permd:
10061 case Intrinsic::x86_avx2_permps:
10062 // Operands intentionally swapped. Mask is last operand to intrinsic,
10063 // but second operand for node/intruction.
10064 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10065 Op.getOperand(2), Op.getOperand(1));
10067 // ptest and testp intrinsics. The intrinsic these come from are designed to
10068 // return an integer value, not just an instruction so lower it to the ptest
10069 // or testp pattern and a setcc for the result.
10070 case Intrinsic::x86_sse41_ptestz:
10071 case Intrinsic::x86_sse41_ptestc:
10072 case Intrinsic::x86_sse41_ptestnzc:
10073 case Intrinsic::x86_avx_ptestz_256:
10074 case Intrinsic::x86_avx_ptestc_256:
10075 case Intrinsic::x86_avx_ptestnzc_256:
10076 case Intrinsic::x86_avx_vtestz_ps:
10077 case Intrinsic::x86_avx_vtestc_ps:
10078 case Intrinsic::x86_avx_vtestnzc_ps:
10079 case Intrinsic::x86_avx_vtestz_pd:
10080 case Intrinsic::x86_avx_vtestc_pd:
10081 case Intrinsic::x86_avx_vtestnzc_pd:
10082 case Intrinsic::x86_avx_vtestz_ps_256:
10083 case Intrinsic::x86_avx_vtestc_ps_256:
10084 case Intrinsic::x86_avx_vtestnzc_ps_256:
10085 case Intrinsic::x86_avx_vtestz_pd_256:
10086 case Intrinsic::x86_avx_vtestc_pd_256:
10087 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10088 bool IsTestPacked = false;
10091 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10092 case Intrinsic::x86_avx_vtestz_ps:
10093 case Intrinsic::x86_avx_vtestz_pd:
10094 case Intrinsic::x86_avx_vtestz_ps_256:
10095 case Intrinsic::x86_avx_vtestz_pd_256:
10096 IsTestPacked = true; // Fallthrough
10097 case Intrinsic::x86_sse41_ptestz:
10098 case Intrinsic::x86_avx_ptestz_256:
10100 X86CC = X86::COND_E;
10102 case Intrinsic::x86_avx_vtestc_ps:
10103 case Intrinsic::x86_avx_vtestc_pd:
10104 case Intrinsic::x86_avx_vtestc_ps_256:
10105 case Intrinsic::x86_avx_vtestc_pd_256:
10106 IsTestPacked = true; // Fallthrough
10107 case Intrinsic::x86_sse41_ptestc:
10108 case Intrinsic::x86_avx_ptestc_256:
10110 X86CC = X86::COND_B;
10112 case Intrinsic::x86_avx_vtestnzc_ps:
10113 case Intrinsic::x86_avx_vtestnzc_pd:
10114 case Intrinsic::x86_avx_vtestnzc_ps_256:
10115 case Intrinsic::x86_avx_vtestnzc_pd_256:
10116 IsTestPacked = true; // Fallthrough
10117 case Intrinsic::x86_sse41_ptestnzc:
10118 case Intrinsic::x86_avx_ptestnzc_256:
10120 X86CC = X86::COND_A;
10124 SDValue LHS = Op.getOperand(1);
10125 SDValue RHS = Op.getOperand(2);
10126 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10127 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10128 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10129 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10130 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10133 // SSE/AVX shift intrinsics
10134 case Intrinsic::x86_sse2_psll_w:
10135 case Intrinsic::x86_sse2_psll_d:
10136 case Intrinsic::x86_sse2_psll_q:
10137 case Intrinsic::x86_avx2_psll_w:
10138 case Intrinsic::x86_avx2_psll_d:
10139 case Intrinsic::x86_avx2_psll_q:
10140 case Intrinsic::x86_sse2_psrl_w:
10141 case Intrinsic::x86_sse2_psrl_d:
10142 case Intrinsic::x86_sse2_psrl_q:
10143 case Intrinsic::x86_avx2_psrl_w:
10144 case Intrinsic::x86_avx2_psrl_d:
10145 case Intrinsic::x86_avx2_psrl_q:
10146 case Intrinsic::x86_sse2_psra_w:
10147 case Intrinsic::x86_sse2_psra_d:
10148 case Intrinsic::x86_avx2_psra_w:
10149 case Intrinsic::x86_avx2_psra_d: {
10152 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10153 case Intrinsic::x86_sse2_psll_w:
10154 case Intrinsic::x86_sse2_psll_d:
10155 case Intrinsic::x86_sse2_psll_q:
10156 case Intrinsic::x86_avx2_psll_w:
10157 case Intrinsic::x86_avx2_psll_d:
10158 case Intrinsic::x86_avx2_psll_q:
10159 Opcode = X86ISD::VSHL;
10161 case Intrinsic::x86_sse2_psrl_w:
10162 case Intrinsic::x86_sse2_psrl_d:
10163 case Intrinsic::x86_sse2_psrl_q:
10164 case Intrinsic::x86_avx2_psrl_w:
10165 case Intrinsic::x86_avx2_psrl_d:
10166 case Intrinsic::x86_avx2_psrl_q:
10167 Opcode = X86ISD::VSRL;
10169 case Intrinsic::x86_sse2_psra_w:
10170 case Intrinsic::x86_sse2_psra_d:
10171 case Intrinsic::x86_avx2_psra_w:
10172 case Intrinsic::x86_avx2_psra_d:
10173 Opcode = X86ISD::VSRA;
10176 return DAG.getNode(Opcode, dl, Op.getValueType(),
10177 Op.getOperand(1), Op.getOperand(2));
10180 // SSE/AVX immediate shift intrinsics
10181 case Intrinsic::x86_sse2_pslli_w:
10182 case Intrinsic::x86_sse2_pslli_d:
10183 case Intrinsic::x86_sse2_pslli_q:
10184 case Intrinsic::x86_avx2_pslli_w:
10185 case Intrinsic::x86_avx2_pslli_d:
10186 case Intrinsic::x86_avx2_pslli_q:
10187 case Intrinsic::x86_sse2_psrli_w:
10188 case Intrinsic::x86_sse2_psrli_d:
10189 case Intrinsic::x86_sse2_psrli_q:
10190 case Intrinsic::x86_avx2_psrli_w:
10191 case Intrinsic::x86_avx2_psrli_d:
10192 case Intrinsic::x86_avx2_psrli_q:
10193 case Intrinsic::x86_sse2_psrai_w:
10194 case Intrinsic::x86_sse2_psrai_d:
10195 case Intrinsic::x86_avx2_psrai_w:
10196 case Intrinsic::x86_avx2_psrai_d: {
10199 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10200 case Intrinsic::x86_sse2_pslli_w:
10201 case Intrinsic::x86_sse2_pslli_d:
10202 case Intrinsic::x86_sse2_pslli_q:
10203 case Intrinsic::x86_avx2_pslli_w:
10204 case Intrinsic::x86_avx2_pslli_d:
10205 case Intrinsic::x86_avx2_pslli_q:
10206 Opcode = X86ISD::VSHLI;
10208 case Intrinsic::x86_sse2_psrli_w:
10209 case Intrinsic::x86_sse2_psrli_d:
10210 case Intrinsic::x86_sse2_psrli_q:
10211 case Intrinsic::x86_avx2_psrli_w:
10212 case Intrinsic::x86_avx2_psrli_d:
10213 case Intrinsic::x86_avx2_psrli_q:
10214 Opcode = X86ISD::VSRLI;
10216 case Intrinsic::x86_sse2_psrai_w:
10217 case Intrinsic::x86_sse2_psrai_d:
10218 case Intrinsic::x86_avx2_psrai_w:
10219 case Intrinsic::x86_avx2_psrai_d:
10220 Opcode = X86ISD::VSRAI;
10223 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10224 Op.getOperand(1), Op.getOperand(2), DAG);
10227 case Intrinsic::x86_sse42_pcmpistria128:
10228 case Intrinsic::x86_sse42_pcmpestria128:
10229 case Intrinsic::x86_sse42_pcmpistric128:
10230 case Intrinsic::x86_sse42_pcmpestric128:
10231 case Intrinsic::x86_sse42_pcmpistrio128:
10232 case Intrinsic::x86_sse42_pcmpestrio128:
10233 case Intrinsic::x86_sse42_pcmpistris128:
10234 case Intrinsic::x86_sse42_pcmpestris128:
10235 case Intrinsic::x86_sse42_pcmpistriz128:
10236 case Intrinsic::x86_sse42_pcmpestriz128: {
10240 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10241 case Intrinsic::x86_sse42_pcmpistria128:
10242 Opcode = X86ISD::PCMPISTRI;
10243 X86CC = X86::COND_A;
10245 case Intrinsic::x86_sse42_pcmpestria128:
10246 Opcode = X86ISD::PCMPESTRI;
10247 X86CC = X86::COND_A;
10249 case Intrinsic::x86_sse42_pcmpistric128:
10250 Opcode = X86ISD::PCMPISTRI;
10251 X86CC = X86::COND_B;
10253 case Intrinsic::x86_sse42_pcmpestric128:
10254 Opcode = X86ISD::PCMPESTRI;
10255 X86CC = X86::COND_B;
10257 case Intrinsic::x86_sse42_pcmpistrio128:
10258 Opcode = X86ISD::PCMPISTRI;
10259 X86CC = X86::COND_O;
10261 case Intrinsic::x86_sse42_pcmpestrio128:
10262 Opcode = X86ISD::PCMPESTRI;
10263 X86CC = X86::COND_O;
10265 case Intrinsic::x86_sse42_pcmpistris128:
10266 Opcode = X86ISD::PCMPISTRI;
10267 X86CC = X86::COND_S;
10269 case Intrinsic::x86_sse42_pcmpestris128:
10270 Opcode = X86ISD::PCMPESTRI;
10271 X86CC = X86::COND_S;
10273 case Intrinsic::x86_sse42_pcmpistriz128:
10274 Opcode = X86ISD::PCMPISTRI;
10275 X86CC = X86::COND_E;
10277 case Intrinsic::x86_sse42_pcmpestriz128:
10278 Opcode = X86ISD::PCMPESTRI;
10279 X86CC = X86::COND_E;
10282 SmallVector<SDValue, 5> NewOps;
10283 NewOps.append(Op->op_begin()+1, Op->op_end());
10284 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10285 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10286 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10287 DAG.getConstant(X86CC, MVT::i8),
10288 SDValue(PCMP.getNode(), 1));
10289 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10292 case Intrinsic::x86_sse42_pcmpistri128:
10293 case Intrinsic::x86_sse42_pcmpestri128: {
10295 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10296 Opcode = X86ISD::PCMPISTRI;
10298 Opcode = X86ISD::PCMPESTRI;
10300 SmallVector<SDValue, 5> NewOps;
10301 NewOps.append(Op->op_begin()+1, Op->op_end());
10302 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10303 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10305 case Intrinsic::x86_fma_vfmadd_ps:
10306 case Intrinsic::x86_fma_vfmadd_pd:
10307 case Intrinsic::x86_fma_vfmsub_ps:
10308 case Intrinsic::x86_fma_vfmsub_pd:
10309 case Intrinsic::x86_fma_vfnmadd_ps:
10310 case Intrinsic::x86_fma_vfnmadd_pd:
10311 case Intrinsic::x86_fma_vfnmsub_ps:
10312 case Intrinsic::x86_fma_vfnmsub_pd:
10313 case Intrinsic::x86_fma_vfmaddsub_ps:
10314 case Intrinsic::x86_fma_vfmaddsub_pd:
10315 case Intrinsic::x86_fma_vfmsubadd_ps:
10316 case Intrinsic::x86_fma_vfmsubadd_pd:
10317 case Intrinsic::x86_fma_vfmadd_ps_256:
10318 case Intrinsic::x86_fma_vfmadd_pd_256:
10319 case Intrinsic::x86_fma_vfmsub_ps_256:
10320 case Intrinsic::x86_fma_vfmsub_pd_256:
10321 case Intrinsic::x86_fma_vfnmadd_ps_256:
10322 case Intrinsic::x86_fma_vfnmadd_pd_256:
10323 case Intrinsic::x86_fma_vfnmsub_ps_256:
10324 case Intrinsic::x86_fma_vfnmsub_pd_256:
10325 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10326 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10327 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10328 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10331 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10332 case Intrinsic::x86_fma_vfmadd_ps:
10333 case Intrinsic::x86_fma_vfmadd_pd:
10334 case Intrinsic::x86_fma_vfmadd_ps_256:
10335 case Intrinsic::x86_fma_vfmadd_pd_256:
10336 Opc = X86ISD::FMADD;
10338 case Intrinsic::x86_fma_vfmsub_ps:
10339 case Intrinsic::x86_fma_vfmsub_pd:
10340 case Intrinsic::x86_fma_vfmsub_ps_256:
10341 case Intrinsic::x86_fma_vfmsub_pd_256:
10342 Opc = X86ISD::FMSUB;
10344 case Intrinsic::x86_fma_vfnmadd_ps:
10345 case Intrinsic::x86_fma_vfnmadd_pd:
10346 case Intrinsic::x86_fma_vfnmadd_ps_256:
10347 case Intrinsic::x86_fma_vfnmadd_pd_256:
10348 Opc = X86ISD::FNMADD;
10350 case Intrinsic::x86_fma_vfnmsub_ps:
10351 case Intrinsic::x86_fma_vfnmsub_pd:
10352 case Intrinsic::x86_fma_vfnmsub_ps_256:
10353 case Intrinsic::x86_fma_vfnmsub_pd_256:
10354 Opc = X86ISD::FNMSUB;
10356 case Intrinsic::x86_fma_vfmaddsub_ps:
10357 case Intrinsic::x86_fma_vfmaddsub_pd:
10358 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10359 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10360 Opc = X86ISD::FMADDSUB;
10362 case Intrinsic::x86_fma_vfmsubadd_ps:
10363 case Intrinsic::x86_fma_vfmsubadd_pd:
10364 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10365 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10366 Opc = X86ISD::FMSUBADD;
10370 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10371 Op.getOperand(2), Op.getOperand(3));
10376 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10377 DebugLoc dl = Op.getDebugLoc();
10378 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10380 default: return SDValue(); // Don't custom lower most intrinsics.
10382 // RDRAND intrinsics.
10383 case Intrinsic::x86_rdrand_16:
10384 case Intrinsic::x86_rdrand_32:
10385 case Intrinsic::x86_rdrand_64: {
10386 // Emit the node with the right value type.
10387 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10388 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10390 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10391 // return the value from Rand, which is always 0, casted to i32.
10392 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10393 DAG.getConstant(1, Op->getValueType(1)),
10394 DAG.getConstant(X86::COND_B, MVT::i32),
10395 SDValue(Result.getNode(), 1) };
10396 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10397 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10400 // Return { result, isValid, chain }.
10401 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10402 SDValue(Result.getNode(), 2));
10407 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10408 SelectionDAG &DAG) const {
10409 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10410 MFI->setReturnAddressIsTaken(true);
10412 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10413 DebugLoc dl = Op.getDebugLoc();
10416 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10418 DAG.getConstant(TD->getPointerSize(0),
10419 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10420 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10421 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10422 FrameAddr, Offset),
10423 MachinePointerInfo(), false, false, false, 0);
10426 // Just load the return address.
10427 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10428 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10429 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10432 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10433 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10434 MFI->setFrameAddressIsTaken(true);
10436 EVT VT = Op.getValueType();
10437 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10438 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10439 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10440 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10442 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10443 MachinePointerInfo(),
10444 false, false, false, 0);
10448 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10449 SelectionDAG &DAG) const {
10450 return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10453 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10454 SDValue Chain = Op.getOperand(0);
10455 SDValue Offset = Op.getOperand(1);
10456 SDValue Handler = Op.getOperand(2);
10457 DebugLoc dl = Op.getDebugLoc();
10459 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10460 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10462 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10464 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10465 DAG.getIntPtrConstant(TD->getPointerSize(0)));
10466 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10467 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10469 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10471 return DAG.getNode(X86ISD::EH_RETURN, dl,
10473 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10476 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10477 SelectionDAG &DAG) const {
10478 DebugLoc DL = Op.getDebugLoc();
10479 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10480 DAG.getVTList(MVT::i32, MVT::Other),
10481 Op.getOperand(0), Op.getOperand(1));
10484 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10485 SelectionDAG &DAG) const {
10486 DebugLoc DL = Op.getDebugLoc();
10487 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10488 Op.getOperand(0), Op.getOperand(1));
10491 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10492 return Op.getOperand(0);
10495 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10496 SelectionDAG &DAG) const {
10497 SDValue Root = Op.getOperand(0);
10498 SDValue Trmp = Op.getOperand(1); // trampoline
10499 SDValue FPtr = Op.getOperand(2); // nested function
10500 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10501 DebugLoc dl = Op.getDebugLoc();
10503 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10504 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10506 if (Subtarget->is64Bit()) {
10507 SDValue OutChains[6];
10509 // Large code-model.
10510 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10511 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10513 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10514 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10516 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10518 // Load the pointer to the nested function into R11.
10519 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10520 SDValue Addr = Trmp;
10521 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10522 Addr, MachinePointerInfo(TrmpAddr),
10525 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10526 DAG.getConstant(2, MVT::i64));
10527 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10528 MachinePointerInfo(TrmpAddr, 2),
10531 // Load the 'nest' parameter value into R10.
10532 // R10 is specified in X86CallingConv.td
10533 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10534 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10535 DAG.getConstant(10, MVT::i64));
10536 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10537 Addr, MachinePointerInfo(TrmpAddr, 10),
10540 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10541 DAG.getConstant(12, MVT::i64));
10542 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10543 MachinePointerInfo(TrmpAddr, 12),
10546 // Jump to the nested function.
10547 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10548 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10549 DAG.getConstant(20, MVT::i64));
10550 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10551 Addr, MachinePointerInfo(TrmpAddr, 20),
10554 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10555 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10556 DAG.getConstant(22, MVT::i64));
10557 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10558 MachinePointerInfo(TrmpAddr, 22),
10561 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10563 const Function *Func =
10564 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10565 CallingConv::ID CC = Func->getCallingConv();
10570 llvm_unreachable("Unsupported calling convention");
10571 case CallingConv::C:
10572 case CallingConv::X86_StdCall: {
10573 // Pass 'nest' parameter in ECX.
10574 // Must be kept in sync with X86CallingConv.td
10575 NestReg = X86::ECX;
10577 // Check that ECX wasn't needed by an 'inreg' parameter.
10578 FunctionType *FTy = Func->getFunctionType();
10579 const AttrListPtr &Attrs = Func->getAttributes();
10581 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10582 unsigned InRegCount = 0;
10585 for (FunctionType::param_iterator I = FTy->param_begin(),
10586 E = FTy->param_end(); I != E; ++I, ++Idx)
10587 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10588 // FIXME: should only count parameters that are lowered to integers.
10589 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10591 if (InRegCount > 2) {
10592 report_fatal_error("Nest register in use - reduce number of inreg"
10598 case CallingConv::X86_FastCall:
10599 case CallingConv::X86_ThisCall:
10600 case CallingConv::Fast:
10601 // Pass 'nest' parameter in EAX.
10602 // Must be kept in sync with X86CallingConv.td
10603 NestReg = X86::EAX;
10607 SDValue OutChains[4];
10608 SDValue Addr, Disp;
10610 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10611 DAG.getConstant(10, MVT::i32));
10612 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10614 // This is storing the opcode for MOV32ri.
10615 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10616 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10617 OutChains[0] = DAG.getStore(Root, dl,
10618 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10619 Trmp, MachinePointerInfo(TrmpAddr),
10622 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10623 DAG.getConstant(1, MVT::i32));
10624 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10625 MachinePointerInfo(TrmpAddr, 1),
10628 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10629 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10630 DAG.getConstant(5, MVT::i32));
10631 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10632 MachinePointerInfo(TrmpAddr, 5),
10635 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10636 DAG.getConstant(6, MVT::i32));
10637 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10638 MachinePointerInfo(TrmpAddr, 6),
10641 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10645 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10646 SelectionDAG &DAG) const {
10648 The rounding mode is in bits 11:10 of FPSR, and has the following
10650 00 Round to nearest
10655 FLT_ROUNDS, on the other hand, expects the following:
10662 To perform the conversion, we do:
10663 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10666 MachineFunction &MF = DAG.getMachineFunction();
10667 const TargetMachine &TM = MF.getTarget();
10668 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10669 unsigned StackAlignment = TFI.getStackAlignment();
10670 EVT VT = Op.getValueType();
10671 DebugLoc DL = Op.getDebugLoc();
10673 // Save FP Control Word to stack slot
10674 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10675 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10678 MachineMemOperand *MMO =
10679 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10680 MachineMemOperand::MOStore, 2, 2);
10682 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10683 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10684 DAG.getVTList(MVT::Other),
10685 Ops, 2, MVT::i16, MMO);
10687 // Load FP Control Word from stack slot
10688 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10689 MachinePointerInfo(), false, false, false, 0);
10691 // Transform as necessary
10693 DAG.getNode(ISD::SRL, DL, MVT::i16,
10694 DAG.getNode(ISD::AND, DL, MVT::i16,
10695 CWD, DAG.getConstant(0x800, MVT::i16)),
10696 DAG.getConstant(11, MVT::i8));
10698 DAG.getNode(ISD::SRL, DL, MVT::i16,
10699 DAG.getNode(ISD::AND, DL, MVT::i16,
10700 CWD, DAG.getConstant(0x400, MVT::i16)),
10701 DAG.getConstant(9, MVT::i8));
10704 DAG.getNode(ISD::AND, DL, MVT::i16,
10705 DAG.getNode(ISD::ADD, DL, MVT::i16,
10706 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10707 DAG.getConstant(1, MVT::i16)),
10708 DAG.getConstant(3, MVT::i16));
10711 return DAG.getNode((VT.getSizeInBits() < 16 ?
10712 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10715 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10716 EVT VT = Op.getValueType();
10718 unsigned NumBits = VT.getSizeInBits();
10719 DebugLoc dl = Op.getDebugLoc();
10721 Op = Op.getOperand(0);
10722 if (VT == MVT::i8) {
10723 // Zero extend to i32 since there is not an i8 bsr.
10725 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10728 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10729 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10730 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10732 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10735 DAG.getConstant(NumBits+NumBits-1, OpVT),
10736 DAG.getConstant(X86::COND_E, MVT::i8),
10739 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10741 // Finally xor with NumBits-1.
10742 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10745 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10749 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10750 EVT VT = Op.getValueType();
10752 unsigned NumBits = VT.getSizeInBits();
10753 DebugLoc dl = Op.getDebugLoc();
10755 Op = Op.getOperand(0);
10756 if (VT == MVT::i8) {
10757 // Zero extend to i32 since there is not an i8 bsr.
10759 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10762 // Issue a bsr (scan bits in reverse).
10763 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10764 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10766 // And xor with NumBits-1.
10767 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10770 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10774 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10775 EVT VT = Op.getValueType();
10776 unsigned NumBits = VT.getSizeInBits();
10777 DebugLoc dl = Op.getDebugLoc();
10778 Op = Op.getOperand(0);
10780 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10781 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10782 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10784 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10787 DAG.getConstant(NumBits, VT),
10788 DAG.getConstant(X86::COND_E, MVT::i8),
10791 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10794 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10795 // ones, and then concatenate the result back.
10796 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10797 EVT VT = Op.getValueType();
10799 assert(VT.is256BitVector() && VT.isInteger() &&
10800 "Unsupported value type for operation");
10802 unsigned NumElems = VT.getVectorNumElements();
10803 DebugLoc dl = Op.getDebugLoc();
10805 // Extract the LHS vectors
10806 SDValue LHS = Op.getOperand(0);
10807 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10808 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10810 // Extract the RHS vectors
10811 SDValue RHS = Op.getOperand(1);
10812 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10813 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10815 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10816 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10818 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10819 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10820 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10823 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10824 assert(Op.getValueType().is256BitVector() &&
10825 Op.getValueType().isInteger() &&
10826 "Only handle AVX 256-bit vector integer operation");
10827 return Lower256IntArith(Op, DAG);
10830 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10831 assert(Op.getValueType().is256BitVector() &&
10832 Op.getValueType().isInteger() &&
10833 "Only handle AVX 256-bit vector integer operation");
10834 return Lower256IntArith(Op, DAG);
10837 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10838 SelectionDAG &DAG) {
10839 EVT VT = Op.getValueType();
10841 // Decompose 256-bit ops into smaller 128-bit ops.
10842 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10843 return Lower256IntArith(Op, DAG);
10845 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10846 "Only know how to lower V2I64/V4I64 multiply");
10848 DebugLoc dl = Op.getDebugLoc();
10850 // Ahi = psrlqi(a, 32);
10851 // Bhi = psrlqi(b, 32);
10853 // AloBlo = pmuludq(a, b);
10854 // AloBhi = pmuludq(a, Bhi);
10855 // AhiBlo = pmuludq(Ahi, b);
10857 // AloBhi = psllqi(AloBhi, 32);
10858 // AhiBlo = psllqi(AhiBlo, 32);
10859 // return AloBlo + AloBhi + AhiBlo;
10861 SDValue A = Op.getOperand(0);
10862 SDValue B = Op.getOperand(1);
10864 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10866 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10867 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10869 // Bit cast to 32-bit vectors for MULUDQ
10870 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10871 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10872 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10873 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10874 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10876 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10877 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10878 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10880 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10881 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10883 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10884 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10887 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10889 EVT VT = Op.getValueType();
10890 DebugLoc dl = Op.getDebugLoc();
10891 SDValue R = Op.getOperand(0);
10892 SDValue Amt = Op.getOperand(1);
10893 LLVMContext *Context = DAG.getContext();
10895 if (!Subtarget->hasSSE2())
10898 // Optimize shl/srl/sra with constant shift amount.
10899 if (isSplatVector(Amt.getNode())) {
10900 SDValue SclrAmt = Amt->getOperand(0);
10901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10902 uint64_t ShiftAmt = C->getZExtValue();
10904 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10905 (Subtarget->hasAVX2() &&
10906 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10907 if (Op.getOpcode() == ISD::SHL)
10908 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10909 DAG.getConstant(ShiftAmt, MVT::i32));
10910 if (Op.getOpcode() == ISD::SRL)
10911 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10912 DAG.getConstant(ShiftAmt, MVT::i32));
10913 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10914 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10915 DAG.getConstant(ShiftAmt, MVT::i32));
10918 if (VT == MVT::v16i8) {
10919 if (Op.getOpcode() == ISD::SHL) {
10920 // Make a large shift.
10921 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10922 DAG.getConstant(ShiftAmt, MVT::i32));
10923 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10924 // Zero out the rightmost bits.
10925 SmallVector<SDValue, 16> V(16,
10926 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10928 return DAG.getNode(ISD::AND, dl, VT, SHL,
10929 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10931 if (Op.getOpcode() == ISD::SRL) {
10932 // Make a large shift.
10933 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10934 DAG.getConstant(ShiftAmt, MVT::i32));
10935 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10936 // Zero out the leftmost bits.
10937 SmallVector<SDValue, 16> V(16,
10938 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10940 return DAG.getNode(ISD::AND, dl, VT, SRL,
10941 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10943 if (Op.getOpcode() == ISD::SRA) {
10944 if (ShiftAmt == 7) {
10945 // R s>> 7 === R s< 0
10946 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10947 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10950 // R s>> a === ((R u>> a) ^ m) - m
10951 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10952 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10954 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10955 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10956 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10959 llvm_unreachable("Unknown shift opcode.");
10962 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10963 if (Op.getOpcode() == ISD::SHL) {
10964 // Make a large shift.
10965 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10966 DAG.getConstant(ShiftAmt, MVT::i32));
10967 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10968 // Zero out the rightmost bits.
10969 SmallVector<SDValue, 32> V(32,
10970 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10972 return DAG.getNode(ISD::AND, dl, VT, SHL,
10973 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10975 if (Op.getOpcode() == ISD::SRL) {
10976 // Make a large shift.
10977 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10978 DAG.getConstant(ShiftAmt, MVT::i32));
10979 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10980 // Zero out the leftmost bits.
10981 SmallVector<SDValue, 32> V(32,
10982 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10984 return DAG.getNode(ISD::AND, dl, VT, SRL,
10985 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10987 if (Op.getOpcode() == ISD::SRA) {
10988 if (ShiftAmt == 7) {
10989 // R s>> 7 === R s< 0
10990 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10991 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10994 // R s>> a === ((R u>> a) ^ m) - m
10995 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10996 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10998 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10999 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11000 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11003 llvm_unreachable("Unknown shift opcode.");
11008 // Lower SHL with variable shift amount.
11009 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11010 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11011 DAG.getConstant(23, MVT::i32));
11013 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11014 Constant *C = ConstantDataVector::get(*Context, CV);
11015 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11016 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11017 MachinePointerInfo::getConstantPool(),
11018 false, false, false, 16);
11020 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11021 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11022 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11023 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11025 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11026 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11029 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11030 DAG.getConstant(5, MVT::i32));
11031 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11033 // Turn 'a' into a mask suitable for VSELECT
11034 SDValue VSelM = DAG.getConstant(0x80, VT);
11035 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11036 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11038 SDValue CM1 = DAG.getConstant(0x0f, VT);
11039 SDValue CM2 = DAG.getConstant(0x3f, VT);
11041 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11042 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11043 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11044 DAG.getConstant(4, MVT::i32), DAG);
11045 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11046 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11049 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11050 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11051 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11053 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11054 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11055 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11056 DAG.getConstant(2, MVT::i32), DAG);
11057 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11058 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11061 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11062 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11063 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11065 // return VSELECT(r, r+r, a);
11066 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11067 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11071 // Decompose 256-bit shifts into smaller 128-bit shifts.
11072 if (VT.is256BitVector()) {
11073 unsigned NumElems = VT.getVectorNumElements();
11074 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11075 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11077 // Extract the two vectors
11078 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11079 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11081 // Recreate the shift amount vectors
11082 SDValue Amt1, Amt2;
11083 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11084 // Constant shift amount
11085 SmallVector<SDValue, 4> Amt1Csts;
11086 SmallVector<SDValue, 4> Amt2Csts;
11087 for (unsigned i = 0; i != NumElems/2; ++i)
11088 Amt1Csts.push_back(Amt->getOperand(i));
11089 for (unsigned i = NumElems/2; i != NumElems; ++i)
11090 Amt2Csts.push_back(Amt->getOperand(i));
11092 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11093 &Amt1Csts[0], NumElems/2);
11094 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11095 &Amt2Csts[0], NumElems/2);
11097 // Variable shift amount
11098 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11099 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11102 // Issue new vector shifts for the smaller types
11103 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11104 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11106 // Concatenate the result back
11107 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11113 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11114 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11115 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11116 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11117 // has only one use.
11118 SDNode *N = Op.getNode();
11119 SDValue LHS = N->getOperand(0);
11120 SDValue RHS = N->getOperand(1);
11121 unsigned BaseOp = 0;
11123 DebugLoc DL = Op.getDebugLoc();
11124 switch (Op.getOpcode()) {
11125 default: llvm_unreachable("Unknown ovf instruction!");
11127 // A subtract of one will be selected as a INC. Note that INC doesn't
11128 // set CF, so we can't do this for UADDO.
11129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11131 BaseOp = X86ISD::INC;
11132 Cond = X86::COND_O;
11135 BaseOp = X86ISD::ADD;
11136 Cond = X86::COND_O;
11139 BaseOp = X86ISD::ADD;
11140 Cond = X86::COND_B;
11143 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11144 // set CF, so we can't do this for USUBO.
11145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11147 BaseOp = X86ISD::DEC;
11148 Cond = X86::COND_O;
11151 BaseOp = X86ISD::SUB;
11152 Cond = X86::COND_O;
11155 BaseOp = X86ISD::SUB;
11156 Cond = X86::COND_B;
11159 BaseOp = X86ISD::SMUL;
11160 Cond = X86::COND_O;
11162 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11163 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11165 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11168 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11169 DAG.getConstant(X86::COND_O, MVT::i32),
11170 SDValue(Sum.getNode(), 2));
11172 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11176 // Also sets EFLAGS.
11177 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11178 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11181 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11182 DAG.getConstant(Cond, MVT::i32),
11183 SDValue(Sum.getNode(), 1));
11185 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11188 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11189 SelectionDAG &DAG) const {
11190 DebugLoc dl = Op.getDebugLoc();
11191 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11192 EVT VT = Op.getValueType();
11194 if (!Subtarget->hasSSE2() || !VT.isVector())
11197 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11198 ExtraVT.getScalarType().getSizeInBits();
11199 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11201 switch (VT.getSimpleVT().SimpleTy) {
11202 default: return SDValue();
11205 if (!Subtarget->hasAVX())
11207 if (!Subtarget->hasAVX2()) {
11208 // needs to be split
11209 unsigned NumElems = VT.getVectorNumElements();
11211 // Extract the LHS vectors
11212 SDValue LHS = Op.getOperand(0);
11213 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11214 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11216 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11217 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11219 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11220 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11221 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11223 SDValue Extra = DAG.getValueType(ExtraVT);
11225 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11226 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11228 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11233 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11234 Op.getOperand(0), ShAmt, DAG);
11235 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11241 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11242 SelectionDAG &DAG) {
11243 DebugLoc dl = Op.getDebugLoc();
11245 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11246 // There isn't any reason to disable it if the target processor supports it.
11247 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11248 SDValue Chain = Op.getOperand(0);
11249 SDValue Zero = DAG.getConstant(0, MVT::i32);
11251 DAG.getRegister(X86::ESP, MVT::i32), // Base
11252 DAG.getTargetConstant(1, MVT::i8), // Scale
11253 DAG.getRegister(0, MVT::i32), // Index
11254 DAG.getTargetConstant(0, MVT::i32), // Disp
11255 DAG.getRegister(0, MVT::i32), // Segment.
11260 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11261 array_lengthof(Ops));
11262 return SDValue(Res, 0);
11265 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11267 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11269 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11270 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11271 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11272 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11274 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11275 if (!Op1 && !Op2 && !Op3 && Op4)
11276 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11278 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11279 if (Op1 && !Op2 && !Op3 && !Op4)
11280 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11282 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11284 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11287 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11288 SelectionDAG &DAG) {
11289 DebugLoc dl = Op.getDebugLoc();
11290 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11291 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11292 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11293 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11295 // The only fence that needs an instruction is a sequentially-consistent
11296 // cross-thread fence.
11297 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11298 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11299 // no-sse2). There isn't any reason to disable it if the target processor
11301 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11302 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11304 SDValue Chain = Op.getOperand(0);
11305 SDValue Zero = DAG.getConstant(0, MVT::i32);
11307 DAG.getRegister(X86::ESP, MVT::i32), // Base
11308 DAG.getTargetConstant(1, MVT::i8), // Scale
11309 DAG.getRegister(0, MVT::i32), // Index
11310 DAG.getTargetConstant(0, MVT::i32), // Disp
11311 DAG.getRegister(0, MVT::i32), // Segment.
11316 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11317 array_lengthof(Ops));
11318 return SDValue(Res, 0);
11321 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11322 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11326 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11327 SelectionDAG &DAG) {
11328 EVT T = Op.getValueType();
11329 DebugLoc DL = Op.getDebugLoc();
11332 switch(T.getSimpleVT().SimpleTy) {
11333 default: llvm_unreachable("Invalid value type!");
11334 case MVT::i8: Reg = X86::AL; size = 1; break;
11335 case MVT::i16: Reg = X86::AX; size = 2; break;
11336 case MVT::i32: Reg = X86::EAX; size = 4; break;
11338 assert(Subtarget->is64Bit() && "Node not type legal!");
11339 Reg = X86::RAX; size = 8;
11342 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11343 Op.getOperand(2), SDValue());
11344 SDValue Ops[] = { cpIn.getValue(0),
11347 DAG.getTargetConstant(size, MVT::i8),
11348 cpIn.getValue(1) };
11349 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11350 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11351 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11354 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11358 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11359 SelectionDAG &DAG) {
11360 assert(Subtarget->is64Bit() && "Result not type legalized?");
11361 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11362 SDValue TheChain = Op.getOperand(0);
11363 DebugLoc dl = Op.getDebugLoc();
11364 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11365 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11366 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11368 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11369 DAG.getConstant(32, MVT::i8));
11371 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11374 return DAG.getMergeValues(Ops, 2, dl);
11377 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11378 EVT SrcVT = Op.getOperand(0).getValueType();
11379 EVT DstVT = Op.getValueType();
11380 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11381 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11382 assert((DstVT == MVT::i64 ||
11383 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11384 "Unexpected custom BITCAST");
11385 // i64 <=> MMX conversions are Legal.
11386 if (SrcVT==MVT::i64 && DstVT.isVector())
11388 if (DstVT==MVT::i64 && SrcVT.isVector())
11390 // MMX <=> MMX conversions are Legal.
11391 if (SrcVT.isVector() && DstVT.isVector())
11393 // All other conversions need to be expanded.
11397 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11398 SDNode *Node = Op.getNode();
11399 DebugLoc dl = Node->getDebugLoc();
11400 EVT T = Node->getValueType(0);
11401 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11402 DAG.getConstant(0, T), Node->getOperand(2));
11403 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11404 cast<AtomicSDNode>(Node)->getMemoryVT(),
11405 Node->getOperand(0),
11406 Node->getOperand(1), negOp,
11407 cast<AtomicSDNode>(Node)->getSrcValue(),
11408 cast<AtomicSDNode>(Node)->getAlignment(),
11409 cast<AtomicSDNode>(Node)->getOrdering(),
11410 cast<AtomicSDNode>(Node)->getSynchScope());
11413 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11414 SDNode *Node = Op.getNode();
11415 DebugLoc dl = Node->getDebugLoc();
11416 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11418 // Convert seq_cst store -> xchg
11419 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11420 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11421 // (The only way to get a 16-byte store is cmpxchg16b)
11422 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11423 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11424 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11425 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11426 cast<AtomicSDNode>(Node)->getMemoryVT(),
11427 Node->getOperand(0),
11428 Node->getOperand(1), Node->getOperand(2),
11429 cast<AtomicSDNode>(Node)->getMemOperand(),
11430 cast<AtomicSDNode>(Node)->getOrdering(),
11431 cast<AtomicSDNode>(Node)->getSynchScope());
11432 return Swap.getValue(1);
11434 // Other atomic stores have a simple pattern.
11438 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11439 EVT VT = Op.getNode()->getValueType(0);
11441 // Let legalize expand this if it isn't a legal type yet.
11442 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11445 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11448 bool ExtraOp = false;
11449 switch (Op.getOpcode()) {
11450 default: llvm_unreachable("Invalid code");
11451 case ISD::ADDC: Opc = X86ISD::ADD; break;
11452 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11453 case ISD::SUBC: Opc = X86ISD::SUB; break;
11454 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11458 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11460 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11461 Op.getOperand(1), Op.getOperand(2));
11464 /// LowerOperation - Provide custom lowering hooks for some operations.
11466 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11467 switch (Op.getOpcode()) {
11468 default: llvm_unreachable("Should not custom lower this!");
11469 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11470 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11471 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11472 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11473 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11474 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11475 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11476 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11477 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11478 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11479 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11480 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11481 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11482 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11483 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11484 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11485 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11486 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11487 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11488 case ISD::SHL_PARTS:
11489 case ISD::SRA_PARTS:
11490 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11491 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11492 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11493 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11494 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11495 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11496 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11497 case ISD::FABS: return LowerFABS(Op, DAG);
11498 case ISD::FNEG: return LowerFNEG(Op, DAG);
11499 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11500 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11501 case ISD::SETCC: return LowerSETCC(Op, DAG);
11502 case ISD::SELECT: return LowerSELECT(Op, DAG);
11503 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11504 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11505 case ISD::VASTART: return LowerVASTART(Op, DAG);
11506 case ISD::VAARG: return LowerVAARG(Op, DAG);
11507 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11508 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11509 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11510 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11511 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11512 case ISD::FRAME_TO_ARGS_OFFSET:
11513 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11514 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11515 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11516 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11517 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11518 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11519 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11520 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11521 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11522 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11523 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11524 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11527 case ISD::SHL: return LowerShift(Op, DAG);
11533 case ISD::UMULO: return LowerXALUO(Op, DAG);
11534 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11535 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11539 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11540 case ISD::ADD: return LowerADD(Op, DAG);
11541 case ISD::SUB: return LowerSUB(Op, DAG);
11545 static void ReplaceATOMIC_LOAD(SDNode *Node,
11546 SmallVectorImpl<SDValue> &Results,
11547 SelectionDAG &DAG) {
11548 DebugLoc dl = Node->getDebugLoc();
11549 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11551 // Convert wide load -> cmpxchg8b/cmpxchg16b
11552 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11553 // (The only way to get a 16-byte load is cmpxchg16b)
11554 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11555 SDValue Zero = DAG.getConstant(0, VT);
11556 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11557 Node->getOperand(0),
11558 Node->getOperand(1), Zero, Zero,
11559 cast<AtomicSDNode>(Node)->getMemOperand(),
11560 cast<AtomicSDNode>(Node)->getOrdering(),
11561 cast<AtomicSDNode>(Node)->getSynchScope());
11562 Results.push_back(Swap.getValue(0));
11563 Results.push_back(Swap.getValue(1));
11567 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11568 SelectionDAG &DAG, unsigned NewOp) {
11569 DebugLoc dl = Node->getDebugLoc();
11570 assert (Node->getValueType(0) == MVT::i64 &&
11571 "Only know how to expand i64 atomics");
11573 SDValue Chain = Node->getOperand(0);
11574 SDValue In1 = Node->getOperand(1);
11575 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11576 Node->getOperand(2), DAG.getIntPtrConstant(0));
11577 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11578 Node->getOperand(2), DAG.getIntPtrConstant(1));
11579 SDValue Ops[] = { Chain, In1, In2L, In2H };
11580 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11582 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11583 cast<MemSDNode>(Node)->getMemOperand());
11584 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11585 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11586 Results.push_back(Result.getValue(2));
11589 /// ReplaceNodeResults - Replace a node with an illegal result type
11590 /// with a new node built out of custom code.
11591 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11592 SmallVectorImpl<SDValue>&Results,
11593 SelectionDAG &DAG) const {
11594 DebugLoc dl = N->getDebugLoc();
11595 switch (N->getOpcode()) {
11597 llvm_unreachable("Do not know how to custom type legalize this operation!");
11598 case ISD::SIGN_EXTEND_INREG:
11603 // We don't want to expand or promote these.
11605 case ISD::FP_TO_SINT:
11606 case ISD::FP_TO_UINT: {
11607 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11609 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11612 std::pair<SDValue,SDValue> Vals =
11613 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11614 SDValue FIST = Vals.first, StackSlot = Vals.second;
11615 if (FIST.getNode() != 0) {
11616 EVT VT = N->getValueType(0);
11617 // Return a load from the stack slot.
11618 if (StackSlot.getNode() != 0)
11619 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11620 MachinePointerInfo(),
11621 false, false, false, 0));
11623 Results.push_back(FIST);
11627 case ISD::FP_ROUND: {
11628 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11629 Results.push_back(V);
11632 case ISD::READCYCLECOUNTER: {
11633 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11634 SDValue TheChain = N->getOperand(0);
11635 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11636 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11638 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11640 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11641 SDValue Ops[] = { eax, edx };
11642 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11643 Results.push_back(edx.getValue(1));
11646 case ISD::ATOMIC_CMP_SWAP: {
11647 EVT T = N->getValueType(0);
11648 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11649 bool Regs64bit = T == MVT::i128;
11650 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11651 SDValue cpInL, cpInH;
11652 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11653 DAG.getConstant(0, HalfT));
11654 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11655 DAG.getConstant(1, HalfT));
11656 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11657 Regs64bit ? X86::RAX : X86::EAX,
11659 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11660 Regs64bit ? X86::RDX : X86::EDX,
11661 cpInH, cpInL.getValue(1));
11662 SDValue swapInL, swapInH;
11663 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11664 DAG.getConstant(0, HalfT));
11665 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11666 DAG.getConstant(1, HalfT));
11667 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11668 Regs64bit ? X86::RBX : X86::EBX,
11669 swapInL, cpInH.getValue(1));
11670 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11671 Regs64bit ? X86::RCX : X86::ECX,
11672 swapInH, swapInL.getValue(1));
11673 SDValue Ops[] = { swapInH.getValue(0),
11675 swapInH.getValue(1) };
11676 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11677 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11678 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11679 X86ISD::LCMPXCHG8_DAG;
11680 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11682 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11683 Regs64bit ? X86::RAX : X86::EAX,
11684 HalfT, Result.getValue(1));
11685 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11686 Regs64bit ? X86::RDX : X86::EDX,
11687 HalfT, cpOutL.getValue(2));
11688 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11689 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11690 Results.push_back(cpOutH.getValue(1));
11693 case ISD::ATOMIC_LOAD_ADD:
11694 case ISD::ATOMIC_LOAD_AND:
11695 case ISD::ATOMIC_LOAD_NAND:
11696 case ISD::ATOMIC_LOAD_OR:
11697 case ISD::ATOMIC_LOAD_SUB:
11698 case ISD::ATOMIC_LOAD_XOR:
11699 case ISD::ATOMIC_LOAD_MAX:
11700 case ISD::ATOMIC_LOAD_MIN:
11701 case ISD::ATOMIC_LOAD_UMAX:
11702 case ISD::ATOMIC_LOAD_UMIN:
11703 case ISD::ATOMIC_SWAP: {
11705 switch (N->getOpcode()) {
11706 default: llvm_unreachable("Unexpected opcode");
11707 case ISD::ATOMIC_LOAD_ADD:
11708 Opc = X86ISD::ATOMADD64_DAG;
11710 case ISD::ATOMIC_LOAD_AND:
11711 Opc = X86ISD::ATOMAND64_DAG;
11713 case ISD::ATOMIC_LOAD_NAND:
11714 Opc = X86ISD::ATOMNAND64_DAG;
11716 case ISD::ATOMIC_LOAD_OR:
11717 Opc = X86ISD::ATOMOR64_DAG;
11719 case ISD::ATOMIC_LOAD_SUB:
11720 Opc = X86ISD::ATOMSUB64_DAG;
11722 case ISD::ATOMIC_LOAD_XOR:
11723 Opc = X86ISD::ATOMXOR64_DAG;
11725 case ISD::ATOMIC_LOAD_MAX:
11726 Opc = X86ISD::ATOMMAX64_DAG;
11728 case ISD::ATOMIC_LOAD_MIN:
11729 Opc = X86ISD::ATOMMIN64_DAG;
11731 case ISD::ATOMIC_LOAD_UMAX:
11732 Opc = X86ISD::ATOMUMAX64_DAG;
11734 case ISD::ATOMIC_LOAD_UMIN:
11735 Opc = X86ISD::ATOMUMIN64_DAG;
11737 case ISD::ATOMIC_SWAP:
11738 Opc = X86ISD::ATOMSWAP64_DAG;
11741 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11744 case ISD::ATOMIC_LOAD:
11745 ReplaceATOMIC_LOAD(N, Results, DAG);
11749 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11751 default: return NULL;
11752 case X86ISD::BSF: return "X86ISD::BSF";
11753 case X86ISD::BSR: return "X86ISD::BSR";
11754 case X86ISD::SHLD: return "X86ISD::SHLD";
11755 case X86ISD::SHRD: return "X86ISD::SHRD";
11756 case X86ISD::FAND: return "X86ISD::FAND";
11757 case X86ISD::FOR: return "X86ISD::FOR";
11758 case X86ISD::FXOR: return "X86ISD::FXOR";
11759 case X86ISD::FSRL: return "X86ISD::FSRL";
11760 case X86ISD::FILD: return "X86ISD::FILD";
11761 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11762 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11763 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11764 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11765 case X86ISD::FLD: return "X86ISD::FLD";
11766 case X86ISD::FST: return "X86ISD::FST";
11767 case X86ISD::CALL: return "X86ISD::CALL";
11768 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11769 case X86ISD::BT: return "X86ISD::BT";
11770 case X86ISD::CMP: return "X86ISD::CMP";
11771 case X86ISD::COMI: return "X86ISD::COMI";
11772 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11773 case X86ISD::SETCC: return "X86ISD::SETCC";
11774 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11775 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11776 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11777 case X86ISD::CMOV: return "X86ISD::CMOV";
11778 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11779 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11780 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11781 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11782 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11783 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11784 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11785 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11786 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11787 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11788 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11789 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11790 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11791 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11792 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11793 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11794 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11795 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11796 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11797 case X86ISD::HADD: return "X86ISD::HADD";
11798 case X86ISD::HSUB: return "X86ISD::HSUB";
11799 case X86ISD::FHADD: return "X86ISD::FHADD";
11800 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11801 case X86ISD::FMAX: return "X86ISD::FMAX";
11802 case X86ISD::FMIN: return "X86ISD::FMIN";
11803 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11804 case X86ISD::FMINC: return "X86ISD::FMINC";
11805 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11806 case X86ISD::FRCP: return "X86ISD::FRCP";
11807 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11808 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11809 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11810 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11811 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11812 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11813 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11814 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11815 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11816 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11817 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11818 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11819 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11820 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11821 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11822 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11823 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11824 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11825 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11826 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11827 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11828 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11829 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11830 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11831 case X86ISD::VSHL: return "X86ISD::VSHL";
11832 case X86ISD::VSRL: return "X86ISD::VSRL";
11833 case X86ISD::VSRA: return "X86ISD::VSRA";
11834 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11835 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11836 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11837 case X86ISD::CMPP: return "X86ISD::CMPP";
11838 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11839 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11840 case X86ISD::ADD: return "X86ISD::ADD";
11841 case X86ISD::SUB: return "X86ISD::SUB";
11842 case X86ISD::ADC: return "X86ISD::ADC";
11843 case X86ISD::SBB: return "X86ISD::SBB";
11844 case X86ISD::SMUL: return "X86ISD::SMUL";
11845 case X86ISD::UMUL: return "X86ISD::UMUL";
11846 case X86ISD::INC: return "X86ISD::INC";
11847 case X86ISD::DEC: return "X86ISD::DEC";
11848 case X86ISD::OR: return "X86ISD::OR";
11849 case X86ISD::XOR: return "X86ISD::XOR";
11850 case X86ISD::AND: return "X86ISD::AND";
11851 case X86ISD::ANDN: return "X86ISD::ANDN";
11852 case X86ISD::BLSI: return "X86ISD::BLSI";
11853 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11854 case X86ISD::BLSR: return "X86ISD::BLSR";
11855 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11856 case X86ISD::PTEST: return "X86ISD::PTEST";
11857 case X86ISD::TESTP: return "X86ISD::TESTP";
11858 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11859 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11860 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11861 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11862 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11863 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11864 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11865 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11866 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11867 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11868 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11869 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11870 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11871 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11872 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11873 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11874 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11875 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11876 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11877 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11878 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11879 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11880 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11881 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11882 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11883 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11884 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11885 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11886 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11887 case X86ISD::SAHF: return "X86ISD::SAHF";
11888 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11889 case X86ISD::FMADD: return "X86ISD::FMADD";
11890 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11891 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11892 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11893 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11894 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11898 // isLegalAddressingMode - Return true if the addressing mode represented
11899 // by AM is legal for this target, for a load/store of the specified type.
11900 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11902 // X86 supports extremely general addressing modes.
11903 CodeModel::Model M = getTargetMachine().getCodeModel();
11904 Reloc::Model R = getTargetMachine().getRelocationModel();
11906 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11907 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11912 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11914 // If a reference to this global requires an extra load, we can't fold it.
11915 if (isGlobalStubReference(GVFlags))
11918 // If BaseGV requires a register for the PIC base, we cannot also have a
11919 // BaseReg specified.
11920 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11923 // If lower 4G is not available, then we must use rip-relative addressing.
11924 if ((M != CodeModel::Small || R != Reloc::Static) &&
11925 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11929 switch (AM.Scale) {
11935 // These scales always work.
11940 // These scales are formed with basereg+scalereg. Only accept if there is
11945 default: // Other stuff never works.
11953 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11954 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11956 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11957 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11958 if (NumBits1 <= NumBits2)
11963 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11964 return Imm == (int32_t)Imm;
11967 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11968 // Can also use sub to handle negated immediates.
11969 return Imm == (int32_t)Imm;
11972 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11973 if (!VT1.isInteger() || !VT2.isInteger())
11975 unsigned NumBits1 = VT1.getSizeInBits();
11976 unsigned NumBits2 = VT2.getSizeInBits();
11977 if (NumBits1 <= NumBits2)
11982 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11983 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11984 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11987 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11988 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11989 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11992 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11993 // i16 instructions are longer (0x66 prefix) and potentially slower.
11994 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11997 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11998 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11999 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12000 /// are assumed to be legal.
12002 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12004 // Very little shuffling can be done for 64-bit vectors right now.
12005 if (VT.getSizeInBits() == 64)
12008 // FIXME: pshufb, blends, shifts.
12009 return (VT.getVectorNumElements() == 2 ||
12010 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12011 isMOVLMask(M, VT) ||
12012 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12013 isPSHUFDMask(M, VT) ||
12014 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12015 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12016 isPALIGNRMask(M, VT, Subtarget) ||
12017 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12018 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12019 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12020 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12024 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12026 unsigned NumElts = VT.getVectorNumElements();
12027 // FIXME: This collection of masks seems suspect.
12030 if (NumElts == 4 && VT.is128BitVector()) {
12031 return (isMOVLMask(Mask, VT) ||
12032 isCommutedMOVLMask(Mask, VT, true) ||
12033 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12034 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12039 //===----------------------------------------------------------------------===//
12040 // X86 Scheduler Hooks
12041 //===----------------------------------------------------------------------===//
12043 // private utility function
12045 // Get CMPXCHG opcode for the specified data type.
12046 static unsigned getCmpXChgOpcode(EVT VT) {
12047 switch (VT.getSimpleVT().SimpleTy) {
12048 case MVT::i8: return X86::LCMPXCHG8;
12049 case MVT::i16: return X86::LCMPXCHG16;
12050 case MVT::i32: return X86::LCMPXCHG32;
12051 case MVT::i64: return X86::LCMPXCHG64;
12055 llvm_unreachable("Invalid operand size!");
12058 // Get LOAD opcode for the specified data type.
12059 static unsigned getLoadOpcode(EVT VT) {
12060 switch (VT.getSimpleVT().SimpleTy) {
12061 case MVT::i8: return X86::MOV8rm;
12062 case MVT::i16: return X86::MOV16rm;
12063 case MVT::i32: return X86::MOV32rm;
12064 case MVT::i64: return X86::MOV64rm;
12068 llvm_unreachable("Invalid operand size!");
12071 // Get opcode of the non-atomic one from the specified atomic instruction.
12072 static unsigned getNonAtomicOpcode(unsigned Opc) {
12074 case X86::ATOMAND8: return X86::AND8rr;
12075 case X86::ATOMAND16: return X86::AND16rr;
12076 case X86::ATOMAND32: return X86::AND32rr;
12077 case X86::ATOMAND64: return X86::AND64rr;
12078 case X86::ATOMOR8: return X86::OR8rr;
12079 case X86::ATOMOR16: return X86::OR16rr;
12080 case X86::ATOMOR32: return X86::OR32rr;
12081 case X86::ATOMOR64: return X86::OR64rr;
12082 case X86::ATOMXOR8: return X86::XOR8rr;
12083 case X86::ATOMXOR16: return X86::XOR16rr;
12084 case X86::ATOMXOR32: return X86::XOR32rr;
12085 case X86::ATOMXOR64: return X86::XOR64rr;
12087 llvm_unreachable("Unhandled atomic-load-op opcode!");
12090 // Get opcode of the non-atomic one from the specified atomic instruction with
12092 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12093 unsigned &ExtraOpc) {
12095 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12096 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12097 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12098 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12099 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12100 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12101 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12102 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12103 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12104 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12105 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12106 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12107 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12108 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12109 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12110 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12111 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12112 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12113 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12114 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12116 llvm_unreachable("Unhandled atomic-load-op opcode!");
12119 // Get opcode of the non-atomic one from the specified atomic instruction for
12120 // 64-bit data type on 32-bit target.
12121 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12123 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12124 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12125 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12126 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12127 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12128 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12129 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12130 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12131 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12132 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12134 llvm_unreachable("Unhandled atomic-load-op opcode!");
12137 // Get opcode of the non-atomic one from the specified atomic instruction for
12138 // 64-bit data type on 32-bit target with extra opcode.
12139 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12141 unsigned &ExtraOpc) {
12143 case X86::ATOMNAND6432:
12144 ExtraOpc = X86::NOT32r;
12145 HiOpc = X86::AND32rr;
12146 return X86::AND32rr;
12148 llvm_unreachable("Unhandled atomic-load-op opcode!");
12151 // Get pseudo CMOV opcode from the specified data type.
12152 static unsigned getPseudoCMOVOpc(EVT VT) {
12153 switch (VT.getSimpleVT().SimpleTy) {
12154 case MVT::i8: return X86::CMOV_GR8;
12155 case MVT::i16: return X86::CMOV_GR16;
12156 case MVT::i32: return X86::CMOV_GR32;
12160 llvm_unreachable("Unknown CMOV opcode!");
12163 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12164 // They will be translated into a spin-loop or compare-exchange loop from
12167 // dst = atomic-fetch-op MI.addr, MI.val
12173 // EAX = LOAD MI.addr
12175 // t1 = OP MI.val, EAX
12176 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12181 MachineBasicBlock *
12182 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12183 MachineBasicBlock *MBB) const {
12184 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12185 DebugLoc DL = MI->getDebugLoc();
12187 MachineFunction *MF = MBB->getParent();
12188 MachineRegisterInfo &MRI = MF->getRegInfo();
12190 const BasicBlock *BB = MBB->getBasicBlock();
12191 MachineFunction::iterator I = MBB;
12194 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12195 "Unexpected number of operands");
12197 assert(MI->hasOneMemOperand() &&
12198 "Expected atomic-load-op to have one memoperand");
12200 // Memory Reference
12201 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12202 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12204 unsigned DstReg, SrcReg;
12205 unsigned MemOpndSlot;
12207 unsigned CurOp = 0;
12209 DstReg = MI->getOperand(CurOp++).getReg();
12210 MemOpndSlot = CurOp;
12211 CurOp += X86::AddrNumOperands;
12212 SrcReg = MI->getOperand(CurOp++).getReg();
12214 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12215 MVT::SimpleValueType VT = *RC->vt_begin();
12216 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12218 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12219 unsigned LOADOpc = getLoadOpcode(VT);
12221 // For the atomic load-arith operator, we generate
12224 // EAX = LOAD [MI.addr]
12226 // t1 = OP MI.val, EAX
12227 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12231 MachineBasicBlock *thisMBB = MBB;
12232 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12233 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12234 MF->insert(I, mainMBB);
12235 MF->insert(I, sinkMBB);
12237 MachineInstrBuilder MIB;
12239 // Transfer the remainder of BB and its successor edges to sinkMBB.
12240 sinkMBB->splice(sinkMBB->begin(), MBB,
12241 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12242 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12245 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12246 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12247 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12248 MIB.setMemRefs(MMOBegin, MMOEnd);
12250 thisMBB->addSuccessor(mainMBB);
12253 MachineBasicBlock *origMainMBB = mainMBB;
12254 mainMBB->addLiveIn(AccPhyReg);
12256 // Copy AccPhyReg as it is used more than once.
12257 unsigned AccReg = MRI.createVirtualRegister(RC);
12258 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12259 .addReg(AccPhyReg);
12261 unsigned t1 = MRI.createVirtualRegister(RC);
12262 unsigned Opc = MI->getOpcode();
12265 llvm_unreachable("Unhandled atomic-load-op opcode!");
12266 case X86::ATOMAND8:
12267 case X86::ATOMAND16:
12268 case X86::ATOMAND32:
12269 case X86::ATOMAND64:
12271 case X86::ATOMOR16:
12272 case X86::ATOMOR32:
12273 case X86::ATOMOR64:
12274 case X86::ATOMXOR8:
12275 case X86::ATOMXOR16:
12276 case X86::ATOMXOR32:
12277 case X86::ATOMXOR64: {
12278 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12279 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12283 case X86::ATOMNAND8:
12284 case X86::ATOMNAND16:
12285 case X86::ATOMNAND32:
12286 case X86::ATOMNAND64: {
12287 unsigned t2 = MRI.createVirtualRegister(RC);
12289 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12290 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12292 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12295 case X86::ATOMMAX8:
12296 case X86::ATOMMAX16:
12297 case X86::ATOMMAX32:
12298 case X86::ATOMMAX64:
12299 case X86::ATOMMIN8:
12300 case X86::ATOMMIN16:
12301 case X86::ATOMMIN32:
12302 case X86::ATOMMIN64:
12303 case X86::ATOMUMAX8:
12304 case X86::ATOMUMAX16:
12305 case X86::ATOMUMAX32:
12306 case X86::ATOMUMAX64:
12307 case X86::ATOMUMIN8:
12308 case X86::ATOMUMIN16:
12309 case X86::ATOMUMIN32:
12310 case X86::ATOMUMIN64: {
12312 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12314 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12318 if (Subtarget->hasCMov()) {
12319 if (VT != MVT::i8) {
12321 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12325 // Promote i8 to i32 to use CMOV32
12326 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12327 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12328 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12329 unsigned t2 = MRI.createVirtualRegister(RC32);
12331 unsigned Undef = MRI.createVirtualRegister(RC32);
12332 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12334 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12337 .addImm(X86::sub_8bit);
12338 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12341 .addImm(X86::sub_8bit);
12343 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12347 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12348 .addReg(t2, 0, X86::sub_8bit);
12351 // Use pseudo select and lower them.
12352 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12353 "Invalid atomic-load-op transformation!");
12354 unsigned SelOpc = getPseudoCMOVOpc(VT);
12355 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12356 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12357 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12358 .addReg(SrcReg).addReg(AccReg)
12360 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12366 // Copy AccPhyReg back from virtual register.
12367 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12370 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12371 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12372 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12374 MIB.setMemRefs(MMOBegin, MMOEnd);
12376 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12378 mainMBB->addSuccessor(origMainMBB);
12379 mainMBB->addSuccessor(sinkMBB);
12382 sinkMBB->addLiveIn(AccPhyReg);
12384 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12385 TII->get(TargetOpcode::COPY), DstReg)
12386 .addReg(AccPhyReg);
12388 MI->eraseFromParent();
12392 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12393 // instructions. They will be translated into a spin-loop or compare-exchange
12397 // dst = atomic-fetch-op MI.addr, MI.val
12403 // EAX = LOAD [MI.addr + 0]
12404 // EDX = LOAD [MI.addr + 4]
12406 // EBX = OP MI.val.lo, EAX
12407 // ECX = OP MI.val.hi, EDX
12408 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12413 MachineBasicBlock *
12414 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12415 MachineBasicBlock *MBB) const {
12416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12417 DebugLoc DL = MI->getDebugLoc();
12419 MachineFunction *MF = MBB->getParent();
12420 MachineRegisterInfo &MRI = MF->getRegInfo();
12422 const BasicBlock *BB = MBB->getBasicBlock();
12423 MachineFunction::iterator I = MBB;
12426 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12427 "Unexpected number of operands");
12429 assert(MI->hasOneMemOperand() &&
12430 "Expected atomic-load-op32 to have one memoperand");
12432 // Memory Reference
12433 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12434 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12436 unsigned DstLoReg, DstHiReg;
12437 unsigned SrcLoReg, SrcHiReg;
12438 unsigned MemOpndSlot;
12440 unsigned CurOp = 0;
12442 DstLoReg = MI->getOperand(CurOp++).getReg();
12443 DstHiReg = MI->getOperand(CurOp++).getReg();
12444 MemOpndSlot = CurOp;
12445 CurOp += X86::AddrNumOperands;
12446 SrcLoReg = MI->getOperand(CurOp++).getReg();
12447 SrcHiReg = MI->getOperand(CurOp++).getReg();
12449 const TargetRegisterClass *RC = &X86::GR32RegClass;
12450 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12452 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12453 unsigned LOADOpc = X86::MOV32rm;
12455 // For the atomic load-arith operator, we generate
12458 // EAX = LOAD [MI.addr + 0]
12459 // EDX = LOAD [MI.addr + 4]
12461 // EBX = OP MI.vallo, EAX
12462 // ECX = OP MI.valhi, EDX
12463 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12467 MachineBasicBlock *thisMBB = MBB;
12468 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12469 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12470 MF->insert(I, mainMBB);
12471 MF->insert(I, sinkMBB);
12473 MachineInstrBuilder MIB;
12475 // Transfer the remainder of BB and its successor edges to sinkMBB.
12476 sinkMBB->splice(sinkMBB->begin(), MBB,
12477 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12478 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12482 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12483 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12484 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12485 MIB.setMemRefs(MMOBegin, MMOEnd);
12487 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12488 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12489 if (i == X86::AddrDisp)
12490 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12492 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12494 MIB.setMemRefs(MMOBegin, MMOEnd);
12496 thisMBB->addSuccessor(mainMBB);
12499 MachineBasicBlock *origMainMBB = mainMBB;
12500 mainMBB->addLiveIn(X86::EAX);
12501 mainMBB->addLiveIn(X86::EDX);
12503 // Copy EDX:EAX as they are used more than once.
12504 unsigned LoReg = MRI.createVirtualRegister(RC);
12505 unsigned HiReg = MRI.createVirtualRegister(RC);
12506 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12507 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12509 unsigned t1L = MRI.createVirtualRegister(RC);
12510 unsigned t1H = MRI.createVirtualRegister(RC);
12512 unsigned Opc = MI->getOpcode();
12515 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12516 case X86::ATOMAND6432:
12517 case X86::ATOMOR6432:
12518 case X86::ATOMXOR6432:
12519 case X86::ATOMADD6432:
12520 case X86::ATOMSUB6432: {
12522 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12523 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12524 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12527 case X86::ATOMNAND6432: {
12528 unsigned HiOpc, NOTOpc;
12529 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12530 unsigned t2L = MRI.createVirtualRegister(RC);
12531 unsigned t2H = MRI.createVirtualRegister(RC);
12532 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12533 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12534 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12535 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12538 case X86::ATOMMAX6432:
12539 case X86::ATOMMIN6432:
12540 case X86::ATOMUMAX6432:
12541 case X86::ATOMUMIN6432: {
12543 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12544 unsigned cL = MRI.createVirtualRegister(RC8);
12545 unsigned cH = MRI.createVirtualRegister(RC8);
12546 unsigned cL32 = MRI.createVirtualRegister(RC);
12547 unsigned cH32 = MRI.createVirtualRegister(RC);
12548 unsigned cc = MRI.createVirtualRegister(RC);
12549 // cl := cmp src_lo, lo
12550 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12551 .addReg(SrcLoReg).addReg(LoReg);
12552 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12553 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12554 // ch := cmp src_hi, hi
12555 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12556 .addReg(SrcHiReg).addReg(HiReg);
12557 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12558 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12559 // cc := if (src_hi == hi) ? cl : ch;
12560 if (Subtarget->hasCMov()) {
12561 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12562 .addReg(cH32).addReg(cL32);
12564 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12565 .addReg(cH32).addReg(cL32)
12566 .addImm(X86::COND_E);
12567 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12569 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12570 if (Subtarget->hasCMov()) {
12571 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12572 .addReg(SrcLoReg).addReg(LoReg);
12573 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12574 .addReg(SrcHiReg).addReg(HiReg);
12576 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12577 .addReg(SrcLoReg).addReg(LoReg)
12578 .addImm(X86::COND_NE);
12579 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12580 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12581 .addReg(SrcHiReg).addReg(HiReg)
12582 .addImm(X86::COND_NE);
12583 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12587 case X86::ATOMSWAP6432: {
12589 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12590 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12591 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12596 // Copy EDX:EAX back from HiReg:LoReg
12597 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12598 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12599 // Copy ECX:EBX from t1H:t1L
12600 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12601 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12603 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12604 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12605 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12606 MIB.setMemRefs(MMOBegin, MMOEnd);
12608 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12610 mainMBB->addSuccessor(origMainMBB);
12611 mainMBB->addSuccessor(sinkMBB);
12614 sinkMBB->addLiveIn(X86::EAX);
12615 sinkMBB->addLiveIn(X86::EDX);
12617 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12618 TII->get(TargetOpcode::COPY), DstLoReg)
12620 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12621 TII->get(TargetOpcode::COPY), DstHiReg)
12624 MI->eraseFromParent();
12628 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12629 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12630 // in the .td file.
12631 MachineBasicBlock *
12632 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12633 unsigned numArgs, bool memArg) const {
12634 assert(Subtarget->hasSSE42() &&
12635 "Target must have SSE4.2 or AVX features enabled");
12637 DebugLoc dl = MI->getDebugLoc();
12638 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12640 if (!Subtarget->hasAVX()) {
12642 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12644 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12647 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12649 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12652 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12653 for (unsigned i = 0; i < numArgs; ++i) {
12654 MachineOperand &Op = MI->getOperand(i+1);
12655 if (!(Op.isReg() && Op.isImplicit()))
12656 MIB.addOperand(Op);
12658 BuildMI(*BB, MI, dl,
12659 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12660 .addReg(X86::XMM0);
12662 MI->eraseFromParent();
12666 MachineBasicBlock *
12667 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12668 DebugLoc dl = MI->getDebugLoc();
12669 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12671 // Address into RAX/EAX, other two args into ECX, EDX.
12672 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12673 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12674 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12675 for (int i = 0; i < X86::AddrNumOperands; ++i)
12676 MIB.addOperand(MI->getOperand(i));
12678 unsigned ValOps = X86::AddrNumOperands;
12679 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12680 .addReg(MI->getOperand(ValOps).getReg());
12681 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12682 .addReg(MI->getOperand(ValOps+1).getReg());
12684 // The instruction doesn't actually take any operands though.
12685 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12687 MI->eraseFromParent(); // The pseudo is gone now.
12691 MachineBasicBlock *
12692 X86TargetLowering::EmitVAARG64WithCustomInserter(
12694 MachineBasicBlock *MBB) const {
12695 // Emit va_arg instruction on X86-64.
12697 // Operands to this pseudo-instruction:
12698 // 0 ) Output : destination address (reg)
12699 // 1-5) Input : va_list address (addr, i64mem)
12700 // 6 ) ArgSize : Size (in bytes) of vararg type
12701 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12702 // 8 ) Align : Alignment of type
12703 // 9 ) EFLAGS (implicit-def)
12705 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12706 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12708 unsigned DestReg = MI->getOperand(0).getReg();
12709 MachineOperand &Base = MI->getOperand(1);
12710 MachineOperand &Scale = MI->getOperand(2);
12711 MachineOperand &Index = MI->getOperand(3);
12712 MachineOperand &Disp = MI->getOperand(4);
12713 MachineOperand &Segment = MI->getOperand(5);
12714 unsigned ArgSize = MI->getOperand(6).getImm();
12715 unsigned ArgMode = MI->getOperand(7).getImm();
12716 unsigned Align = MI->getOperand(8).getImm();
12718 // Memory Reference
12719 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12720 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12721 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12723 // Machine Information
12724 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12725 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12726 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12727 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12728 DebugLoc DL = MI->getDebugLoc();
12730 // struct va_list {
12733 // i64 overflow_area (address)
12734 // i64 reg_save_area (address)
12736 // sizeof(va_list) = 24
12737 // alignment(va_list) = 8
12739 unsigned TotalNumIntRegs = 6;
12740 unsigned TotalNumXMMRegs = 8;
12741 bool UseGPOffset = (ArgMode == 1);
12742 bool UseFPOffset = (ArgMode == 2);
12743 unsigned MaxOffset = TotalNumIntRegs * 8 +
12744 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12746 /* Align ArgSize to a multiple of 8 */
12747 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12748 bool NeedsAlign = (Align > 8);
12750 MachineBasicBlock *thisMBB = MBB;
12751 MachineBasicBlock *overflowMBB;
12752 MachineBasicBlock *offsetMBB;
12753 MachineBasicBlock *endMBB;
12755 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12756 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12757 unsigned OffsetReg = 0;
12759 if (!UseGPOffset && !UseFPOffset) {
12760 // If we only pull from the overflow region, we don't create a branch.
12761 // We don't need to alter control flow.
12762 OffsetDestReg = 0; // unused
12763 OverflowDestReg = DestReg;
12766 overflowMBB = thisMBB;
12769 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12770 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12771 // If not, pull from overflow_area. (branch to overflowMBB)
12776 // offsetMBB overflowMBB
12781 // Registers for the PHI in endMBB
12782 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12783 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12785 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12786 MachineFunction *MF = MBB->getParent();
12787 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12788 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12789 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12791 MachineFunction::iterator MBBIter = MBB;
12794 // Insert the new basic blocks
12795 MF->insert(MBBIter, offsetMBB);
12796 MF->insert(MBBIter, overflowMBB);
12797 MF->insert(MBBIter, endMBB);
12799 // Transfer the remainder of MBB and its successor edges to endMBB.
12800 endMBB->splice(endMBB->begin(), thisMBB,
12801 llvm::next(MachineBasicBlock::iterator(MI)),
12803 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12805 // Make offsetMBB and overflowMBB successors of thisMBB
12806 thisMBB->addSuccessor(offsetMBB);
12807 thisMBB->addSuccessor(overflowMBB);
12809 // endMBB is a successor of both offsetMBB and overflowMBB
12810 offsetMBB->addSuccessor(endMBB);
12811 overflowMBB->addSuccessor(endMBB);
12813 // Load the offset value into a register
12814 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12815 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12819 .addDisp(Disp, UseFPOffset ? 4 : 0)
12820 .addOperand(Segment)
12821 .setMemRefs(MMOBegin, MMOEnd);
12823 // Check if there is enough room left to pull this argument.
12824 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12826 .addImm(MaxOffset + 8 - ArgSizeA8);
12828 // Branch to "overflowMBB" if offset >= max
12829 // Fall through to "offsetMBB" otherwise
12830 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12831 .addMBB(overflowMBB);
12834 // In offsetMBB, emit code to use the reg_save_area.
12836 assert(OffsetReg != 0);
12838 // Read the reg_save_area address.
12839 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12840 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12845 .addOperand(Segment)
12846 .setMemRefs(MMOBegin, MMOEnd);
12848 // Zero-extend the offset
12849 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12850 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12853 .addImm(X86::sub_32bit);
12855 // Add the offset to the reg_save_area to get the final address.
12856 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12857 .addReg(OffsetReg64)
12858 .addReg(RegSaveReg);
12860 // Compute the offset for the next argument
12861 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12862 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12864 .addImm(UseFPOffset ? 16 : 8);
12866 // Store it back into the va_list.
12867 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12871 .addDisp(Disp, UseFPOffset ? 4 : 0)
12872 .addOperand(Segment)
12873 .addReg(NextOffsetReg)
12874 .setMemRefs(MMOBegin, MMOEnd);
12877 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12882 // Emit code to use overflow area
12885 // Load the overflow_area address into a register.
12886 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12887 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12892 .addOperand(Segment)
12893 .setMemRefs(MMOBegin, MMOEnd);
12895 // If we need to align it, do so. Otherwise, just copy the address
12896 // to OverflowDestReg.
12898 // Align the overflow address
12899 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12900 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12902 // aligned_addr = (addr + (align-1)) & ~(align-1)
12903 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12904 .addReg(OverflowAddrReg)
12907 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12909 .addImm(~(uint64_t)(Align-1));
12911 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12912 .addReg(OverflowAddrReg);
12915 // Compute the next overflow address after this argument.
12916 // (the overflow address should be kept 8-byte aligned)
12917 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12918 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12919 .addReg(OverflowDestReg)
12920 .addImm(ArgSizeA8);
12922 // Store the new overflow address.
12923 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12928 .addOperand(Segment)
12929 .addReg(NextAddrReg)
12930 .setMemRefs(MMOBegin, MMOEnd);
12932 // If we branched, emit the PHI to the front of endMBB.
12934 BuildMI(*endMBB, endMBB->begin(), DL,
12935 TII->get(X86::PHI), DestReg)
12936 .addReg(OffsetDestReg).addMBB(offsetMBB)
12937 .addReg(OverflowDestReg).addMBB(overflowMBB);
12940 // Erase the pseudo instruction
12941 MI->eraseFromParent();
12946 MachineBasicBlock *
12947 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12949 MachineBasicBlock *MBB) const {
12950 // Emit code to save XMM registers to the stack. The ABI says that the
12951 // number of registers to save is given in %al, so it's theoretically
12952 // possible to do an indirect jump trick to avoid saving all of them,
12953 // however this code takes a simpler approach and just executes all
12954 // of the stores if %al is non-zero. It's less code, and it's probably
12955 // easier on the hardware branch predictor, and stores aren't all that
12956 // expensive anyway.
12958 // Create the new basic blocks. One block contains all the XMM stores,
12959 // and one block is the final destination regardless of whether any
12960 // stores were performed.
12961 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12962 MachineFunction *F = MBB->getParent();
12963 MachineFunction::iterator MBBIter = MBB;
12965 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12966 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12967 F->insert(MBBIter, XMMSaveMBB);
12968 F->insert(MBBIter, EndMBB);
12970 // Transfer the remainder of MBB and its successor edges to EndMBB.
12971 EndMBB->splice(EndMBB->begin(), MBB,
12972 llvm::next(MachineBasicBlock::iterator(MI)),
12974 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12976 // The original block will now fall through to the XMM save block.
12977 MBB->addSuccessor(XMMSaveMBB);
12978 // The XMMSaveMBB will fall through to the end block.
12979 XMMSaveMBB->addSuccessor(EndMBB);
12981 // Now add the instructions.
12982 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12983 DebugLoc DL = MI->getDebugLoc();
12985 unsigned CountReg = MI->getOperand(0).getReg();
12986 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12987 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12989 if (!Subtarget->isTargetWin64()) {
12990 // If %al is 0, branch around the XMM save block.
12991 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12992 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12993 MBB->addSuccessor(EndMBB);
12996 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12997 // In the XMM save block, save all the XMM argument registers.
12998 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12999 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13000 MachineMemOperand *MMO =
13001 F->getMachineMemOperand(
13002 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13003 MachineMemOperand::MOStore,
13004 /*Size=*/16, /*Align=*/16);
13005 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13006 .addFrameIndex(RegSaveFrameIndex)
13007 .addImm(/*Scale=*/1)
13008 .addReg(/*IndexReg=*/0)
13009 .addImm(/*Disp=*/Offset)
13010 .addReg(/*Segment=*/0)
13011 .addReg(MI->getOperand(i).getReg())
13012 .addMemOperand(MMO);
13015 MI->eraseFromParent(); // The pseudo instruction is gone now.
13020 // The EFLAGS operand of SelectItr might be missing a kill marker
13021 // because there were multiple uses of EFLAGS, and ISel didn't know
13022 // which to mark. Figure out whether SelectItr should have had a
13023 // kill marker, and set it if it should. Returns the correct kill
13025 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13026 MachineBasicBlock* BB,
13027 const TargetRegisterInfo* TRI) {
13028 // Scan forward through BB for a use/def of EFLAGS.
13029 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13030 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13031 const MachineInstr& mi = *miI;
13032 if (mi.readsRegister(X86::EFLAGS))
13034 if (mi.definesRegister(X86::EFLAGS))
13035 break; // Should have kill-flag - update below.
13038 // If we hit the end of the block, check whether EFLAGS is live into a
13040 if (miI == BB->end()) {
13041 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13042 sEnd = BB->succ_end();
13043 sItr != sEnd; ++sItr) {
13044 MachineBasicBlock* succ = *sItr;
13045 if (succ->isLiveIn(X86::EFLAGS))
13050 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13051 // out. SelectMI should have a kill flag on EFLAGS.
13052 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13056 MachineBasicBlock *
13057 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13058 MachineBasicBlock *BB) const {
13059 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13060 DebugLoc DL = MI->getDebugLoc();
13062 // To "insert" a SELECT_CC instruction, we actually have to insert the
13063 // diamond control-flow pattern. The incoming instruction knows the
13064 // destination vreg to set, the condition code register to branch on, the
13065 // true/false values to select between, and a branch opcode to use.
13066 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13067 MachineFunction::iterator It = BB;
13073 // cmpTY ccX, r1, r2
13075 // fallthrough --> copy0MBB
13076 MachineBasicBlock *thisMBB = BB;
13077 MachineFunction *F = BB->getParent();
13078 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13079 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13080 F->insert(It, copy0MBB);
13081 F->insert(It, sinkMBB);
13083 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13084 // live into the sink and copy blocks.
13085 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13086 if (!MI->killsRegister(X86::EFLAGS) &&
13087 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13088 copy0MBB->addLiveIn(X86::EFLAGS);
13089 sinkMBB->addLiveIn(X86::EFLAGS);
13092 // Transfer the remainder of BB and its successor edges to sinkMBB.
13093 sinkMBB->splice(sinkMBB->begin(), BB,
13094 llvm::next(MachineBasicBlock::iterator(MI)),
13096 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13098 // Add the true and fallthrough blocks as its successors.
13099 BB->addSuccessor(copy0MBB);
13100 BB->addSuccessor(sinkMBB);
13102 // Create the conditional branch instruction.
13104 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13105 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13108 // %FalseValue = ...
13109 // # fallthrough to sinkMBB
13110 copy0MBB->addSuccessor(sinkMBB);
13113 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13115 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13116 TII->get(X86::PHI), MI->getOperand(0).getReg())
13117 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13118 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13120 MI->eraseFromParent(); // The pseudo instruction is gone now.
13124 MachineBasicBlock *
13125 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13126 bool Is64Bit) const {
13127 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13128 DebugLoc DL = MI->getDebugLoc();
13129 MachineFunction *MF = BB->getParent();
13130 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13132 assert(getTargetMachine().Options.EnableSegmentedStacks);
13134 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13135 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13138 // ... [Till the alloca]
13139 // If stacklet is not large enough, jump to mallocMBB
13142 // Allocate by subtracting from RSP
13143 // Jump to continueMBB
13146 // Allocate by call to runtime
13150 // [rest of original BB]
13153 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13154 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13155 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13157 MachineRegisterInfo &MRI = MF->getRegInfo();
13158 const TargetRegisterClass *AddrRegClass =
13159 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13161 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13162 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13163 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13164 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13165 sizeVReg = MI->getOperand(1).getReg(),
13166 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13168 MachineFunction::iterator MBBIter = BB;
13171 MF->insert(MBBIter, bumpMBB);
13172 MF->insert(MBBIter, mallocMBB);
13173 MF->insert(MBBIter, continueMBB);
13175 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13176 (MachineBasicBlock::iterator(MI)), BB->end());
13177 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13179 // Add code to the main basic block to check if the stack limit has been hit,
13180 // and if so, jump to mallocMBB otherwise to bumpMBB.
13181 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13182 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13183 .addReg(tmpSPVReg).addReg(sizeVReg);
13184 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13185 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13186 .addReg(SPLimitVReg);
13187 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13189 // bumpMBB simply decreases the stack pointer, since we know the current
13190 // stacklet has enough space.
13191 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13192 .addReg(SPLimitVReg);
13193 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13194 .addReg(SPLimitVReg);
13195 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13197 // Calls into a routine in libgcc to allocate more space from the heap.
13198 const uint32_t *RegMask =
13199 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13201 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13203 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13204 .addExternalSymbol("__morestack_allocate_stack_space")
13205 .addRegMask(RegMask)
13206 .addReg(X86::RDI, RegState::Implicit)
13207 .addReg(X86::RAX, RegState::ImplicitDefine);
13209 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13211 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13212 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13213 .addExternalSymbol("__morestack_allocate_stack_space")
13214 .addRegMask(RegMask)
13215 .addReg(X86::EAX, RegState::ImplicitDefine);
13219 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13222 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13223 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13224 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13226 // Set up the CFG correctly.
13227 BB->addSuccessor(bumpMBB);
13228 BB->addSuccessor(mallocMBB);
13229 mallocMBB->addSuccessor(continueMBB);
13230 bumpMBB->addSuccessor(continueMBB);
13232 // Take care of the PHI nodes.
13233 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13234 MI->getOperand(0).getReg())
13235 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13236 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13238 // Delete the original pseudo instruction.
13239 MI->eraseFromParent();
13242 return continueMBB;
13245 MachineBasicBlock *
13246 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13247 MachineBasicBlock *BB) const {
13248 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13249 DebugLoc DL = MI->getDebugLoc();
13251 assert(!Subtarget->isTargetEnvMacho());
13253 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13254 // non-trivial part is impdef of ESP.
13256 if (Subtarget->isTargetWin64()) {
13257 if (Subtarget->isTargetCygMing()) {
13258 // ___chkstk(Mingw64):
13259 // Clobbers R10, R11, RAX and EFLAGS.
13261 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13262 .addExternalSymbol("___chkstk")
13263 .addReg(X86::RAX, RegState::Implicit)
13264 .addReg(X86::RSP, RegState::Implicit)
13265 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13266 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13267 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13269 // __chkstk(MSVCRT): does not update stack pointer.
13270 // Clobbers R10, R11 and EFLAGS.
13271 // FIXME: RAX(allocated size) might be reused and not killed.
13272 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13273 .addExternalSymbol("__chkstk")
13274 .addReg(X86::RAX, RegState::Implicit)
13275 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13276 // RAX has the offset to subtracted from RSP.
13277 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13282 const char *StackProbeSymbol =
13283 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13285 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13286 .addExternalSymbol(StackProbeSymbol)
13287 .addReg(X86::EAX, RegState::Implicit)
13288 .addReg(X86::ESP, RegState::Implicit)
13289 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13290 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13291 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13294 MI->eraseFromParent(); // The pseudo instruction is gone now.
13298 MachineBasicBlock *
13299 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13300 MachineBasicBlock *BB) const {
13301 // This is pretty easy. We're taking the value that we received from
13302 // our load from the relocation, sticking it in either RDI (x86-64)
13303 // or EAX and doing an indirect call. The return value will then
13304 // be in the normal return register.
13305 const X86InstrInfo *TII
13306 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13307 DebugLoc DL = MI->getDebugLoc();
13308 MachineFunction *F = BB->getParent();
13310 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13311 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13313 // Get a register mask for the lowered call.
13314 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13315 // proper register mask.
13316 const uint32_t *RegMask =
13317 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13318 if (Subtarget->is64Bit()) {
13319 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13320 TII->get(X86::MOV64rm), X86::RDI)
13322 .addImm(0).addReg(0)
13323 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13324 MI->getOperand(3).getTargetFlags())
13326 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13327 addDirectMem(MIB, X86::RDI);
13328 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13329 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13330 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13331 TII->get(X86::MOV32rm), X86::EAX)
13333 .addImm(0).addReg(0)
13334 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13335 MI->getOperand(3).getTargetFlags())
13337 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13338 addDirectMem(MIB, X86::EAX);
13339 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13341 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13342 TII->get(X86::MOV32rm), X86::EAX)
13343 .addReg(TII->getGlobalBaseReg(F))
13344 .addImm(0).addReg(0)
13345 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13346 MI->getOperand(3).getTargetFlags())
13348 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13349 addDirectMem(MIB, X86::EAX);
13350 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13353 MI->eraseFromParent(); // The pseudo instruction is gone now.
13357 MachineBasicBlock *
13358 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13359 MachineBasicBlock *MBB) const {
13360 DebugLoc DL = MI->getDebugLoc();
13361 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13363 MachineFunction *MF = MBB->getParent();
13364 MachineRegisterInfo &MRI = MF->getRegInfo();
13366 const BasicBlock *BB = MBB->getBasicBlock();
13367 MachineFunction::iterator I = MBB;
13370 // Memory Reference
13371 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13372 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13375 unsigned MemOpndSlot = 0;
13377 unsigned CurOp = 0;
13379 DstReg = MI->getOperand(CurOp++).getReg();
13380 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13381 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13382 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13383 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13385 MemOpndSlot = CurOp;
13387 MVT PVT = getPointerTy();
13388 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13389 "Invalid Pointer Size!");
13391 // For v = setjmp(buf), we generate
13394 // buf[LabelOffset] = restoreMBB
13395 // SjLjSetup restoreMBB
13401 // v = phi(main, restore)
13406 MachineBasicBlock *thisMBB = MBB;
13407 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13408 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13409 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13410 MF->insert(I, mainMBB);
13411 MF->insert(I, sinkMBB);
13412 MF->push_back(restoreMBB);
13414 MachineInstrBuilder MIB;
13416 // Transfer the remainder of BB and its successor edges to sinkMBB.
13417 sinkMBB->splice(sinkMBB->begin(), MBB,
13418 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13419 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13422 unsigned PtrStoreOpc = 0;
13423 unsigned LabelReg = 0;
13424 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13425 Reloc::Model RM = getTargetMachine().getRelocationModel();
13426 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13427 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13429 // Prepare IP either in reg or imm.
13430 if (!UseImmLabel) {
13431 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13432 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13433 LabelReg = MRI.createVirtualRegister(PtrRC);
13434 if (Subtarget->is64Bit()) {
13435 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13439 .addMBB(restoreMBB)
13442 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13443 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13444 .addReg(XII->getGlobalBaseReg(MF))
13447 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13451 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13453 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13454 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13455 if (i == X86::AddrDisp)
13456 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13458 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13461 MIB.addReg(LabelReg);
13463 MIB.addMBB(restoreMBB);
13464 MIB.setMemRefs(MMOBegin, MMOEnd);
13466 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13467 .addMBB(restoreMBB);
13468 MIB.addRegMask(RegInfo->getNoPreservedMask());
13469 thisMBB->addSuccessor(mainMBB);
13470 thisMBB->addSuccessor(restoreMBB);
13474 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13475 mainMBB->addSuccessor(sinkMBB);
13478 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13479 TII->get(X86::PHI), DstReg)
13480 .addReg(mainDstReg).addMBB(mainMBB)
13481 .addReg(restoreDstReg).addMBB(restoreMBB);
13484 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13485 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13486 restoreMBB->addSuccessor(sinkMBB);
13488 MI->eraseFromParent();
13492 MachineBasicBlock *
13493 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13494 MachineBasicBlock *MBB) const {
13495 DebugLoc DL = MI->getDebugLoc();
13496 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13498 MachineFunction *MF = MBB->getParent();
13499 MachineRegisterInfo &MRI = MF->getRegInfo();
13501 // Memory Reference
13502 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13503 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13505 MVT PVT = getPointerTy();
13506 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13507 "Invalid Pointer Size!");
13509 const TargetRegisterClass *RC =
13510 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13511 unsigned Tmp = MRI.createVirtualRegister(RC);
13512 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13513 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13514 unsigned SP = RegInfo->getStackRegister();
13516 MachineInstrBuilder MIB;
13518 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13519 const int64_t SPOffset = 2 * PVT.getStoreSize();
13521 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13522 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13525 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13526 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13527 MIB.addOperand(MI->getOperand(i));
13528 MIB.setMemRefs(MMOBegin, MMOEnd);
13530 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13531 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13532 if (i == X86::AddrDisp)
13533 MIB.addDisp(MI->getOperand(i), LabelOffset);
13535 MIB.addOperand(MI->getOperand(i));
13537 MIB.setMemRefs(MMOBegin, MMOEnd);
13539 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13540 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13541 if (i == X86::AddrDisp)
13542 MIB.addDisp(MI->getOperand(i), SPOffset);
13544 MIB.addOperand(MI->getOperand(i));
13546 MIB.setMemRefs(MMOBegin, MMOEnd);
13548 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13550 MI->eraseFromParent();
13554 MachineBasicBlock *
13555 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13556 MachineBasicBlock *BB) const {
13557 switch (MI->getOpcode()) {
13558 default: llvm_unreachable("Unexpected instr type to insert");
13559 case X86::TAILJMPd64:
13560 case X86::TAILJMPr64:
13561 case X86::TAILJMPm64:
13562 llvm_unreachable("TAILJMP64 would not be touched here.");
13563 case X86::TCRETURNdi64:
13564 case X86::TCRETURNri64:
13565 case X86::TCRETURNmi64:
13567 case X86::WIN_ALLOCA:
13568 return EmitLoweredWinAlloca(MI, BB);
13569 case X86::SEG_ALLOCA_32:
13570 return EmitLoweredSegAlloca(MI, BB, false);
13571 case X86::SEG_ALLOCA_64:
13572 return EmitLoweredSegAlloca(MI, BB, true);
13573 case X86::TLSCall_32:
13574 case X86::TLSCall_64:
13575 return EmitLoweredTLSCall(MI, BB);
13576 case X86::CMOV_GR8:
13577 case X86::CMOV_FR32:
13578 case X86::CMOV_FR64:
13579 case X86::CMOV_V4F32:
13580 case X86::CMOV_V2F64:
13581 case X86::CMOV_V2I64:
13582 case X86::CMOV_V8F32:
13583 case X86::CMOV_V4F64:
13584 case X86::CMOV_V4I64:
13585 case X86::CMOV_GR16:
13586 case X86::CMOV_GR32:
13587 case X86::CMOV_RFP32:
13588 case X86::CMOV_RFP64:
13589 case X86::CMOV_RFP80:
13590 return EmitLoweredSelect(MI, BB);
13592 case X86::FP32_TO_INT16_IN_MEM:
13593 case X86::FP32_TO_INT32_IN_MEM:
13594 case X86::FP32_TO_INT64_IN_MEM:
13595 case X86::FP64_TO_INT16_IN_MEM:
13596 case X86::FP64_TO_INT32_IN_MEM:
13597 case X86::FP64_TO_INT64_IN_MEM:
13598 case X86::FP80_TO_INT16_IN_MEM:
13599 case X86::FP80_TO_INT32_IN_MEM:
13600 case X86::FP80_TO_INT64_IN_MEM: {
13601 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13602 DebugLoc DL = MI->getDebugLoc();
13604 // Change the floating point control register to use "round towards zero"
13605 // mode when truncating to an integer value.
13606 MachineFunction *F = BB->getParent();
13607 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13608 addFrameReference(BuildMI(*BB, MI, DL,
13609 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13611 // Load the old value of the high byte of the control word...
13613 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13614 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13617 // Set the high part to be round to zero...
13618 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13621 // Reload the modified control word now...
13622 addFrameReference(BuildMI(*BB, MI, DL,
13623 TII->get(X86::FLDCW16m)), CWFrameIdx);
13625 // Restore the memory image of control word to original value
13626 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13629 // Get the X86 opcode to use.
13631 switch (MI->getOpcode()) {
13632 default: llvm_unreachable("illegal opcode!");
13633 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13634 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13635 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13636 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13637 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13638 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13639 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13640 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13641 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13645 MachineOperand &Op = MI->getOperand(0);
13647 AM.BaseType = X86AddressMode::RegBase;
13648 AM.Base.Reg = Op.getReg();
13650 AM.BaseType = X86AddressMode::FrameIndexBase;
13651 AM.Base.FrameIndex = Op.getIndex();
13653 Op = MI->getOperand(1);
13655 AM.Scale = Op.getImm();
13656 Op = MI->getOperand(2);
13658 AM.IndexReg = Op.getImm();
13659 Op = MI->getOperand(3);
13660 if (Op.isGlobal()) {
13661 AM.GV = Op.getGlobal();
13663 AM.Disp = Op.getImm();
13665 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13666 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13668 // Reload the original control word now.
13669 addFrameReference(BuildMI(*BB, MI, DL,
13670 TII->get(X86::FLDCW16m)), CWFrameIdx);
13672 MI->eraseFromParent(); // The pseudo instruction is gone now.
13675 // String/text processing lowering.
13676 case X86::PCMPISTRM128REG:
13677 case X86::VPCMPISTRM128REG:
13678 case X86::PCMPISTRM128MEM:
13679 case X86::VPCMPISTRM128MEM:
13680 case X86::PCMPESTRM128REG:
13681 case X86::VPCMPESTRM128REG:
13682 case X86::PCMPESTRM128MEM:
13683 case X86::VPCMPESTRM128MEM: {
13686 switch (MI->getOpcode()) {
13687 default: llvm_unreachable("illegal opcode!");
13688 case X86::PCMPISTRM128REG:
13689 case X86::VPCMPISTRM128REG:
13690 NumArgs = 3; MemArg = false; break;
13691 case X86::PCMPISTRM128MEM:
13692 case X86::VPCMPISTRM128MEM:
13693 NumArgs = 3; MemArg = true; break;
13694 case X86::PCMPESTRM128REG:
13695 case X86::VPCMPESTRM128REG:
13696 NumArgs = 5; MemArg = false; break;
13697 case X86::PCMPESTRM128MEM:
13698 case X86::VPCMPESTRM128MEM:
13699 NumArgs = 5; MemArg = true; break;
13701 return EmitPCMP(MI, BB, NumArgs, MemArg);
13704 // Thread synchronization.
13706 return EmitMonitor(MI, BB);
13708 // Atomic Lowering.
13709 case X86::ATOMAND8:
13710 case X86::ATOMAND16:
13711 case X86::ATOMAND32:
13712 case X86::ATOMAND64:
13715 case X86::ATOMOR16:
13716 case X86::ATOMOR32:
13717 case X86::ATOMOR64:
13719 case X86::ATOMXOR16:
13720 case X86::ATOMXOR8:
13721 case X86::ATOMXOR32:
13722 case X86::ATOMXOR64:
13724 case X86::ATOMNAND8:
13725 case X86::ATOMNAND16:
13726 case X86::ATOMNAND32:
13727 case X86::ATOMNAND64:
13729 case X86::ATOMMAX8:
13730 case X86::ATOMMAX16:
13731 case X86::ATOMMAX32:
13732 case X86::ATOMMAX64:
13734 case X86::ATOMMIN8:
13735 case X86::ATOMMIN16:
13736 case X86::ATOMMIN32:
13737 case X86::ATOMMIN64:
13739 case X86::ATOMUMAX8:
13740 case X86::ATOMUMAX16:
13741 case X86::ATOMUMAX32:
13742 case X86::ATOMUMAX64:
13744 case X86::ATOMUMIN8:
13745 case X86::ATOMUMIN16:
13746 case X86::ATOMUMIN32:
13747 case X86::ATOMUMIN64:
13748 return EmitAtomicLoadArith(MI, BB);
13750 // This group does 64-bit operations on a 32-bit host.
13751 case X86::ATOMAND6432:
13752 case X86::ATOMOR6432:
13753 case X86::ATOMXOR6432:
13754 case X86::ATOMNAND6432:
13755 case X86::ATOMADD6432:
13756 case X86::ATOMSUB6432:
13757 case X86::ATOMMAX6432:
13758 case X86::ATOMMIN6432:
13759 case X86::ATOMUMAX6432:
13760 case X86::ATOMUMIN6432:
13761 case X86::ATOMSWAP6432:
13762 return EmitAtomicLoadArith6432(MI, BB);
13764 case X86::VASTART_SAVE_XMM_REGS:
13765 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13767 case X86::VAARG_64:
13768 return EmitVAARG64WithCustomInserter(MI, BB);
13770 case X86::EH_SjLj_SetJmp32:
13771 case X86::EH_SjLj_SetJmp64:
13772 return emitEHSjLjSetJmp(MI, BB);
13774 case X86::EH_SjLj_LongJmp32:
13775 case X86::EH_SjLj_LongJmp64:
13776 return emitEHSjLjLongJmp(MI, BB);
13780 //===----------------------------------------------------------------------===//
13781 // X86 Optimization Hooks
13782 //===----------------------------------------------------------------------===//
13784 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13787 const SelectionDAG &DAG,
13788 unsigned Depth) const {
13789 unsigned BitWidth = KnownZero.getBitWidth();
13790 unsigned Opc = Op.getOpcode();
13791 assert((Opc >= ISD::BUILTIN_OP_END ||
13792 Opc == ISD::INTRINSIC_WO_CHAIN ||
13793 Opc == ISD::INTRINSIC_W_CHAIN ||
13794 Opc == ISD::INTRINSIC_VOID) &&
13795 "Should use MaskedValueIsZero if you don't know whether Op"
13796 " is a target node!");
13798 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13812 // These nodes' second result is a boolean.
13813 if (Op.getResNo() == 0)
13816 case X86ISD::SETCC:
13817 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13819 case ISD::INTRINSIC_WO_CHAIN: {
13820 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13821 unsigned NumLoBits = 0;
13824 case Intrinsic::x86_sse_movmsk_ps:
13825 case Intrinsic::x86_avx_movmsk_ps_256:
13826 case Intrinsic::x86_sse2_movmsk_pd:
13827 case Intrinsic::x86_avx_movmsk_pd_256:
13828 case Intrinsic::x86_mmx_pmovmskb:
13829 case Intrinsic::x86_sse2_pmovmskb_128:
13830 case Intrinsic::x86_avx2_pmovmskb: {
13831 // High bits of movmskp{s|d}, pmovmskb are known zero.
13833 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13834 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13835 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13836 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13837 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13838 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13839 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13840 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13842 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13851 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13852 unsigned Depth) const {
13853 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13854 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13855 return Op.getValueType().getScalarType().getSizeInBits();
13861 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13862 /// node is a GlobalAddress + offset.
13863 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13864 const GlobalValue* &GA,
13865 int64_t &Offset) const {
13866 if (N->getOpcode() == X86ISD::Wrapper) {
13867 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13868 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13869 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13873 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13876 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13877 /// same as extracting the high 128-bit part of 256-bit vector and then
13878 /// inserting the result into the low part of a new 256-bit vector
13879 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13880 EVT VT = SVOp->getValueType(0);
13881 unsigned NumElems = VT.getVectorNumElements();
13883 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13884 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13885 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13886 SVOp->getMaskElt(j) >= 0)
13892 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13893 /// same as extracting the low 128-bit part of 256-bit vector and then
13894 /// inserting the result into the high part of a new 256-bit vector
13895 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13896 EVT VT = SVOp->getValueType(0);
13897 unsigned NumElems = VT.getVectorNumElements();
13899 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13900 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13901 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13902 SVOp->getMaskElt(j) >= 0)
13908 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13909 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13910 TargetLowering::DAGCombinerInfo &DCI,
13911 const X86Subtarget* Subtarget) {
13912 DebugLoc dl = N->getDebugLoc();
13913 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13914 SDValue V1 = SVOp->getOperand(0);
13915 SDValue V2 = SVOp->getOperand(1);
13916 EVT VT = SVOp->getValueType(0);
13917 unsigned NumElems = VT.getVectorNumElements();
13919 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13920 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13924 // V UNDEF BUILD_VECTOR UNDEF
13926 // CONCAT_VECTOR CONCAT_VECTOR
13929 // RESULT: V + zero extended
13931 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13932 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13933 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13936 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13939 // To match the shuffle mask, the first half of the mask should
13940 // be exactly the first vector, and all the rest a splat with the
13941 // first element of the second one.
13942 for (unsigned i = 0; i != NumElems/2; ++i)
13943 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13944 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13947 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13948 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13949 if (Ld->hasNUsesOfValue(1, 0)) {
13950 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13951 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13953 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13955 Ld->getPointerInfo(),
13956 Ld->getAlignment(),
13957 false/*isVolatile*/, true/*ReadMem*/,
13958 false/*WriteMem*/);
13959 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13963 // Emit a zeroed vector and insert the desired subvector on its
13965 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13966 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13967 return DCI.CombineTo(N, InsV);
13970 //===--------------------------------------------------------------------===//
13971 // Combine some shuffles into subvector extracts and inserts:
13974 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13975 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13976 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13977 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13978 return DCI.CombineTo(N, InsV);
13981 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13982 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13983 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13984 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13985 return DCI.CombineTo(N, InsV);
13991 /// PerformShuffleCombine - Performs several different shuffle combines.
13992 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13993 TargetLowering::DAGCombinerInfo &DCI,
13994 const X86Subtarget *Subtarget) {
13995 DebugLoc dl = N->getDebugLoc();
13996 EVT VT = N->getValueType(0);
13998 // Don't create instructions with illegal types after legalize types has run.
13999 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14000 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14003 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14004 if (Subtarget->hasAVX() && VT.is256BitVector() &&
14005 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14006 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14008 // Only handle 128 wide vector from here on.
14009 if (!VT.is128BitVector())
14012 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14013 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14014 // consecutive, non-overlapping, and in the right order.
14015 SmallVector<SDValue, 16> Elts;
14016 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14017 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14019 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14023 /// PerformTruncateCombine - Converts truncate operation to
14024 /// a sequence of vector shuffle operations.
14025 /// It is possible when we truncate 256-bit vector to 128-bit vector
14026 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14027 TargetLowering::DAGCombinerInfo &DCI,
14028 const X86Subtarget *Subtarget) {
14029 if (!DCI.isBeforeLegalizeOps())
14032 if (!Subtarget->hasAVX())
14035 EVT VT = N->getValueType(0);
14036 SDValue Op = N->getOperand(0);
14037 EVT OpVT = Op.getValueType();
14038 DebugLoc dl = N->getDebugLoc();
14040 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14042 if (Subtarget->hasAVX2()) {
14043 // AVX2: v4i64 -> v4i32
14046 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14048 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14049 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14052 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14053 DAG.getIntPtrConstant(0));
14056 // AVX: v4i64 -> v4i32
14057 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14058 DAG.getIntPtrConstant(0));
14060 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14061 DAG.getIntPtrConstant(2));
14063 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14064 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14067 static const int ShufMask1[] = {0, 2, 0, 0};
14069 SDValue Undef = DAG.getUNDEF(VT);
14070 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14071 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14074 static const int ShufMask2[] = {0, 1, 4, 5};
14076 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14079 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14081 if (Subtarget->hasAVX2()) {
14082 // AVX2: v8i32 -> v8i16
14084 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14087 SmallVector<SDValue,32> pshufbMask;
14088 for (unsigned i = 0; i < 2; ++i) {
14089 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14090 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14091 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14092 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14093 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14094 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14095 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14096 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14097 for (unsigned j = 0; j < 8; ++j)
14098 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14100 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14101 &pshufbMask[0], 32);
14102 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14104 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14106 static const int ShufMask[] = {0, 2, -1, -1};
14107 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14110 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14111 DAG.getIntPtrConstant(0));
14113 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14116 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14117 DAG.getIntPtrConstant(0));
14119 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14120 DAG.getIntPtrConstant(4));
14122 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14123 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14126 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14127 -1, -1, -1, -1, -1, -1, -1, -1};
14129 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14130 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14131 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14133 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14134 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14137 static const int ShufMask2[] = {0, 1, 4, 5};
14139 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14140 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14146 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14147 /// specific shuffle of a load can be folded into a single element load.
14148 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14149 /// shuffles have been customed lowered so we need to handle those here.
14150 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14151 TargetLowering::DAGCombinerInfo &DCI) {
14152 if (DCI.isBeforeLegalizeOps())
14155 SDValue InVec = N->getOperand(0);
14156 SDValue EltNo = N->getOperand(1);
14158 if (!isa<ConstantSDNode>(EltNo))
14161 EVT VT = InVec.getValueType();
14163 bool HasShuffleIntoBitcast = false;
14164 if (InVec.getOpcode() == ISD::BITCAST) {
14165 // Don't duplicate a load with other uses.
14166 if (!InVec.hasOneUse())
14168 EVT BCVT = InVec.getOperand(0).getValueType();
14169 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14171 InVec = InVec.getOperand(0);
14172 HasShuffleIntoBitcast = true;
14175 if (!isTargetShuffle(InVec.getOpcode()))
14178 // Don't duplicate a load with other uses.
14179 if (!InVec.hasOneUse())
14182 SmallVector<int, 16> ShuffleMask;
14184 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14188 // Select the input vector, guarding against out of range extract vector.
14189 unsigned NumElems = VT.getVectorNumElements();
14190 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14191 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14192 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14193 : InVec.getOperand(1);
14195 // If inputs to shuffle are the same for both ops, then allow 2 uses
14196 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14198 if (LdNode.getOpcode() == ISD::BITCAST) {
14199 // Don't duplicate a load with other uses.
14200 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14203 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14204 LdNode = LdNode.getOperand(0);
14207 if (!ISD::isNormalLoad(LdNode.getNode()))
14210 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14212 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14215 if (HasShuffleIntoBitcast) {
14216 // If there's a bitcast before the shuffle, check if the load type and
14217 // alignment is valid.
14218 unsigned Align = LN0->getAlignment();
14219 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14220 unsigned NewAlign = TLI.getDataLayout()->
14221 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14223 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14227 // All checks match so transform back to vector_shuffle so that DAG combiner
14228 // can finish the job
14229 DebugLoc dl = N->getDebugLoc();
14231 // Create shuffle node taking into account the case that its a unary shuffle
14232 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14233 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14234 InVec.getOperand(0), Shuffle,
14236 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14237 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14241 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14242 /// generation and convert it from being a bunch of shuffles and extracts
14243 /// to a simple store and scalar loads to extract the elements.
14244 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14245 TargetLowering::DAGCombinerInfo &DCI) {
14246 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14247 if (NewOp.getNode())
14250 SDValue InputVector = N->getOperand(0);
14252 // Only operate on vectors of 4 elements, where the alternative shuffling
14253 // gets to be more expensive.
14254 if (InputVector.getValueType() != MVT::v4i32)
14257 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14258 // single use which is a sign-extend or zero-extend, and all elements are
14260 SmallVector<SDNode *, 4> Uses;
14261 unsigned ExtractedElements = 0;
14262 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14263 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14264 if (UI.getUse().getResNo() != InputVector.getResNo())
14267 SDNode *Extract = *UI;
14268 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14271 if (Extract->getValueType(0) != MVT::i32)
14273 if (!Extract->hasOneUse())
14275 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14276 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14278 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14281 // Record which element was extracted.
14282 ExtractedElements |=
14283 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14285 Uses.push_back(Extract);
14288 // If not all the elements were used, this may not be worthwhile.
14289 if (ExtractedElements != 15)
14292 // Ok, we've now decided to do the transformation.
14293 DebugLoc dl = InputVector.getDebugLoc();
14295 // Store the value to a temporary stack slot.
14296 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14297 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14298 MachinePointerInfo(), false, false, 0);
14300 // Replace each use (extract) with a load of the appropriate element.
14301 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14302 UE = Uses.end(); UI != UE; ++UI) {
14303 SDNode *Extract = *UI;
14305 // cOMpute the element's address.
14306 SDValue Idx = Extract->getOperand(1);
14308 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14309 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14310 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14311 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14313 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14314 StackPtr, OffsetVal);
14316 // Load the scalar.
14317 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14318 ScalarAddr, MachinePointerInfo(),
14319 false, false, false, 0);
14321 // Replace the exact with the load.
14322 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14325 // The replacement was made in place; don't return anything.
14329 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14331 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14332 TargetLowering::DAGCombinerInfo &DCI,
14333 const X86Subtarget *Subtarget) {
14334 DebugLoc DL = N->getDebugLoc();
14335 SDValue Cond = N->getOperand(0);
14336 // Get the LHS/RHS of the select.
14337 SDValue LHS = N->getOperand(1);
14338 SDValue RHS = N->getOperand(2);
14339 EVT VT = LHS.getValueType();
14341 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14342 // instructions match the semantics of the common C idiom x<y?x:y but not
14343 // x<=y?x:y, because of how they handle negative zero (which can be
14344 // ignored in unsafe-math mode).
14345 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14346 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14347 (Subtarget->hasSSE2() ||
14348 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14349 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14351 unsigned Opcode = 0;
14352 // Check for x CC y ? x : y.
14353 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14354 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14358 // Converting this to a min would handle NaNs incorrectly, and swapping
14359 // the operands would cause it to handle comparisons between positive
14360 // and negative zero incorrectly.
14361 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14362 if (!DAG.getTarget().Options.UnsafeFPMath &&
14363 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14365 std::swap(LHS, RHS);
14367 Opcode = X86ISD::FMIN;
14370 // Converting this to a min would handle comparisons between positive
14371 // and negative zero incorrectly.
14372 if (!DAG.getTarget().Options.UnsafeFPMath &&
14373 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14375 Opcode = X86ISD::FMIN;
14378 // Converting this to a min would handle both negative zeros and NaNs
14379 // incorrectly, but we can swap the operands to fix both.
14380 std::swap(LHS, RHS);
14384 Opcode = X86ISD::FMIN;
14388 // Converting this to a max would handle comparisons between positive
14389 // and negative zero incorrectly.
14390 if (!DAG.getTarget().Options.UnsafeFPMath &&
14391 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14393 Opcode = X86ISD::FMAX;
14396 // Converting this to a max would handle NaNs incorrectly, and swapping
14397 // the operands would cause it to handle comparisons between positive
14398 // and negative zero incorrectly.
14399 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14400 if (!DAG.getTarget().Options.UnsafeFPMath &&
14401 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14403 std::swap(LHS, RHS);
14405 Opcode = X86ISD::FMAX;
14408 // Converting this to a max would handle both negative zeros and NaNs
14409 // incorrectly, but we can swap the operands to fix both.
14410 std::swap(LHS, RHS);
14414 Opcode = X86ISD::FMAX;
14417 // Check for x CC y ? y : x -- a min/max with reversed arms.
14418 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14419 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14423 // Converting this to a min would handle comparisons between positive
14424 // and negative zero incorrectly, and swapping the operands would
14425 // cause it to handle NaNs incorrectly.
14426 if (!DAG.getTarget().Options.UnsafeFPMath &&
14427 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14428 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14430 std::swap(LHS, RHS);
14432 Opcode = X86ISD::FMIN;
14435 // Converting this to a min would handle NaNs incorrectly.
14436 if (!DAG.getTarget().Options.UnsafeFPMath &&
14437 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14439 Opcode = X86ISD::FMIN;
14442 // Converting this to a min would handle both negative zeros and NaNs
14443 // incorrectly, but we can swap the operands to fix both.
14444 std::swap(LHS, RHS);
14448 Opcode = X86ISD::FMIN;
14452 // Converting this to a max would handle NaNs incorrectly.
14453 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14455 Opcode = X86ISD::FMAX;
14458 // Converting this to a max would handle comparisons between positive
14459 // and negative zero incorrectly, and swapping the operands would
14460 // cause it to handle NaNs incorrectly.
14461 if (!DAG.getTarget().Options.UnsafeFPMath &&
14462 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14463 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14465 std::swap(LHS, RHS);
14467 Opcode = X86ISD::FMAX;
14470 // Converting this to a max would handle both negative zeros and NaNs
14471 // incorrectly, but we can swap the operands to fix both.
14472 std::swap(LHS, RHS);
14476 Opcode = X86ISD::FMAX;
14482 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14485 // If this is a select between two integer constants, try to do some
14487 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14488 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14489 // Don't do this for crazy integer types.
14490 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14491 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14492 // so that TrueC (the true value) is larger than FalseC.
14493 bool NeedsCondInvert = false;
14495 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14496 // Efficiently invertible.
14497 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14498 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14499 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14500 NeedsCondInvert = true;
14501 std::swap(TrueC, FalseC);
14504 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14505 if (FalseC->getAPIntValue() == 0 &&
14506 TrueC->getAPIntValue().isPowerOf2()) {
14507 if (NeedsCondInvert) // Invert the condition if needed.
14508 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14509 DAG.getConstant(1, Cond.getValueType()));
14511 // Zero extend the condition if needed.
14512 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14514 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14515 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14516 DAG.getConstant(ShAmt, MVT::i8));
14519 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14520 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14521 if (NeedsCondInvert) // Invert the condition if needed.
14522 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14523 DAG.getConstant(1, Cond.getValueType()));
14525 // Zero extend the condition if needed.
14526 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14527 FalseC->getValueType(0), Cond);
14528 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14529 SDValue(FalseC, 0));
14532 // Optimize cases that will turn into an LEA instruction. This requires
14533 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14534 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14535 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14536 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14538 bool isFastMultiplier = false;
14540 switch ((unsigned char)Diff) {
14542 case 1: // result = add base, cond
14543 case 2: // result = lea base( , cond*2)
14544 case 3: // result = lea base(cond, cond*2)
14545 case 4: // result = lea base( , cond*4)
14546 case 5: // result = lea base(cond, cond*4)
14547 case 8: // result = lea base( , cond*8)
14548 case 9: // result = lea base(cond, cond*8)
14549 isFastMultiplier = true;
14554 if (isFastMultiplier) {
14555 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14556 if (NeedsCondInvert) // Invert the condition if needed.
14557 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14558 DAG.getConstant(1, Cond.getValueType()));
14560 // Zero extend the condition if needed.
14561 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14563 // Scale the condition by the difference.
14565 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14566 DAG.getConstant(Diff, Cond.getValueType()));
14568 // Add the base if non-zero.
14569 if (FalseC->getAPIntValue() != 0)
14570 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14571 SDValue(FalseC, 0));
14578 // Canonicalize max and min:
14579 // (x > y) ? x : y -> (x >= y) ? x : y
14580 // (x < y) ? x : y -> (x <= y) ? x : y
14581 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14582 // the need for an extra compare
14583 // against zero. e.g.
14584 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14586 // testl %edi, %edi
14588 // cmovgl %edi, %eax
14592 // cmovsl %eax, %edi
14593 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14594 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14595 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14596 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14601 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14602 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14603 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14604 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14609 // If we know that this node is legal then we know that it is going to be
14610 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14611 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14612 // to simplify previous instructions.
14613 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14614 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14615 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14616 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14618 // Don't optimize vector selects that map to mask-registers.
14622 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14623 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14625 APInt KnownZero, KnownOne;
14626 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14627 DCI.isBeforeLegalizeOps());
14628 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14629 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14630 DCI.CommitTargetLoweringOpt(TLO);
14636 // Check whether a boolean test is testing a boolean value generated by
14637 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14640 // Simplify the following patterns:
14641 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14642 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14643 // to (Op EFLAGS Cond)
14645 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14646 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14647 // to (Op EFLAGS !Cond)
14649 // where Op could be BRCOND or CMOV.
14651 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14652 // Quit if not CMP and SUB with its value result used.
14653 if (Cmp.getOpcode() != X86ISD::CMP &&
14654 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14657 // Quit if not used as a boolean value.
14658 if (CC != X86::COND_E && CC != X86::COND_NE)
14661 // Check CMP operands. One of them should be 0 or 1 and the other should be
14662 // an SetCC or extended from it.
14663 SDValue Op1 = Cmp.getOperand(0);
14664 SDValue Op2 = Cmp.getOperand(1);
14667 const ConstantSDNode* C = 0;
14668 bool needOppositeCond = (CC == X86::COND_E);
14670 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14672 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14674 else // Quit if all operands are not constants.
14677 if (C->getZExtValue() == 1)
14678 needOppositeCond = !needOppositeCond;
14679 else if (C->getZExtValue() != 0)
14680 // Quit if the constant is neither 0 or 1.
14683 // Skip 'zext' node.
14684 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14685 SetCC = SetCC.getOperand(0);
14687 switch (SetCC.getOpcode()) {
14688 case X86ISD::SETCC:
14689 // Set the condition code or opposite one if necessary.
14690 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14691 if (needOppositeCond)
14692 CC = X86::GetOppositeBranchCondition(CC);
14693 return SetCC.getOperand(1);
14694 case X86ISD::CMOV: {
14695 // Check whether false/true value has canonical one, i.e. 0 or 1.
14696 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14697 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14698 // Quit if true value is not a constant.
14701 // Quit if false value is not a constant.
14703 // A special case for rdrand, where 0 is set if false cond is found.
14704 SDValue Op = SetCC.getOperand(0);
14705 if (Op.getOpcode() != X86ISD::RDRAND)
14708 // Quit if false value is not the constant 0 or 1.
14709 bool FValIsFalse = true;
14710 if (FVal && FVal->getZExtValue() != 0) {
14711 if (FVal->getZExtValue() != 1)
14713 // If FVal is 1, opposite cond is needed.
14714 needOppositeCond = !needOppositeCond;
14715 FValIsFalse = false;
14717 // Quit if TVal is not the constant opposite of FVal.
14718 if (FValIsFalse && TVal->getZExtValue() != 1)
14720 if (!FValIsFalse && TVal->getZExtValue() != 0)
14722 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14723 if (needOppositeCond)
14724 CC = X86::GetOppositeBranchCondition(CC);
14725 return SetCC.getOperand(3);
14732 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14733 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14734 TargetLowering::DAGCombinerInfo &DCI,
14735 const X86Subtarget *Subtarget) {
14736 DebugLoc DL = N->getDebugLoc();
14738 // If the flag operand isn't dead, don't touch this CMOV.
14739 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14742 SDValue FalseOp = N->getOperand(0);
14743 SDValue TrueOp = N->getOperand(1);
14744 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14745 SDValue Cond = N->getOperand(3);
14747 if (CC == X86::COND_E || CC == X86::COND_NE) {
14748 switch (Cond.getOpcode()) {
14752 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14753 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14754 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14760 Flags = checkBoolTestSetCCCombine(Cond, CC);
14761 if (Flags.getNode() &&
14762 // Extra check as FCMOV only supports a subset of X86 cond.
14763 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14764 SDValue Ops[] = { FalseOp, TrueOp,
14765 DAG.getConstant(CC, MVT::i8), Flags };
14766 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14767 Ops, array_lengthof(Ops));
14770 // If this is a select between two integer constants, try to do some
14771 // optimizations. Note that the operands are ordered the opposite of SELECT
14773 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14774 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14775 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14776 // larger than FalseC (the false value).
14777 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14778 CC = X86::GetOppositeBranchCondition(CC);
14779 std::swap(TrueC, FalseC);
14780 std::swap(TrueOp, FalseOp);
14783 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14784 // This is efficient for any integer data type (including i8/i16) and
14786 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14787 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14788 DAG.getConstant(CC, MVT::i8), Cond);
14790 // Zero extend the condition if needed.
14791 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14793 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14794 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14795 DAG.getConstant(ShAmt, MVT::i8));
14796 if (N->getNumValues() == 2) // Dead flag value?
14797 return DCI.CombineTo(N, Cond, SDValue());
14801 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14802 // for any integer data type, including i8/i16.
14803 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14804 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14805 DAG.getConstant(CC, MVT::i8), Cond);
14807 // Zero extend the condition if needed.
14808 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14809 FalseC->getValueType(0), Cond);
14810 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14811 SDValue(FalseC, 0));
14813 if (N->getNumValues() == 2) // Dead flag value?
14814 return DCI.CombineTo(N, Cond, SDValue());
14818 // Optimize cases that will turn into an LEA instruction. This requires
14819 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14820 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14821 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14822 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14824 bool isFastMultiplier = false;
14826 switch ((unsigned char)Diff) {
14828 case 1: // result = add base, cond
14829 case 2: // result = lea base( , cond*2)
14830 case 3: // result = lea base(cond, cond*2)
14831 case 4: // result = lea base( , cond*4)
14832 case 5: // result = lea base(cond, cond*4)
14833 case 8: // result = lea base( , cond*8)
14834 case 9: // result = lea base(cond, cond*8)
14835 isFastMultiplier = true;
14840 if (isFastMultiplier) {
14841 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14842 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14843 DAG.getConstant(CC, MVT::i8), Cond);
14844 // Zero extend the condition if needed.
14845 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14847 // Scale the condition by the difference.
14849 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14850 DAG.getConstant(Diff, Cond.getValueType()));
14852 // Add the base if non-zero.
14853 if (FalseC->getAPIntValue() != 0)
14854 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14855 SDValue(FalseC, 0));
14856 if (N->getNumValues() == 2) // Dead flag value?
14857 return DCI.CombineTo(N, Cond, SDValue());
14864 // Handle these cases:
14865 // (select (x != c), e, c) -> select (x != c), e, x),
14866 // (select (x == c), c, e) -> select (x == c), x, e)
14867 // where the c is an integer constant, and the "select" is the combination
14868 // of CMOV and CMP.
14870 // The rationale for this change is that the conditional-move from a constant
14871 // needs two instructions, however, conditional-move from a register needs
14872 // only one instruction.
14874 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14875 // some instruction-combining opportunities. This opt needs to be
14876 // postponed as late as possible.
14878 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14879 // the DCI.xxxx conditions are provided to postpone the optimization as
14880 // late as possible.
14882 ConstantSDNode *CmpAgainst = 0;
14883 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14884 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14885 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14887 if (CC == X86::COND_NE &&
14888 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14889 CC = X86::GetOppositeBranchCondition(CC);
14890 std::swap(TrueOp, FalseOp);
14893 if (CC == X86::COND_E &&
14894 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14895 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14896 DAG.getConstant(CC, MVT::i8), Cond };
14897 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14898 array_lengthof(Ops));
14907 /// PerformMulCombine - Optimize a single multiply with constant into two
14908 /// in order to implement it with two cheaper instructions, e.g.
14909 /// LEA + SHL, LEA + LEA.
14910 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14911 TargetLowering::DAGCombinerInfo &DCI) {
14912 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14915 EVT VT = N->getValueType(0);
14916 if (VT != MVT::i64)
14919 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14922 uint64_t MulAmt = C->getZExtValue();
14923 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14926 uint64_t MulAmt1 = 0;
14927 uint64_t MulAmt2 = 0;
14928 if ((MulAmt % 9) == 0) {
14930 MulAmt2 = MulAmt / 9;
14931 } else if ((MulAmt % 5) == 0) {
14933 MulAmt2 = MulAmt / 5;
14934 } else if ((MulAmt % 3) == 0) {
14936 MulAmt2 = MulAmt / 3;
14939 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14940 DebugLoc DL = N->getDebugLoc();
14942 if (isPowerOf2_64(MulAmt2) &&
14943 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14944 // If second multiplifer is pow2, issue it first. We want the multiply by
14945 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14947 std::swap(MulAmt1, MulAmt2);
14950 if (isPowerOf2_64(MulAmt1))
14951 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14952 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14954 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14955 DAG.getConstant(MulAmt1, VT));
14957 if (isPowerOf2_64(MulAmt2))
14958 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14959 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14961 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14962 DAG.getConstant(MulAmt2, VT));
14964 // Do not add new nodes to DAG combiner worklist.
14965 DCI.CombineTo(N, NewMul, false);
14970 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14971 SDValue N0 = N->getOperand(0);
14972 SDValue N1 = N->getOperand(1);
14973 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14974 EVT VT = N0.getValueType();
14976 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14977 // since the result of setcc_c is all zero's or all ones.
14978 if (VT.isInteger() && !VT.isVector() &&
14979 N1C && N0.getOpcode() == ISD::AND &&
14980 N0.getOperand(1).getOpcode() == ISD::Constant) {
14981 SDValue N00 = N0.getOperand(0);
14982 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14983 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14984 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14985 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14986 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14987 APInt ShAmt = N1C->getAPIntValue();
14988 Mask = Mask.shl(ShAmt);
14990 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14991 N00, DAG.getConstant(Mask, VT));
14996 // Hardware support for vector shifts is sparse which makes us scalarize the
14997 // vector operations in many cases. Also, on sandybridge ADD is faster than
14999 // (shl V, 1) -> add V,V
15000 if (isSplatVector(N1.getNode())) {
15001 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15002 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15003 // We shift all of the values by one. In many cases we do not have
15004 // hardware support for this operation. This is better expressed as an ADD
15006 if (N1C && (1 == N1C->getZExtValue())) {
15007 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15014 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15016 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15017 TargetLowering::DAGCombinerInfo &DCI,
15018 const X86Subtarget *Subtarget) {
15019 EVT VT = N->getValueType(0);
15020 if (N->getOpcode() == ISD::SHL) {
15021 SDValue V = PerformSHLCombine(N, DAG);
15022 if (V.getNode()) return V;
15025 // On X86 with SSE2 support, we can transform this to a vector shift if
15026 // all elements are shifted by the same amount. We can't do this in legalize
15027 // because the a constant vector is typically transformed to a constant pool
15028 // so we have no knowledge of the shift amount.
15029 if (!Subtarget->hasSSE2())
15032 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15033 (!Subtarget->hasAVX2() ||
15034 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15037 SDValue ShAmtOp = N->getOperand(1);
15038 EVT EltVT = VT.getVectorElementType();
15039 DebugLoc DL = N->getDebugLoc();
15040 SDValue BaseShAmt = SDValue();
15041 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15042 unsigned NumElts = VT.getVectorNumElements();
15044 for (; i != NumElts; ++i) {
15045 SDValue Arg = ShAmtOp.getOperand(i);
15046 if (Arg.getOpcode() == ISD::UNDEF) continue;
15050 // Handle the case where the build_vector is all undef
15051 // FIXME: Should DAG allow this?
15055 for (; i != NumElts; ++i) {
15056 SDValue Arg = ShAmtOp.getOperand(i);
15057 if (Arg.getOpcode() == ISD::UNDEF) continue;
15058 if (Arg != BaseShAmt) {
15062 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15063 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15064 SDValue InVec = ShAmtOp.getOperand(0);
15065 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15066 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15068 for (; i != NumElts; ++i) {
15069 SDValue Arg = InVec.getOperand(i);
15070 if (Arg.getOpcode() == ISD::UNDEF) continue;
15074 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15075 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15076 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15077 if (C->getZExtValue() == SplatIdx)
15078 BaseShAmt = InVec.getOperand(1);
15081 if (BaseShAmt.getNode() == 0) {
15082 // Don't create instructions with illegal types after legalize
15084 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15085 !DCI.isBeforeLegalize())
15088 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15089 DAG.getIntPtrConstant(0));
15094 // The shift amount is an i32.
15095 if (EltVT.bitsGT(MVT::i32))
15096 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15097 else if (EltVT.bitsLT(MVT::i32))
15098 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15100 // The shift amount is identical so we can do a vector shift.
15101 SDValue ValOp = N->getOperand(0);
15102 switch (N->getOpcode()) {
15104 llvm_unreachable("Unknown shift opcode!");
15106 switch (VT.getSimpleVT().SimpleTy) {
15107 default: return SDValue();
15114 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15117 switch (VT.getSimpleVT().SimpleTy) {
15118 default: return SDValue();
15123 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15126 switch (VT.getSimpleVT().SimpleTy) {
15127 default: return SDValue();
15134 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15140 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15141 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15142 // and friends. Likewise for OR -> CMPNEQSS.
15143 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15144 TargetLowering::DAGCombinerInfo &DCI,
15145 const X86Subtarget *Subtarget) {
15148 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15149 // we're requiring SSE2 for both.
15150 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15151 SDValue N0 = N->getOperand(0);
15152 SDValue N1 = N->getOperand(1);
15153 SDValue CMP0 = N0->getOperand(1);
15154 SDValue CMP1 = N1->getOperand(1);
15155 DebugLoc DL = N->getDebugLoc();
15157 // The SETCCs should both refer to the same CMP.
15158 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15161 SDValue CMP00 = CMP0->getOperand(0);
15162 SDValue CMP01 = CMP0->getOperand(1);
15163 EVT VT = CMP00.getValueType();
15165 if (VT == MVT::f32 || VT == MVT::f64) {
15166 bool ExpectingFlags = false;
15167 // Check for any users that want flags:
15168 for (SDNode::use_iterator UI = N->use_begin(),
15170 !ExpectingFlags && UI != UE; ++UI)
15171 switch (UI->getOpcode()) {
15176 ExpectingFlags = true;
15178 case ISD::CopyToReg:
15179 case ISD::SIGN_EXTEND:
15180 case ISD::ZERO_EXTEND:
15181 case ISD::ANY_EXTEND:
15185 if (!ExpectingFlags) {
15186 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15187 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15189 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15190 X86::CondCode tmp = cc0;
15195 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15196 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15197 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15198 X86ISD::NodeType NTOperator = is64BitFP ?
15199 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15200 // FIXME: need symbolic constants for these magic numbers.
15201 // See X86ATTInstPrinter.cpp:printSSECC().
15202 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15203 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15204 DAG.getConstant(x86cc, MVT::i8));
15205 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15207 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15208 DAG.getConstant(1, MVT::i32));
15209 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15210 return OneBitOfTruth;
15218 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15219 /// so it can be folded inside ANDNP.
15220 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15221 EVT VT = N->getValueType(0);
15223 // Match direct AllOnes for 128 and 256-bit vectors
15224 if (ISD::isBuildVectorAllOnes(N))
15227 // Look through a bit convert.
15228 if (N->getOpcode() == ISD::BITCAST)
15229 N = N->getOperand(0).getNode();
15231 // Sometimes the operand may come from a insert_subvector building a 256-bit
15233 if (VT.is256BitVector() &&
15234 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15235 SDValue V1 = N->getOperand(0);
15236 SDValue V2 = N->getOperand(1);
15238 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15239 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15240 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15241 ISD::isBuildVectorAllOnes(V2.getNode()))
15248 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15249 TargetLowering::DAGCombinerInfo &DCI,
15250 const X86Subtarget *Subtarget) {
15251 if (DCI.isBeforeLegalizeOps())
15254 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15258 EVT VT = N->getValueType(0);
15260 // Create ANDN, BLSI, and BLSR instructions
15261 // BLSI is X & (-X)
15262 // BLSR is X & (X-1)
15263 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15264 SDValue N0 = N->getOperand(0);
15265 SDValue N1 = N->getOperand(1);
15266 DebugLoc DL = N->getDebugLoc();
15268 // Check LHS for not
15269 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15270 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15271 // Check RHS for not
15272 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15273 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15275 // Check LHS for neg
15276 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15277 isZero(N0.getOperand(0)))
15278 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15280 // Check RHS for neg
15281 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15282 isZero(N1.getOperand(0)))
15283 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15285 // Check LHS for X-1
15286 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15287 isAllOnes(N0.getOperand(1)))
15288 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15290 // Check RHS for X-1
15291 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15292 isAllOnes(N1.getOperand(1)))
15293 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15298 // Want to form ANDNP nodes:
15299 // 1) In the hopes of then easily combining them with OR and AND nodes
15300 // to form PBLEND/PSIGN.
15301 // 2) To match ANDN packed intrinsics
15302 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15305 SDValue N0 = N->getOperand(0);
15306 SDValue N1 = N->getOperand(1);
15307 DebugLoc DL = N->getDebugLoc();
15309 // Check LHS for vnot
15310 if (N0.getOpcode() == ISD::XOR &&
15311 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15312 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15313 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15315 // Check RHS for vnot
15316 if (N1.getOpcode() == ISD::XOR &&
15317 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15318 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15319 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15324 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15325 TargetLowering::DAGCombinerInfo &DCI,
15326 const X86Subtarget *Subtarget) {
15327 if (DCI.isBeforeLegalizeOps())
15330 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15334 EVT VT = N->getValueType(0);
15336 SDValue N0 = N->getOperand(0);
15337 SDValue N1 = N->getOperand(1);
15339 // look for psign/blend
15340 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15341 if (!Subtarget->hasSSSE3() ||
15342 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15345 // Canonicalize pandn to RHS
15346 if (N0.getOpcode() == X86ISD::ANDNP)
15348 // or (and (m, y), (pandn m, x))
15349 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15350 SDValue Mask = N1.getOperand(0);
15351 SDValue X = N1.getOperand(1);
15353 if (N0.getOperand(0) == Mask)
15354 Y = N0.getOperand(1);
15355 if (N0.getOperand(1) == Mask)
15356 Y = N0.getOperand(0);
15358 // Check to see if the mask appeared in both the AND and ANDNP and
15362 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15363 // Look through mask bitcast.
15364 if (Mask.getOpcode() == ISD::BITCAST)
15365 Mask = Mask.getOperand(0);
15366 if (X.getOpcode() == ISD::BITCAST)
15367 X = X.getOperand(0);
15368 if (Y.getOpcode() == ISD::BITCAST)
15369 Y = Y.getOperand(0);
15371 EVT MaskVT = Mask.getValueType();
15373 // Validate that the Mask operand is a vector sra node.
15374 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15375 // there is no psrai.b
15376 if (Mask.getOpcode() != X86ISD::VSRAI)
15379 // Check that the SRA is all signbits.
15380 SDValue SraC = Mask.getOperand(1);
15381 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15382 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15383 if ((SraAmt + 1) != EltBits)
15386 DebugLoc DL = N->getDebugLoc();
15388 // Now we know we at least have a plendvb with the mask val. See if
15389 // we can form a psignb/w/d.
15390 // psign = x.type == y.type == mask.type && y = sub(0, x);
15391 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15392 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15393 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15394 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15395 "Unsupported VT for PSIGN");
15396 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15397 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15399 // PBLENDVB only available on SSE 4.1
15400 if (!Subtarget->hasSSE41())
15403 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15405 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15406 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15407 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15408 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15409 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15413 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15416 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15417 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15419 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15421 if (!N0.hasOneUse() || !N1.hasOneUse())
15424 SDValue ShAmt0 = N0.getOperand(1);
15425 if (ShAmt0.getValueType() != MVT::i8)
15427 SDValue ShAmt1 = N1.getOperand(1);
15428 if (ShAmt1.getValueType() != MVT::i8)
15430 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15431 ShAmt0 = ShAmt0.getOperand(0);
15432 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15433 ShAmt1 = ShAmt1.getOperand(0);
15435 DebugLoc DL = N->getDebugLoc();
15436 unsigned Opc = X86ISD::SHLD;
15437 SDValue Op0 = N0.getOperand(0);
15438 SDValue Op1 = N1.getOperand(0);
15439 if (ShAmt0.getOpcode() == ISD::SUB) {
15440 Opc = X86ISD::SHRD;
15441 std::swap(Op0, Op1);
15442 std::swap(ShAmt0, ShAmt1);
15445 unsigned Bits = VT.getSizeInBits();
15446 if (ShAmt1.getOpcode() == ISD::SUB) {
15447 SDValue Sum = ShAmt1.getOperand(0);
15448 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15449 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15450 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15451 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15452 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15453 return DAG.getNode(Opc, DL, VT,
15455 DAG.getNode(ISD::TRUNCATE, DL,
15458 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15459 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15461 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15462 return DAG.getNode(Opc, DL, VT,
15463 N0.getOperand(0), N1.getOperand(0),
15464 DAG.getNode(ISD::TRUNCATE, DL,
15471 // Generate NEG and CMOV for integer abs.
15472 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15473 EVT VT = N->getValueType(0);
15475 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15476 // 8-bit integer abs to NEG and CMOV.
15477 if (VT.isInteger() && VT.getSizeInBits() == 8)
15480 SDValue N0 = N->getOperand(0);
15481 SDValue N1 = N->getOperand(1);
15482 DebugLoc DL = N->getDebugLoc();
15484 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15485 // and change it to SUB and CMOV.
15486 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15487 N0.getOpcode() == ISD::ADD &&
15488 N0.getOperand(1) == N1 &&
15489 N1.getOpcode() == ISD::SRA &&
15490 N1.getOperand(0) == N0.getOperand(0))
15491 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15492 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15493 // Generate SUB & CMOV.
15494 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15495 DAG.getConstant(0, VT), N0.getOperand(0));
15497 SDValue Ops[] = { N0.getOperand(0), Neg,
15498 DAG.getConstant(X86::COND_GE, MVT::i8),
15499 SDValue(Neg.getNode(), 1) };
15500 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15501 Ops, array_lengthof(Ops));
15506 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15507 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15508 TargetLowering::DAGCombinerInfo &DCI,
15509 const X86Subtarget *Subtarget) {
15510 if (DCI.isBeforeLegalizeOps())
15513 if (Subtarget->hasCMov()) {
15514 SDValue RV = performIntegerAbsCombine(N, DAG);
15519 // Try forming BMI if it is available.
15520 if (!Subtarget->hasBMI())
15523 EVT VT = N->getValueType(0);
15525 if (VT != MVT::i32 && VT != MVT::i64)
15528 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15530 // Create BLSMSK instructions by finding X ^ (X-1)
15531 SDValue N0 = N->getOperand(0);
15532 SDValue N1 = N->getOperand(1);
15533 DebugLoc DL = N->getDebugLoc();
15535 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15536 isAllOnes(N0.getOperand(1)))
15537 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15539 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15540 isAllOnes(N1.getOperand(1)))
15541 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15546 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15547 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15548 TargetLowering::DAGCombinerInfo &DCI,
15549 const X86Subtarget *Subtarget) {
15550 LoadSDNode *Ld = cast<LoadSDNode>(N);
15551 EVT RegVT = Ld->getValueType(0);
15552 EVT MemVT = Ld->getMemoryVT();
15553 DebugLoc dl = Ld->getDebugLoc();
15554 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15556 ISD::LoadExtType Ext = Ld->getExtensionType();
15558 // If this is a vector EXT Load then attempt to optimize it using a
15559 // shuffle. We need SSSE3 shuffles.
15560 // TODO: It is possible to support ZExt by zeroing the undef values
15561 // during the shuffle phase or after the shuffle.
15562 if (RegVT.isVector() && RegVT.isInteger() &&
15563 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15564 assert(MemVT != RegVT && "Cannot extend to the same type");
15565 assert(MemVT.isVector() && "Must load a vector from memory");
15567 unsigned NumElems = RegVT.getVectorNumElements();
15568 unsigned RegSz = RegVT.getSizeInBits();
15569 unsigned MemSz = MemVT.getSizeInBits();
15570 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15572 // All sizes must be a power of two.
15573 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15576 // Attempt to load the original value using scalar loads.
15577 // Find the largest scalar type that divides the total loaded size.
15578 MVT SclrLoadTy = MVT::i8;
15579 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15580 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15581 MVT Tp = (MVT::SimpleValueType)tp;
15582 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15587 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15588 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15590 SclrLoadTy = MVT::f64;
15592 // Calculate the number of scalar loads that we need to perform
15593 // in order to load our vector from memory.
15594 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15596 // Represent our vector as a sequence of elements which are the
15597 // largest scalar that we can load.
15598 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15599 RegSz/SclrLoadTy.getSizeInBits());
15601 // Represent the data using the same element type that is stored in
15602 // memory. In practice, we ''widen'' MemVT.
15603 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15604 RegSz/MemVT.getScalarType().getSizeInBits());
15606 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15607 "Invalid vector type");
15609 // We can't shuffle using an illegal type.
15610 if (!TLI.isTypeLegal(WideVecVT))
15613 SmallVector<SDValue, 8> Chains;
15614 SDValue Ptr = Ld->getBasePtr();
15615 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15616 TLI.getPointerTy());
15617 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15619 for (unsigned i = 0; i < NumLoads; ++i) {
15620 // Perform a single load.
15621 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15622 Ptr, Ld->getPointerInfo(),
15623 Ld->isVolatile(), Ld->isNonTemporal(),
15624 Ld->isInvariant(), Ld->getAlignment());
15625 Chains.push_back(ScalarLoad.getValue(1));
15626 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15627 // another round of DAGCombining.
15629 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15631 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15632 ScalarLoad, DAG.getIntPtrConstant(i));
15634 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15637 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15640 // Bitcast the loaded value to a vector of the original element type, in
15641 // the size of the target vector type.
15642 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15643 unsigned SizeRatio = RegSz/MemSz;
15645 // Redistribute the loaded elements into the different locations.
15646 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15647 for (unsigned i = 0; i != NumElems; ++i)
15648 ShuffleVec[i*SizeRatio] = i;
15650 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15651 DAG.getUNDEF(WideVecVT),
15654 // Bitcast to the requested type.
15655 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15656 // Replace the original load with the new sequence
15657 // and return the new chain.
15658 return DCI.CombineTo(N, Shuff, TF, true);
15664 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15665 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15666 const X86Subtarget *Subtarget) {
15667 StoreSDNode *St = cast<StoreSDNode>(N);
15668 EVT VT = St->getValue().getValueType();
15669 EVT StVT = St->getMemoryVT();
15670 DebugLoc dl = St->getDebugLoc();
15671 SDValue StoredVal = St->getOperand(1);
15672 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15674 // If we are saving a concatenation of two XMM registers, perform two stores.
15675 // On Sandy Bridge, 256-bit memory operations are executed by two
15676 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15677 // memory operation.
15678 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15679 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15680 StoredVal.getNumOperands() == 2) {
15681 SDValue Value0 = StoredVal.getOperand(0);
15682 SDValue Value1 = StoredVal.getOperand(1);
15684 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15685 SDValue Ptr0 = St->getBasePtr();
15686 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15688 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15689 St->getPointerInfo(), St->isVolatile(),
15690 St->isNonTemporal(), St->getAlignment());
15691 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15692 St->getPointerInfo(), St->isVolatile(),
15693 St->isNonTemporal(), St->getAlignment());
15694 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15697 // Optimize trunc store (of multiple scalars) to shuffle and store.
15698 // First, pack all of the elements in one place. Next, store to memory
15699 // in fewer chunks.
15700 if (St->isTruncatingStore() && VT.isVector()) {
15701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15702 unsigned NumElems = VT.getVectorNumElements();
15703 assert(StVT != VT && "Cannot truncate to the same type");
15704 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15705 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15707 // From, To sizes and ElemCount must be pow of two
15708 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15709 // We are going to use the original vector elt for storing.
15710 // Accumulated smaller vector elements must be a multiple of the store size.
15711 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15713 unsigned SizeRatio = FromSz / ToSz;
15715 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15717 // Create a type on which we perform the shuffle
15718 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15719 StVT.getScalarType(), NumElems*SizeRatio);
15721 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15723 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15724 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15725 for (unsigned i = 0; i != NumElems; ++i)
15726 ShuffleVec[i] = i * SizeRatio;
15728 // Can't shuffle using an illegal type.
15729 if (!TLI.isTypeLegal(WideVecVT))
15732 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15733 DAG.getUNDEF(WideVecVT),
15735 // At this point all of the data is stored at the bottom of the
15736 // register. We now need to save it to mem.
15738 // Find the largest store unit
15739 MVT StoreType = MVT::i8;
15740 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15741 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15742 MVT Tp = (MVT::SimpleValueType)tp;
15743 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15747 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15748 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15749 (64 <= NumElems * ToSz))
15750 StoreType = MVT::f64;
15752 // Bitcast the original vector into a vector of store-size units
15753 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15754 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15755 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15756 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15757 SmallVector<SDValue, 8> Chains;
15758 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15759 TLI.getPointerTy());
15760 SDValue Ptr = St->getBasePtr();
15762 // Perform one or more big stores into memory.
15763 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15764 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15765 StoreType, ShuffWide,
15766 DAG.getIntPtrConstant(i));
15767 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15768 St->getPointerInfo(), St->isVolatile(),
15769 St->isNonTemporal(), St->getAlignment());
15770 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15771 Chains.push_back(Ch);
15774 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15779 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15780 // the FP state in cases where an emms may be missing.
15781 // A preferable solution to the general problem is to figure out the right
15782 // places to insert EMMS. This qualifies as a quick hack.
15784 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15785 if (VT.getSizeInBits() != 64)
15788 const Function *F = DAG.getMachineFunction().getFunction();
15789 bool NoImplicitFloatOps = F->getFnAttributes().
15790 hasAttribute(Attributes::NoImplicitFloat);
15791 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15792 && Subtarget->hasSSE2();
15793 if ((VT.isVector() ||
15794 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15795 isa<LoadSDNode>(St->getValue()) &&
15796 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15797 St->getChain().hasOneUse() && !St->isVolatile()) {
15798 SDNode* LdVal = St->getValue().getNode();
15799 LoadSDNode *Ld = 0;
15800 int TokenFactorIndex = -1;
15801 SmallVector<SDValue, 8> Ops;
15802 SDNode* ChainVal = St->getChain().getNode();
15803 // Must be a store of a load. We currently handle two cases: the load
15804 // is a direct child, and it's under an intervening TokenFactor. It is
15805 // possible to dig deeper under nested TokenFactors.
15806 if (ChainVal == LdVal)
15807 Ld = cast<LoadSDNode>(St->getChain());
15808 else if (St->getValue().hasOneUse() &&
15809 ChainVal->getOpcode() == ISD::TokenFactor) {
15810 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15811 if (ChainVal->getOperand(i).getNode() == LdVal) {
15812 TokenFactorIndex = i;
15813 Ld = cast<LoadSDNode>(St->getValue());
15815 Ops.push_back(ChainVal->getOperand(i));
15819 if (!Ld || !ISD::isNormalLoad(Ld))
15822 // If this is not the MMX case, i.e. we are just turning i64 load/store
15823 // into f64 load/store, avoid the transformation if there are multiple
15824 // uses of the loaded value.
15825 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15828 DebugLoc LdDL = Ld->getDebugLoc();
15829 DebugLoc StDL = N->getDebugLoc();
15830 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15831 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15833 if (Subtarget->is64Bit() || F64IsLegal) {
15834 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15835 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15836 Ld->getPointerInfo(), Ld->isVolatile(),
15837 Ld->isNonTemporal(), Ld->isInvariant(),
15838 Ld->getAlignment());
15839 SDValue NewChain = NewLd.getValue(1);
15840 if (TokenFactorIndex != -1) {
15841 Ops.push_back(NewChain);
15842 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15845 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15846 St->getPointerInfo(),
15847 St->isVolatile(), St->isNonTemporal(),
15848 St->getAlignment());
15851 // Otherwise, lower to two pairs of 32-bit loads / stores.
15852 SDValue LoAddr = Ld->getBasePtr();
15853 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15854 DAG.getConstant(4, MVT::i32));
15856 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15857 Ld->getPointerInfo(),
15858 Ld->isVolatile(), Ld->isNonTemporal(),
15859 Ld->isInvariant(), Ld->getAlignment());
15860 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15861 Ld->getPointerInfo().getWithOffset(4),
15862 Ld->isVolatile(), Ld->isNonTemporal(),
15864 MinAlign(Ld->getAlignment(), 4));
15866 SDValue NewChain = LoLd.getValue(1);
15867 if (TokenFactorIndex != -1) {
15868 Ops.push_back(LoLd);
15869 Ops.push_back(HiLd);
15870 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15874 LoAddr = St->getBasePtr();
15875 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15876 DAG.getConstant(4, MVT::i32));
15878 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15879 St->getPointerInfo(),
15880 St->isVolatile(), St->isNonTemporal(),
15881 St->getAlignment());
15882 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15883 St->getPointerInfo().getWithOffset(4),
15885 St->isNonTemporal(),
15886 MinAlign(St->getAlignment(), 4));
15887 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15892 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15893 /// and return the operands for the horizontal operation in LHS and RHS. A
15894 /// horizontal operation performs the binary operation on successive elements
15895 /// of its first operand, then on successive elements of its second operand,
15896 /// returning the resulting values in a vector. For example, if
15897 /// A = < float a0, float a1, float a2, float a3 >
15899 /// B = < float b0, float b1, float b2, float b3 >
15900 /// then the result of doing a horizontal operation on A and B is
15901 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15902 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15903 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15904 /// set to A, RHS to B, and the routine returns 'true'.
15905 /// Note that the binary operation should have the property that if one of the
15906 /// operands is UNDEF then the result is UNDEF.
15907 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15908 // Look for the following pattern: if
15909 // A = < float a0, float a1, float a2, float a3 >
15910 // B = < float b0, float b1, float b2, float b3 >
15912 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15913 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15914 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15915 // which is A horizontal-op B.
15917 // At least one of the operands should be a vector shuffle.
15918 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15919 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15922 EVT VT = LHS.getValueType();
15924 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15925 "Unsupported vector type for horizontal add/sub");
15927 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15928 // operate independently on 128-bit lanes.
15929 unsigned NumElts = VT.getVectorNumElements();
15930 unsigned NumLanes = VT.getSizeInBits()/128;
15931 unsigned NumLaneElts = NumElts / NumLanes;
15932 assert((NumLaneElts % 2 == 0) &&
15933 "Vector type should have an even number of elements in each lane");
15934 unsigned HalfLaneElts = NumLaneElts/2;
15936 // View LHS in the form
15937 // LHS = VECTOR_SHUFFLE A, B, LMask
15938 // If LHS is not a shuffle then pretend it is the shuffle
15939 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15940 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15943 SmallVector<int, 16> LMask(NumElts);
15944 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15945 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15946 A = LHS.getOperand(0);
15947 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15948 B = LHS.getOperand(1);
15949 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15950 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15952 if (LHS.getOpcode() != ISD::UNDEF)
15954 for (unsigned i = 0; i != NumElts; ++i)
15958 // Likewise, view RHS in the form
15959 // RHS = VECTOR_SHUFFLE C, D, RMask
15961 SmallVector<int, 16> RMask(NumElts);
15962 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15963 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15964 C = RHS.getOperand(0);
15965 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15966 D = RHS.getOperand(1);
15967 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15968 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15970 if (RHS.getOpcode() != ISD::UNDEF)
15972 for (unsigned i = 0; i != NumElts; ++i)
15976 // Check that the shuffles are both shuffling the same vectors.
15977 if (!(A == C && B == D) && !(A == D && B == C))
15980 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15981 if (!A.getNode() && !B.getNode())
15984 // If A and B occur in reverse order in RHS, then "swap" them (which means
15985 // rewriting the mask).
15987 CommuteVectorShuffleMask(RMask, NumElts);
15989 // At this point LHS and RHS are equivalent to
15990 // LHS = VECTOR_SHUFFLE A, B, LMask
15991 // RHS = VECTOR_SHUFFLE A, B, RMask
15992 // Check that the masks correspond to performing a horizontal operation.
15993 for (unsigned i = 0; i != NumElts; ++i) {
15994 int LIdx = LMask[i], RIdx = RMask[i];
15996 // Ignore any UNDEF components.
15997 if (LIdx < 0 || RIdx < 0 ||
15998 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15999 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16002 // Check that successive elements are being operated on. If not, this is
16003 // not a horizontal operation.
16004 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16005 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16006 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16007 if (!(LIdx == Index && RIdx == Index + 1) &&
16008 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16012 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16013 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16017 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16018 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16019 const X86Subtarget *Subtarget) {
16020 EVT VT = N->getValueType(0);
16021 SDValue LHS = N->getOperand(0);
16022 SDValue RHS = N->getOperand(1);
16024 // Try to synthesize horizontal adds from adds of shuffles.
16025 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16026 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16027 isHorizontalBinOp(LHS, RHS, true))
16028 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16032 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16033 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16034 const X86Subtarget *Subtarget) {
16035 EVT VT = N->getValueType(0);
16036 SDValue LHS = N->getOperand(0);
16037 SDValue RHS = N->getOperand(1);
16039 // Try to synthesize horizontal subs from subs of shuffles.
16040 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16041 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16042 isHorizontalBinOp(LHS, RHS, false))
16043 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16047 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16048 /// X86ISD::FXOR nodes.
16049 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16050 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16051 // F[X]OR(0.0, x) -> x
16052 // F[X]OR(x, 0.0) -> x
16053 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16054 if (C->getValueAPF().isPosZero())
16055 return N->getOperand(1);
16056 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16057 if (C->getValueAPF().isPosZero())
16058 return N->getOperand(0);
16062 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16063 /// X86ISD::FMAX nodes.
16064 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16065 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16067 // Only perform optimizations if UnsafeMath is used.
16068 if (!DAG.getTarget().Options.UnsafeFPMath)
16071 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16072 // into FMINC and FMAXC, which are Commutative operations.
16073 unsigned NewOp = 0;
16074 switch (N->getOpcode()) {
16075 default: llvm_unreachable("unknown opcode");
16076 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16077 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16080 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16081 N->getOperand(0), N->getOperand(1));
16085 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16086 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16087 // FAND(0.0, x) -> 0.0
16088 // FAND(x, 0.0) -> 0.0
16089 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16090 if (C->getValueAPF().isPosZero())
16091 return N->getOperand(0);
16092 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16093 if (C->getValueAPF().isPosZero())
16094 return N->getOperand(1);
16098 static SDValue PerformBTCombine(SDNode *N,
16100 TargetLowering::DAGCombinerInfo &DCI) {
16101 // BT ignores high bits in the bit index operand.
16102 SDValue Op1 = N->getOperand(1);
16103 if (Op1.hasOneUse()) {
16104 unsigned BitWidth = Op1.getValueSizeInBits();
16105 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16106 APInt KnownZero, KnownOne;
16107 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16108 !DCI.isBeforeLegalizeOps());
16109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16110 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16111 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16112 DCI.CommitTargetLoweringOpt(TLO);
16117 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16118 SDValue Op = N->getOperand(0);
16119 if (Op.getOpcode() == ISD::BITCAST)
16120 Op = Op.getOperand(0);
16121 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16122 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16123 VT.getVectorElementType().getSizeInBits() ==
16124 OpVT.getVectorElementType().getSizeInBits()) {
16125 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16130 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16131 TargetLowering::DAGCombinerInfo &DCI,
16132 const X86Subtarget *Subtarget) {
16133 if (!DCI.isBeforeLegalizeOps())
16136 if (!Subtarget->hasAVX())
16139 EVT VT = N->getValueType(0);
16140 SDValue Op = N->getOperand(0);
16141 EVT OpVT = Op.getValueType();
16142 DebugLoc dl = N->getDebugLoc();
16144 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16145 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16147 if (Subtarget->hasAVX2())
16148 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16150 // Optimize vectors in AVX mode
16151 // Sign extend v8i16 to v8i32 and
16154 // Divide input vector into two parts
16155 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16156 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16157 // concat the vectors to original VT
16159 unsigned NumElems = OpVT.getVectorNumElements();
16160 SDValue Undef = DAG.getUNDEF(OpVT);
16162 SmallVector<int,8> ShufMask1(NumElems, -1);
16163 for (unsigned i = 0; i != NumElems/2; ++i)
16166 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16168 SmallVector<int,8> ShufMask2(NumElems, -1);
16169 for (unsigned i = 0; i != NumElems/2; ++i)
16170 ShufMask2[i] = i + NumElems/2;
16172 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16174 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16175 VT.getVectorNumElements()/2);
16177 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16178 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16180 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16185 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16186 const X86Subtarget* Subtarget) {
16187 DebugLoc dl = N->getDebugLoc();
16188 EVT VT = N->getValueType(0);
16190 // Let legalize expand this if it isn't a legal type yet.
16191 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16194 EVT ScalarVT = VT.getScalarType();
16195 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16196 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16199 SDValue A = N->getOperand(0);
16200 SDValue B = N->getOperand(1);
16201 SDValue C = N->getOperand(2);
16203 bool NegA = (A.getOpcode() == ISD::FNEG);
16204 bool NegB = (B.getOpcode() == ISD::FNEG);
16205 bool NegC = (C.getOpcode() == ISD::FNEG);
16207 // Negative multiplication when NegA xor NegB
16208 bool NegMul = (NegA != NegB);
16210 A = A.getOperand(0);
16212 B = B.getOperand(0);
16214 C = C.getOperand(0);
16218 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16220 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16222 return DAG.getNode(Opcode, dl, VT, A, B, C);
16225 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16226 TargetLowering::DAGCombinerInfo &DCI,
16227 const X86Subtarget *Subtarget) {
16228 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16229 // (and (i32 x86isd::setcc_carry), 1)
16230 // This eliminates the zext. This transformation is necessary because
16231 // ISD::SETCC is always legalized to i8.
16232 DebugLoc dl = N->getDebugLoc();
16233 SDValue N0 = N->getOperand(0);
16234 EVT VT = N->getValueType(0);
16235 EVT OpVT = N0.getValueType();
16237 if (N0.getOpcode() == ISD::AND &&
16239 N0.getOperand(0).hasOneUse()) {
16240 SDValue N00 = N0.getOperand(0);
16241 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16244 if (!C || C->getZExtValue() != 1)
16246 return DAG.getNode(ISD::AND, dl, VT,
16247 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16248 N00.getOperand(0), N00.getOperand(1)),
16249 DAG.getConstant(1, VT));
16252 // Optimize vectors in AVX mode:
16255 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16256 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16257 // Concat upper and lower parts.
16260 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16261 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16262 // Concat upper and lower parts.
16264 if (!DCI.isBeforeLegalizeOps())
16267 if (!Subtarget->hasAVX())
16270 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16271 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16273 if (Subtarget->hasAVX2())
16274 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16276 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16277 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16278 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16280 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16281 VT.getVectorNumElements()/2);
16283 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16284 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16286 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16292 // Optimize x == -y --> x+y == 0
16293 // x != -y --> x+y != 0
16294 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16295 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16296 SDValue LHS = N->getOperand(0);
16297 SDValue RHS = N->getOperand(1);
16299 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16300 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16301 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16302 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16303 LHS.getValueType(), RHS, LHS.getOperand(1));
16304 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16305 addV, DAG.getConstant(0, addV.getValueType()), CC);
16307 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16308 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16309 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16310 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16311 RHS.getValueType(), LHS, RHS.getOperand(1));
16312 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16313 addV, DAG.getConstant(0, addV.getValueType()), CC);
16318 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16319 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16320 TargetLowering::DAGCombinerInfo &DCI,
16321 const X86Subtarget *Subtarget) {
16322 DebugLoc DL = N->getDebugLoc();
16323 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16324 SDValue EFLAGS = N->getOperand(1);
16326 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16327 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16329 if (CC == X86::COND_B)
16330 return DAG.getNode(ISD::AND, DL, MVT::i8,
16331 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16332 DAG.getConstant(CC, MVT::i8), EFLAGS),
16333 DAG.getConstant(1, MVT::i8));
16337 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16338 if (Flags.getNode()) {
16339 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16340 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16346 // Optimize branch condition evaluation.
16348 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16349 TargetLowering::DAGCombinerInfo &DCI,
16350 const X86Subtarget *Subtarget) {
16351 DebugLoc DL = N->getDebugLoc();
16352 SDValue Chain = N->getOperand(0);
16353 SDValue Dest = N->getOperand(1);
16354 SDValue EFLAGS = N->getOperand(3);
16355 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16359 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16360 if (Flags.getNode()) {
16361 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16362 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16369 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16370 SDValue Op0 = N->getOperand(0);
16371 EVT InVT = Op0->getValueType(0);
16373 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16374 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16375 DebugLoc dl = N->getDebugLoc();
16376 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16377 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16378 // Notice that we use SINT_TO_FP because we know that the high bits
16379 // are zero and SINT_TO_FP is better supported by the hardware.
16380 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16386 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16387 const X86TargetLowering *XTLI) {
16388 SDValue Op0 = N->getOperand(0);
16389 EVT InVT = Op0->getValueType(0);
16391 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16392 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16393 DebugLoc dl = N->getDebugLoc();
16394 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16395 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16396 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16399 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16400 // a 32-bit target where SSE doesn't support i64->FP operations.
16401 if (Op0.getOpcode() == ISD::LOAD) {
16402 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16403 EVT VT = Ld->getValueType(0);
16404 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16405 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16406 !XTLI->getSubtarget()->is64Bit() &&
16407 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16408 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16409 Ld->getChain(), Op0, DAG);
16410 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16417 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16418 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16419 X86TargetLowering::DAGCombinerInfo &DCI) {
16420 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16421 // the result is either zero or one (depending on the input carry bit).
16422 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16423 if (X86::isZeroNode(N->getOperand(0)) &&
16424 X86::isZeroNode(N->getOperand(1)) &&
16425 // We don't have a good way to replace an EFLAGS use, so only do this when
16427 SDValue(N, 1).use_empty()) {
16428 DebugLoc DL = N->getDebugLoc();
16429 EVT VT = N->getValueType(0);
16430 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16431 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16432 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16433 DAG.getConstant(X86::COND_B,MVT::i8),
16435 DAG.getConstant(1, VT));
16436 return DCI.CombineTo(N, Res1, CarryOut);
16442 // fold (add Y, (sete X, 0)) -> adc 0, Y
16443 // (add Y, (setne X, 0)) -> sbb -1, Y
16444 // (sub (sete X, 0), Y) -> sbb 0, Y
16445 // (sub (setne X, 0), Y) -> adc -1, Y
16446 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16447 DebugLoc DL = N->getDebugLoc();
16449 // Look through ZExts.
16450 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16451 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16454 SDValue SetCC = Ext.getOperand(0);
16455 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16458 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16459 if (CC != X86::COND_E && CC != X86::COND_NE)
16462 SDValue Cmp = SetCC.getOperand(1);
16463 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16464 !X86::isZeroNode(Cmp.getOperand(1)) ||
16465 !Cmp.getOperand(0).getValueType().isInteger())
16468 SDValue CmpOp0 = Cmp.getOperand(0);
16469 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16470 DAG.getConstant(1, CmpOp0.getValueType()));
16472 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16473 if (CC == X86::COND_NE)
16474 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16475 DL, OtherVal.getValueType(), OtherVal,
16476 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16477 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16478 DL, OtherVal.getValueType(), OtherVal,
16479 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16482 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16483 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16484 const X86Subtarget *Subtarget) {
16485 EVT VT = N->getValueType(0);
16486 SDValue Op0 = N->getOperand(0);
16487 SDValue Op1 = N->getOperand(1);
16489 // Try to synthesize horizontal adds from adds of shuffles.
16490 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16491 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16492 isHorizontalBinOp(Op0, Op1, true))
16493 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16495 return OptimizeConditionalInDecrement(N, DAG);
16498 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16499 const X86Subtarget *Subtarget) {
16500 SDValue Op0 = N->getOperand(0);
16501 SDValue Op1 = N->getOperand(1);
16503 // X86 can't encode an immediate LHS of a sub. See if we can push the
16504 // negation into a preceding instruction.
16505 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16506 // If the RHS of the sub is a XOR with one use and a constant, invert the
16507 // immediate. Then add one to the LHS of the sub so we can turn
16508 // X-Y -> X+~Y+1, saving one register.
16509 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16510 isa<ConstantSDNode>(Op1.getOperand(1))) {
16511 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16512 EVT VT = Op0.getValueType();
16513 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16515 DAG.getConstant(~XorC, VT));
16516 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16517 DAG.getConstant(C->getAPIntValue()+1, VT));
16521 // Try to synthesize horizontal adds from adds of shuffles.
16522 EVT VT = N->getValueType(0);
16523 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16524 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16525 isHorizontalBinOp(Op0, Op1, true))
16526 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16528 return OptimizeConditionalInDecrement(N, DAG);
16531 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16532 DAGCombinerInfo &DCI) const {
16533 SelectionDAG &DAG = DCI.DAG;
16534 switch (N->getOpcode()) {
16536 case ISD::EXTRACT_VECTOR_ELT:
16537 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16539 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16540 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16541 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16542 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16543 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16544 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16547 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16548 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16549 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16550 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16551 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16552 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16553 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16554 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16555 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16556 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16558 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16560 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16561 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16562 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16563 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16564 case ISD::ANY_EXTEND:
16565 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16566 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16567 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16568 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16569 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16570 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16571 case X86ISD::SHUFP: // Handle all target specific shuffles
16572 case X86ISD::PALIGN:
16573 case X86ISD::UNPCKH:
16574 case X86ISD::UNPCKL:
16575 case X86ISD::MOVHLPS:
16576 case X86ISD::MOVLHPS:
16577 case X86ISD::PSHUFD:
16578 case X86ISD::PSHUFHW:
16579 case X86ISD::PSHUFLW:
16580 case X86ISD::MOVSS:
16581 case X86ISD::MOVSD:
16582 case X86ISD::VPERMILP:
16583 case X86ISD::VPERM2X128:
16584 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16585 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16591 /// isTypeDesirableForOp - Return true if the target has native support for
16592 /// the specified value type and it is 'desirable' to use the type for the
16593 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16594 /// instruction encodings are longer and some i16 instructions are slow.
16595 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16596 if (!isTypeLegal(VT))
16598 if (VT != MVT::i16)
16605 case ISD::SIGN_EXTEND:
16606 case ISD::ZERO_EXTEND:
16607 case ISD::ANY_EXTEND:
16620 /// IsDesirableToPromoteOp - This method query the target whether it is
16621 /// beneficial for dag combiner to promote the specified node. If true, it
16622 /// should return the desired promotion type by reference.
16623 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16624 EVT VT = Op.getValueType();
16625 if (VT != MVT::i16)
16628 bool Promote = false;
16629 bool Commute = false;
16630 switch (Op.getOpcode()) {
16633 LoadSDNode *LD = cast<LoadSDNode>(Op);
16634 // If the non-extending load has a single use and it's not live out, then it
16635 // might be folded.
16636 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16637 Op.hasOneUse()*/) {
16638 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16639 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16640 // The only case where we'd want to promote LOAD (rather then it being
16641 // promoted as an operand is when it's only use is liveout.
16642 if (UI->getOpcode() != ISD::CopyToReg)
16649 case ISD::SIGN_EXTEND:
16650 case ISD::ZERO_EXTEND:
16651 case ISD::ANY_EXTEND:
16656 SDValue N0 = Op.getOperand(0);
16657 // Look out for (store (shl (load), x)).
16658 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16671 SDValue N0 = Op.getOperand(0);
16672 SDValue N1 = Op.getOperand(1);
16673 if (!Commute && MayFoldLoad(N1))
16675 // Avoid disabling potential load folding opportunities.
16676 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16678 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16688 //===----------------------------------------------------------------------===//
16689 // X86 Inline Assembly Support
16690 //===----------------------------------------------------------------------===//
16693 // Helper to match a string separated by whitespace.
16694 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16695 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16697 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16698 StringRef piece(*args[i]);
16699 if (!s.startswith(piece)) // Check if the piece matches.
16702 s = s.substr(piece.size());
16703 StringRef::size_type pos = s.find_first_not_of(" \t");
16704 if (pos == 0) // We matched a prefix.
16712 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16715 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16716 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16718 std::string AsmStr = IA->getAsmString();
16720 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16721 if (!Ty || Ty->getBitWidth() % 16 != 0)
16724 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16725 SmallVector<StringRef, 4> AsmPieces;
16726 SplitString(AsmStr, AsmPieces, ";\n");
16728 switch (AsmPieces.size()) {
16729 default: return false;
16731 // FIXME: this should verify that we are targeting a 486 or better. If not,
16732 // we will turn this bswap into something that will be lowered to logical
16733 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16734 // lower so don't worry about this.
16736 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16737 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16738 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16739 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16740 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16741 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16742 // No need to check constraints, nothing other than the equivalent of
16743 // "=r,0" would be valid here.
16744 return IntrinsicLowering::LowerToByteSwap(CI);
16747 // rorw $$8, ${0:w} --> llvm.bswap.i16
16748 if (CI->getType()->isIntegerTy(16) &&
16749 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16750 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16751 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16753 const std::string &ConstraintsStr = IA->getConstraintString();
16754 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16755 std::sort(AsmPieces.begin(), AsmPieces.end());
16756 if (AsmPieces.size() == 4 &&
16757 AsmPieces[0] == "~{cc}" &&
16758 AsmPieces[1] == "~{dirflag}" &&
16759 AsmPieces[2] == "~{flags}" &&
16760 AsmPieces[3] == "~{fpsr}")
16761 return IntrinsicLowering::LowerToByteSwap(CI);
16765 if (CI->getType()->isIntegerTy(32) &&
16766 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16767 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16768 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16769 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16771 const std::string &ConstraintsStr = IA->getConstraintString();
16772 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16773 std::sort(AsmPieces.begin(), AsmPieces.end());
16774 if (AsmPieces.size() == 4 &&
16775 AsmPieces[0] == "~{cc}" &&
16776 AsmPieces[1] == "~{dirflag}" &&
16777 AsmPieces[2] == "~{flags}" &&
16778 AsmPieces[3] == "~{fpsr}")
16779 return IntrinsicLowering::LowerToByteSwap(CI);
16782 if (CI->getType()->isIntegerTy(64)) {
16783 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16784 if (Constraints.size() >= 2 &&
16785 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16786 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16787 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16788 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16789 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16790 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16791 return IntrinsicLowering::LowerToByteSwap(CI);
16801 /// getConstraintType - Given a constraint letter, return the type of
16802 /// constraint it is for this target.
16803 X86TargetLowering::ConstraintType
16804 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16805 if (Constraint.size() == 1) {
16806 switch (Constraint[0]) {
16817 return C_RegisterClass;
16841 return TargetLowering::getConstraintType(Constraint);
16844 /// Examine constraint type and operand type and determine a weight value.
16845 /// This object must already have been set up with the operand type
16846 /// and the current alternative constraint selected.
16847 TargetLowering::ConstraintWeight
16848 X86TargetLowering::getSingleConstraintMatchWeight(
16849 AsmOperandInfo &info, const char *constraint) const {
16850 ConstraintWeight weight = CW_Invalid;
16851 Value *CallOperandVal = info.CallOperandVal;
16852 // If we don't have a value, we can't do a match,
16853 // but allow it at the lowest weight.
16854 if (CallOperandVal == NULL)
16856 Type *type = CallOperandVal->getType();
16857 // Look at the constraint type.
16858 switch (*constraint) {
16860 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16871 if (CallOperandVal->getType()->isIntegerTy())
16872 weight = CW_SpecificReg;
16877 if (type->isFloatingPointTy())
16878 weight = CW_SpecificReg;
16881 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16882 weight = CW_SpecificReg;
16886 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16887 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16888 weight = CW_Register;
16891 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16892 if (C->getZExtValue() <= 31)
16893 weight = CW_Constant;
16897 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16898 if (C->getZExtValue() <= 63)
16899 weight = CW_Constant;
16903 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16904 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16905 weight = CW_Constant;
16909 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16910 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16911 weight = CW_Constant;
16915 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16916 if (C->getZExtValue() <= 3)
16917 weight = CW_Constant;
16921 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16922 if (C->getZExtValue() <= 0xff)
16923 weight = CW_Constant;
16928 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16929 weight = CW_Constant;
16933 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16934 if ((C->getSExtValue() >= -0x80000000LL) &&
16935 (C->getSExtValue() <= 0x7fffffffLL))
16936 weight = CW_Constant;
16940 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16941 if (C->getZExtValue() <= 0xffffffff)
16942 weight = CW_Constant;
16949 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16950 /// with another that has more specific requirements based on the type of the
16951 /// corresponding operand.
16952 const char *X86TargetLowering::
16953 LowerXConstraint(EVT ConstraintVT) const {
16954 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16955 // 'f' like normal targets.
16956 if (ConstraintVT.isFloatingPoint()) {
16957 if (Subtarget->hasSSE2())
16959 if (Subtarget->hasSSE1())
16963 return TargetLowering::LowerXConstraint(ConstraintVT);
16966 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16967 /// vector. If it is invalid, don't add anything to Ops.
16968 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16969 std::string &Constraint,
16970 std::vector<SDValue>&Ops,
16971 SelectionDAG &DAG) const {
16972 SDValue Result(0, 0);
16974 // Only support length 1 constraints for now.
16975 if (Constraint.length() > 1) return;
16977 char ConstraintLetter = Constraint[0];
16978 switch (ConstraintLetter) {
16981 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16982 if (C->getZExtValue() <= 31) {
16983 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16990 if (C->getZExtValue() <= 63) {
16991 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16997 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16998 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16999 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17005 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17006 if (C->getZExtValue() <= 255) {
17007 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17013 // 32-bit signed value
17014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17015 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17016 C->getSExtValue())) {
17017 // Widen to 64 bits here to get it sign extended.
17018 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17021 // FIXME gcc accepts some relocatable values here too, but only in certain
17022 // memory models; it's complicated.
17027 // 32-bit unsigned value
17028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17029 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17030 C->getZExtValue())) {
17031 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17035 // FIXME gcc accepts some relocatable values here too, but only in certain
17036 // memory models; it's complicated.
17040 // Literal immediates are always ok.
17041 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17042 // Widen to 64 bits here to get it sign extended.
17043 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17047 // In any sort of PIC mode addresses need to be computed at runtime by
17048 // adding in a register or some sort of table lookup. These can't
17049 // be used as immediates.
17050 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17053 // If we are in non-pic codegen mode, we allow the address of a global (with
17054 // an optional displacement) to be used with 'i'.
17055 GlobalAddressSDNode *GA = 0;
17056 int64_t Offset = 0;
17058 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17060 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17061 Offset += GA->getOffset();
17063 } else if (Op.getOpcode() == ISD::ADD) {
17064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17065 Offset += C->getZExtValue();
17066 Op = Op.getOperand(0);
17069 } else if (Op.getOpcode() == ISD::SUB) {
17070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17071 Offset += -C->getZExtValue();
17072 Op = Op.getOperand(0);
17077 // Otherwise, this isn't something we can handle, reject it.
17081 const GlobalValue *GV = GA->getGlobal();
17082 // If we require an extra load to get this address, as in PIC mode, we
17083 // can't accept it.
17084 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17085 getTargetMachine())))
17088 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17089 GA->getValueType(0), Offset);
17094 if (Result.getNode()) {
17095 Ops.push_back(Result);
17098 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17101 std::pair<unsigned, const TargetRegisterClass*>
17102 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17104 // First, see if this is a constraint that directly corresponds to an LLVM
17106 if (Constraint.size() == 1) {
17107 // GCC Constraint Letters
17108 switch (Constraint[0]) {
17110 // TODO: Slight differences here in allocation order and leaving
17111 // RIP in the class. Do they matter any more here than they do
17112 // in the normal allocation?
17113 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17114 if (Subtarget->is64Bit()) {
17115 if (VT == MVT::i32 || VT == MVT::f32)
17116 return std::make_pair(0U, &X86::GR32RegClass);
17117 if (VT == MVT::i16)
17118 return std::make_pair(0U, &X86::GR16RegClass);
17119 if (VT == MVT::i8 || VT == MVT::i1)
17120 return std::make_pair(0U, &X86::GR8RegClass);
17121 if (VT == MVT::i64 || VT == MVT::f64)
17122 return std::make_pair(0U, &X86::GR64RegClass);
17125 // 32-bit fallthrough
17126 case 'Q': // Q_REGS
17127 if (VT == MVT::i32 || VT == MVT::f32)
17128 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17129 if (VT == MVT::i16)
17130 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17131 if (VT == MVT::i8 || VT == MVT::i1)
17132 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17133 if (VT == MVT::i64)
17134 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17136 case 'r': // GENERAL_REGS
17137 case 'l': // INDEX_REGS
17138 if (VT == MVT::i8 || VT == MVT::i1)
17139 return std::make_pair(0U, &X86::GR8RegClass);
17140 if (VT == MVT::i16)
17141 return std::make_pair(0U, &X86::GR16RegClass);
17142 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17143 return std::make_pair(0U, &X86::GR32RegClass);
17144 return std::make_pair(0U, &X86::GR64RegClass);
17145 case 'R': // LEGACY_REGS
17146 if (VT == MVT::i8 || VT == MVT::i1)
17147 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17148 if (VT == MVT::i16)
17149 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17150 if (VT == MVT::i32 || !Subtarget->is64Bit())
17151 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17152 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17153 case 'f': // FP Stack registers.
17154 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17155 // value to the correct fpstack register class.
17156 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17157 return std::make_pair(0U, &X86::RFP32RegClass);
17158 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17159 return std::make_pair(0U, &X86::RFP64RegClass);
17160 return std::make_pair(0U, &X86::RFP80RegClass);
17161 case 'y': // MMX_REGS if MMX allowed.
17162 if (!Subtarget->hasMMX()) break;
17163 return std::make_pair(0U, &X86::VR64RegClass);
17164 case 'Y': // SSE_REGS if SSE2 allowed
17165 if (!Subtarget->hasSSE2()) break;
17167 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17168 if (!Subtarget->hasSSE1()) break;
17170 switch (VT.getSimpleVT().SimpleTy) {
17172 // Scalar SSE types.
17175 return std::make_pair(0U, &X86::FR32RegClass);
17178 return std::make_pair(0U, &X86::FR64RegClass);
17186 return std::make_pair(0U, &X86::VR128RegClass);
17194 return std::make_pair(0U, &X86::VR256RegClass);
17200 // Use the default implementation in TargetLowering to convert the register
17201 // constraint into a member of a register class.
17202 std::pair<unsigned, const TargetRegisterClass*> Res;
17203 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17205 // Not found as a standard register?
17206 if (Res.second == 0) {
17207 // Map st(0) -> st(7) -> ST0
17208 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17209 tolower(Constraint[1]) == 's' &&
17210 tolower(Constraint[2]) == 't' &&
17211 Constraint[3] == '(' &&
17212 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17213 Constraint[5] == ')' &&
17214 Constraint[6] == '}') {
17216 Res.first = X86::ST0+Constraint[4]-'0';
17217 Res.second = &X86::RFP80RegClass;
17221 // GCC allows "st(0)" to be called just plain "st".
17222 if (StringRef("{st}").equals_lower(Constraint)) {
17223 Res.first = X86::ST0;
17224 Res.second = &X86::RFP80RegClass;
17229 if (StringRef("{flags}").equals_lower(Constraint)) {
17230 Res.first = X86::EFLAGS;
17231 Res.second = &X86::CCRRegClass;
17235 // 'A' means EAX + EDX.
17236 if (Constraint == "A") {
17237 Res.first = X86::EAX;
17238 Res.second = &X86::GR32_ADRegClass;
17244 // Otherwise, check to see if this is a register class of the wrong value
17245 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17246 // turn into {ax},{dx}.
17247 if (Res.second->hasType(VT))
17248 return Res; // Correct type already, nothing to do.
17250 // All of the single-register GCC register classes map their values onto
17251 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17252 // really want an 8-bit or 32-bit register, map to the appropriate register
17253 // class and return the appropriate register.
17254 if (Res.second == &X86::GR16RegClass) {
17255 if (VT == MVT::i8) {
17256 unsigned DestReg = 0;
17257 switch (Res.first) {
17259 case X86::AX: DestReg = X86::AL; break;
17260 case X86::DX: DestReg = X86::DL; break;
17261 case X86::CX: DestReg = X86::CL; break;
17262 case X86::BX: DestReg = X86::BL; break;
17265 Res.first = DestReg;
17266 Res.second = &X86::GR8RegClass;
17268 } else if (VT == MVT::i32) {
17269 unsigned DestReg = 0;
17270 switch (Res.first) {
17272 case X86::AX: DestReg = X86::EAX; break;
17273 case X86::DX: DestReg = X86::EDX; break;
17274 case X86::CX: DestReg = X86::ECX; break;
17275 case X86::BX: DestReg = X86::EBX; break;
17276 case X86::SI: DestReg = X86::ESI; break;
17277 case X86::DI: DestReg = X86::EDI; break;
17278 case X86::BP: DestReg = X86::EBP; break;
17279 case X86::SP: DestReg = X86::ESP; break;
17282 Res.first = DestReg;
17283 Res.second = &X86::GR32RegClass;
17285 } else if (VT == MVT::i64) {
17286 unsigned DestReg = 0;
17287 switch (Res.first) {
17289 case X86::AX: DestReg = X86::RAX; break;
17290 case X86::DX: DestReg = X86::RDX; break;
17291 case X86::CX: DestReg = X86::RCX; break;
17292 case X86::BX: DestReg = X86::RBX; break;
17293 case X86::SI: DestReg = X86::RSI; break;
17294 case X86::DI: DestReg = X86::RDI; break;
17295 case X86::BP: DestReg = X86::RBP; break;
17296 case X86::SP: DestReg = X86::RSP; break;
17299 Res.first = DestReg;
17300 Res.second = &X86::GR64RegClass;
17303 } else if (Res.second == &X86::FR32RegClass ||
17304 Res.second == &X86::FR64RegClass ||
17305 Res.second == &X86::VR128RegClass) {
17306 // Handle references to XMM physical registers that got mapped into the
17307 // wrong class. This can happen with constraints like {xmm0} where the
17308 // target independent register mapper will just pick the first match it can
17309 // find, ignoring the required type.
17311 if (VT == MVT::f32 || VT == MVT::i32)
17312 Res.second = &X86::FR32RegClass;
17313 else if (VT == MVT::f64 || VT == MVT::i64)
17314 Res.second = &X86::FR64RegClass;
17315 else if (X86::VR128RegClass.hasType(VT))
17316 Res.second = &X86::VR128RegClass;
17317 else if (X86::VR256RegClass.hasType(VT))
17318 Res.second = &X86::VR256RegClass;