1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getDataLayout();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDiv(32, 8);
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462 // support continuation, user-level threading, and etc.. As a result, no
463 // other SjLj exception interfaces are implemented and please don't build
464 // your own exception handling based on them.
465 // LLVM/Clang supports zero-cost DWARF exception handling.
466 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
470 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
471 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
473 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
474 if (Subtarget->is64Bit())
475 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
477 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
480 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
481 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
482 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
483 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
485 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
488 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
492 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
495 if (Subtarget->hasSSE1())
496 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
498 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
499 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
501 // On X86 and X86-64, atomic operations are lowered to locked instructions.
502 // Locked instructions, in turn, have implicit fence semantics (all memory
503 // operations are flushed before issuing the locked instruction, and they
504 // are not buffered), so we can fold away the common pattern of
505 // fence-atomic-fence.
506 setShouldFoldAtomicFences(true);
508 // Expand certain atomics
509 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
511 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
516 if (!Subtarget->is64Bit()) {
517 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
531 if (Subtarget->hasCmpxchg16b()) {
532 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
535 // FIXME - use subtarget debug flags
536 if (!Subtarget->isTargetDarwin() &&
537 !Subtarget->isTargetELF() &&
538 !Subtarget->isTargetCygMing()) {
539 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
542 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
544 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
546 if (Subtarget->is64Bit()) {
547 setExceptionPointerRegister(X86::RAX);
548 setExceptionSelectorRegister(X86::RDX);
550 setExceptionPointerRegister(X86::EAX);
551 setExceptionSelectorRegister(X86::EDX);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
556 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
559 setOperationAction(ISD::TRAP, MVT::Other, Legal);
560 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
562 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563 setOperationAction(ISD::VASTART , MVT::Other, Custom);
564 setOperationAction(ISD::VAEND , MVT::Other, Expand);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::VAARG , MVT::Other, Custom);
567 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
569 setOperationAction(ISD::VAARG , MVT::Other, Expand);
570 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
573 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
574 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
576 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578 MVT::i64 : MVT::i32, Custom);
579 else if (TM.Options.EnableSegmentedStacks)
580 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581 MVT::i64 : MVT::i32, Custom);
583 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584 MVT::i64 : MVT::i32, Expand);
586 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587 // f32 and f64 use SSE.
588 // Set up the FP register classes.
589 addRegisterClass(MVT::f32, &X86::FR32RegClass);
590 addRegisterClass(MVT::f64, &X86::FR64RegClass);
592 // Use ANDPD to simulate FABS.
593 setOperationAction(ISD::FABS , MVT::f64, Custom);
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f64, Custom);
598 setOperationAction(ISD::FNEG , MVT::f32, Custom);
600 // Use ANDPD and ORPD to simulate FCOPYSIGN.
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604 // Lower this to FGETSIGNx86 plus an AND.
605 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
608 // We don't support sin/cos/fmod
609 setOperationAction(ISD::FSIN , MVT::f64, Expand);
610 setOperationAction(ISD::FCOS , MVT::f64, Expand);
611 setOperationAction(ISD::FSIN , MVT::f32, Expand);
612 setOperationAction(ISD::FCOS , MVT::f32, Expand);
614 // Expand FP immediates into loads from the stack, except for the special
616 addLegalFPImmediate(APFloat(+0.0)); // xorpd
617 addLegalFPImmediate(APFloat(+0.0f)); // xorps
618 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619 // Use SSE for f32, x87 for f64.
620 // Set up the FP register classes.
621 addRegisterClass(MVT::f32, &X86::FR32RegClass);
622 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
624 // Use ANDPS to simulate FABS.
625 setOperationAction(ISD::FABS , MVT::f32, Custom);
627 // Use XORP to simulate FNEG.
628 setOperationAction(ISD::FNEG , MVT::f32, Custom);
630 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
632 // Use ANDPS and ORPS to simulate FCOPYSIGN.
633 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
636 // We don't support sin/cos/fmod
637 setOperationAction(ISD::FSIN , MVT::f32, Expand);
638 setOperationAction(ISD::FCOS , MVT::f32, Expand);
640 // Special cases we handle for FP constants.
641 addLegalFPImmediate(APFloat(+0.0f)); // xorps
642 addLegalFPImmediate(APFloat(+0.0)); // FLD0
643 addLegalFPImmediate(APFloat(+1.0)); // FLD1
644 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647 if (!TM.Options.UnsafeFPMath) {
648 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
649 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
651 } else if (!TM.Options.UseSoftFloat) {
652 // f32 and f64 in x87.
653 // Set up the FP register classes.
654 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
657 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
658 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
662 if (!TM.Options.UnsafeFPMath) {
663 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
664 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
666 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
668 addLegalFPImmediate(APFloat(+0.0)); // FLD0
669 addLegalFPImmediate(APFloat(+1.0)); // FLD1
670 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
678 // We don't support FMA.
679 setOperationAction(ISD::FMA, MVT::f64, Expand);
680 setOperationAction(ISD::FMA, MVT::f32, Expand);
682 // Long double always uses X87.
683 if (!TM.Options.UseSoftFloat) {
684 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
686 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
688 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689 addLegalFPImmediate(TmpFlt); // FLD0
691 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
694 APFloat TmpFlt2(+1.0);
695 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
697 addLegalFPImmediate(TmpFlt2); // FLD1
698 TmpFlt2.changeSign();
699 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
702 if (!TM.Options.UnsafeFPMath) {
703 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
704 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
707 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
709 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710 setOperationAction(ISD::FRINT, MVT::f80, Expand);
711 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712 setOperationAction(ISD::FMA, MVT::f80, Expand);
715 // Always use a library call for pow.
716 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
718 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
720 setOperationAction(ISD::FLOG, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP, MVT::f80, Expand);
724 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
726 // First set operation action for all vector types to either promote
727 // (for widening) or expand (for scalarization). Then we will selectively
728 // turn on ones that can be effectively codegen'd.
729 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
786 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
787 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
788 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
789 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
790 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792 setTruncStoreAction((MVT::SimpleValueType)VT,
793 (MVT::SimpleValueType)InnerVT, Expand);
794 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
799 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800 // with -msoft-float, disable use of MMX as well.
801 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803 // No operations on x86mmx supported, everything uses intrinsics.
806 // MMX-sized vectors (other than x86mmx) are expected to be expanded
807 // into smaller operations.
808 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
809 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
810 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
811 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
812 setOperationAction(ISD::AND, MVT::v8i8, Expand);
813 setOperationAction(ISD::AND, MVT::v4i16, Expand);
814 setOperationAction(ISD::AND, MVT::v2i32, Expand);
815 setOperationAction(ISD::AND, MVT::v1i64, Expand);
816 setOperationAction(ISD::OR, MVT::v8i8, Expand);
817 setOperationAction(ISD::OR, MVT::v4i16, Expand);
818 setOperationAction(ISD::OR, MVT::v2i32, Expand);
819 setOperationAction(ISD::OR, MVT::v1i64, Expand);
820 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
821 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
822 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
823 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
829 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
830 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
831 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
832 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
833 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
834 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
835 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
836 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
838 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
841 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
842 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
843 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
844 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
845 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
846 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
847 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
848 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
849 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
850 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
855 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
858 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859 // registers cannot be used even for integer operations.
860 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
865 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
866 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
867 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
868 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
869 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
870 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
871 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
872 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
873 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
874 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
875 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
876 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
877 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
878 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
879 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
880 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
881 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
883 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
884 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
885 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
886 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
897 // Do not attempt to custom lower non-power-of-2 vectors
898 if (!isPowerOf2_32(VT.getVectorNumElements()))
900 // Do not attempt to custom lower non-128-bit vectors
901 if (!VT.is128BitVector())
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
909 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
911 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
915 if (Subtarget->is64Bit()) {
916 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
920 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922 MVT VT = (MVT::SimpleValueType)i;
924 // Do not attempt to promote non-128-bit vectors
925 if (!VT.is128BitVector())
928 setOperationAction(ISD::AND, VT, Promote);
929 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
930 setOperationAction(ISD::OR, VT, Promote);
931 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
932 setOperationAction(ISD::XOR, VT, Promote);
933 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
934 setOperationAction(ISD::LOAD, VT, Promote);
935 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
936 setOperationAction(ISD::SELECT, VT, Promote);
937 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
940 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // Custom lower v2i64 and v2f64 selects.
943 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
944 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
945 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
946 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
948 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
949 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
951 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
952 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
954 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
957 if (Subtarget->hasSSE41()) {
958 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
959 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
960 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
961 setOperationAction(ISD::FRINT, MVT::f32, Legal);
962 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
963 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
964 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
965 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
966 setOperationAction(ISD::FRINT, MVT::f64, Legal);
967 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
969 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
970 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
972 // FIXME: Do we need to handle scalar-to-vector here?
973 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
975 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
976 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
977 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
978 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
979 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
981 // i8 and i16 vectors are custom , because the source register and source
982 // source memory operand types are not the same width. f32 vectors are
983 // custom since the immediate controlling the insert encodes additional
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
995 // FIXME: these should be Legal but thats only for the case where
996 // the index is constant. For now custom expand to deal with that.
997 if (Subtarget->is64Bit()) {
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003 if (Subtarget->hasSSE2()) {
1004 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1005 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1007 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1008 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1010 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1013 if (Subtarget->hasAVX2()) {
1014 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1015 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1017 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1022 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1023 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1025 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1032 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1033 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1040 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1042 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1044 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1051 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1053 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1060 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1062 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1064 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1066 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1067 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1068 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1070 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1072 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1073 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1075 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1076 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1078 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1079 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1081 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1083 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1084 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1086 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1087 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1088 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1090 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1091 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1092 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1093 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1095 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1096 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1097 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1098 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1099 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1100 setOperationAction(ISD::FMA, MVT::f32, Custom);
1101 setOperationAction(ISD::FMA, MVT::f64, Custom);
1104 if (Subtarget->hasAVX2()) {
1105 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1106 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1107 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1108 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1110 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1111 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1112 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1113 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1115 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1116 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1117 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1118 // Don't lower v32i8 because there is no 128-bit byte mul
1120 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1122 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1123 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1125 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1126 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1128 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1130 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1131 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1132 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1133 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1135 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1136 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1137 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1138 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1140 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1141 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1142 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1143 // Don't lower v32i8 because there is no 128-bit byte mul
1145 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1146 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1148 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1149 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1151 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1154 // Custom lower several nodes for 256-bit types.
1155 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1156 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1157 MVT VT = (MVT::SimpleValueType)i;
1159 // Extract subvector is special because the value type
1160 // (result) is 128-bit but the source is 256-bit wide.
1161 if (VT.is128BitVector())
1162 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1164 // Do not attempt to custom lower other non-256-bit vectors
1165 if (!VT.is256BitVector())
1168 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1169 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1170 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1171 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1172 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1173 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1174 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1177 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1178 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1179 MVT VT = (MVT::SimpleValueType)i;
1181 // Do not attempt to promote non-256-bit vectors
1182 if (!VT.is256BitVector())
1185 setOperationAction(ISD::AND, VT, Promote);
1186 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1187 setOperationAction(ISD::OR, VT, Promote);
1188 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1189 setOperationAction(ISD::XOR, VT, Promote);
1190 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1191 setOperationAction(ISD::LOAD, VT, Promote);
1192 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1193 setOperationAction(ISD::SELECT, VT, Promote);
1194 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1198 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1199 // of this type with custom code.
1200 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1201 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1202 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1206 // We want to custom lower some of our intrinsics.
1207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1208 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1211 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1212 // handle type legalization for these operations here.
1214 // FIXME: We really should do custom legalization for addition and
1215 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1216 // than generic legalization for 64-bit multiplication-with-overflow, though.
1217 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1218 // Add/Sub/Mul with overflow operations are custom lowered.
1220 setOperationAction(ISD::SADDO, VT, Custom);
1221 setOperationAction(ISD::UADDO, VT, Custom);
1222 setOperationAction(ISD::SSUBO, VT, Custom);
1223 setOperationAction(ISD::USUBO, VT, Custom);
1224 setOperationAction(ISD::SMULO, VT, Custom);
1225 setOperationAction(ISD::UMULO, VT, Custom);
1228 // There are no 8-bit 3-address imul/mul instructions
1229 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1230 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1232 if (!Subtarget->is64Bit()) {
1233 // These libcalls are not available in 32-bit.
1234 setLibcallName(RTLIB::SHL_I128, 0);
1235 setLibcallName(RTLIB::SRL_I128, 0);
1236 setLibcallName(RTLIB::SRA_I128, 0);
1239 // We have target-specific dag combine patterns for the following nodes:
1240 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1241 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1242 setTargetDAGCombine(ISD::VSELECT);
1243 setTargetDAGCombine(ISD::SELECT);
1244 setTargetDAGCombine(ISD::SHL);
1245 setTargetDAGCombine(ISD::SRA);
1246 setTargetDAGCombine(ISD::SRL);
1247 setTargetDAGCombine(ISD::OR);
1248 setTargetDAGCombine(ISD::AND);
1249 setTargetDAGCombine(ISD::ADD);
1250 setTargetDAGCombine(ISD::FADD);
1251 setTargetDAGCombine(ISD::FSUB);
1252 setTargetDAGCombine(ISD::FMA);
1253 setTargetDAGCombine(ISD::SUB);
1254 setTargetDAGCombine(ISD::LOAD);
1255 setTargetDAGCombine(ISD::STORE);
1256 setTargetDAGCombine(ISD::ZERO_EXTEND);
1257 setTargetDAGCombine(ISD::ANY_EXTEND);
1258 setTargetDAGCombine(ISD::SIGN_EXTEND);
1259 setTargetDAGCombine(ISD::TRUNCATE);
1260 setTargetDAGCombine(ISD::UINT_TO_FP);
1261 setTargetDAGCombine(ISD::SINT_TO_FP);
1262 setTargetDAGCombine(ISD::SETCC);
1263 if (Subtarget->is64Bit())
1264 setTargetDAGCombine(ISD::MUL);
1265 setTargetDAGCombine(ISD::XOR);
1267 computeRegisterProperties();
1269 // On Darwin, -Os means optimize for size without hurting performance,
1270 // do not reduce the limit.
1271 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1272 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1273 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1274 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1275 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1276 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1277 setPrefLoopAlignment(4); // 2^4 bytes.
1278 benefitFromCodePlacementOpt = true;
1280 // Predictable cmov don't hurt on atom because it's in-order.
1281 predictableSelectIsExpensive = !Subtarget->isAtom();
1283 setPrefFunctionAlignment(4); // 2^4 bytes.
1287 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1288 if (!VT.isVector()) return MVT::i8;
1289 return VT.changeVectorElementTypeToInteger();
1293 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1294 /// the desired ByVal argument alignment.
1295 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1298 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1299 if (VTy->getBitWidth() == 128)
1301 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1302 unsigned EltAlign = 0;
1303 getMaxByValAlign(ATy->getElementType(), EltAlign);
1304 if (EltAlign > MaxAlign)
1305 MaxAlign = EltAlign;
1306 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1307 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1308 unsigned EltAlign = 0;
1309 getMaxByValAlign(STy->getElementType(i), EltAlign);
1310 if (EltAlign > MaxAlign)
1311 MaxAlign = EltAlign;
1318 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1319 /// function arguments in the caller parameter area. For X86, aggregates
1320 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1321 /// are at 4-byte boundaries.
1322 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1323 if (Subtarget->is64Bit()) {
1324 // Max of 8 and alignment of type.
1325 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1332 if (Subtarget->hasSSE1())
1333 getMaxByValAlign(Ty, Align);
1337 /// getOptimalMemOpType - Returns the target specific optimal type for load
1338 /// and store operations as a result of memset, memcpy, and memmove
1339 /// lowering. If DstAlign is zero that means it's safe to destination
1340 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1341 /// means there isn't a need to check it against alignment requirement,
1342 /// probably because the source does not need to be loaded. If
1343 /// 'IsZeroVal' is true, that means it's safe to return a
1344 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1345 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1346 /// constant so it does not need to be loaded.
1347 /// It returns EVT::Other if the type should be determined using generic
1348 /// target-independent logic.
1350 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1351 unsigned DstAlign, unsigned SrcAlign,
1354 MachineFunction &MF) const {
1355 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1356 // linux. This is because the stack realignment code can't handle certain
1357 // cases like PR2962. This should be removed when PR2962 is fixed.
1358 const Function *F = MF.getFunction();
1360 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1362 (Subtarget->isUnalignedMemAccessFast() ||
1363 ((DstAlign == 0 || DstAlign >= 16) &&
1364 (SrcAlign == 0 || SrcAlign >= 16))) &&
1365 Subtarget->getStackAlignment() >= 16) {
1366 if (Subtarget->getStackAlignment() >= 32) {
1367 if (Subtarget->hasAVX2())
1369 if (Subtarget->hasAVX())
1372 if (Subtarget->hasSSE2())
1374 if (Subtarget->hasSSE1())
1376 } else if (!MemcpyStrSrc && Size >= 8 &&
1377 !Subtarget->is64Bit() &&
1378 Subtarget->getStackAlignment() >= 8 &&
1379 Subtarget->hasSSE2()) {
1380 // Do not use f64 to lower memcpy if source is string constant. It's
1381 // better to use i32 to avoid the loads.
1385 if (Subtarget->is64Bit() && Size >= 8)
1390 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1391 /// current function. The returned value is a member of the
1392 /// MachineJumpTableInfo::JTEntryKind enum.
1393 unsigned X86TargetLowering::getJumpTableEncoding() const {
1394 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1396 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1397 Subtarget->isPICStyleGOT())
1398 return MachineJumpTableInfo::EK_Custom32;
1400 // Otherwise, use the normal jump table encoding heuristics.
1401 return TargetLowering::getJumpTableEncoding();
1405 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1406 const MachineBasicBlock *MBB,
1407 unsigned uid,MCContext &Ctx) const{
1408 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1409 Subtarget->isPICStyleGOT());
1410 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1412 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1413 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1416 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1418 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1419 SelectionDAG &DAG) const {
1420 if (!Subtarget->is64Bit())
1421 // This doesn't have DebugLoc associated with it, but is not really the
1422 // same as a Register.
1423 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1427 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1428 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1430 const MCExpr *X86TargetLowering::
1431 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1432 MCContext &Ctx) const {
1433 // X86-64 uses RIP relative addressing based on the jump table label.
1434 if (Subtarget->isPICStyleRIPRel())
1435 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1437 // Otherwise, the reference is relative to the PIC base.
1438 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1441 // FIXME: Why this routine is here? Move to RegInfo!
1442 std::pair<const TargetRegisterClass*, uint8_t>
1443 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1444 const TargetRegisterClass *RRC = 0;
1446 switch (VT.getSimpleVT().SimpleTy) {
1448 return TargetLowering::findRepresentativeClass(VT);
1449 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1450 RRC = Subtarget->is64Bit() ?
1451 (const TargetRegisterClass*)&X86::GR64RegClass :
1452 (const TargetRegisterClass*)&X86::GR32RegClass;
1455 RRC = &X86::VR64RegClass;
1457 case MVT::f32: case MVT::f64:
1458 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1459 case MVT::v4f32: case MVT::v2f64:
1460 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1462 RRC = &X86::VR128RegClass;
1465 return std::make_pair(RRC, Cost);
1468 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1469 unsigned &Offset) const {
1470 if (!Subtarget->isTargetLinux())
1473 if (Subtarget->is64Bit()) {
1474 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1476 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1489 //===----------------------------------------------------------------------===//
1490 // Return Value Calling Convention Implementation
1491 //===----------------------------------------------------------------------===//
1493 #include "X86GenCallingConv.inc"
1496 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1497 MachineFunction &MF, bool isVarArg,
1498 const SmallVectorImpl<ISD::OutputArg> &Outs,
1499 LLVMContext &Context) const {
1500 SmallVector<CCValAssign, 16> RVLocs;
1501 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1503 return CCInfo.CheckReturn(Outs, RetCC_X86);
1507 X86TargetLowering::LowerReturn(SDValue Chain,
1508 CallingConv::ID CallConv, bool isVarArg,
1509 const SmallVectorImpl<ISD::OutputArg> &Outs,
1510 const SmallVectorImpl<SDValue> &OutVals,
1511 DebugLoc dl, SelectionDAG &DAG) const {
1512 MachineFunction &MF = DAG.getMachineFunction();
1513 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1515 SmallVector<CCValAssign, 16> RVLocs;
1516 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1517 RVLocs, *DAG.getContext());
1518 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1520 // Add the regs to the liveout set for the function.
1521 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1522 for (unsigned i = 0; i != RVLocs.size(); ++i)
1523 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1524 MRI.addLiveOut(RVLocs[i].getLocReg());
1528 SmallVector<SDValue, 6> RetOps;
1529 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1530 // Operand #1 = Bytes To Pop
1531 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1534 // Copy the result values into the output registers.
1535 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1536 CCValAssign &VA = RVLocs[i];
1537 assert(VA.isRegLoc() && "Can only return in registers!");
1538 SDValue ValToCopy = OutVals[i];
1539 EVT ValVT = ValToCopy.getValueType();
1541 // Promote values to the appropriate types
1542 if (VA.getLocInfo() == CCValAssign::SExt)
1543 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1544 else if (VA.getLocInfo() == CCValAssign::ZExt)
1545 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1546 else if (VA.getLocInfo() == CCValAssign::AExt)
1547 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1548 else if (VA.getLocInfo() == CCValAssign::BCvt)
1549 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1551 // If this is x86-64, and we disabled SSE, we can't return FP values,
1552 // or SSE or MMX vectors.
1553 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1554 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1555 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1556 report_fatal_error("SSE register return with SSE disabled");
1558 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1559 // llvm-gcc has never done it right and no one has noticed, so this
1560 // should be OK for now.
1561 if (ValVT == MVT::f64 &&
1562 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1563 report_fatal_error("SSE2 register return with SSE2 disabled");
1565 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1566 // the RET instruction and handled by the FP Stackifier.
1567 if (VA.getLocReg() == X86::ST0 ||
1568 VA.getLocReg() == X86::ST1) {
1569 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1570 // change the value to the FP stack register class.
1571 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1572 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1573 RetOps.push_back(ValToCopy);
1574 // Don't emit a copytoreg.
1578 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1579 // which is returned in RAX / RDX.
1580 if (Subtarget->is64Bit()) {
1581 if (ValVT == MVT::x86mmx) {
1582 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1583 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1584 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1586 // If we don't have SSE2 available, convert to v4f32 so the generated
1587 // register is legal.
1588 if (!Subtarget->hasSSE2())
1589 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1594 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1595 Flag = Chain.getValue(1);
1598 // The x86-64 ABI for returning structs by value requires that we copy
1599 // the sret argument into %rax for the return. We saved the argument into
1600 // a virtual register in the entry block, so now we copy the value out
1602 if (Subtarget->is64Bit() &&
1603 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1604 MachineFunction &MF = DAG.getMachineFunction();
1605 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1606 unsigned Reg = FuncInfo->getSRetReturnReg();
1608 "SRetReturnReg should have been set in LowerFormalArguments().");
1609 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1611 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1612 Flag = Chain.getValue(1);
1614 // RAX now acts like a return value.
1615 MRI.addLiveOut(X86::RAX);
1618 RetOps[0] = Chain; // Update chain.
1620 // Add the flag if we have it.
1622 RetOps.push_back(Flag);
1624 return DAG.getNode(X86ISD::RET_FLAG, dl,
1625 MVT::Other, &RetOps[0], RetOps.size());
1628 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1629 if (N->getNumValues() != 1)
1631 if (!N->hasNUsesOfValue(1, 0))
1634 SDValue TCChain = Chain;
1635 SDNode *Copy = *N->use_begin();
1636 if (Copy->getOpcode() == ISD::CopyToReg) {
1637 // If the copy has a glue operand, we conservatively assume it isn't safe to
1638 // perform a tail call.
1639 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1641 TCChain = Copy->getOperand(0);
1642 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1645 bool HasRet = false;
1646 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1648 if (UI->getOpcode() != X86ISD::RET_FLAG)
1661 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1662 ISD::NodeType ExtendKind) const {
1664 // TODO: Is this also valid on 32-bit?
1665 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1666 ReturnMVT = MVT::i8;
1668 ReturnMVT = MVT::i32;
1670 EVT MinVT = getRegisterType(Context, ReturnMVT);
1671 return VT.bitsLT(MinVT) ? MinVT : VT;
1674 /// LowerCallResult - Lower the result values of a call into the
1675 /// appropriate copies out of appropriate physical registers.
1678 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1679 CallingConv::ID CallConv, bool isVarArg,
1680 const SmallVectorImpl<ISD::InputArg> &Ins,
1681 DebugLoc dl, SelectionDAG &DAG,
1682 SmallVectorImpl<SDValue> &InVals) const {
1684 // Assign locations to each value returned by this call.
1685 SmallVector<CCValAssign, 16> RVLocs;
1686 bool Is64Bit = Subtarget->is64Bit();
1687 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1688 getTargetMachine(), RVLocs, *DAG.getContext());
1689 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1691 // Copy all of the result registers out of their specified physreg.
1692 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1693 CCValAssign &VA = RVLocs[i];
1694 EVT CopyVT = VA.getValVT();
1696 // If this is x86-64, and we disabled SSE, we can't return FP values
1697 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1698 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1699 report_fatal_error("SSE register return with SSE disabled");
1704 // If this is a call to a function that returns an fp value on the floating
1705 // point stack, we must guarantee the value is popped from the stack, so
1706 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1707 // if the return value is not used. We use the FpPOP_RETVAL instruction
1709 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1710 // If we prefer to use the value in xmm registers, copy it out as f80 and
1711 // use a truncate to move it from fp stack reg to xmm reg.
1712 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1713 SDValue Ops[] = { Chain, InFlag };
1714 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1715 MVT::Other, MVT::Glue, Ops, 2), 1);
1716 Val = Chain.getValue(0);
1718 // Round the f80 to the right size, which also moves it to the appropriate
1720 if (CopyVT != VA.getValVT())
1721 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1722 // This truncation won't change the value.
1723 DAG.getIntPtrConstant(1));
1725 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1726 CopyVT, InFlag).getValue(1);
1727 Val = Chain.getValue(0);
1729 InFlag = Chain.getValue(2);
1730 InVals.push_back(Val);
1737 //===----------------------------------------------------------------------===//
1738 // C & StdCall & Fast Calling Convention implementation
1739 //===----------------------------------------------------------------------===//
1740 // StdCall calling convention seems to be standard for many Windows' API
1741 // routines and around. It differs from C calling convention just a little:
1742 // callee should clean up the stack, not caller. Symbols should be also
1743 // decorated in some fancy way :) It doesn't support any vector arguments.
1744 // For info on fast calling convention see Fast Calling Convention (tail call)
1745 // implementation LowerX86_32FastCCCallTo.
1747 /// CallIsStructReturn - Determines whether a call uses struct return
1749 enum StructReturnType {
1754 static StructReturnType
1755 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1757 return NotStructReturn;
1759 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1760 if (!Flags.isSRet())
1761 return NotStructReturn;
1762 if (Flags.isInReg())
1763 return RegStructReturn;
1764 return StackStructReturn;
1767 /// ArgsAreStructReturn - Determines whether a function uses struct
1768 /// return semantics.
1769 static StructReturnType
1770 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1772 return NotStructReturn;
1774 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1775 if (!Flags.isSRet())
1776 return NotStructReturn;
1777 if (Flags.isInReg())
1778 return RegStructReturn;
1779 return StackStructReturn;
1782 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1783 /// by "Src" to address "Dst" with size and alignment information specified by
1784 /// the specific parameter attribute. The copy will be passed as a byval
1785 /// function parameter.
1787 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1788 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1790 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1792 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1793 /*isVolatile*/false, /*AlwaysInline=*/true,
1794 MachinePointerInfo(), MachinePointerInfo());
1797 /// IsTailCallConvention - Return true if the calling convention is one that
1798 /// supports tail call optimization.
1799 static bool IsTailCallConvention(CallingConv::ID CC) {
1800 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1803 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1804 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1808 CallingConv::ID CalleeCC = CS.getCallingConv();
1809 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1815 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1816 /// a tailcall target by changing its ABI.
1817 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1818 bool GuaranteedTailCallOpt) {
1819 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1823 X86TargetLowering::LowerMemArgument(SDValue Chain,
1824 CallingConv::ID CallConv,
1825 const SmallVectorImpl<ISD::InputArg> &Ins,
1826 DebugLoc dl, SelectionDAG &DAG,
1827 const CCValAssign &VA,
1828 MachineFrameInfo *MFI,
1830 // Create the nodes corresponding to a load from this parameter slot.
1831 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1832 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1833 getTargetMachine().Options.GuaranteedTailCallOpt);
1834 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1837 // If value is passed by pointer we have address passed instead of the value
1839 if (VA.getLocInfo() == CCValAssign::Indirect)
1840 ValVT = VA.getLocVT();
1842 ValVT = VA.getValVT();
1844 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1845 // changed with more analysis.
1846 // In case of tail call optimization mark all arguments mutable. Since they
1847 // could be overwritten by lowering of arguments in case of a tail call.
1848 if (Flags.isByVal()) {
1849 unsigned Bytes = Flags.getByValSize();
1850 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1851 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1852 return DAG.getFrameIndex(FI, getPointerTy());
1854 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1855 VA.getLocMemOffset(), isImmutable);
1856 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1857 return DAG.getLoad(ValVT, dl, Chain, FIN,
1858 MachinePointerInfo::getFixedStack(FI),
1859 false, false, false, 0);
1864 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1865 CallingConv::ID CallConv,
1867 const SmallVectorImpl<ISD::InputArg> &Ins,
1870 SmallVectorImpl<SDValue> &InVals)
1872 MachineFunction &MF = DAG.getMachineFunction();
1873 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1875 const Function* Fn = MF.getFunction();
1876 if (Fn->hasExternalLinkage() &&
1877 Subtarget->isTargetCygMing() &&
1878 Fn->getName() == "main")
1879 FuncInfo->setForceFramePointer(true);
1881 MachineFrameInfo *MFI = MF.getFrameInfo();
1882 bool Is64Bit = Subtarget->is64Bit();
1883 bool IsWindows = Subtarget->isTargetWindows();
1884 bool IsWin64 = Subtarget->isTargetWin64();
1886 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1887 "Var args not supported with calling convention fastcc or ghc");
1889 // Assign locations to all of the incoming arguments.
1890 SmallVector<CCValAssign, 16> ArgLocs;
1891 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1892 ArgLocs, *DAG.getContext());
1894 // Allocate shadow area for Win64
1896 CCInfo.AllocateStack(32, 8);
1899 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1901 unsigned LastVal = ~0U;
1903 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1904 CCValAssign &VA = ArgLocs[i];
1905 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1907 assert(VA.getValNo() != LastVal &&
1908 "Don't support value assigned to multiple locs yet");
1910 LastVal = VA.getValNo();
1912 if (VA.isRegLoc()) {
1913 EVT RegVT = VA.getLocVT();
1914 const TargetRegisterClass *RC;
1915 if (RegVT == MVT::i32)
1916 RC = &X86::GR32RegClass;
1917 else if (Is64Bit && RegVT == MVT::i64)
1918 RC = &X86::GR64RegClass;
1919 else if (RegVT == MVT::f32)
1920 RC = &X86::FR32RegClass;
1921 else if (RegVT == MVT::f64)
1922 RC = &X86::FR64RegClass;
1923 else if (RegVT.is256BitVector())
1924 RC = &X86::VR256RegClass;
1925 else if (RegVT.is128BitVector())
1926 RC = &X86::VR128RegClass;
1927 else if (RegVT == MVT::x86mmx)
1928 RC = &X86::VR64RegClass;
1930 llvm_unreachable("Unknown argument type!");
1932 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1933 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1935 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1936 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1938 if (VA.getLocInfo() == CCValAssign::SExt)
1939 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1940 DAG.getValueType(VA.getValVT()));
1941 else if (VA.getLocInfo() == CCValAssign::ZExt)
1942 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1943 DAG.getValueType(VA.getValVT()));
1944 else if (VA.getLocInfo() == CCValAssign::BCvt)
1945 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1947 if (VA.isExtInLoc()) {
1948 // Handle MMX values passed in XMM regs.
1949 if (RegVT.isVector()) {
1950 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1953 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1956 assert(VA.isMemLoc());
1957 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1960 // If value is passed via pointer - do a load.
1961 if (VA.getLocInfo() == CCValAssign::Indirect)
1962 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1963 MachinePointerInfo(), false, false, false, 0);
1965 InVals.push_back(ArgValue);
1968 // The x86-64 ABI for returning structs by value requires that we copy
1969 // the sret argument into %rax for the return. Save the argument into
1970 // a virtual register so that we can access it from the return points.
1971 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1972 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1973 unsigned Reg = FuncInfo->getSRetReturnReg();
1975 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1976 FuncInfo->setSRetReturnReg(Reg);
1978 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1979 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1982 unsigned StackSize = CCInfo.getNextStackOffset();
1983 // Align stack specially for tail calls.
1984 if (FuncIsMadeTailCallSafe(CallConv,
1985 MF.getTarget().Options.GuaranteedTailCallOpt))
1986 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1988 // If the function takes variable number of arguments, make a frame index for
1989 // the start of the first vararg value... for expansion of llvm.va_start.
1991 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1992 CallConv != CallingConv::X86_ThisCall)) {
1993 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1996 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1998 // FIXME: We should really autogenerate these arrays
1999 static const uint16_t GPR64ArgRegsWin64[] = {
2000 X86::RCX, X86::RDX, X86::R8, X86::R9
2002 static const uint16_t GPR64ArgRegs64Bit[] = {
2003 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2005 static const uint16_t XMMArgRegs64Bit[] = {
2006 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2007 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2009 const uint16_t *GPR64ArgRegs;
2010 unsigned NumXMMRegs = 0;
2013 // The XMM registers which might contain var arg parameters are shadowed
2014 // in their paired GPR. So we only need to save the GPR to their home
2016 TotalNumIntRegs = 4;
2017 GPR64ArgRegs = GPR64ArgRegsWin64;
2019 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2020 GPR64ArgRegs = GPR64ArgRegs64Bit;
2022 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2025 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2028 bool NoImplicitFloatOps = Fn->getFnAttributes().
2029 hasAttribute(Attributes::NoImplicitFloat);
2030 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2031 "SSE register cannot be used when SSE is disabled!");
2032 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2033 NoImplicitFloatOps) &&
2034 "SSE register cannot be used when SSE is disabled!");
2035 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2036 !Subtarget->hasSSE1())
2037 // Kernel mode asks for SSE to be disabled, so don't push them
2039 TotalNumXMMRegs = 0;
2042 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2043 // Get to the caller-allocated home save location. Add 8 to account
2044 // for the return address.
2045 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2046 FuncInfo->setRegSaveFrameIndex(
2047 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2048 // Fixup to set vararg frame on shadow area (4 x i64).
2050 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2052 // For X86-64, if there are vararg parameters that are passed via
2053 // registers, then we must store them to their spots on the stack so
2054 // they may be loaded by deferencing the result of va_next.
2055 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2056 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2057 FuncInfo->setRegSaveFrameIndex(
2058 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2062 // Store the integer parameter registers.
2063 SmallVector<SDValue, 8> MemOps;
2064 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2066 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2067 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2068 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2069 DAG.getIntPtrConstant(Offset));
2070 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2071 &X86::GR64RegClass);
2072 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2074 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2075 MachinePointerInfo::getFixedStack(
2076 FuncInfo->getRegSaveFrameIndex(), Offset),
2078 MemOps.push_back(Store);
2082 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2083 // Now store the XMM (fp + vector) parameter registers.
2084 SmallVector<SDValue, 11> SaveXMMOps;
2085 SaveXMMOps.push_back(Chain);
2087 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2088 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2089 SaveXMMOps.push_back(ALVal);
2091 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2092 FuncInfo->getRegSaveFrameIndex()));
2093 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2094 FuncInfo->getVarArgsFPOffset()));
2096 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2097 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2098 &X86::VR128RegClass);
2099 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2100 SaveXMMOps.push_back(Val);
2102 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2104 &SaveXMMOps[0], SaveXMMOps.size()));
2107 if (!MemOps.empty())
2108 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2109 &MemOps[0], MemOps.size());
2113 // Some CCs need callee pop.
2114 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2115 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2116 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2118 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2119 // If this is an sret function, the return should pop the hidden pointer.
2120 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2121 argsAreStructReturn(Ins) == StackStructReturn)
2122 FuncInfo->setBytesToPopOnReturn(4);
2126 // RegSaveFrameIndex is X86-64 only.
2127 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2128 if (CallConv == CallingConv::X86_FastCall ||
2129 CallConv == CallingConv::X86_ThisCall)
2130 // fastcc functions can't have varargs.
2131 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2134 FuncInfo->setArgumentStackSize(StackSize);
2140 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2141 SDValue StackPtr, SDValue Arg,
2142 DebugLoc dl, SelectionDAG &DAG,
2143 const CCValAssign &VA,
2144 ISD::ArgFlagsTy Flags) const {
2145 unsigned LocMemOffset = VA.getLocMemOffset();
2146 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2147 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2148 if (Flags.isByVal())
2149 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2151 return DAG.getStore(Chain, dl, Arg, PtrOff,
2152 MachinePointerInfo::getStack(LocMemOffset),
2156 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2157 /// optimization is performed and it is required.
2159 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2160 SDValue &OutRetAddr, SDValue Chain,
2161 bool IsTailCall, bool Is64Bit,
2162 int FPDiff, DebugLoc dl) const {
2163 // Adjust the Return address stack slot.
2164 EVT VT = getPointerTy();
2165 OutRetAddr = getReturnAddressFrameIndex(DAG);
2167 // Load the "old" Return address.
2168 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2169 false, false, false, 0);
2170 return SDValue(OutRetAddr.getNode(), 1);
2173 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2174 /// optimization is performed and it is required (FPDiff!=0).
2176 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2177 SDValue Chain, SDValue RetAddrFrIdx,
2178 bool Is64Bit, int FPDiff, DebugLoc dl) {
2179 // Store the return address to the appropriate stack slot.
2180 if (!FPDiff) return Chain;
2181 // Calculate the new stack slot for the return address.
2182 int SlotSize = Is64Bit ? 8 : 4;
2183 int NewReturnAddrFI =
2184 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2185 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2186 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2187 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2188 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2194 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2195 SmallVectorImpl<SDValue> &InVals) const {
2196 SelectionDAG &DAG = CLI.DAG;
2197 DebugLoc &dl = CLI.DL;
2198 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2199 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2200 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2201 SDValue Chain = CLI.Chain;
2202 SDValue Callee = CLI.Callee;
2203 CallingConv::ID CallConv = CLI.CallConv;
2204 bool &isTailCall = CLI.IsTailCall;
2205 bool isVarArg = CLI.IsVarArg;
2207 MachineFunction &MF = DAG.getMachineFunction();
2208 bool Is64Bit = Subtarget->is64Bit();
2209 bool IsWin64 = Subtarget->isTargetWin64();
2210 bool IsWindows = Subtarget->isTargetWindows();
2211 StructReturnType SR = callIsStructReturn(Outs);
2212 bool IsSibcall = false;
2214 if (MF.getTarget().Options.DisableTailCalls)
2218 // Check if it's really possible to do a tail call.
2219 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2220 isVarArg, SR != NotStructReturn,
2221 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2222 Outs, OutVals, Ins, DAG);
2224 // Sibcalls are automatically detected tailcalls which do not require
2226 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2233 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2234 "Var args not supported with calling convention fastcc or ghc");
2236 // Analyze operands of the call, assigning locations to each operand.
2237 SmallVector<CCValAssign, 16> ArgLocs;
2238 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2239 ArgLocs, *DAG.getContext());
2241 // Allocate shadow area for Win64
2243 CCInfo.AllocateStack(32, 8);
2246 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2248 // Get a count of how many bytes are to be pushed on the stack.
2249 unsigned NumBytes = CCInfo.getNextStackOffset();
2251 // This is a sibcall. The memory operands are available in caller's
2252 // own caller's stack.
2254 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2255 IsTailCallConvention(CallConv))
2256 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2259 if (isTailCall && !IsSibcall) {
2260 // Lower arguments at fp - stackoffset + fpdiff.
2261 unsigned NumBytesCallerPushed =
2262 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2263 FPDiff = NumBytesCallerPushed - NumBytes;
2265 // Set the delta of movement of the returnaddr stackslot.
2266 // But only set if delta is greater than previous delta.
2267 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2268 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2272 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2274 SDValue RetAddrFrIdx;
2275 // Load return address for tail calls.
2276 if (isTailCall && FPDiff)
2277 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2278 Is64Bit, FPDiff, dl);
2280 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2281 SmallVector<SDValue, 8> MemOpChains;
2284 // Walk the register/memloc assignments, inserting copies/loads. In the case
2285 // of tail call optimization arguments are handle later.
2286 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2287 CCValAssign &VA = ArgLocs[i];
2288 EVT RegVT = VA.getLocVT();
2289 SDValue Arg = OutVals[i];
2290 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2291 bool isByVal = Flags.isByVal();
2293 // Promote the value if needed.
2294 switch (VA.getLocInfo()) {
2295 default: llvm_unreachable("Unknown loc info!");
2296 case CCValAssign::Full: break;
2297 case CCValAssign::SExt:
2298 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2300 case CCValAssign::ZExt:
2301 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2303 case CCValAssign::AExt:
2304 if (RegVT.is128BitVector()) {
2305 // Special case: passing MMX values in XMM registers.
2306 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2307 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2308 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2310 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2312 case CCValAssign::BCvt:
2313 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2315 case CCValAssign::Indirect: {
2316 // Store the argument.
2317 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2318 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2319 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2320 MachinePointerInfo::getFixedStack(FI),
2327 if (VA.isRegLoc()) {
2328 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2329 if (isVarArg && IsWin64) {
2330 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2331 // shadow reg if callee is a varargs function.
2332 unsigned ShadowReg = 0;
2333 switch (VA.getLocReg()) {
2334 case X86::XMM0: ShadowReg = X86::RCX; break;
2335 case X86::XMM1: ShadowReg = X86::RDX; break;
2336 case X86::XMM2: ShadowReg = X86::R8; break;
2337 case X86::XMM3: ShadowReg = X86::R9; break;
2340 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2342 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2343 assert(VA.isMemLoc());
2344 if (StackPtr.getNode() == 0)
2345 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2346 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2347 dl, DAG, VA, Flags));
2351 if (!MemOpChains.empty())
2352 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2353 &MemOpChains[0], MemOpChains.size());
2355 if (Subtarget->isPICStyleGOT()) {
2356 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2359 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2360 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2362 // If we are tail calling and generating PIC/GOT style code load the
2363 // address of the callee into ECX. The value in ecx is used as target of
2364 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2365 // for tail calls on PIC/GOT architectures. Normally we would just put the
2366 // address of GOT into ebx and then call target@PLT. But for tail calls
2367 // ebx would be restored (since ebx is callee saved) before jumping to the
2370 // Note: The actual moving to ECX is done further down.
2371 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2372 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2373 !G->getGlobal()->hasProtectedVisibility())
2374 Callee = LowerGlobalAddress(Callee, DAG);
2375 else if (isa<ExternalSymbolSDNode>(Callee))
2376 Callee = LowerExternalSymbol(Callee, DAG);
2380 if (Is64Bit && isVarArg && !IsWin64) {
2381 // From AMD64 ABI document:
2382 // For calls that may call functions that use varargs or stdargs
2383 // (prototype-less calls or calls to functions containing ellipsis (...) in
2384 // the declaration) %al is used as hidden argument to specify the number
2385 // of SSE registers used. The contents of %al do not need to match exactly
2386 // the number of registers, but must be an ubound on the number of SSE
2387 // registers used and is in the range 0 - 8 inclusive.
2389 // Count the number of XMM registers allocated.
2390 static const uint16_t XMMArgRegs[] = {
2391 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2392 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2394 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2395 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2396 && "SSE registers cannot be used when SSE is disabled");
2398 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2399 DAG.getConstant(NumXMMRegs, MVT::i8)));
2402 // For tail calls lower the arguments to the 'real' stack slot.
2404 // Force all the incoming stack arguments to be loaded from the stack
2405 // before any new outgoing arguments are stored to the stack, because the
2406 // outgoing stack slots may alias the incoming argument stack slots, and
2407 // the alias isn't otherwise explicit. This is slightly more conservative
2408 // than necessary, because it means that each store effectively depends
2409 // on every argument instead of just those arguments it would clobber.
2410 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2412 SmallVector<SDValue, 8> MemOpChains2;
2415 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2416 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2417 CCValAssign &VA = ArgLocs[i];
2420 assert(VA.isMemLoc());
2421 SDValue Arg = OutVals[i];
2422 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2423 // Create frame index.
2424 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2425 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2426 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2427 FIN = DAG.getFrameIndex(FI, getPointerTy());
2429 if (Flags.isByVal()) {
2430 // Copy relative to framepointer.
2431 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2432 if (StackPtr.getNode() == 0)
2433 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2435 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2437 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2441 // Store relative to framepointer.
2442 MemOpChains2.push_back(
2443 DAG.getStore(ArgChain, dl, Arg, FIN,
2444 MachinePointerInfo::getFixedStack(FI),
2450 if (!MemOpChains2.empty())
2451 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2452 &MemOpChains2[0], MemOpChains2.size());
2454 // Store the return address to the appropriate stack slot.
2455 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2459 // Build a sequence of copy-to-reg nodes chained together with token chain
2460 // and flag operands which copy the outgoing args into registers.
2462 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2463 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2464 RegsToPass[i].second, InFlag);
2465 InFlag = Chain.getValue(1);
2468 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2469 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2470 // In the 64-bit large code model, we have to make all calls
2471 // through a register, since the call instruction's 32-bit
2472 // pc-relative offset may not be large enough to hold the whole
2474 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2475 // If the callee is a GlobalAddress node (quite common, every direct call
2476 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2479 // We should use extra load for direct calls to dllimported functions in
2481 const GlobalValue *GV = G->getGlobal();
2482 if (!GV->hasDLLImportLinkage()) {
2483 unsigned char OpFlags = 0;
2484 bool ExtraLoad = false;
2485 unsigned WrapperKind = ISD::DELETED_NODE;
2487 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2488 // external symbols most go through the PLT in PIC mode. If the symbol
2489 // has hidden or protected visibility, or if it is static or local, then
2490 // we don't need to use the PLT - we can directly call it.
2491 if (Subtarget->isTargetELF() &&
2492 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2493 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2494 OpFlags = X86II::MO_PLT;
2495 } else if (Subtarget->isPICStyleStubAny() &&
2496 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2497 (!Subtarget->getTargetTriple().isMacOSX() ||
2498 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2499 // PC-relative references to external symbols should go through $stub,
2500 // unless we're building with the leopard linker or later, which
2501 // automatically synthesizes these stubs.
2502 OpFlags = X86II::MO_DARWIN_STUB;
2503 } else if (Subtarget->isPICStyleRIPRel() &&
2504 isa<Function>(GV) &&
2505 cast<Function>(GV)->getFnAttributes().
2506 hasAttribute(Attributes::NonLazyBind)) {
2507 // If the function is marked as non-lazy, generate an indirect call
2508 // which loads from the GOT directly. This avoids runtime overhead
2509 // at the cost of eager binding (and one extra byte of encoding).
2510 OpFlags = X86II::MO_GOTPCREL;
2511 WrapperKind = X86ISD::WrapperRIP;
2515 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2516 G->getOffset(), OpFlags);
2518 // Add a wrapper if needed.
2519 if (WrapperKind != ISD::DELETED_NODE)
2520 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2521 // Add extra indirection if needed.
2523 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2524 MachinePointerInfo::getGOT(),
2525 false, false, false, 0);
2527 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2528 unsigned char OpFlags = 0;
2530 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2531 // external symbols should go through the PLT.
2532 if (Subtarget->isTargetELF() &&
2533 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2534 OpFlags = X86II::MO_PLT;
2535 } else if (Subtarget->isPICStyleStubAny() &&
2536 (!Subtarget->getTargetTriple().isMacOSX() ||
2537 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2538 // PC-relative references to external symbols should go through $stub,
2539 // unless we're building with the leopard linker or later, which
2540 // automatically synthesizes these stubs.
2541 OpFlags = X86II::MO_DARWIN_STUB;
2544 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2548 // Returns a chain & a flag for retval copy to use.
2549 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2550 SmallVector<SDValue, 8> Ops;
2552 if (!IsSibcall && isTailCall) {
2553 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2554 DAG.getIntPtrConstant(0, true), InFlag);
2555 InFlag = Chain.getValue(1);
2558 Ops.push_back(Chain);
2559 Ops.push_back(Callee);
2562 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2564 // Add argument registers to the end of the list so that they are known live
2566 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2567 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2568 RegsToPass[i].second.getValueType()));
2570 // Add a register mask operand representing the call-preserved registers.
2571 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2572 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2573 assert(Mask && "Missing call preserved mask for calling convention");
2574 Ops.push_back(DAG.getRegisterMask(Mask));
2576 if (InFlag.getNode())
2577 Ops.push_back(InFlag);
2581 //// If this is the first return lowered for this function, add the regs
2582 //// to the liveout set for the function.
2583 // This isn't right, although it's probably harmless on x86; liveouts
2584 // should be computed from returns not tail calls. Consider a void
2585 // function making a tail call to a function returning int.
2586 return DAG.getNode(X86ISD::TC_RETURN, dl,
2587 NodeTys, &Ops[0], Ops.size());
2590 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2591 InFlag = Chain.getValue(1);
2593 // Create the CALLSEQ_END node.
2594 unsigned NumBytesForCalleeToPush;
2595 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2596 getTargetMachine().Options.GuaranteedTailCallOpt))
2597 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2598 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2599 SR == StackStructReturn)
2600 // If this is a call to a struct-return function, the callee
2601 // pops the hidden struct pointer, so we have to push it back.
2602 // This is common for Darwin/X86, Linux & Mingw32 targets.
2603 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2604 NumBytesForCalleeToPush = 4;
2606 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2608 // Returns a flag for retval copy to use.
2610 Chain = DAG.getCALLSEQ_END(Chain,
2611 DAG.getIntPtrConstant(NumBytes, true),
2612 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2615 InFlag = Chain.getValue(1);
2618 // Handle result values, copying them out of physregs into vregs that we
2620 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2621 Ins, dl, DAG, InVals);
2625 //===----------------------------------------------------------------------===//
2626 // Fast Calling Convention (tail call) implementation
2627 //===----------------------------------------------------------------------===//
2629 // Like std call, callee cleans arguments, convention except that ECX is
2630 // reserved for storing the tail called function address. Only 2 registers are
2631 // free for argument passing (inreg). Tail call optimization is performed
2633 // * tailcallopt is enabled
2634 // * caller/callee are fastcc
2635 // On X86_64 architecture with GOT-style position independent code only local
2636 // (within module) calls are supported at the moment.
2637 // To keep the stack aligned according to platform abi the function
2638 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2639 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2640 // If a tail called function callee has more arguments than the caller the
2641 // caller needs to make sure that there is room to move the RETADDR to. This is
2642 // achieved by reserving an area the size of the argument delta right after the
2643 // original REtADDR, but before the saved framepointer or the spilled registers
2644 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2656 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2657 /// for a 16 byte align requirement.
2659 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2660 SelectionDAG& DAG) const {
2661 MachineFunction &MF = DAG.getMachineFunction();
2662 const TargetMachine &TM = MF.getTarget();
2663 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2664 unsigned StackAlignment = TFI.getStackAlignment();
2665 uint64_t AlignMask = StackAlignment - 1;
2666 int64_t Offset = StackSize;
2667 uint64_t SlotSize = TD->getPointerSize(0);
2668 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2669 // Number smaller than 12 so just add the difference.
2670 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2672 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2673 Offset = ((~AlignMask) & Offset) + StackAlignment +
2674 (StackAlignment-SlotSize);
2679 /// MatchingStackOffset - Return true if the given stack call argument is
2680 /// already available in the same position (relatively) of the caller's
2681 /// incoming argument stack.
2683 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2684 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2685 const X86InstrInfo *TII) {
2686 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2688 if (Arg.getOpcode() == ISD::CopyFromReg) {
2689 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2690 if (!TargetRegisterInfo::isVirtualRegister(VR))
2692 MachineInstr *Def = MRI->getVRegDef(VR);
2695 if (!Flags.isByVal()) {
2696 if (!TII->isLoadFromStackSlot(Def, FI))
2699 unsigned Opcode = Def->getOpcode();
2700 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2701 Def->getOperand(1).isFI()) {
2702 FI = Def->getOperand(1).getIndex();
2703 Bytes = Flags.getByValSize();
2707 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2708 if (Flags.isByVal())
2709 // ByVal argument is passed in as a pointer but it's now being
2710 // dereferenced. e.g.
2711 // define @foo(%struct.X* %A) {
2712 // tail call @bar(%struct.X* byval %A)
2715 SDValue Ptr = Ld->getBasePtr();
2716 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2719 FI = FINode->getIndex();
2720 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2721 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2722 FI = FINode->getIndex();
2723 Bytes = Flags.getByValSize();
2727 assert(FI != INT_MAX);
2728 if (!MFI->isFixedObjectIndex(FI))
2730 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2733 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2734 /// for tail call optimization. Targets which want to do tail call
2735 /// optimization should implement this function.
2737 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2738 CallingConv::ID CalleeCC,
2740 bool isCalleeStructRet,
2741 bool isCallerStructRet,
2743 const SmallVectorImpl<ISD::OutputArg> &Outs,
2744 const SmallVectorImpl<SDValue> &OutVals,
2745 const SmallVectorImpl<ISD::InputArg> &Ins,
2746 SelectionDAG& DAG) const {
2747 if (!IsTailCallConvention(CalleeCC) &&
2748 CalleeCC != CallingConv::C)
2751 // If -tailcallopt is specified, make fastcc functions tail-callable.
2752 const MachineFunction &MF = DAG.getMachineFunction();
2753 const Function *CallerF = DAG.getMachineFunction().getFunction();
2755 // If the function return type is x86_fp80 and the callee return type is not,
2756 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2757 // perform a tailcall optimization here.
2758 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2761 CallingConv::ID CallerCC = CallerF->getCallingConv();
2762 bool CCMatch = CallerCC == CalleeCC;
2764 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2765 if (IsTailCallConvention(CalleeCC) && CCMatch)
2770 // Look for obvious safe cases to perform tail call optimization that do not
2771 // require ABI changes. This is what gcc calls sibcall.
2773 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2774 // emit a special epilogue.
2775 if (RegInfo->needsStackRealignment(MF))
2778 // Also avoid sibcall optimization if either caller or callee uses struct
2779 // return semantics.
2780 if (isCalleeStructRet || isCallerStructRet)
2783 // An stdcall caller is expected to clean up its arguments; the callee
2784 // isn't going to do that.
2785 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2788 // Do not sibcall optimize vararg calls unless all arguments are passed via
2790 if (isVarArg && !Outs.empty()) {
2792 // Optimizing for varargs on Win64 is unlikely to be safe without
2793 // additional testing.
2794 if (Subtarget->isTargetWin64())
2797 SmallVector<CCValAssign, 16> ArgLocs;
2798 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2799 getTargetMachine(), ArgLocs, *DAG.getContext());
2801 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2802 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2803 if (!ArgLocs[i].isRegLoc())
2807 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2808 // stack. Therefore, if it's not used by the call it is not safe to optimize
2809 // this into a sibcall.
2810 bool Unused = false;
2811 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2818 SmallVector<CCValAssign, 16> RVLocs;
2819 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2820 getTargetMachine(), RVLocs, *DAG.getContext());
2821 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2822 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2823 CCValAssign &VA = RVLocs[i];
2824 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2829 // If the calling conventions do not match, then we'd better make sure the
2830 // results are returned in the same way as what the caller expects.
2832 SmallVector<CCValAssign, 16> RVLocs1;
2833 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2834 getTargetMachine(), RVLocs1, *DAG.getContext());
2835 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2837 SmallVector<CCValAssign, 16> RVLocs2;
2838 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2839 getTargetMachine(), RVLocs2, *DAG.getContext());
2840 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2842 if (RVLocs1.size() != RVLocs2.size())
2844 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2845 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2847 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2849 if (RVLocs1[i].isRegLoc()) {
2850 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2853 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2859 // If the callee takes no arguments then go on to check the results of the
2861 if (!Outs.empty()) {
2862 // Check if stack adjustment is needed. For now, do not do this if any
2863 // argument is passed on the stack.
2864 SmallVector<CCValAssign, 16> ArgLocs;
2865 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2866 getTargetMachine(), ArgLocs, *DAG.getContext());
2868 // Allocate shadow area for Win64
2869 if (Subtarget->isTargetWin64()) {
2870 CCInfo.AllocateStack(32, 8);
2873 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2874 if (CCInfo.getNextStackOffset()) {
2875 MachineFunction &MF = DAG.getMachineFunction();
2876 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2879 // Check if the arguments are already laid out in the right way as
2880 // the caller's fixed stack objects.
2881 MachineFrameInfo *MFI = MF.getFrameInfo();
2882 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2883 const X86InstrInfo *TII =
2884 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2885 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2886 CCValAssign &VA = ArgLocs[i];
2887 SDValue Arg = OutVals[i];
2888 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2889 if (VA.getLocInfo() == CCValAssign::Indirect)
2891 if (!VA.isRegLoc()) {
2892 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2899 // If the tailcall address may be in a register, then make sure it's
2900 // possible to register allocate for it. In 32-bit, the call address can
2901 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2902 // callee-saved registers are restored. These happen to be the same
2903 // registers used to pass 'inreg' arguments so watch out for those.
2904 if (!Subtarget->is64Bit() &&
2905 !isa<GlobalAddressSDNode>(Callee) &&
2906 !isa<ExternalSymbolSDNode>(Callee)) {
2907 unsigned NumInRegs = 0;
2908 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2909 CCValAssign &VA = ArgLocs[i];
2912 unsigned Reg = VA.getLocReg();
2915 case X86::EAX: case X86::EDX: case X86::ECX:
2916 if (++NumInRegs == 3)
2928 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2929 const TargetLibraryInfo *libInfo) const {
2930 return X86::createFastISel(funcInfo, libInfo);
2934 //===----------------------------------------------------------------------===//
2935 // Other Lowering Hooks
2936 //===----------------------------------------------------------------------===//
2938 static bool MayFoldLoad(SDValue Op) {
2939 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2942 static bool MayFoldIntoStore(SDValue Op) {
2943 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2946 static bool isTargetShuffle(unsigned Opcode) {
2948 default: return false;
2949 case X86ISD::PSHUFD:
2950 case X86ISD::PSHUFHW:
2951 case X86ISD::PSHUFLW:
2953 case X86ISD::PALIGN:
2954 case X86ISD::MOVLHPS:
2955 case X86ISD::MOVLHPD:
2956 case X86ISD::MOVHLPS:
2957 case X86ISD::MOVLPS:
2958 case X86ISD::MOVLPD:
2959 case X86ISD::MOVSHDUP:
2960 case X86ISD::MOVSLDUP:
2961 case X86ISD::MOVDDUP:
2964 case X86ISD::UNPCKL:
2965 case X86ISD::UNPCKH:
2966 case X86ISD::VPERMILP:
2967 case X86ISD::VPERM2X128:
2968 case X86ISD::VPERMI:
2973 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2974 SDValue V1, SelectionDAG &DAG) {
2976 default: llvm_unreachable("Unknown x86 shuffle node");
2977 case X86ISD::MOVSHDUP:
2978 case X86ISD::MOVSLDUP:
2979 case X86ISD::MOVDDUP:
2980 return DAG.getNode(Opc, dl, VT, V1);
2984 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2985 SDValue V1, unsigned TargetMask,
2986 SelectionDAG &DAG) {
2988 default: llvm_unreachable("Unknown x86 shuffle node");
2989 case X86ISD::PSHUFD:
2990 case X86ISD::PSHUFHW:
2991 case X86ISD::PSHUFLW:
2992 case X86ISD::VPERMILP:
2993 case X86ISD::VPERMI:
2994 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2998 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2999 SDValue V1, SDValue V2, unsigned TargetMask,
3000 SelectionDAG &DAG) {
3002 default: llvm_unreachable("Unknown x86 shuffle node");
3003 case X86ISD::PALIGN:
3005 case X86ISD::VPERM2X128:
3006 return DAG.getNode(Opc, dl, VT, V1, V2,
3007 DAG.getConstant(TargetMask, MVT::i8));
3011 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3012 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3014 default: llvm_unreachable("Unknown x86 shuffle node");
3015 case X86ISD::MOVLHPS:
3016 case X86ISD::MOVLHPD:
3017 case X86ISD::MOVHLPS:
3018 case X86ISD::MOVLPS:
3019 case X86ISD::MOVLPD:
3022 case X86ISD::UNPCKL:
3023 case X86ISD::UNPCKH:
3024 return DAG.getNode(Opc, dl, VT, V1, V2);
3028 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3029 MachineFunction &MF = DAG.getMachineFunction();
3030 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3031 int ReturnAddrIndex = FuncInfo->getRAIndex();
3033 if (ReturnAddrIndex == 0) {
3034 // Set up a frame object for the return address.
3035 uint64_t SlotSize = TD->getPointerSize(0);
3036 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3038 FuncInfo->setRAIndex(ReturnAddrIndex);
3041 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3045 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3046 bool hasSymbolicDisplacement) {
3047 // Offset should fit into 32 bit immediate field.
3048 if (!isInt<32>(Offset))
3051 // If we don't have a symbolic displacement - we don't have any extra
3053 if (!hasSymbolicDisplacement)
3056 // FIXME: Some tweaks might be needed for medium code model.
3057 if (M != CodeModel::Small && M != CodeModel::Kernel)
3060 // For small code model we assume that latest object is 16MB before end of 31
3061 // bits boundary. We may also accept pretty large negative constants knowing
3062 // that all objects are in the positive half of address space.
3063 if (M == CodeModel::Small && Offset < 16*1024*1024)
3066 // For kernel code model we know that all object resist in the negative half
3067 // of 32bits address space. We may not accept negative offsets, since they may
3068 // be just off and we may accept pretty large positive ones.
3069 if (M == CodeModel::Kernel && Offset > 0)
3075 /// isCalleePop - Determines whether the callee is required to pop its
3076 /// own arguments. Callee pop is necessary to support tail calls.
3077 bool X86::isCalleePop(CallingConv::ID CallingConv,
3078 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3082 switch (CallingConv) {
3085 case CallingConv::X86_StdCall:
3087 case CallingConv::X86_FastCall:
3089 case CallingConv::X86_ThisCall:
3091 case CallingConv::Fast:
3093 case CallingConv::GHC:
3098 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3099 /// specific condition code, returning the condition code and the LHS/RHS of the
3100 /// comparison to make.
3101 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3102 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3104 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3105 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3106 // X > -1 -> X == 0, jump !sign.
3107 RHS = DAG.getConstant(0, RHS.getValueType());
3108 return X86::COND_NS;
3110 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3111 // X < 0 -> X == 0, jump on sign.
3114 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3116 RHS = DAG.getConstant(0, RHS.getValueType());
3117 return X86::COND_LE;
3121 switch (SetCCOpcode) {
3122 default: llvm_unreachable("Invalid integer condition!");
3123 case ISD::SETEQ: return X86::COND_E;
3124 case ISD::SETGT: return X86::COND_G;
3125 case ISD::SETGE: return X86::COND_GE;
3126 case ISD::SETLT: return X86::COND_L;
3127 case ISD::SETLE: return X86::COND_LE;
3128 case ISD::SETNE: return X86::COND_NE;
3129 case ISD::SETULT: return X86::COND_B;
3130 case ISD::SETUGT: return X86::COND_A;
3131 case ISD::SETULE: return X86::COND_BE;
3132 case ISD::SETUGE: return X86::COND_AE;
3136 // First determine if it is required or is profitable to flip the operands.
3138 // If LHS is a foldable load, but RHS is not, flip the condition.
3139 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3140 !ISD::isNON_EXTLoad(RHS.getNode())) {
3141 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3142 std::swap(LHS, RHS);
3145 switch (SetCCOpcode) {
3151 std::swap(LHS, RHS);
3155 // On a floating point condition, the flags are set as follows:
3157 // 0 | 0 | 0 | X > Y
3158 // 0 | 0 | 1 | X < Y
3159 // 1 | 0 | 0 | X == Y
3160 // 1 | 1 | 1 | unordered
3161 switch (SetCCOpcode) {
3162 default: llvm_unreachable("Condcode should be pre-legalized away");
3164 case ISD::SETEQ: return X86::COND_E;
3165 case ISD::SETOLT: // flipped
3167 case ISD::SETGT: return X86::COND_A;
3168 case ISD::SETOLE: // flipped
3170 case ISD::SETGE: return X86::COND_AE;
3171 case ISD::SETUGT: // flipped
3173 case ISD::SETLT: return X86::COND_B;
3174 case ISD::SETUGE: // flipped
3176 case ISD::SETLE: return X86::COND_BE;
3178 case ISD::SETNE: return X86::COND_NE;
3179 case ISD::SETUO: return X86::COND_P;
3180 case ISD::SETO: return X86::COND_NP;
3182 case ISD::SETUNE: return X86::COND_INVALID;
3186 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3187 /// code. Current x86 isa includes the following FP cmov instructions:
3188 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3189 static bool hasFPCMov(unsigned X86CC) {
3205 /// isFPImmLegal - Returns true if the target can instruction select the
3206 /// specified FP immediate natively. If false, the legalizer will
3207 /// materialize the FP immediate as a load from a constant pool.
3208 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3209 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3210 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3216 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3217 /// the specified range (L, H].
3218 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3219 return (Val < 0) || (Val >= Low && Val < Hi);
3222 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3223 /// specified value.
3224 static bool isUndefOrEqual(int Val, int CmpVal) {
3225 if (Val < 0 || Val == CmpVal)
3230 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3231 /// from position Pos and ending in Pos+Size, falls within the specified
3232 /// sequential range (L, L+Pos]. or is undef.
3233 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3234 unsigned Pos, unsigned Size, int Low) {
3235 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3236 if (!isUndefOrEqual(Mask[i], Low))
3241 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3242 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3243 /// the second operand.
3244 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3245 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3246 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3247 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3248 return (Mask[0] < 2 && Mask[1] < 2);
3252 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3253 /// is suitable for input to PSHUFHW.
3254 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3255 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3258 // Lower quadword copied in order or undef.
3259 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3262 // Upper quadword shuffled.
3263 for (unsigned i = 4; i != 8; ++i)
3264 if (!isUndefOrInRange(Mask[i], 4, 8))
3267 if (VT == MVT::v16i16) {
3268 // Lower quadword copied in order or undef.
3269 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3272 // Upper quadword shuffled.
3273 for (unsigned i = 12; i != 16; ++i)
3274 if (!isUndefOrInRange(Mask[i], 12, 16))
3281 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3282 /// is suitable for input to PSHUFLW.
3283 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3284 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3287 // Upper quadword copied in order.
3288 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3291 // Lower quadword shuffled.
3292 for (unsigned i = 0; i != 4; ++i)
3293 if (!isUndefOrInRange(Mask[i], 0, 4))
3296 if (VT == MVT::v16i16) {
3297 // Upper quadword copied in order.
3298 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3301 // Lower quadword shuffled.
3302 for (unsigned i = 8; i != 12; ++i)
3303 if (!isUndefOrInRange(Mask[i], 8, 12))
3310 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3311 /// is suitable for input to PALIGNR.
3312 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3313 const X86Subtarget *Subtarget) {
3314 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3315 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3318 unsigned NumElts = VT.getVectorNumElements();
3319 unsigned NumLanes = VT.getSizeInBits()/128;
3320 unsigned NumLaneElts = NumElts/NumLanes;
3322 // Do not handle 64-bit element shuffles with palignr.
3323 if (NumLaneElts == 2)
3326 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3328 for (i = 0; i != NumLaneElts; ++i) {
3333 // Lane is all undef, go to next lane
3334 if (i == NumLaneElts)
3337 int Start = Mask[i+l];
3339 // Make sure its in this lane in one of the sources
3340 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3341 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3344 // If not lane 0, then we must match lane 0
3345 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3348 // Correct second source to be contiguous with first source
3349 if (Start >= (int)NumElts)
3350 Start -= NumElts - NumLaneElts;
3352 // Make sure we're shifting in the right direction.
3353 if (Start <= (int)(i+l))
3358 // Check the rest of the elements to see if they are consecutive.
3359 for (++i; i != NumLaneElts; ++i) {
3360 int Idx = Mask[i+l];
3362 // Make sure its in this lane
3363 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3364 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3367 // If not lane 0, then we must match lane 0
3368 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3371 if (Idx >= (int)NumElts)
3372 Idx -= NumElts - NumLaneElts;
3374 if (!isUndefOrEqual(Idx, Start+i))
3383 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3384 /// the two vector operands have swapped position.
3385 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3386 unsigned NumElems) {
3387 for (unsigned i = 0; i != NumElems; ++i) {
3391 else if (idx < (int)NumElems)
3392 Mask[i] = idx + NumElems;
3394 Mask[i] = idx - NumElems;
3398 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3399 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3400 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3401 /// reverse of what x86 shuffles want.
3402 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3403 bool Commuted = false) {
3404 if (!HasAVX && VT.getSizeInBits() == 256)
3407 unsigned NumElems = VT.getVectorNumElements();
3408 unsigned NumLanes = VT.getSizeInBits()/128;
3409 unsigned NumLaneElems = NumElems/NumLanes;
3411 if (NumLaneElems != 2 && NumLaneElems != 4)
3414 // VSHUFPSY divides the resulting vector into 4 chunks.
3415 // The sources are also splitted into 4 chunks, and each destination
3416 // chunk must come from a different source chunk.
3418 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3419 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3421 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3422 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3424 // VSHUFPDY divides the resulting vector into 4 chunks.
3425 // The sources are also splitted into 4 chunks, and each destination
3426 // chunk must come from a different source chunk.
3428 // SRC1 => X3 X2 X1 X0
3429 // SRC2 => Y3 Y2 Y1 Y0
3431 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3433 unsigned HalfLaneElems = NumLaneElems/2;
3434 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3435 for (unsigned i = 0; i != NumLaneElems; ++i) {
3436 int Idx = Mask[i+l];
3437 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3438 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3440 // For VSHUFPSY, the mask of the second half must be the same as the
3441 // first but with the appropriate offsets. This works in the same way as
3442 // VPERMILPS works with masks.
3443 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3445 if (!isUndefOrEqual(Idx, Mask[i]+l))
3453 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3454 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3455 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3456 if (!VT.is128BitVector())
3459 unsigned NumElems = VT.getVectorNumElements();
3464 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3465 return isUndefOrEqual(Mask[0], 6) &&
3466 isUndefOrEqual(Mask[1], 7) &&
3467 isUndefOrEqual(Mask[2], 2) &&
3468 isUndefOrEqual(Mask[3], 3);
3471 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3472 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3474 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3475 if (!VT.is128BitVector())
3478 unsigned NumElems = VT.getVectorNumElements();
3483 return isUndefOrEqual(Mask[0], 2) &&
3484 isUndefOrEqual(Mask[1], 3) &&
3485 isUndefOrEqual(Mask[2], 2) &&
3486 isUndefOrEqual(Mask[3], 3);
3489 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3491 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3492 if (!VT.is128BitVector())
3495 unsigned NumElems = VT.getVectorNumElements();
3497 if (NumElems != 2 && NumElems != 4)
3500 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3501 if (!isUndefOrEqual(Mask[i], i + NumElems))
3504 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3505 if (!isUndefOrEqual(Mask[i], i))
3511 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3512 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3513 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3514 if (!VT.is128BitVector())
3517 unsigned NumElems = VT.getVectorNumElements();
3519 if (NumElems != 2 && NumElems != 4)
3522 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3523 if (!isUndefOrEqual(Mask[i], i))
3526 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3527 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3534 // Some special combinations that can be optimized.
3537 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3538 SelectionDAG &DAG) {
3539 EVT VT = SVOp->getValueType(0);
3540 DebugLoc dl = SVOp->getDebugLoc();
3542 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3545 ArrayRef<int> Mask = SVOp->getMask();
3547 // These are the special masks that may be optimized.
3548 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3549 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3550 bool MatchEvenMask = true;
3551 bool MatchOddMask = true;
3552 for (int i=0; i<8; ++i) {
3553 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3554 MatchEvenMask = false;
3555 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3556 MatchOddMask = false;
3559 if (!MatchEvenMask && !MatchOddMask)
3562 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3564 SDValue Op0 = SVOp->getOperand(0);
3565 SDValue Op1 = SVOp->getOperand(1);
3567 if (MatchEvenMask) {
3568 // Shift the second operand right to 32 bits.
3569 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3570 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3572 // Shift the first operand left to 32 bits.
3573 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3574 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3576 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3577 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3580 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3581 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3582 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3583 bool HasAVX2, bool V2IsSplat = false) {
3584 unsigned NumElts = VT.getVectorNumElements();
3586 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3587 "Unsupported vector type for unpckh");
3589 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3590 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3593 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3594 // independently on 128-bit lanes.
3595 unsigned NumLanes = VT.getSizeInBits()/128;
3596 unsigned NumLaneElts = NumElts/NumLanes;
3598 for (unsigned l = 0; l != NumLanes; ++l) {
3599 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3600 i != (l+1)*NumLaneElts;
3603 int BitI1 = Mask[i+1];
3604 if (!isUndefOrEqual(BitI, j))
3607 if (!isUndefOrEqual(BitI1, NumElts))
3610 if (!isUndefOrEqual(BitI1, j + NumElts))
3619 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3620 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3621 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3622 bool HasAVX2, bool V2IsSplat = false) {
3623 unsigned NumElts = VT.getVectorNumElements();
3625 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3626 "Unsupported vector type for unpckh");
3628 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3629 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3632 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3633 // independently on 128-bit lanes.
3634 unsigned NumLanes = VT.getSizeInBits()/128;
3635 unsigned NumLaneElts = NumElts/NumLanes;
3637 for (unsigned l = 0; l != NumLanes; ++l) {
3638 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3639 i != (l+1)*NumLaneElts; i += 2, ++j) {
3641 int BitI1 = Mask[i+1];
3642 if (!isUndefOrEqual(BitI, j))
3645 if (isUndefOrEqual(BitI1, NumElts))
3648 if (!isUndefOrEqual(BitI1, j+NumElts))
3656 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3657 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3659 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3661 unsigned NumElts = VT.getVectorNumElements();
3663 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3664 "Unsupported vector type for unpckh");
3666 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3667 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3670 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3671 // FIXME: Need a better way to get rid of this, there's no latency difference
3672 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3673 // the former later. We should also remove the "_undef" special mask.
3674 if (NumElts == 4 && VT.getSizeInBits() == 256)
3677 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3678 // independently on 128-bit lanes.
3679 unsigned NumLanes = VT.getSizeInBits()/128;
3680 unsigned NumLaneElts = NumElts/NumLanes;
3682 for (unsigned l = 0; l != NumLanes; ++l) {
3683 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3684 i != (l+1)*NumLaneElts;
3687 int BitI1 = Mask[i+1];
3689 if (!isUndefOrEqual(BitI, j))
3691 if (!isUndefOrEqual(BitI1, j))
3699 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3700 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3702 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3703 unsigned NumElts = VT.getVectorNumElements();
3705 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3706 "Unsupported vector type for unpckh");
3708 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3709 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3712 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713 // independently on 128-bit lanes.
3714 unsigned NumLanes = VT.getSizeInBits()/128;
3715 unsigned NumLaneElts = NumElts/NumLanes;
3717 for (unsigned l = 0; l != NumLanes; ++l) {
3718 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3719 i != (l+1)*NumLaneElts; i += 2, ++j) {
3721 int BitI1 = Mask[i+1];
3722 if (!isUndefOrEqual(BitI, j))
3724 if (!isUndefOrEqual(BitI1, j))
3731 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3732 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3733 /// MOVSD, and MOVD, i.e. setting the lowest element.
3734 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3735 if (VT.getVectorElementType().getSizeInBits() < 32)
3737 if (!VT.is128BitVector())
3740 unsigned NumElts = VT.getVectorNumElements();
3742 if (!isUndefOrEqual(Mask[0], NumElts))
3745 for (unsigned i = 1; i != NumElts; ++i)
3746 if (!isUndefOrEqual(Mask[i], i))
3752 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3753 /// as permutations between 128-bit chunks or halves. As an example: this
3755 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3756 /// The first half comes from the second half of V1 and the second half from the
3757 /// the second half of V2.
3758 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3759 if (!HasAVX || !VT.is256BitVector())
3762 // The shuffle result is divided into half A and half B. In total the two
3763 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3764 // B must come from C, D, E or F.
3765 unsigned HalfSize = VT.getVectorNumElements()/2;
3766 bool MatchA = false, MatchB = false;
3768 // Check if A comes from one of C, D, E, F.
3769 for (unsigned Half = 0; Half != 4; ++Half) {
3770 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3776 // Check if B comes from one of C, D, E, F.
3777 for (unsigned Half = 0; Half != 4; ++Half) {
3778 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3784 return MatchA && MatchB;
3787 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3788 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3789 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3790 EVT VT = SVOp->getValueType(0);
3792 unsigned HalfSize = VT.getVectorNumElements()/2;
3794 unsigned FstHalf = 0, SndHalf = 0;
3795 for (unsigned i = 0; i < HalfSize; ++i) {
3796 if (SVOp->getMaskElt(i) > 0) {
3797 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3801 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3802 if (SVOp->getMaskElt(i) > 0) {
3803 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3808 return (FstHalf | (SndHalf << 4));
3811 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3812 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3813 /// Note that VPERMIL mask matching is different depending whether theunderlying
3814 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3815 /// to the same elements of the low, but to the higher half of the source.
3816 /// In VPERMILPD the two lanes could be shuffled independently of each other
3817 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3818 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3822 unsigned NumElts = VT.getVectorNumElements();
3823 // Only match 256-bit with 32/64-bit types
3824 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3827 unsigned NumLanes = VT.getSizeInBits()/128;
3828 unsigned LaneSize = NumElts/NumLanes;
3829 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3830 for (unsigned i = 0; i != LaneSize; ++i) {
3831 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3833 if (NumElts != 8 || l == 0)
3835 // VPERMILPS handling
3838 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3846 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3847 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3848 /// element of vector 2 and the other elements to come from vector 1 in order.
3849 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3850 bool V2IsSplat = false, bool V2IsUndef = false) {
3851 if (!VT.is128BitVector())
3854 unsigned NumOps = VT.getVectorNumElements();
3855 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3858 if (!isUndefOrEqual(Mask[0], 0))
3861 for (unsigned i = 1; i != NumOps; ++i)
3862 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3863 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3864 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3870 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3871 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3872 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3873 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3874 const X86Subtarget *Subtarget) {
3875 if (!Subtarget->hasSSE3())
3878 unsigned NumElems = VT.getVectorNumElements();
3880 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3881 (VT.getSizeInBits() == 256 && NumElems != 8))
3884 // "i+1" is the value the indexed mask element must have
3885 for (unsigned i = 0; i != NumElems; i += 2)
3886 if (!isUndefOrEqual(Mask[i], i+1) ||
3887 !isUndefOrEqual(Mask[i+1], i+1))
3893 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3894 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3895 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3896 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3897 const X86Subtarget *Subtarget) {
3898 if (!Subtarget->hasSSE3())
3901 unsigned NumElems = VT.getVectorNumElements();
3903 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3904 (VT.getSizeInBits() == 256 && NumElems != 8))
3907 // "i" is the value the indexed mask element must have
3908 for (unsigned i = 0; i != NumElems; i += 2)
3909 if (!isUndefOrEqual(Mask[i], i) ||
3910 !isUndefOrEqual(Mask[i+1], i))
3916 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3917 /// specifies a shuffle of elements that is suitable for input to 256-bit
3918 /// version of MOVDDUP.
3919 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3920 if (!HasAVX || !VT.is256BitVector())
3923 unsigned NumElts = VT.getVectorNumElements();
3927 for (unsigned i = 0; i != NumElts/2; ++i)
3928 if (!isUndefOrEqual(Mask[i], 0))
3930 for (unsigned i = NumElts/2; i != NumElts; ++i)
3931 if (!isUndefOrEqual(Mask[i], NumElts/2))
3936 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3937 /// specifies a shuffle of elements that is suitable for input to 128-bit
3938 /// version of MOVDDUP.
3939 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3940 if (!VT.is128BitVector())
3943 unsigned e = VT.getVectorNumElements() / 2;
3944 for (unsigned i = 0; i != e; ++i)
3945 if (!isUndefOrEqual(Mask[i], i))
3947 for (unsigned i = 0; i != e; ++i)
3948 if (!isUndefOrEqual(Mask[e+i], i))
3953 /// isVEXTRACTF128Index - Return true if the specified
3954 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3955 /// suitable for input to VEXTRACTF128.
3956 bool X86::isVEXTRACTF128Index(SDNode *N) {
3957 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3960 // The index should be aligned on a 128-bit boundary.
3962 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3964 unsigned VL = N->getValueType(0).getVectorNumElements();
3965 unsigned VBits = N->getValueType(0).getSizeInBits();
3966 unsigned ElSize = VBits / VL;
3967 bool Result = (Index * ElSize) % 128 == 0;
3972 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3973 /// operand specifies a subvector insert that is suitable for input to
3975 bool X86::isVINSERTF128Index(SDNode *N) {
3976 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3979 // The index should be aligned on a 128-bit boundary.
3981 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3983 unsigned VL = N->getValueType(0).getVectorNumElements();
3984 unsigned VBits = N->getValueType(0).getSizeInBits();
3985 unsigned ElSize = VBits / VL;
3986 bool Result = (Index * ElSize) % 128 == 0;
3991 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3992 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3993 /// Handles 128-bit and 256-bit.
3994 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3995 EVT VT = N->getValueType(0);
3997 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3998 "Unsupported vector type for PSHUF/SHUFP");
4000 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4001 // independently on 128-bit lanes.
4002 unsigned NumElts = VT.getVectorNumElements();
4003 unsigned NumLanes = VT.getSizeInBits()/128;
4004 unsigned NumLaneElts = NumElts/NumLanes;
4006 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4007 "Only supports 2 or 4 elements per lane");
4009 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4011 for (unsigned i = 0; i != NumElts; ++i) {
4012 int Elt = N->getMaskElt(i);
4013 if (Elt < 0) continue;
4014 Elt &= NumLaneElts - 1;
4015 unsigned ShAmt = (i << Shift) % 8;
4016 Mask |= Elt << ShAmt;
4022 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4023 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4024 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4025 EVT VT = N->getValueType(0);
4027 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4028 "Unsupported vector type for PSHUFHW");
4030 unsigned NumElts = VT.getVectorNumElements();
4033 for (unsigned l = 0; l != NumElts; l += 8) {
4034 // 8 nodes per lane, but we only care about the last 4.
4035 for (unsigned i = 0; i < 4; ++i) {
4036 int Elt = N->getMaskElt(l+i+4);
4037 if (Elt < 0) continue;
4038 Elt &= 0x3; // only 2-bits.
4039 Mask |= Elt << (i * 2);
4046 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4047 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4048 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4049 EVT VT = N->getValueType(0);
4051 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4052 "Unsupported vector type for PSHUFHW");
4054 unsigned NumElts = VT.getVectorNumElements();
4057 for (unsigned l = 0; l != NumElts; l += 8) {
4058 // 8 nodes per lane, but we only care about the first 4.
4059 for (unsigned i = 0; i < 4; ++i) {
4060 int Elt = N->getMaskElt(l+i);
4061 if (Elt < 0) continue;
4062 Elt &= 0x3; // only 2-bits
4063 Mask |= Elt << (i * 2);
4070 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4071 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4072 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4073 EVT VT = SVOp->getValueType(0);
4074 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4076 unsigned NumElts = VT.getVectorNumElements();
4077 unsigned NumLanes = VT.getSizeInBits()/128;
4078 unsigned NumLaneElts = NumElts/NumLanes;
4082 for (i = 0; i != NumElts; ++i) {
4083 Val = SVOp->getMaskElt(i);
4087 if (Val >= (int)NumElts)
4088 Val -= NumElts - NumLaneElts;
4090 assert(Val - i > 0 && "PALIGNR imm should be positive");
4091 return (Val - i) * EltSize;
4094 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4095 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4097 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4098 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4099 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4102 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4104 EVT VecVT = N->getOperand(0).getValueType();
4105 EVT ElVT = VecVT.getVectorElementType();
4107 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4108 return Index / NumElemsPerChunk;
4111 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4112 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4114 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4115 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4116 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4119 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4121 EVT VecVT = N->getValueType(0);
4122 EVT ElVT = VecVT.getVectorElementType();
4124 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4125 return Index / NumElemsPerChunk;
4128 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4129 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4130 /// Handles 256-bit.
4131 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4132 EVT VT = N->getValueType(0);
4134 unsigned NumElts = VT.getVectorNumElements();
4136 assert((VT.is256BitVector() && NumElts == 4) &&
4137 "Unsupported vector type for VPERMQ/VPERMPD");
4140 for (unsigned i = 0; i != NumElts; ++i) {
4141 int Elt = N->getMaskElt(i);
4144 Mask |= Elt << (i*2);
4149 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4151 bool X86::isZeroNode(SDValue Elt) {
4152 return ((isa<ConstantSDNode>(Elt) &&
4153 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4154 (isa<ConstantFPSDNode>(Elt) &&
4155 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4158 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4159 /// their permute mask.
4160 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4161 SelectionDAG &DAG) {
4162 EVT VT = SVOp->getValueType(0);
4163 unsigned NumElems = VT.getVectorNumElements();
4164 SmallVector<int, 8> MaskVec;
4166 for (unsigned i = 0; i != NumElems; ++i) {
4167 int Idx = SVOp->getMaskElt(i);
4169 if (Idx < (int)NumElems)
4174 MaskVec.push_back(Idx);
4176 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4177 SVOp->getOperand(0), &MaskVec[0]);
4180 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4181 /// match movhlps. The lower half elements should come from upper half of
4182 /// V1 (and in order), and the upper half elements should come from the upper
4183 /// half of V2 (and in order).
4184 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4185 if (!VT.is128BitVector())
4187 if (VT.getVectorNumElements() != 4)
4189 for (unsigned i = 0, e = 2; i != e; ++i)
4190 if (!isUndefOrEqual(Mask[i], i+2))
4192 for (unsigned i = 2; i != 4; ++i)
4193 if (!isUndefOrEqual(Mask[i], i+4))
4198 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4199 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4201 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4202 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4204 N = N->getOperand(0).getNode();
4205 if (!ISD::isNON_EXTLoad(N))
4208 *LD = cast<LoadSDNode>(N);
4212 // Test whether the given value is a vector value which will be legalized
4214 static bool WillBeConstantPoolLoad(SDNode *N) {
4215 if (N->getOpcode() != ISD::BUILD_VECTOR)
4218 // Check for any non-constant elements.
4219 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4220 switch (N->getOperand(i).getNode()->getOpcode()) {
4222 case ISD::ConstantFP:
4229 // Vectors of all-zeros and all-ones are materialized with special
4230 // instructions rather than being loaded.
4231 return !ISD::isBuildVectorAllZeros(N) &&
4232 !ISD::isBuildVectorAllOnes(N);
4235 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4236 /// match movlp{s|d}. The lower half elements should come from lower half of
4237 /// V1 (and in order), and the upper half elements should come from the upper
4238 /// half of V2 (and in order). And since V1 will become the source of the
4239 /// MOVLP, it must be either a vector load or a scalar load to vector.
4240 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4241 ArrayRef<int> Mask, EVT VT) {
4242 if (!VT.is128BitVector())
4245 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4247 // Is V2 is a vector load, don't do this transformation. We will try to use
4248 // load folding shufps op.
4249 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4252 unsigned NumElems = VT.getVectorNumElements();
4254 if (NumElems != 2 && NumElems != 4)
4256 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4257 if (!isUndefOrEqual(Mask[i], i))
4259 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4260 if (!isUndefOrEqual(Mask[i], i+NumElems))
4265 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4267 static bool isSplatVector(SDNode *N) {
4268 if (N->getOpcode() != ISD::BUILD_VECTOR)
4271 SDValue SplatValue = N->getOperand(0);
4272 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4273 if (N->getOperand(i) != SplatValue)
4278 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4279 /// to an zero vector.
4280 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4281 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4282 SDValue V1 = N->getOperand(0);
4283 SDValue V2 = N->getOperand(1);
4284 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4285 for (unsigned i = 0; i != NumElems; ++i) {
4286 int Idx = N->getMaskElt(i);
4287 if (Idx >= (int)NumElems) {
4288 unsigned Opc = V2.getOpcode();
4289 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4291 if (Opc != ISD::BUILD_VECTOR ||
4292 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4294 } else if (Idx >= 0) {
4295 unsigned Opc = V1.getOpcode();
4296 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4298 if (Opc != ISD::BUILD_VECTOR ||
4299 !X86::isZeroNode(V1.getOperand(Idx)))
4306 /// getZeroVector - Returns a vector of specified type with all zero elements.
4308 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4309 SelectionDAG &DAG, DebugLoc dl) {
4310 assert(VT.isVector() && "Expected a vector type");
4311 unsigned Size = VT.getSizeInBits();
4313 // Always build SSE zero vectors as <4 x i32> bitcasted
4314 // to their dest type. This ensures they get CSE'd.
4316 if (Size == 128) { // SSE
4317 if (Subtarget->hasSSE2()) { // SSE2
4318 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4319 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4321 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4322 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4324 } else if (Size == 256) { // AVX
4325 if (Subtarget->hasAVX2()) { // AVX2
4326 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4327 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4328 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4330 // 256-bit logic and arithmetic instructions in AVX are all
4331 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4332 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4333 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4337 llvm_unreachable("Unexpected vector type");
4339 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4342 /// getOnesVector - Returns a vector of specified type with all bits set.
4343 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4344 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4345 /// Then bitcast to their original type, ensuring they get CSE'd.
4346 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4348 assert(VT.isVector() && "Expected a vector type");
4349 unsigned Size = VT.getSizeInBits();
4351 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4354 if (HasAVX2) { // AVX2
4355 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4358 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4359 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4361 } else if (Size == 128) {
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4364 llvm_unreachable("Unexpected vector type");
4366 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4369 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4370 /// that point to V2 points to its first element.
4371 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4372 for (unsigned i = 0; i != NumElems; ++i) {
4373 if (Mask[i] > (int)NumElems) {
4379 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4380 /// operation of specified width.
4381 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4383 unsigned NumElems = VT.getVectorNumElements();
4384 SmallVector<int, 8> Mask;
4385 Mask.push_back(NumElems);
4386 for (unsigned i = 1; i != NumElems; ++i)
4388 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4391 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4392 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4394 unsigned NumElems = VT.getVectorNumElements();
4395 SmallVector<int, 8> Mask;
4396 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4398 Mask.push_back(i + NumElems);
4400 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4403 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4404 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4406 unsigned NumElems = VT.getVectorNumElements();
4407 SmallVector<int, 8> Mask;
4408 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4409 Mask.push_back(i + Half);
4410 Mask.push_back(i + NumElems + Half);
4412 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4415 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4416 // a generic shuffle instruction because the target has no such instructions.
4417 // Generate shuffles which repeat i16 and i8 several times until they can be
4418 // represented by v4f32 and then be manipulated by target suported shuffles.
4419 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4420 EVT VT = V.getValueType();
4421 int NumElems = VT.getVectorNumElements();
4422 DebugLoc dl = V.getDebugLoc();
4424 while (NumElems > 4) {
4425 if (EltNo < NumElems/2) {
4426 V = getUnpackl(DAG, dl, VT, V, V);
4428 V = getUnpackh(DAG, dl, VT, V, V);
4429 EltNo -= NumElems/2;
4436 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4437 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4438 EVT VT = V.getValueType();
4439 DebugLoc dl = V.getDebugLoc();
4440 unsigned Size = VT.getSizeInBits();
4443 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4444 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4445 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4447 } else if (Size == 256) {
4448 // To use VPERMILPS to splat scalars, the second half of indicies must
4449 // refer to the higher part, which is a duplication of the lower one,
4450 // because VPERMILPS can only handle in-lane permutations.
4451 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4452 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4454 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4455 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4458 llvm_unreachable("Vector size not supported");
4460 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4463 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4464 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4465 EVT SrcVT = SV->getValueType(0);
4466 SDValue V1 = SV->getOperand(0);
4467 DebugLoc dl = SV->getDebugLoc();
4469 int EltNo = SV->getSplatIndex();
4470 int NumElems = SrcVT.getVectorNumElements();
4471 unsigned Size = SrcVT.getSizeInBits();
4473 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4474 "Unknown how to promote splat for type");
4476 // Extract the 128-bit part containing the splat element and update
4477 // the splat element index when it refers to the higher register.
4479 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4480 if (EltNo >= NumElems/2)
4481 EltNo -= NumElems/2;
4484 // All i16 and i8 vector types can't be used directly by a generic shuffle
4485 // instruction because the target has no such instruction. Generate shuffles
4486 // which repeat i16 and i8 several times until they fit in i32, and then can
4487 // be manipulated by target suported shuffles.
4488 EVT EltVT = SrcVT.getVectorElementType();
4489 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4490 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4492 // Recreate the 256-bit vector and place the same 128-bit vector
4493 // into the low and high part. This is necessary because we want
4494 // to use VPERM* to shuffle the vectors
4496 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4499 return getLegalSplat(DAG, V1, EltNo);
4502 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4503 /// vector of zero or undef vector. This produces a shuffle where the low
4504 /// element of V2 is swizzled into the zero/undef vector, landing at element
4505 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4506 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4508 const X86Subtarget *Subtarget,
4509 SelectionDAG &DAG) {
4510 EVT VT = V2.getValueType();
4512 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4513 unsigned NumElems = VT.getVectorNumElements();
4514 SmallVector<int, 16> MaskVec;
4515 for (unsigned i = 0; i != NumElems; ++i)
4516 // If this is the insertion idx, put the low elt of V2 here.
4517 MaskVec.push_back(i == Idx ? NumElems : i);
4518 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4521 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4522 /// target specific opcode. Returns true if the Mask could be calculated.
4523 /// Sets IsUnary to true if only uses one source.
4524 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4525 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4526 unsigned NumElems = VT.getVectorNumElements();
4530 switch(N->getOpcode()) {
4532 ImmN = N->getOperand(N->getNumOperands()-1);
4533 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4535 case X86ISD::UNPCKH:
4536 DecodeUNPCKHMask(VT, Mask);
4538 case X86ISD::UNPCKL:
4539 DecodeUNPCKLMask(VT, Mask);
4541 case X86ISD::MOVHLPS:
4542 DecodeMOVHLPSMask(NumElems, Mask);
4544 case X86ISD::MOVLHPS:
4545 DecodeMOVLHPSMask(NumElems, Mask);
4547 case X86ISD::PSHUFD:
4548 case X86ISD::VPERMILP:
4549 ImmN = N->getOperand(N->getNumOperands()-1);
4550 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4553 case X86ISD::PSHUFHW:
4554 ImmN = N->getOperand(N->getNumOperands()-1);
4555 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4558 case X86ISD::PSHUFLW:
4559 ImmN = N->getOperand(N->getNumOperands()-1);
4560 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563 case X86ISD::VPERMI:
4564 ImmN = N->getOperand(N->getNumOperands()-1);
4565 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569 case X86ISD::MOVSD: {
4570 // The index 0 always comes from the first element of the second source,
4571 // this is why MOVSS and MOVSD are used in the first place. The other
4572 // elements come from the other positions of the first source vector
4573 Mask.push_back(NumElems);
4574 for (unsigned i = 1; i != NumElems; ++i) {
4579 case X86ISD::VPERM2X128:
4580 ImmN = N->getOperand(N->getNumOperands()-1);
4581 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4582 if (Mask.empty()) return false;
4584 case X86ISD::MOVDDUP:
4585 case X86ISD::MOVLHPD:
4586 case X86ISD::MOVLPD:
4587 case X86ISD::MOVLPS:
4588 case X86ISD::MOVSHDUP:
4589 case X86ISD::MOVSLDUP:
4590 case X86ISD::PALIGN:
4591 // Not yet implemented
4593 default: llvm_unreachable("unknown target shuffle node");
4599 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4600 /// element of the result of the vector shuffle.
4601 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4604 return SDValue(); // Limit search depth.
4606 SDValue V = SDValue(N, 0);
4607 EVT VT = V.getValueType();
4608 unsigned Opcode = V.getOpcode();
4610 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4611 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4612 int Elt = SV->getMaskElt(Index);
4615 return DAG.getUNDEF(VT.getVectorElementType());
4617 unsigned NumElems = VT.getVectorNumElements();
4618 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4619 : SV->getOperand(1);
4620 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4623 // Recurse into target specific vector shuffles to find scalars.
4624 if (isTargetShuffle(Opcode)) {
4625 MVT ShufVT = V.getValueType().getSimpleVT();
4626 unsigned NumElems = ShufVT.getVectorNumElements();
4627 SmallVector<int, 16> ShuffleMask;
4631 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4634 int Elt = ShuffleMask[Index];
4636 return DAG.getUNDEF(ShufVT.getVectorElementType());
4638 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4640 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4644 // Actual nodes that may contain scalar elements
4645 if (Opcode == ISD::BITCAST) {
4646 V = V.getOperand(0);
4647 EVT SrcVT = V.getValueType();
4648 unsigned NumElems = VT.getVectorNumElements();
4650 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4654 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4655 return (Index == 0) ? V.getOperand(0)
4656 : DAG.getUNDEF(VT.getVectorElementType());
4658 if (V.getOpcode() == ISD::BUILD_VECTOR)
4659 return V.getOperand(Index);
4664 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4665 /// shuffle operation which come from a consecutively from a zero. The
4666 /// search can start in two different directions, from left or right.
4668 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4669 bool ZerosFromLeft, SelectionDAG &DAG) {
4671 for (i = 0; i != NumElems; ++i) {
4672 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4673 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4674 if (!(Elt.getNode() &&
4675 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4682 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4683 /// correspond consecutively to elements from one of the vector operands,
4684 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4686 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4687 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4688 unsigned NumElems, unsigned &OpNum) {
4689 bool SeenV1 = false;
4690 bool SeenV2 = false;
4692 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4693 int Idx = SVOp->getMaskElt(i);
4694 // Ignore undef indicies
4698 if (Idx < (int)NumElems)
4703 // Only accept consecutive elements from the same vector
4704 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4708 OpNum = SeenV1 ? 0 : 1;
4712 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4713 /// logical left shift of a vector.
4714 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4715 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4716 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4717 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4718 false /* check zeros from right */, DAG);
4724 // Considering the elements in the mask that are not consecutive zeros,
4725 // check if they consecutively come from only one of the source vectors.
4727 // V1 = {X, A, B, C} 0
4729 // vector_shuffle V1, V2 <1, 2, 3, X>
4731 if (!isShuffleMaskConsecutive(SVOp,
4732 0, // Mask Start Index
4733 NumElems-NumZeros, // Mask End Index(exclusive)
4734 NumZeros, // Where to start looking in the src vector
4735 NumElems, // Number of elements in vector
4736 OpSrc)) // Which source operand ?
4741 ShVal = SVOp->getOperand(OpSrc);
4745 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4746 /// logical left shift of a vector.
4747 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4748 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4749 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4750 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4751 true /* check zeros from left */, DAG);
4757 // Considering the elements in the mask that are not consecutive zeros,
4758 // check if they consecutively come from only one of the source vectors.
4760 // 0 { A, B, X, X } = V2
4762 // vector_shuffle V1, V2 <X, X, 4, 5>
4764 if (!isShuffleMaskConsecutive(SVOp,
4765 NumZeros, // Mask Start Index
4766 NumElems, // Mask End Index(exclusive)
4767 0, // Where to start looking in the src vector
4768 NumElems, // Number of elements in vector
4769 OpSrc)) // Which source operand ?
4774 ShVal = SVOp->getOperand(OpSrc);
4778 /// isVectorShift - Returns true if the shuffle can be implemented as a
4779 /// logical left or right shift of a vector.
4780 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4781 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4782 // Although the logic below support any bitwidth size, there are no
4783 // shift instructions which handle more than 128-bit vectors.
4784 if (!SVOp->getValueType(0).is128BitVector())
4787 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4788 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4794 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4796 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4797 unsigned NumNonZero, unsigned NumZero,
4799 const X86Subtarget* Subtarget,
4800 const TargetLowering &TLI) {
4804 DebugLoc dl = Op.getDebugLoc();
4807 for (unsigned i = 0; i < 16; ++i) {
4808 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4809 if (ThisIsNonZero && First) {
4811 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4813 V = DAG.getUNDEF(MVT::v8i16);
4818 SDValue ThisElt(0, 0), LastElt(0, 0);
4819 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4820 if (LastIsNonZero) {
4821 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4822 MVT::i16, Op.getOperand(i-1));
4824 if (ThisIsNonZero) {
4825 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4826 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4827 ThisElt, DAG.getConstant(8, MVT::i8));
4829 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4833 if (ThisElt.getNode())
4834 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4835 DAG.getIntPtrConstant(i/2));
4839 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4842 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4844 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4845 unsigned NumNonZero, unsigned NumZero,
4847 const X86Subtarget* Subtarget,
4848 const TargetLowering &TLI) {
4852 DebugLoc dl = Op.getDebugLoc();
4855 for (unsigned i = 0; i < 8; ++i) {
4856 bool isNonZero = (NonZeros & (1 << i)) != 0;
4860 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4862 V = DAG.getUNDEF(MVT::v8i16);
4865 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4866 MVT::v8i16, V, Op.getOperand(i),
4867 DAG.getIntPtrConstant(i));
4874 /// getVShift - Return a vector logical shift node.
4876 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4877 unsigned NumBits, SelectionDAG &DAG,
4878 const TargetLowering &TLI, DebugLoc dl) {
4879 assert(VT.is128BitVector() && "Unknown type for VShift");
4880 EVT ShVT = MVT::v2i64;
4881 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4882 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4883 return DAG.getNode(ISD::BITCAST, dl, VT,
4884 DAG.getNode(Opc, dl, ShVT, SrcOp,
4885 DAG.getConstant(NumBits,
4886 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4890 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4891 SelectionDAG &DAG) const {
4893 // Check if the scalar load can be widened into a vector load. And if
4894 // the address is "base + cst" see if the cst can be "absorbed" into
4895 // the shuffle mask.
4896 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4897 SDValue Ptr = LD->getBasePtr();
4898 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4900 EVT PVT = LD->getValueType(0);
4901 if (PVT != MVT::i32 && PVT != MVT::f32)
4906 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4907 FI = FINode->getIndex();
4909 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4910 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4911 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4912 Offset = Ptr.getConstantOperandVal(1);
4913 Ptr = Ptr.getOperand(0);
4918 // FIXME: 256-bit vector instructions don't require a strict alignment,
4919 // improve this code to support it better.
4920 unsigned RequiredAlign = VT.getSizeInBits()/8;
4921 SDValue Chain = LD->getChain();
4922 // Make sure the stack object alignment is at least 16 or 32.
4923 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4924 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4925 if (MFI->isFixedObjectIndex(FI)) {
4926 // Can't change the alignment. FIXME: It's possible to compute
4927 // the exact stack offset and reference FI + adjust offset instead.
4928 // If someone *really* cares about this. That's the way to implement it.
4931 MFI->setObjectAlignment(FI, RequiredAlign);
4935 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4936 // Ptr + (Offset & ~15).
4939 if ((Offset % RequiredAlign) & 3)
4941 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4943 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4944 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4946 int EltNo = (Offset - StartOffset) >> 2;
4947 unsigned NumElems = VT.getVectorNumElements();
4949 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4950 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4951 LD->getPointerInfo().getWithOffset(StartOffset),
4952 false, false, false, 0);
4954 SmallVector<int, 8> Mask;
4955 for (unsigned i = 0; i != NumElems; ++i)
4956 Mask.push_back(EltNo);
4958 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4964 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4965 /// vector of type 'VT', see if the elements can be replaced by a single large
4966 /// load which has the same value as a build_vector whose operands are 'elts'.
4968 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4970 /// FIXME: we'd also like to handle the case where the last elements are zero
4971 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4972 /// There's even a handy isZeroNode for that purpose.
4973 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4974 DebugLoc &DL, SelectionDAG &DAG) {
4975 EVT EltVT = VT.getVectorElementType();
4976 unsigned NumElems = Elts.size();
4978 LoadSDNode *LDBase = NULL;
4979 unsigned LastLoadedElt = -1U;
4981 // For each element in the initializer, see if we've found a load or an undef.
4982 // If we don't find an initial load element, or later load elements are
4983 // non-consecutive, bail out.
4984 for (unsigned i = 0; i < NumElems; ++i) {
4985 SDValue Elt = Elts[i];
4987 if (!Elt.getNode() ||
4988 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4991 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4993 LDBase = cast<LoadSDNode>(Elt.getNode());
4997 if (Elt.getOpcode() == ISD::UNDEF)
5000 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5001 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5006 // If we have found an entire vector of loads and undefs, then return a large
5007 // load of the entire vector width starting at the base pointer. If we found
5008 // consecutive loads for the low half, generate a vzext_load node.
5009 if (LastLoadedElt == NumElems - 1) {
5010 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5011 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5012 LDBase->getPointerInfo(),
5013 LDBase->isVolatile(), LDBase->isNonTemporal(),
5014 LDBase->isInvariant(), 0);
5015 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5016 LDBase->getPointerInfo(),
5017 LDBase->isVolatile(), LDBase->isNonTemporal(),
5018 LDBase->isInvariant(), LDBase->getAlignment());
5020 if (NumElems == 4 && LastLoadedElt == 1 &&
5021 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5022 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5023 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5025 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5026 LDBase->getPointerInfo(),
5027 LDBase->getAlignment(),
5028 false/*isVolatile*/, true/*ReadMem*/,
5031 // Make sure the newly-created LOAD is in the same position as LDBase in
5032 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5033 // update uses of LDBase's output chain to use the TokenFactor.
5034 if (LDBase->hasAnyUseOfValue(1)) {
5035 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5036 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5037 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5038 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5039 SDValue(ResNode.getNode(), 1));
5042 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5047 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5048 /// to generate a splat value for the following cases:
5049 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5050 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5051 /// a scalar load, or a constant.
5052 /// The VBROADCAST node is returned when a pattern is found,
5053 /// or SDValue() otherwise.
5055 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5056 if (!Subtarget->hasAVX())
5059 EVT VT = Op.getValueType();
5060 DebugLoc dl = Op.getDebugLoc();
5062 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5063 "Unsupported vector type for broadcast.");
5068 switch (Op.getOpcode()) {
5070 // Unknown pattern found.
5073 case ISD::BUILD_VECTOR: {
5074 // The BUILD_VECTOR node must be a splat.
5075 if (!isSplatVector(Op.getNode()))
5078 Ld = Op.getOperand(0);
5079 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5080 Ld.getOpcode() == ISD::ConstantFP);
5082 // The suspected load node has several users. Make sure that all
5083 // of its users are from the BUILD_VECTOR node.
5084 // Constants may have multiple users.
5085 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5090 case ISD::VECTOR_SHUFFLE: {
5091 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5093 // Shuffles must have a splat mask where the first element is
5095 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5098 SDValue Sc = Op.getOperand(0);
5099 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5100 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5102 if (!Subtarget->hasAVX2())
5105 // Use the register form of the broadcast instruction available on AVX2.
5106 if (VT.is256BitVector())
5107 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5108 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5111 Ld = Sc.getOperand(0);
5112 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5113 Ld.getOpcode() == ISD::ConstantFP);
5115 // The scalar_to_vector node and the suspected
5116 // load node must have exactly one user.
5117 // Constants may have multiple users.
5118 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5124 bool Is256 = VT.is256BitVector();
5126 // Handle the broadcasting a single constant scalar from the constant pool
5127 // into a vector. On Sandybridge it is still better to load a constant vector
5128 // from the constant pool and not to broadcast it from a scalar.
5129 if (ConstSplatVal && Subtarget->hasAVX2()) {
5130 EVT CVT = Ld.getValueType();
5131 assert(!CVT.isVector() && "Must not broadcast a vector type");
5132 unsigned ScalarSize = CVT.getSizeInBits();
5134 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5135 const Constant *C = 0;
5136 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5137 C = CI->getConstantIntValue();
5138 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5139 C = CF->getConstantFPValue();
5141 assert(C && "Invalid constant type");
5143 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5144 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5145 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5146 MachinePointerInfo::getConstantPool(),
5147 false, false, false, Alignment);
5149 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5153 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5154 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5156 // Handle AVX2 in-register broadcasts.
5157 if (!IsLoad && Subtarget->hasAVX2() &&
5158 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5159 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5161 // The scalar source must be a normal load.
5165 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5166 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5168 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5169 // double since there is no vbroadcastsd xmm
5170 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5171 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5172 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5175 // Unsupported broadcast.
5180 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5181 EVT VT = Op.getValueType();
5183 // Skip if insert_vec_elt is not supported.
5184 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5187 DebugLoc DL = Op.getDebugLoc();
5188 unsigned NumElems = Op.getNumOperands();
5192 SmallVector<unsigned, 4> InsertIndices;
5193 SmallVector<int, 8> Mask(NumElems, -1);
5195 for (unsigned i = 0; i != NumElems; ++i) {
5196 unsigned Opc = Op.getOperand(i).getOpcode();
5198 if (Opc == ISD::UNDEF)
5201 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5202 // Quit if more than 1 elements need inserting.
5203 if (InsertIndices.size() > 1)
5206 InsertIndices.push_back(i);
5210 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5211 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5213 // Quit if extracted from vector of different type.
5214 if (ExtractedFromVec.getValueType() != VT)
5217 // Quit if non-constant index.
5218 if (!isa<ConstantSDNode>(ExtIdx))
5221 if (VecIn1.getNode() == 0)
5222 VecIn1 = ExtractedFromVec;
5223 else if (VecIn1 != ExtractedFromVec) {
5224 if (VecIn2.getNode() == 0)
5225 VecIn2 = ExtractedFromVec;
5226 else if (VecIn2 != ExtractedFromVec)
5227 // Quit if more than 2 vectors to shuffle
5231 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5233 if (ExtractedFromVec == VecIn1)
5235 else if (ExtractedFromVec == VecIn2)
5236 Mask[i] = Idx + NumElems;
5239 if (VecIn1.getNode() == 0)
5242 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5243 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5244 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5245 unsigned Idx = InsertIndices[i];
5246 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5247 DAG.getIntPtrConstant(Idx));
5254 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5255 DebugLoc dl = Op.getDebugLoc();
5257 EVT VT = Op.getValueType();
5258 EVT ExtVT = VT.getVectorElementType();
5259 unsigned NumElems = Op.getNumOperands();
5261 // Vectors containing all zeros can be matched by pxor and xorps later
5262 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5263 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5264 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5265 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5268 return getZeroVector(VT, Subtarget, DAG, dl);
5271 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5272 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5273 // vpcmpeqd on 256-bit vectors.
5274 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5275 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5278 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5281 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5282 if (Broadcast.getNode())
5285 unsigned EVTBits = ExtVT.getSizeInBits();
5287 unsigned NumZero = 0;
5288 unsigned NumNonZero = 0;
5289 unsigned NonZeros = 0;
5290 bool IsAllConstants = true;
5291 SmallSet<SDValue, 8> Values;
5292 for (unsigned i = 0; i < NumElems; ++i) {
5293 SDValue Elt = Op.getOperand(i);
5294 if (Elt.getOpcode() == ISD::UNDEF)
5297 if (Elt.getOpcode() != ISD::Constant &&
5298 Elt.getOpcode() != ISD::ConstantFP)
5299 IsAllConstants = false;
5300 if (X86::isZeroNode(Elt))
5303 NonZeros |= (1 << i);
5308 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5309 if (NumNonZero == 0)
5310 return DAG.getUNDEF(VT);
5312 // Special case for single non-zero, non-undef, element.
5313 if (NumNonZero == 1) {
5314 unsigned Idx = CountTrailingZeros_32(NonZeros);
5315 SDValue Item = Op.getOperand(Idx);
5317 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5318 // the value are obviously zero, truncate the value to i32 and do the
5319 // insertion that way. Only do this if the value is non-constant or if the
5320 // value is a constant being inserted into element 0. It is cheaper to do
5321 // a constant pool load than it is to do a movd + shuffle.
5322 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5323 (!IsAllConstants || Idx == 0)) {
5324 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5326 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5327 EVT VecVT = MVT::v4i32;
5328 unsigned VecElts = 4;
5330 // Truncate the value (which may itself be a constant) to i32, and
5331 // convert it to a vector with movd (S2V+shuffle to zero extend).
5332 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5333 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5334 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5336 // Now we have our 32-bit value zero extended in the low element of
5337 // a vector. If Idx != 0, swizzle it into place.
5339 SmallVector<int, 4> Mask;
5340 Mask.push_back(Idx);
5341 for (unsigned i = 1; i != VecElts; ++i)
5343 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5346 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5350 // If we have a constant or non-constant insertion into the low element of
5351 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5352 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5353 // depending on what the source datatype is.
5356 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5358 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5359 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5360 if (VT.is256BitVector()) {
5361 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5362 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5363 Item, DAG.getIntPtrConstant(0));
5365 assert(VT.is128BitVector() && "Expected an SSE value type!");
5366 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5368 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5371 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5372 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5373 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5374 if (VT.is256BitVector()) {
5375 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5376 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5378 assert(VT.is128BitVector() && "Expected an SSE value type!");
5379 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5381 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5385 // Is it a vector logical left shift?
5386 if (NumElems == 2 && Idx == 1 &&
5387 X86::isZeroNode(Op.getOperand(0)) &&
5388 !X86::isZeroNode(Op.getOperand(1))) {
5389 unsigned NumBits = VT.getSizeInBits();
5390 return getVShift(true, VT,
5391 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5392 VT, Op.getOperand(1)),
5393 NumBits/2, DAG, *this, dl);
5396 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5399 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5400 // is a non-constant being inserted into an element other than the low one,
5401 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5402 // movd/movss) to move this into the low element, then shuffle it into
5404 if (EVTBits == 32) {
5405 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5407 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5408 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5409 SmallVector<int, 8> MaskVec;
5410 for (unsigned i = 0; i != NumElems; ++i)
5411 MaskVec.push_back(i == Idx ? 0 : 1);
5412 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5416 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5417 if (Values.size() == 1) {
5418 if (EVTBits == 32) {
5419 // Instead of a shuffle like this:
5420 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5421 // Check if it's possible to issue this instead.
5422 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5423 unsigned Idx = CountTrailingZeros_32(NonZeros);
5424 SDValue Item = Op.getOperand(Idx);
5425 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5426 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5431 // A vector full of immediates; various special cases are already
5432 // handled, so this is best done with a single constant-pool load.
5436 // For AVX-length vectors, build the individual 128-bit pieces and use
5437 // shuffles to put them in place.
5438 if (VT.is256BitVector()) {
5439 SmallVector<SDValue, 32> V;
5440 for (unsigned i = 0; i != NumElems; ++i)
5441 V.push_back(Op.getOperand(i));
5443 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5445 // Build both the lower and upper subvector.
5446 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5447 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5450 // Recreate the wider vector with the lower and upper part.
5451 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5454 // Let legalizer expand 2-wide build_vectors.
5455 if (EVTBits == 64) {
5456 if (NumNonZero == 1) {
5457 // One half is zero or undef.
5458 unsigned Idx = CountTrailingZeros_32(NonZeros);
5459 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5460 Op.getOperand(Idx));
5461 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5466 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5467 if (EVTBits == 8 && NumElems == 16) {
5468 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5470 if (V.getNode()) return V;
5473 if (EVTBits == 16 && NumElems == 8) {
5474 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5476 if (V.getNode()) return V;
5479 // If element VT is == 32 bits, turn it into a number of shuffles.
5480 SmallVector<SDValue, 8> V(NumElems);
5481 if (NumElems == 4 && NumZero > 0) {
5482 for (unsigned i = 0; i < 4; ++i) {
5483 bool isZero = !(NonZeros & (1 << i));
5485 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5487 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5490 for (unsigned i = 0; i < 2; ++i) {
5491 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5494 V[i] = V[i*2]; // Must be a zero vector.
5497 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5500 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5503 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5508 bool Reverse1 = (NonZeros & 0x3) == 2;
5509 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5513 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5514 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5516 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5519 if (Values.size() > 1 && VT.is128BitVector()) {
5520 // Check for a build vector of consecutive loads.
5521 for (unsigned i = 0; i < NumElems; ++i)
5522 V[i] = Op.getOperand(i);
5524 // Check for elements which are consecutive loads.
5525 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5529 // Check for a build vector from mostly shuffle plus few inserting.
5530 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5534 // For SSE 4.1, use insertps to put the high elements into the low element.
5535 if (getSubtarget()->hasSSE41()) {
5537 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5538 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5540 Result = DAG.getUNDEF(VT);
5542 for (unsigned i = 1; i < NumElems; ++i) {
5543 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5544 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5545 Op.getOperand(i), DAG.getIntPtrConstant(i));
5550 // Otherwise, expand into a number of unpckl*, start by extending each of
5551 // our (non-undef) elements to the full vector width with the element in the
5552 // bottom slot of the vector (which generates no code for SSE).
5553 for (unsigned i = 0; i < NumElems; ++i) {
5554 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5555 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5557 V[i] = DAG.getUNDEF(VT);
5560 // Next, we iteratively mix elements, e.g. for v4f32:
5561 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5562 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5563 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5564 unsigned EltStride = NumElems >> 1;
5565 while (EltStride != 0) {
5566 for (unsigned i = 0; i < EltStride; ++i) {
5567 // If V[i+EltStride] is undef and this is the first round of mixing,
5568 // then it is safe to just drop this shuffle: V[i] is already in the
5569 // right place, the one element (since it's the first round) being
5570 // inserted as undef can be dropped. This isn't safe for successive
5571 // rounds because they will permute elements within both vectors.
5572 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5573 EltStride == NumElems/2)
5576 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5585 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5586 // to create 256-bit vectors from two other 128-bit ones.
5587 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5588 DebugLoc dl = Op.getDebugLoc();
5589 EVT ResVT = Op.getValueType();
5591 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5593 SDValue V1 = Op.getOperand(0);
5594 SDValue V2 = Op.getOperand(1);
5595 unsigned NumElems = ResVT.getVectorNumElements();
5597 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5600 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5601 assert(Op.getNumOperands() == 2);
5603 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5604 // from two other 128-bit ones.
5605 return LowerAVXCONCAT_VECTORS(Op, DAG);
5608 // Try to lower a shuffle node into a simple blend instruction.
5610 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5611 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5612 SDValue V1 = SVOp->getOperand(0);
5613 SDValue V2 = SVOp->getOperand(1);
5614 DebugLoc dl = SVOp->getDebugLoc();
5615 MVT VT = SVOp->getValueType(0).getSimpleVT();
5616 unsigned NumElems = VT.getVectorNumElements();
5618 if (!Subtarget->hasSSE41())
5624 switch (VT.SimpleTy) {
5625 default: return SDValue();
5627 ISDNo = X86ISD::BLENDPW;
5632 ISDNo = X86ISD::BLENDPS;
5637 ISDNo = X86ISD::BLENDPD;
5642 if (!Subtarget->hasAVX())
5644 ISDNo = X86ISD::BLENDPS;
5649 if (!Subtarget->hasAVX())
5651 ISDNo = X86ISD::BLENDPD;
5655 assert(ISDNo && "Invalid Op Number");
5657 unsigned MaskVals = 0;
5659 for (unsigned i = 0; i != NumElems; ++i) {
5660 int EltIdx = SVOp->getMaskElt(i);
5661 if (EltIdx == (int)i || EltIdx < 0)
5663 else if (EltIdx == (int)(i + NumElems))
5664 continue; // Bit is set to zero;
5669 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5670 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5671 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5672 DAG.getConstant(MaskVals, MVT::i32));
5673 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5676 // v8i16 shuffles - Prefer shuffles in the following order:
5677 // 1. [all] pshuflw, pshufhw, optional move
5678 // 2. [ssse3] 1 x pshufb
5679 // 3. [ssse3] 2 x pshufb + 1 x por
5680 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5682 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5683 SelectionDAG &DAG) {
5684 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5685 SDValue V1 = SVOp->getOperand(0);
5686 SDValue V2 = SVOp->getOperand(1);
5687 DebugLoc dl = SVOp->getDebugLoc();
5688 SmallVector<int, 8> MaskVals;
5690 // Determine if more than 1 of the words in each of the low and high quadwords
5691 // of the result come from the same quadword of one of the two inputs. Undef
5692 // mask values count as coming from any quadword, for better codegen.
5693 unsigned LoQuad[] = { 0, 0, 0, 0 };
5694 unsigned HiQuad[] = { 0, 0, 0, 0 };
5695 std::bitset<4> InputQuads;
5696 for (unsigned i = 0; i < 8; ++i) {
5697 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5698 int EltIdx = SVOp->getMaskElt(i);
5699 MaskVals.push_back(EltIdx);
5708 InputQuads.set(EltIdx / 4);
5711 int BestLoQuad = -1;
5712 unsigned MaxQuad = 1;
5713 for (unsigned i = 0; i < 4; ++i) {
5714 if (LoQuad[i] > MaxQuad) {
5716 MaxQuad = LoQuad[i];
5720 int BestHiQuad = -1;
5722 for (unsigned i = 0; i < 4; ++i) {
5723 if (HiQuad[i] > MaxQuad) {
5725 MaxQuad = HiQuad[i];
5729 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5730 // of the two input vectors, shuffle them into one input vector so only a
5731 // single pshufb instruction is necessary. If There are more than 2 input
5732 // quads, disable the next transformation since it does not help SSSE3.
5733 bool V1Used = InputQuads[0] || InputQuads[1];
5734 bool V2Used = InputQuads[2] || InputQuads[3];
5735 if (Subtarget->hasSSSE3()) {
5736 if (InputQuads.count() == 2 && V1Used && V2Used) {
5737 BestLoQuad = InputQuads[0] ? 0 : 1;
5738 BestHiQuad = InputQuads[2] ? 2 : 3;
5740 if (InputQuads.count() > 2) {
5746 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5747 // the shuffle mask. If a quad is scored as -1, that means that it contains
5748 // words from all 4 input quadwords.
5750 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5752 BestLoQuad < 0 ? 0 : BestLoQuad,
5753 BestHiQuad < 0 ? 1 : BestHiQuad
5755 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5756 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5757 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5758 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5760 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5761 // source words for the shuffle, to aid later transformations.
5762 bool AllWordsInNewV = true;
5763 bool InOrder[2] = { true, true };
5764 for (unsigned i = 0; i != 8; ++i) {
5765 int idx = MaskVals[i];
5767 InOrder[i/4] = false;
5768 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5770 AllWordsInNewV = false;
5774 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5775 if (AllWordsInNewV) {
5776 for (int i = 0; i != 8; ++i) {
5777 int idx = MaskVals[i];
5780 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5781 if ((idx != i) && idx < 4)
5783 if ((idx != i) && idx > 3)
5792 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5793 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5794 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5795 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5796 unsigned TargetMask = 0;
5797 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5798 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5800 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5801 getShufflePSHUFLWImmediate(SVOp);
5802 V1 = NewV.getOperand(0);
5803 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5807 // If we have SSSE3, and all words of the result are from 1 input vector,
5808 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5809 // is present, fall back to case 4.
5810 if (Subtarget->hasSSSE3()) {
5811 SmallVector<SDValue,16> pshufbMask;
5813 // If we have elements from both input vectors, set the high bit of the
5814 // shuffle mask element to zero out elements that come from V2 in the V1
5815 // mask, and elements that come from V1 in the V2 mask, so that the two
5816 // results can be OR'd together.
5817 bool TwoInputs = V1Used && V2Used;
5818 for (unsigned i = 0; i != 8; ++i) {
5819 int EltIdx = MaskVals[i] * 2;
5820 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5821 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5822 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5823 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5825 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5826 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5827 DAG.getNode(ISD::BUILD_VECTOR, dl,
5828 MVT::v16i8, &pshufbMask[0], 16));
5830 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5832 // Calculate the shuffle mask for the second input, shuffle it, and
5833 // OR it with the first shuffled input.
5835 for (unsigned i = 0; i != 8; ++i) {
5836 int EltIdx = MaskVals[i] * 2;
5837 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5838 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5839 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5840 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5842 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5843 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5844 DAG.getNode(ISD::BUILD_VECTOR, dl,
5845 MVT::v16i8, &pshufbMask[0], 16));
5846 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5847 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5850 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5851 // and update MaskVals with new element order.
5852 std::bitset<8> InOrder;
5853 if (BestLoQuad >= 0) {
5854 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5855 for (int i = 0; i != 4; ++i) {
5856 int idx = MaskVals[i];
5859 } else if ((idx / 4) == BestLoQuad) {
5864 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5867 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5868 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5871 getShufflePSHUFLWImmediate(SVOp), DAG);
5875 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5876 // and update MaskVals with the new element order.
5877 if (BestHiQuad >= 0) {
5878 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5879 for (unsigned i = 4; i != 8; ++i) {
5880 int idx = MaskVals[i];
5883 } else if ((idx / 4) == BestHiQuad) {
5884 MaskV[i] = (idx & 3) + 4;
5888 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5891 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5893 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5895 getShufflePSHUFHWImmediate(SVOp), DAG);
5899 // In case BestHi & BestLo were both -1, which means each quadword has a word
5900 // from each of the four input quadwords, calculate the InOrder bitvector now
5901 // before falling through to the insert/extract cleanup.
5902 if (BestLoQuad == -1 && BestHiQuad == -1) {
5904 for (int i = 0; i != 8; ++i)
5905 if (MaskVals[i] < 0 || MaskVals[i] == i)
5909 // The other elements are put in the right place using pextrw and pinsrw.
5910 for (unsigned i = 0; i != 8; ++i) {
5913 int EltIdx = MaskVals[i];
5916 SDValue ExtOp = (EltIdx < 8) ?
5917 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5918 DAG.getIntPtrConstant(EltIdx)) :
5919 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5920 DAG.getIntPtrConstant(EltIdx - 8));
5921 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5922 DAG.getIntPtrConstant(i));
5927 // v16i8 shuffles - Prefer shuffles in the following order:
5928 // 1. [ssse3] 1 x pshufb
5929 // 2. [ssse3] 2 x pshufb + 1 x por
5930 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5932 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5934 const X86TargetLowering &TLI) {
5935 SDValue V1 = SVOp->getOperand(0);
5936 SDValue V2 = SVOp->getOperand(1);
5937 DebugLoc dl = SVOp->getDebugLoc();
5938 ArrayRef<int> MaskVals = SVOp->getMask();
5940 // If we have SSSE3, case 1 is generated when all result bytes come from
5941 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5942 // present, fall back to case 3.
5944 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5945 if (TLI.getSubtarget()->hasSSSE3()) {
5946 SmallVector<SDValue,16> pshufbMask;
5948 // If all result elements are from one input vector, then only translate
5949 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5951 // Otherwise, we have elements from both input vectors, and must zero out
5952 // elements that come from V2 in the first mask, and V1 in the second mask
5953 // so that we can OR them together.
5954 for (unsigned i = 0; i != 16; ++i) {
5955 int EltIdx = MaskVals[i];
5956 if (EltIdx < 0 || EltIdx >= 16)
5958 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5960 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5961 DAG.getNode(ISD::BUILD_VECTOR, dl,
5962 MVT::v16i8, &pshufbMask[0], 16));
5964 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5965 // the 2nd operand if it's undefined or zero.
5966 if (V2.getOpcode() == ISD::UNDEF ||
5967 ISD::isBuildVectorAllZeros(V2.getNode()))
5970 // Calculate the shuffle mask for the second input, shuffle it, and
5971 // OR it with the first shuffled input.
5973 for (unsigned i = 0; i != 16; ++i) {
5974 int EltIdx = MaskVals[i];
5975 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5976 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5978 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5979 DAG.getNode(ISD::BUILD_VECTOR, dl,
5980 MVT::v16i8, &pshufbMask[0], 16));
5981 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5984 // No SSSE3 - Calculate in place words and then fix all out of place words
5985 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5986 // the 16 different words that comprise the two doublequadword input vectors.
5987 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5988 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5990 for (int i = 0; i != 8; ++i) {
5991 int Elt0 = MaskVals[i*2];
5992 int Elt1 = MaskVals[i*2+1];
5994 // This word of the result is all undef, skip it.
5995 if (Elt0 < 0 && Elt1 < 0)
5998 // This word of the result is already in the correct place, skip it.
5999 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6002 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6003 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6006 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6007 // using a single extract together, load it and store it.
6008 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6009 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6010 DAG.getIntPtrConstant(Elt1 / 2));
6011 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6012 DAG.getIntPtrConstant(i));
6016 // If Elt1 is defined, extract it from the appropriate source. If the
6017 // source byte is not also odd, shift the extracted word left 8 bits
6018 // otherwise clear the bottom 8 bits if we need to do an or.
6020 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6021 DAG.getIntPtrConstant(Elt1 / 2));
6022 if ((Elt1 & 1) == 0)
6023 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6025 TLI.getShiftAmountTy(InsElt.getValueType())));
6027 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6028 DAG.getConstant(0xFF00, MVT::i16));
6030 // If Elt0 is defined, extract it from the appropriate source. If the
6031 // source byte is not also even, shift the extracted word right 8 bits. If
6032 // Elt1 was also defined, OR the extracted values together before
6033 // inserting them in the result.
6035 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6036 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6037 if ((Elt0 & 1) != 0)
6038 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6040 TLI.getShiftAmountTy(InsElt0.getValueType())));
6042 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6043 DAG.getConstant(0x00FF, MVT::i16));
6044 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6047 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6048 DAG.getIntPtrConstant(i));
6050 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6053 // v32i8 shuffles - Translate to VPSHUFB if possible.
6055 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6056 const X86Subtarget *Subtarget,
6057 SelectionDAG &DAG) {
6058 EVT VT = SVOp->getValueType(0);
6059 SDValue V1 = SVOp->getOperand(0);
6060 SDValue V2 = SVOp->getOperand(1);
6061 DebugLoc dl = SVOp->getDebugLoc();
6062 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6064 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6065 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6066 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6068 // VPSHUFB may be generated if
6069 // (1) one of input vector is undefined or zeroinitializer.
6070 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6071 // And (2) the mask indexes don't cross the 128-bit lane.
6072 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6073 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6076 if (V1IsAllZero && !V2IsAllZero) {
6077 CommuteVectorShuffleMask(MaskVals, 32);
6080 SmallVector<SDValue, 32> pshufbMask;
6081 for (unsigned i = 0; i != 32; i++) {
6082 int EltIdx = MaskVals[i];
6083 if (EltIdx < 0 || EltIdx >= 32)
6086 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6087 // Cross lane is not allowed.
6091 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6093 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6094 DAG.getNode(ISD::BUILD_VECTOR, dl,
6095 MVT::v32i8, &pshufbMask[0], 32));
6098 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6099 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6100 /// done when every pair / quad of shuffle mask elements point to elements in
6101 /// the right sequence. e.g.
6102 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6104 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6105 SelectionDAG &DAG, DebugLoc dl) {
6106 MVT VT = SVOp->getValueType(0).getSimpleVT();
6107 unsigned NumElems = VT.getVectorNumElements();
6110 switch (VT.SimpleTy) {
6111 default: llvm_unreachable("Unexpected!");
6112 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6113 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6114 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6115 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6116 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6117 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6120 SmallVector<int, 8> MaskVec;
6121 for (unsigned i = 0; i != NumElems; i += Scale) {
6123 for (unsigned j = 0; j != Scale; ++j) {
6124 int EltIdx = SVOp->getMaskElt(i+j);
6128 StartIdx = (EltIdx / Scale);
6129 if (EltIdx != (int)(StartIdx*Scale + j))
6132 MaskVec.push_back(StartIdx);
6135 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6136 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6137 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6140 /// getVZextMovL - Return a zero-extending vector move low node.
6142 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6143 SDValue SrcOp, SelectionDAG &DAG,
6144 const X86Subtarget *Subtarget, DebugLoc dl) {
6145 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6146 LoadSDNode *LD = NULL;
6147 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6148 LD = dyn_cast<LoadSDNode>(SrcOp);
6150 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6152 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6153 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6154 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6155 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6156 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6158 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6159 return DAG.getNode(ISD::BITCAST, dl, VT,
6160 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6161 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6169 return DAG.getNode(ISD::BITCAST, dl, VT,
6170 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6171 DAG.getNode(ISD::BITCAST, dl,
6175 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6176 /// which could not be matched by any known target speficic shuffle
6178 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6180 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6181 if (NewOp.getNode())
6184 EVT VT = SVOp->getValueType(0);
6186 unsigned NumElems = VT.getVectorNumElements();
6187 unsigned NumLaneElems = NumElems / 2;
6189 DebugLoc dl = SVOp->getDebugLoc();
6190 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6191 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6194 SmallVector<int, 16> Mask;
6195 for (unsigned l = 0; l < 2; ++l) {
6196 // Build a shuffle mask for the output, discovering on the fly which
6197 // input vectors to use as shuffle operands (recorded in InputUsed).
6198 // If building a suitable shuffle vector proves too hard, then bail
6199 // out with UseBuildVector set.
6200 bool UseBuildVector = false;
6201 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6202 unsigned LaneStart = l * NumLaneElems;
6203 for (unsigned i = 0; i != NumLaneElems; ++i) {
6204 // The mask element. This indexes into the input.
6205 int Idx = SVOp->getMaskElt(i+LaneStart);
6207 // the mask element does not index into any input vector.
6212 // The input vector this mask element indexes into.
6213 int Input = Idx / NumLaneElems;
6215 // Turn the index into an offset from the start of the input vector.
6216 Idx -= Input * NumLaneElems;
6218 // Find or create a shuffle vector operand to hold this input.
6220 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6221 if (InputUsed[OpNo] == Input)
6222 // This input vector is already an operand.
6224 if (InputUsed[OpNo] < 0) {
6225 // Create a new operand for this input vector.
6226 InputUsed[OpNo] = Input;
6231 if (OpNo >= array_lengthof(InputUsed)) {
6232 // More than two input vectors used! Give up on trying to create a
6233 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6234 UseBuildVector = true;
6238 // Add the mask index for the new shuffle vector.
6239 Mask.push_back(Idx + OpNo * NumLaneElems);
6242 if (UseBuildVector) {
6243 SmallVector<SDValue, 16> SVOps;
6244 for (unsigned i = 0; i != NumLaneElems; ++i) {
6245 // The mask element. This indexes into the input.
6246 int Idx = SVOp->getMaskElt(i+LaneStart);
6248 SVOps.push_back(DAG.getUNDEF(EltVT));
6252 // The input vector this mask element indexes into.
6253 int Input = Idx / NumElems;
6255 // Turn the index into an offset from the start of the input vector.
6256 Idx -= Input * NumElems;
6258 // Extract the vector element by hand.
6259 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6260 SVOp->getOperand(Input),
6261 DAG.getIntPtrConstant(Idx)));
6264 // Construct the output using a BUILD_VECTOR.
6265 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6267 } else if (InputUsed[0] < 0) {
6268 // No input vectors were used! The result is undefined.
6269 Output[l] = DAG.getUNDEF(NVT);
6271 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6272 (InputUsed[0] % 2) * NumLaneElems,
6274 // If only one input was used, use an undefined vector for the other.
6275 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6276 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6277 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6278 // At least one input vector was used. Create a new shuffle vector.
6279 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6285 // Concatenate the result back
6286 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6289 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6290 /// 4 elements, and match them with several different shuffle types.
6292 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6293 SDValue V1 = SVOp->getOperand(0);
6294 SDValue V2 = SVOp->getOperand(1);
6295 DebugLoc dl = SVOp->getDebugLoc();
6296 EVT VT = SVOp->getValueType(0);
6298 assert(VT.is128BitVector() && "Unsupported vector size");
6300 std::pair<int, int> Locs[4];
6301 int Mask1[] = { -1, -1, -1, -1 };
6302 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6306 for (unsigned i = 0; i != 4; ++i) {
6307 int Idx = PermMask[i];
6309 Locs[i] = std::make_pair(-1, -1);
6311 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6313 Locs[i] = std::make_pair(0, NumLo);
6317 Locs[i] = std::make_pair(1, NumHi);
6319 Mask1[2+NumHi] = Idx;
6325 if (NumLo <= 2 && NumHi <= 2) {
6326 // If no more than two elements come from either vector. This can be
6327 // implemented with two shuffles. First shuffle gather the elements.
6328 // The second shuffle, which takes the first shuffle as both of its
6329 // vector operands, put the elements into the right order.
6330 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6332 int Mask2[] = { -1, -1, -1, -1 };
6334 for (unsigned i = 0; i != 4; ++i)
6335 if (Locs[i].first != -1) {
6336 unsigned Idx = (i < 2) ? 0 : 4;
6337 Idx += Locs[i].first * 2 + Locs[i].second;
6341 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6344 if (NumLo == 3 || NumHi == 3) {
6345 // Otherwise, we must have three elements from one vector, call it X, and
6346 // one element from the other, call it Y. First, use a shufps to build an
6347 // intermediate vector with the one element from Y and the element from X
6348 // that will be in the same half in the final destination (the indexes don't
6349 // matter). Then, use a shufps to build the final vector, taking the half
6350 // containing the element from Y from the intermediate, and the other half
6353 // Normalize it so the 3 elements come from V1.
6354 CommuteVectorShuffleMask(PermMask, 4);
6358 // Find the element from V2.
6360 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6361 int Val = PermMask[HiIndex];
6368 Mask1[0] = PermMask[HiIndex];
6370 Mask1[2] = PermMask[HiIndex^1];
6372 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6375 Mask1[0] = PermMask[0];
6376 Mask1[1] = PermMask[1];
6377 Mask1[2] = HiIndex & 1 ? 6 : 4;
6378 Mask1[3] = HiIndex & 1 ? 4 : 6;
6379 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6382 Mask1[0] = HiIndex & 1 ? 2 : 0;
6383 Mask1[1] = HiIndex & 1 ? 0 : 2;
6384 Mask1[2] = PermMask[2];
6385 Mask1[3] = PermMask[3];
6390 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6393 // Break it into (shuffle shuffle_hi, shuffle_lo).
6394 int LoMask[] = { -1, -1, -1, -1 };
6395 int HiMask[] = { -1, -1, -1, -1 };
6397 int *MaskPtr = LoMask;
6398 unsigned MaskIdx = 0;
6401 for (unsigned i = 0; i != 4; ++i) {
6408 int Idx = PermMask[i];
6410 Locs[i] = std::make_pair(-1, -1);
6411 } else if (Idx < 4) {
6412 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6413 MaskPtr[LoIdx] = Idx;
6416 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6417 MaskPtr[HiIdx] = Idx;
6422 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6423 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6424 int MaskOps[] = { -1, -1, -1, -1 };
6425 for (unsigned i = 0; i != 4; ++i)
6426 if (Locs[i].first != -1)
6427 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6428 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6431 static bool MayFoldVectorLoad(SDValue V) {
6432 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6433 V = V.getOperand(0);
6434 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6435 V = V.getOperand(0);
6436 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6437 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6438 // BUILD_VECTOR (load), undef
6439 V = V.getOperand(0);
6445 // FIXME: the version above should always be used. Since there's
6446 // a bug where several vector shuffles can't be folded because the
6447 // DAG is not updated during lowering and a node claims to have two
6448 // uses while it only has one, use this version, and let isel match
6449 // another instruction if the load really happens to have more than
6450 // one use. Remove this version after this bug get fixed.
6451 // rdar://8434668, PR8156
6452 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6453 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6454 V = V.getOperand(0);
6455 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6456 V = V.getOperand(0);
6457 if (ISD::isNormalLoad(V.getNode()))
6463 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6464 EVT VT = Op.getValueType();
6466 // Canonizalize to v2f64.
6467 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6468 return DAG.getNode(ISD::BITCAST, dl, VT,
6469 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6474 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6476 SDValue V1 = Op.getOperand(0);
6477 SDValue V2 = Op.getOperand(1);
6478 EVT VT = Op.getValueType();
6480 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6482 if (HasSSE2 && VT == MVT::v2f64)
6483 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6485 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6486 return DAG.getNode(ISD::BITCAST, dl, VT,
6487 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6488 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6489 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6493 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6494 SDValue V1 = Op.getOperand(0);
6495 SDValue V2 = Op.getOperand(1);
6496 EVT VT = Op.getValueType();
6498 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6499 "unsupported shuffle type");
6501 if (V2.getOpcode() == ISD::UNDEF)
6505 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6509 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6510 SDValue V1 = Op.getOperand(0);
6511 SDValue V2 = Op.getOperand(1);
6512 EVT VT = Op.getValueType();
6513 unsigned NumElems = VT.getVectorNumElements();
6515 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6516 // operand of these instructions is only memory, so check if there's a
6517 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6519 bool CanFoldLoad = false;
6521 // Trivial case, when V2 comes from a load.
6522 if (MayFoldVectorLoad(V2))
6525 // When V1 is a load, it can be folded later into a store in isel, example:
6526 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6528 // (MOVLPSmr addr:$src1, VR128:$src2)
6529 // So, recognize this potential and also use MOVLPS or MOVLPD
6530 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6533 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6535 if (HasSSE2 && NumElems == 2)
6536 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6539 // If we don't care about the second element, proceed to use movss.
6540 if (SVOp->getMaskElt(1) != -1)
6541 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6544 // movl and movlp will both match v2i64, but v2i64 is never matched by
6545 // movl earlier because we make it strict to avoid messing with the movlp load
6546 // folding logic (see the code above getMOVLP call). Match it here then,
6547 // this is horrible, but will stay like this until we move all shuffle
6548 // matching to x86 specific nodes. Note that for the 1st condition all
6549 // types are matched with movsd.
6551 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6552 // as to remove this logic from here, as much as possible
6553 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6554 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6555 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6558 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6560 // Invert the operand order and use SHUFPS to match it.
6561 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6562 getShuffleSHUFImmediate(SVOp), DAG);
6565 // Reduce a vector shuffle to zext.
6567 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6568 // PMOVZX is only available from SSE41.
6569 if (!Subtarget->hasSSE41())
6572 EVT VT = Op.getValueType();
6574 // Only AVX2 support 256-bit vector integer extending.
6575 if (!Subtarget->hasAVX2() && VT.is256BitVector())
6578 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6579 DebugLoc DL = Op.getDebugLoc();
6580 SDValue V1 = Op.getOperand(0);
6581 SDValue V2 = Op.getOperand(1);
6582 unsigned NumElems = VT.getVectorNumElements();
6584 // Extending is an unary operation and the element type of the source vector
6585 // won't be equal to or larger than i64.
6586 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6587 VT.getVectorElementType() == MVT::i64)
6590 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6591 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6592 while ((1 << Shift) < NumElems) {
6593 if (SVOp->getMaskElt(1 << Shift) == 1)
6596 // The maximal ratio is 8, i.e. from i8 to i64.
6601 // Check the shuffle mask.
6602 unsigned Mask = (1U << Shift) - 1;
6603 for (unsigned i = 0; i != NumElems; ++i) {
6604 int EltIdx = SVOp->getMaskElt(i);
6605 if ((i & Mask) != 0 && EltIdx != -1)
6607 if ((i & Mask) == 0 && EltIdx != (i >> Shift))
6611 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6612 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6613 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6615 if (!isTypeLegal(NVT))
6618 // Simplify the operand as it's prepared to be fed into shuffle.
6619 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6620 if (V1.getOpcode() == ISD::BITCAST &&
6621 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6622 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6624 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6625 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6626 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6627 // If it's foldable, i.e. normal load with single use, we will let code
6628 // selection to fold it. Otherwise, we will short the conversion sequence.
6629 if (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())
6630 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6633 return DAG.getNode(ISD::BITCAST, DL, VT,
6634 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6638 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6639 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6640 EVT VT = Op.getValueType();
6641 DebugLoc dl = Op.getDebugLoc();
6642 SDValue V1 = Op.getOperand(0);
6643 SDValue V2 = Op.getOperand(1);
6645 if (isZeroShuffle(SVOp))
6646 return getZeroVector(VT, Subtarget, DAG, dl);
6648 // Handle splat operations
6649 if (SVOp->isSplat()) {
6650 unsigned NumElem = VT.getVectorNumElements();
6651 int Size = VT.getSizeInBits();
6653 // Use vbroadcast whenever the splat comes from a foldable load
6654 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6655 if (Broadcast.getNode())
6658 // Handle splats by matching through known shuffle masks
6659 if ((Size == 128 && NumElem <= 4) ||
6660 (Size == 256 && NumElem < 8))
6663 // All remaning splats are promoted to target supported vector shuffles.
6664 return PromoteSplat(SVOp, DAG);
6667 // Check integer expanding shuffles.
6668 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6669 if (NewOp.getNode())
6672 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6674 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6675 VT == MVT::v16i16 || VT == MVT::v32i8) {
6676 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6677 if (NewOp.getNode())
6678 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6679 } else if ((VT == MVT::v4i32 ||
6680 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6681 // FIXME: Figure out a cleaner way to do this.
6682 // Try to make use of movq to zero out the top part.
6683 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6684 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6685 if (NewOp.getNode()) {
6686 EVT NewVT = NewOp.getValueType();
6687 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6688 NewVT, true, false))
6689 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6690 DAG, Subtarget, dl);
6692 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6693 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694 if (NewOp.getNode()) {
6695 EVT NewVT = NewOp.getValueType();
6696 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6697 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6698 DAG, Subtarget, dl);
6706 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6707 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6708 SDValue V1 = Op.getOperand(0);
6709 SDValue V2 = Op.getOperand(1);
6710 EVT VT = Op.getValueType();
6711 DebugLoc dl = Op.getDebugLoc();
6712 unsigned NumElems = VT.getVectorNumElements();
6713 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6714 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6715 bool V1IsSplat = false;
6716 bool V2IsSplat = false;
6717 bool HasSSE2 = Subtarget->hasSSE2();
6718 bool HasAVX = Subtarget->hasAVX();
6719 bool HasAVX2 = Subtarget->hasAVX2();
6720 MachineFunction &MF = DAG.getMachineFunction();
6721 bool OptForSize = MF.getFunction()->getFnAttributes().
6722 hasAttribute(Attributes::OptimizeForSize);
6724 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6726 if (V1IsUndef && V2IsUndef)
6727 return DAG.getUNDEF(VT);
6729 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6731 // Vector shuffle lowering takes 3 steps:
6733 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6734 // narrowing and commutation of operands should be handled.
6735 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6737 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6738 // so the shuffle can be broken into other shuffles and the legalizer can
6739 // try the lowering again.
6741 // The general idea is that no vector_shuffle operation should be left to
6742 // be matched during isel, all of them must be converted to a target specific
6745 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6746 // narrowing and commutation of operands should be handled. The actual code
6747 // doesn't include all of those, work in progress...
6748 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6749 if (NewOp.getNode())
6752 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6754 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6755 // unpckh_undef). Only use pshufd if speed is more important than size.
6756 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6757 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6758 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6759 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6761 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6762 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6763 return getMOVDDup(Op, dl, V1, DAG);
6765 if (isMOVHLPS_v_undef_Mask(M, VT))
6766 return getMOVHighToLow(Op, dl, DAG);
6768 // Use to match splats
6769 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6770 (VT == MVT::v2f64 || VT == MVT::v2i64))
6771 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6773 if (isPSHUFDMask(M, VT)) {
6774 // The actual implementation will match the mask in the if above and then
6775 // during isel it can match several different instructions, not only pshufd
6776 // as its name says, sad but true, emulate the behavior for now...
6777 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6778 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6780 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6782 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6783 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6785 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6786 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6788 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6792 // Check if this can be converted into a logical shift.
6793 bool isLeft = false;
6796 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6797 if (isShift && ShVal.hasOneUse()) {
6798 // If the shifted value has multiple uses, it may be cheaper to use
6799 // v_set0 + movlhps or movhlps, etc.
6800 EVT EltVT = VT.getVectorElementType();
6801 ShAmt *= EltVT.getSizeInBits();
6802 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6805 if (isMOVLMask(M, VT)) {
6806 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6807 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6808 if (!isMOVLPMask(M, VT)) {
6809 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6810 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6812 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6813 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6817 // FIXME: fold these into legal mask.
6818 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6819 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6821 if (isMOVHLPSMask(M, VT))
6822 return getMOVHighToLow(Op, dl, DAG);
6824 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6825 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6827 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6828 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6830 if (isMOVLPMask(M, VT))
6831 return getMOVLP(Op, dl, DAG, HasSSE2);
6833 if (ShouldXformToMOVHLPS(M, VT) ||
6834 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6835 return CommuteVectorShuffle(SVOp, DAG);
6838 // No better options. Use a vshldq / vsrldq.
6839 EVT EltVT = VT.getVectorElementType();
6840 ShAmt *= EltVT.getSizeInBits();
6841 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6844 bool Commuted = false;
6845 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6846 // 1,1,1,1 -> v8i16 though.
6847 V1IsSplat = isSplatVector(V1.getNode());
6848 V2IsSplat = isSplatVector(V2.getNode());
6850 // Canonicalize the splat or undef, if present, to be on the RHS.
6851 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6852 CommuteVectorShuffleMask(M, NumElems);
6854 std::swap(V1IsSplat, V2IsSplat);
6858 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6859 // Shuffling low element of v1 into undef, just return v1.
6862 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6863 // the instruction selector will not match, so get a canonical MOVL with
6864 // swapped operands to undo the commute.
6865 return getMOVL(DAG, dl, VT, V2, V1);
6868 if (isUNPCKLMask(M, VT, HasAVX2))
6869 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6871 if (isUNPCKHMask(M, VT, HasAVX2))
6872 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6875 // Normalize mask so all entries that point to V2 points to its first
6876 // element then try to match unpck{h|l} again. If match, return a
6877 // new vector_shuffle with the corrected mask.p
6878 SmallVector<int, 8> NewMask(M.begin(), M.end());
6879 NormalizeMask(NewMask, NumElems);
6880 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6881 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6882 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6883 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6887 // Commute is back and try unpck* again.
6888 // FIXME: this seems wrong.
6889 CommuteVectorShuffleMask(M, NumElems);
6891 std::swap(V1IsSplat, V2IsSplat);
6894 if (isUNPCKLMask(M, VT, HasAVX2))
6895 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6897 if (isUNPCKHMask(M, VT, HasAVX2))
6898 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6901 // Normalize the node to match x86 shuffle ops if needed
6902 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6903 return CommuteVectorShuffle(SVOp, DAG);
6905 // The checks below are all present in isShuffleMaskLegal, but they are
6906 // inlined here right now to enable us to directly emit target specific
6907 // nodes, and remove one by one until they don't return Op anymore.
6909 if (isPALIGNRMask(M, VT, Subtarget))
6910 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6911 getShufflePALIGNRImmediate(SVOp),
6914 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6915 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6916 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6917 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6920 if (isPSHUFHWMask(M, VT, HasAVX2))
6921 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6922 getShufflePSHUFHWImmediate(SVOp),
6925 if (isPSHUFLWMask(M, VT, HasAVX2))
6926 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6927 getShufflePSHUFLWImmediate(SVOp),
6930 if (isSHUFPMask(M, VT, HasAVX))
6931 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6932 getShuffleSHUFImmediate(SVOp), DAG);
6934 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6935 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6936 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6937 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6939 //===--------------------------------------------------------------------===//
6940 // Generate target specific nodes for 128 or 256-bit shuffles only
6941 // supported in the AVX instruction set.
6944 // Handle VMOVDDUPY permutations
6945 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6946 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6948 // Handle VPERMILPS/D* permutations
6949 if (isVPERMILPMask(M, VT, HasAVX)) {
6950 if (HasAVX2 && VT == MVT::v8i32)
6951 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6952 getShuffleSHUFImmediate(SVOp), DAG);
6953 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6954 getShuffleSHUFImmediate(SVOp), DAG);
6957 // Handle VPERM2F128/VPERM2I128 permutations
6958 if (isVPERM2X128Mask(M, VT, HasAVX))
6959 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6960 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6962 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6963 if (BlendOp.getNode())
6966 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6967 SmallVector<SDValue, 8> permclMask;
6968 for (unsigned i = 0; i != 8; ++i) {
6969 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6971 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6973 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6974 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6975 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6978 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6979 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6980 getShuffleCLImmediate(SVOp), DAG);
6983 //===--------------------------------------------------------------------===//
6984 // Since no target specific shuffle was selected for this generic one,
6985 // lower it into other known shuffles. FIXME: this isn't true yet, but
6986 // this is the plan.
6989 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6990 if (VT == MVT::v8i16) {
6991 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6992 if (NewOp.getNode())
6996 if (VT == MVT::v16i8) {
6997 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6998 if (NewOp.getNode())
7002 if (VT == MVT::v32i8) {
7003 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7004 if (NewOp.getNode())
7008 // Handle all 128-bit wide vectors with 4 elements, and match them with
7009 // several different shuffle types.
7010 if (NumElems == 4 && VT.is128BitVector())
7011 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7013 // Handle general 256-bit shuffles
7014 if (VT.is256BitVector())
7015 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7021 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7022 SelectionDAG &DAG) const {
7023 EVT VT = Op.getValueType();
7024 DebugLoc dl = Op.getDebugLoc();
7026 if (!Op.getOperand(0).getValueType().is128BitVector())
7029 if (VT.getSizeInBits() == 8) {
7030 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7031 Op.getOperand(0), Op.getOperand(1));
7032 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7033 DAG.getValueType(VT));
7034 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7037 if (VT.getSizeInBits() == 16) {
7038 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7039 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7041 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7042 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7043 DAG.getNode(ISD::BITCAST, dl,
7047 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7048 Op.getOperand(0), Op.getOperand(1));
7049 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7050 DAG.getValueType(VT));
7051 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7054 if (VT == MVT::f32) {
7055 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7056 // the result back to FR32 register. It's only worth matching if the
7057 // result has a single use which is a store or a bitcast to i32. And in
7058 // the case of a store, it's not worth it if the index is a constant 0,
7059 // because a MOVSSmr can be used instead, which is smaller and faster.
7060 if (!Op.hasOneUse())
7062 SDNode *User = *Op.getNode()->use_begin();
7063 if ((User->getOpcode() != ISD::STORE ||
7064 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7065 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7066 (User->getOpcode() != ISD::BITCAST ||
7067 User->getValueType(0) != MVT::i32))
7069 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7070 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7073 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7076 if (VT == MVT::i32 || VT == MVT::i64) {
7077 // ExtractPS/pextrq works with constant index.
7078 if (isa<ConstantSDNode>(Op.getOperand(1)))
7086 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7087 SelectionDAG &DAG) const {
7088 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7091 SDValue Vec = Op.getOperand(0);
7092 EVT VecVT = Vec.getValueType();
7094 // If this is a 256-bit vector result, first extract the 128-bit vector and
7095 // then extract the element from the 128-bit vector.
7096 if (VecVT.is256BitVector()) {
7097 DebugLoc dl = Op.getNode()->getDebugLoc();
7098 unsigned NumElems = VecVT.getVectorNumElements();
7099 SDValue Idx = Op.getOperand(1);
7100 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7102 // Get the 128-bit vector.
7103 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7105 if (IdxVal >= NumElems/2)
7106 IdxVal -= NumElems/2;
7107 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7108 DAG.getConstant(IdxVal, MVT::i32));
7111 assert(VecVT.is128BitVector() && "Unexpected vector length");
7113 if (Subtarget->hasSSE41()) {
7114 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7119 EVT VT = Op.getValueType();
7120 DebugLoc dl = Op.getDebugLoc();
7121 // TODO: handle v16i8.
7122 if (VT.getSizeInBits() == 16) {
7123 SDValue Vec = Op.getOperand(0);
7124 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7126 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7127 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7128 DAG.getNode(ISD::BITCAST, dl,
7131 // Transform it so it match pextrw which produces a 32-bit result.
7132 EVT EltVT = MVT::i32;
7133 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7134 Op.getOperand(0), Op.getOperand(1));
7135 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7136 DAG.getValueType(VT));
7137 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7140 if (VT.getSizeInBits() == 32) {
7141 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7145 // SHUFPS the element to the lowest double word, then movss.
7146 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7147 EVT VVT = Op.getOperand(0).getValueType();
7148 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7149 DAG.getUNDEF(VVT), Mask);
7150 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7151 DAG.getIntPtrConstant(0));
7154 if (VT.getSizeInBits() == 64) {
7155 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7156 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7157 // to match extract_elt for f64.
7158 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7162 // UNPCKHPD the element to the lowest double word, then movsd.
7163 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7164 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7165 int Mask[2] = { 1, -1 };
7166 EVT VVT = Op.getOperand(0).getValueType();
7167 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7168 DAG.getUNDEF(VVT), Mask);
7169 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7170 DAG.getIntPtrConstant(0));
7177 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7178 SelectionDAG &DAG) const {
7179 EVT VT = Op.getValueType();
7180 EVT EltVT = VT.getVectorElementType();
7181 DebugLoc dl = Op.getDebugLoc();
7183 SDValue N0 = Op.getOperand(0);
7184 SDValue N1 = Op.getOperand(1);
7185 SDValue N2 = Op.getOperand(2);
7187 if (!VT.is128BitVector())
7190 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7191 isa<ConstantSDNode>(N2)) {
7193 if (VT == MVT::v8i16)
7194 Opc = X86ISD::PINSRW;
7195 else if (VT == MVT::v16i8)
7196 Opc = X86ISD::PINSRB;
7198 Opc = X86ISD::PINSRB;
7200 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7202 if (N1.getValueType() != MVT::i32)
7203 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7204 if (N2.getValueType() != MVT::i32)
7205 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7206 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7209 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7210 // Bits [7:6] of the constant are the source select. This will always be
7211 // zero here. The DAG Combiner may combine an extract_elt index into these
7212 // bits. For example (insert (extract, 3), 2) could be matched by putting
7213 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7214 // Bits [5:4] of the constant are the destination select. This is the
7215 // value of the incoming immediate.
7216 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7217 // combine either bitwise AND or insert of float 0.0 to set these bits.
7218 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7219 // Create this as a scalar to vector..
7220 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7221 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7224 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7225 // PINSR* works with constant index.
7232 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7233 EVT VT = Op.getValueType();
7234 EVT EltVT = VT.getVectorElementType();
7236 DebugLoc dl = Op.getDebugLoc();
7237 SDValue N0 = Op.getOperand(0);
7238 SDValue N1 = Op.getOperand(1);
7239 SDValue N2 = Op.getOperand(2);
7241 // If this is a 256-bit vector result, first extract the 128-bit vector,
7242 // insert the element into the extracted half and then place it back.
7243 if (VT.is256BitVector()) {
7244 if (!isa<ConstantSDNode>(N2))
7247 // Get the desired 128-bit vector half.
7248 unsigned NumElems = VT.getVectorNumElements();
7249 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7250 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7252 // Insert the element into the desired half.
7253 bool Upper = IdxVal >= NumElems/2;
7254 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7255 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7257 // Insert the changed part back to the 256-bit vector
7258 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7261 if (Subtarget->hasSSE41())
7262 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7264 if (EltVT == MVT::i8)
7267 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7268 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7269 // as its second argument.
7270 if (N1.getValueType() != MVT::i32)
7271 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7272 if (N2.getValueType() != MVT::i32)
7273 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7274 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7279 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7280 LLVMContext *Context = DAG.getContext();
7281 DebugLoc dl = Op.getDebugLoc();
7282 EVT OpVT = Op.getValueType();
7284 // If this is a 256-bit vector result, first insert into a 128-bit
7285 // vector and then insert into the 256-bit vector.
7286 if (!OpVT.is128BitVector()) {
7287 // Insert into a 128-bit vector.
7288 EVT VT128 = EVT::getVectorVT(*Context,
7289 OpVT.getVectorElementType(),
7290 OpVT.getVectorNumElements() / 2);
7292 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7294 // Insert the 128-bit vector.
7295 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7298 if (OpVT == MVT::v1i64 &&
7299 Op.getOperand(0).getValueType() == MVT::i64)
7300 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7302 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7303 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7304 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7305 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7308 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7309 // a simple subregister reference or explicit instructions to grab
7310 // upper bits of a vector.
7311 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7312 SelectionDAG &DAG) {
7313 if (Subtarget->hasAVX()) {
7314 DebugLoc dl = Op.getNode()->getDebugLoc();
7315 SDValue Vec = Op.getNode()->getOperand(0);
7316 SDValue Idx = Op.getNode()->getOperand(1);
7318 if (Op.getNode()->getValueType(0).is128BitVector() &&
7319 Vec.getNode()->getValueType(0).is256BitVector() &&
7320 isa<ConstantSDNode>(Idx)) {
7321 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7322 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7328 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7329 // simple superregister reference or explicit instructions to insert
7330 // the upper bits of a vector.
7331 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7332 SelectionDAG &DAG) {
7333 if (Subtarget->hasAVX()) {
7334 DebugLoc dl = Op.getNode()->getDebugLoc();
7335 SDValue Vec = Op.getNode()->getOperand(0);
7336 SDValue SubVec = Op.getNode()->getOperand(1);
7337 SDValue Idx = Op.getNode()->getOperand(2);
7339 if (Op.getNode()->getValueType(0).is256BitVector() &&
7340 SubVec.getNode()->getValueType(0).is128BitVector() &&
7341 isa<ConstantSDNode>(Idx)) {
7342 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7343 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7349 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7350 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7351 // one of the above mentioned nodes. It has to be wrapped because otherwise
7352 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7353 // be used to form addressing mode. These wrapped nodes will be selected
7356 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7357 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7359 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7361 unsigned char OpFlag = 0;
7362 unsigned WrapperKind = X86ISD::Wrapper;
7363 CodeModel::Model M = getTargetMachine().getCodeModel();
7365 if (Subtarget->isPICStyleRIPRel() &&
7366 (M == CodeModel::Small || M == CodeModel::Kernel))
7367 WrapperKind = X86ISD::WrapperRIP;
7368 else if (Subtarget->isPICStyleGOT())
7369 OpFlag = X86II::MO_GOTOFF;
7370 else if (Subtarget->isPICStyleStubPIC())
7371 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7373 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7375 CP->getOffset(), OpFlag);
7376 DebugLoc DL = CP->getDebugLoc();
7377 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7378 // With PIC, the address is actually $g + Offset.
7380 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7381 DAG.getNode(X86ISD::GlobalBaseReg,
7382 DebugLoc(), getPointerTy()),
7389 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7390 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7392 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7394 unsigned char OpFlag = 0;
7395 unsigned WrapperKind = X86ISD::Wrapper;
7396 CodeModel::Model M = getTargetMachine().getCodeModel();
7398 if (Subtarget->isPICStyleRIPRel() &&
7399 (M == CodeModel::Small || M == CodeModel::Kernel))
7400 WrapperKind = X86ISD::WrapperRIP;
7401 else if (Subtarget->isPICStyleGOT())
7402 OpFlag = X86II::MO_GOTOFF;
7403 else if (Subtarget->isPICStyleStubPIC())
7404 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7406 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7408 DebugLoc DL = JT->getDebugLoc();
7409 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7411 // With PIC, the address is actually $g + Offset.
7413 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7414 DAG.getNode(X86ISD::GlobalBaseReg,
7415 DebugLoc(), getPointerTy()),
7422 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7423 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7425 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7427 unsigned char OpFlag = 0;
7428 unsigned WrapperKind = X86ISD::Wrapper;
7429 CodeModel::Model M = getTargetMachine().getCodeModel();
7431 if (Subtarget->isPICStyleRIPRel() &&
7432 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7433 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7434 OpFlag = X86II::MO_GOTPCREL;
7435 WrapperKind = X86ISD::WrapperRIP;
7436 } else if (Subtarget->isPICStyleGOT()) {
7437 OpFlag = X86II::MO_GOT;
7438 } else if (Subtarget->isPICStyleStubPIC()) {
7439 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7440 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7441 OpFlag = X86II::MO_DARWIN_NONLAZY;
7444 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7446 DebugLoc DL = Op.getDebugLoc();
7447 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7450 // With PIC, the address is actually $g + Offset.
7451 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7452 !Subtarget->is64Bit()) {
7453 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7454 DAG.getNode(X86ISD::GlobalBaseReg,
7455 DebugLoc(), getPointerTy()),
7459 // For symbols that require a load from a stub to get the address, emit the
7461 if (isGlobalStubReference(OpFlag))
7462 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7463 MachinePointerInfo::getGOT(), false, false, false, 0);
7469 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7470 // Create the TargetBlockAddressAddress node.
7471 unsigned char OpFlags =
7472 Subtarget->ClassifyBlockAddressReference();
7473 CodeModel::Model M = getTargetMachine().getCodeModel();
7474 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7475 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7476 DebugLoc dl = Op.getDebugLoc();
7477 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7480 if (Subtarget->isPICStyleRIPRel() &&
7481 (M == CodeModel::Small || M == CodeModel::Kernel))
7482 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7484 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7486 // With PIC, the address is actually $g + Offset.
7487 if (isGlobalRelativeToPICBase(OpFlags)) {
7488 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7489 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7497 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7499 SelectionDAG &DAG) const {
7500 // Create the TargetGlobalAddress node, folding in the constant
7501 // offset if it is legal.
7502 unsigned char OpFlags =
7503 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7504 CodeModel::Model M = getTargetMachine().getCodeModel();
7506 if (OpFlags == X86II::MO_NO_FLAG &&
7507 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7508 // A direct static reference to a global.
7509 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7512 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7515 if (Subtarget->isPICStyleRIPRel() &&
7516 (M == CodeModel::Small || M == CodeModel::Kernel))
7517 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7519 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7521 // With PIC, the address is actually $g + Offset.
7522 if (isGlobalRelativeToPICBase(OpFlags)) {
7523 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7524 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7528 // For globals that require a load from a stub to get the address, emit the
7530 if (isGlobalStubReference(OpFlags))
7531 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7532 MachinePointerInfo::getGOT(), false, false, false, 0);
7534 // If there was a non-zero offset that we didn't fold, create an explicit
7537 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7538 DAG.getConstant(Offset, getPointerTy()));
7544 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7545 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7546 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7547 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7551 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7552 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7553 unsigned char OperandFlags, bool LocalDynamic = false) {
7554 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7555 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7556 DebugLoc dl = GA->getDebugLoc();
7557 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7558 GA->getValueType(0),
7562 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7566 SDValue Ops[] = { Chain, TGA, *InFlag };
7567 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7569 SDValue Ops[] = { Chain, TGA };
7570 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7573 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7574 MFI->setAdjustsStack(true);
7576 SDValue Flag = Chain.getValue(1);
7577 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7580 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7582 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7585 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7586 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7587 DAG.getNode(X86ISD::GlobalBaseReg,
7588 DebugLoc(), PtrVT), InFlag);
7589 InFlag = Chain.getValue(1);
7591 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7596 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7598 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7599 X86::RAX, X86II::MO_TLSGD);
7602 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7606 DebugLoc dl = GA->getDebugLoc();
7608 // Get the start address of the TLS block for this module.
7609 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7610 .getInfo<X86MachineFunctionInfo>();
7611 MFI->incNumLocalDynamicTLSAccesses();
7615 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7616 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7619 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7620 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7621 InFlag = Chain.getValue(1);
7622 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7623 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7626 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7630 unsigned char OperandFlags = X86II::MO_DTPOFF;
7631 unsigned WrapperKind = X86ISD::Wrapper;
7632 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7633 GA->getValueType(0),
7634 GA->getOffset(), OperandFlags);
7635 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7637 // Add x@dtpoff with the base.
7638 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7641 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7642 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7643 const EVT PtrVT, TLSModel::Model model,
7644 bool is64Bit, bool isPIC) {
7645 DebugLoc dl = GA->getDebugLoc();
7647 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7648 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7649 is64Bit ? 257 : 256));
7651 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7652 DAG.getIntPtrConstant(0),
7653 MachinePointerInfo(Ptr),
7654 false, false, false, 0);
7656 unsigned char OperandFlags = 0;
7657 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7659 unsigned WrapperKind = X86ISD::Wrapper;
7660 if (model == TLSModel::LocalExec) {
7661 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7662 } else if (model == TLSModel::InitialExec) {
7664 OperandFlags = X86II::MO_GOTTPOFF;
7665 WrapperKind = X86ISD::WrapperRIP;
7667 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7670 llvm_unreachable("Unexpected model");
7673 // emit "addl x@ntpoff,%eax" (local exec)
7674 // or "addl x@indntpoff,%eax" (initial exec)
7675 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7676 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7677 GA->getValueType(0),
7678 GA->getOffset(), OperandFlags);
7679 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7681 if (model == TLSModel::InitialExec) {
7682 if (isPIC && !is64Bit) {
7683 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7684 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7688 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7689 MachinePointerInfo::getGOT(), false, false, false,
7693 // The address of the thread local variable is the add of the thread
7694 // pointer with the offset of the variable.
7695 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7699 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7701 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7702 const GlobalValue *GV = GA->getGlobal();
7704 if (Subtarget->isTargetELF()) {
7705 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7708 case TLSModel::GeneralDynamic:
7709 if (Subtarget->is64Bit())
7710 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7711 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7712 case TLSModel::LocalDynamic:
7713 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7714 Subtarget->is64Bit());
7715 case TLSModel::InitialExec:
7716 case TLSModel::LocalExec:
7717 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7718 Subtarget->is64Bit(),
7719 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7721 llvm_unreachable("Unknown TLS model.");
7724 if (Subtarget->isTargetDarwin()) {
7725 // Darwin only has one model of TLS. Lower to that.
7726 unsigned char OpFlag = 0;
7727 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7728 X86ISD::WrapperRIP : X86ISD::Wrapper;
7730 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7732 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7733 !Subtarget->is64Bit();
7735 OpFlag = X86II::MO_TLVP_PIC_BASE;
7737 OpFlag = X86II::MO_TLVP;
7738 DebugLoc DL = Op.getDebugLoc();
7739 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7740 GA->getValueType(0),
7741 GA->getOffset(), OpFlag);
7742 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7744 // With PIC32, the address is actually $g + Offset.
7746 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7747 DAG.getNode(X86ISD::GlobalBaseReg,
7748 DebugLoc(), getPointerTy()),
7751 // Lowering the machine isd will make sure everything is in the right
7753 SDValue Chain = DAG.getEntryNode();
7754 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7755 SDValue Args[] = { Chain, Offset };
7756 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7758 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7759 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7760 MFI->setAdjustsStack(true);
7762 // And our return value (tls address) is in the standard call return value
7764 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7765 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7769 if (Subtarget->isTargetWindows()) {
7770 // Just use the implicit TLS architecture
7771 // Need to generate someting similar to:
7772 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7774 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7775 // mov rcx, qword [rdx+rcx*8]
7776 // mov eax, .tls$:tlsvar
7777 // [rax+rcx] contains the address
7778 // Windows 64bit: gs:0x58
7779 // Windows 32bit: fs:__tls_array
7781 // If GV is an alias then use the aliasee for determining
7782 // thread-localness.
7783 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7784 GV = GA->resolveAliasedGlobal(false);
7785 DebugLoc dl = GA->getDebugLoc();
7786 SDValue Chain = DAG.getEntryNode();
7788 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7789 // %gs:0x58 (64-bit).
7790 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7791 ? Type::getInt8PtrTy(*DAG.getContext(),
7793 : Type::getInt32PtrTy(*DAG.getContext(),
7796 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7797 Subtarget->is64Bit()
7798 ? DAG.getIntPtrConstant(0x58)
7799 : DAG.getExternalSymbol("_tls_array",
7801 MachinePointerInfo(Ptr),
7802 false, false, false, 0);
7804 // Load the _tls_index variable
7805 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7806 if (Subtarget->is64Bit())
7807 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7808 IDX, MachinePointerInfo(), MVT::i32,
7811 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7812 false, false, false, 0);
7814 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7816 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7818 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7819 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7820 false, false, false, 0);
7822 // Get the offset of start of .tls section
7823 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7824 GA->getValueType(0),
7825 GA->getOffset(), X86II::MO_SECREL);
7826 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7828 // The address of the thread local variable is the add of the thread
7829 // pointer with the offset of the variable.
7830 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7833 llvm_unreachable("TLS not implemented for this target.");
7837 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7838 /// and take a 2 x i32 value to shift plus a shift amount.
7839 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7840 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7841 EVT VT = Op.getValueType();
7842 unsigned VTBits = VT.getSizeInBits();
7843 DebugLoc dl = Op.getDebugLoc();
7844 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7845 SDValue ShOpLo = Op.getOperand(0);
7846 SDValue ShOpHi = Op.getOperand(1);
7847 SDValue ShAmt = Op.getOperand(2);
7848 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7849 DAG.getConstant(VTBits - 1, MVT::i8))
7850 : DAG.getConstant(0, VT);
7853 if (Op.getOpcode() == ISD::SHL_PARTS) {
7854 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7855 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7857 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7858 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7861 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7862 DAG.getConstant(VTBits, MVT::i8));
7863 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7864 AndNode, DAG.getConstant(0, MVT::i8));
7867 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7868 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7869 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7871 if (Op.getOpcode() == ISD::SHL_PARTS) {
7872 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7873 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7875 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7876 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7879 SDValue Ops[2] = { Lo, Hi };
7880 return DAG.getMergeValues(Ops, 2, dl);
7883 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7884 SelectionDAG &DAG) const {
7885 EVT SrcVT = Op.getOperand(0).getValueType();
7887 if (SrcVT.isVector())
7890 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7891 "Unknown SINT_TO_FP to lower!");
7893 // These are really Legal; return the operand so the caller accepts it as
7895 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7897 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7898 Subtarget->is64Bit()) {
7902 DebugLoc dl = Op.getDebugLoc();
7903 unsigned Size = SrcVT.getSizeInBits()/8;
7904 MachineFunction &MF = DAG.getMachineFunction();
7905 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7906 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7907 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7909 MachinePointerInfo::getFixedStack(SSFI),
7911 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7914 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7916 SelectionDAG &DAG) const {
7918 DebugLoc DL = Op.getDebugLoc();
7920 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7922 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7924 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7926 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7928 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7929 MachineMemOperand *MMO;
7931 int SSFI = FI->getIndex();
7933 DAG.getMachineFunction()
7934 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7935 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7937 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7938 StackSlot = StackSlot.getOperand(1);
7940 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7941 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7943 Tys, Ops, array_lengthof(Ops),
7947 Chain = Result.getValue(1);
7948 SDValue InFlag = Result.getValue(2);
7950 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7951 // shouldn't be necessary except that RFP cannot be live across
7952 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7953 MachineFunction &MF = DAG.getMachineFunction();
7954 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7955 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7956 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7957 Tys = DAG.getVTList(MVT::Other);
7959 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7961 MachineMemOperand *MMO =
7962 DAG.getMachineFunction()
7963 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7964 MachineMemOperand::MOStore, SSFISize, SSFISize);
7966 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7967 Ops, array_lengthof(Ops),
7968 Op.getValueType(), MMO);
7969 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7970 MachinePointerInfo::getFixedStack(SSFI),
7971 false, false, false, 0);
7977 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7978 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7979 SelectionDAG &DAG) const {
7980 // This algorithm is not obvious. Here it is what we're trying to output:
7983 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7984 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7988 pshufd $0x4e, %xmm0, %xmm1
7993 DebugLoc dl = Op.getDebugLoc();
7994 LLVMContext *Context = DAG.getContext();
7996 // Build some magic constants.
7997 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7998 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7999 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8001 SmallVector<Constant*,2> CV1;
8003 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8005 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8006 Constant *C1 = ConstantVector::get(CV1);
8007 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8009 // Load the 64-bit value into an XMM register.
8010 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8012 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8013 MachinePointerInfo::getConstantPool(),
8014 false, false, false, 16);
8015 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8016 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8019 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8020 MachinePointerInfo::getConstantPool(),
8021 false, false, false, 16);
8022 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8023 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8026 if (Subtarget->hasSSE3()) {
8027 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8028 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8030 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8031 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8033 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8034 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8038 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8039 DAG.getIntPtrConstant(0));
8042 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8043 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8044 SelectionDAG &DAG) const {
8045 DebugLoc dl = Op.getDebugLoc();
8046 // FP constant to bias correct the final result.
8047 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8050 // Load the 32-bit value into an XMM register.
8051 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8054 // Zero out the upper parts of the register.
8055 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8057 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8058 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8059 DAG.getIntPtrConstant(0));
8061 // Or the load with the bias.
8062 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8063 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8064 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8066 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8067 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8068 MVT::v2f64, Bias)));
8069 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8070 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8071 DAG.getIntPtrConstant(0));
8073 // Subtract the bias.
8074 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8076 // Handle final rounding.
8077 EVT DestVT = Op.getValueType();
8079 if (DestVT.bitsLT(MVT::f64))
8080 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8081 DAG.getIntPtrConstant(0));
8082 if (DestVT.bitsGT(MVT::f64))
8083 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8085 // Handle final rounding.
8089 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8090 SelectionDAG &DAG) const {
8091 SDValue N0 = Op.getOperand(0);
8092 DebugLoc dl = Op.getDebugLoc();
8094 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8095 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8096 // the optimization here.
8097 if (DAG.SignBitIsZero(N0))
8098 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8100 EVT SrcVT = N0.getValueType();
8101 EVT DstVT = Op.getValueType();
8102 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8103 return LowerUINT_TO_FP_i64(Op, DAG);
8104 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8105 return LowerUINT_TO_FP_i32(Op, DAG);
8106 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8109 // Make a 64-bit buffer, and use it to build an FILD.
8110 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8111 if (SrcVT == MVT::i32) {
8112 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8113 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8114 getPointerTy(), StackSlot, WordOff);
8115 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8116 StackSlot, MachinePointerInfo(),
8118 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8119 OffsetSlot, MachinePointerInfo(),
8121 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8125 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8126 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8127 StackSlot, MachinePointerInfo(),
8129 // For i64 source, we need to add the appropriate power of 2 if the input
8130 // was negative. This is the same as the optimization in
8131 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8132 // we must be careful to do the computation in x87 extended precision, not
8133 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8134 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8135 MachineMemOperand *MMO =
8136 DAG.getMachineFunction()
8137 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8138 MachineMemOperand::MOLoad, 8, 8);
8140 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8141 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8142 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8145 APInt FF(32, 0x5F800000ULL);
8147 // Check whether the sign bit is set.
8148 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8149 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8152 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8153 SDValue FudgePtr = DAG.getConstantPool(
8154 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8157 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8158 SDValue Zero = DAG.getIntPtrConstant(0);
8159 SDValue Four = DAG.getIntPtrConstant(4);
8160 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8162 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8164 // Load the value out, extending it from f32 to f80.
8165 // FIXME: Avoid the extend by constructing the right constant pool?
8166 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8167 FudgePtr, MachinePointerInfo::getConstantPool(),
8168 MVT::f32, false, false, 4);
8169 // Extend everything to 80 bits to force it to be done on x87.
8170 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8171 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8174 std::pair<SDValue,SDValue> X86TargetLowering::
8175 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8176 DebugLoc DL = Op.getDebugLoc();
8178 EVT DstTy = Op.getValueType();
8180 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8181 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8185 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8186 DstTy.getSimpleVT() >= MVT::i16 &&
8187 "Unknown FP_TO_INT to lower!");
8189 // These are really Legal.
8190 if (DstTy == MVT::i32 &&
8191 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8192 return std::make_pair(SDValue(), SDValue());
8193 if (Subtarget->is64Bit() &&
8194 DstTy == MVT::i64 &&
8195 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8196 return std::make_pair(SDValue(), SDValue());
8198 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8199 // stack slot, or into the FTOL runtime function.
8200 MachineFunction &MF = DAG.getMachineFunction();
8201 unsigned MemSize = DstTy.getSizeInBits()/8;
8202 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8203 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8206 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8207 Opc = X86ISD::WIN_FTOL;
8209 switch (DstTy.getSimpleVT().SimpleTy) {
8210 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8211 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8212 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8213 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8216 SDValue Chain = DAG.getEntryNode();
8217 SDValue Value = Op.getOperand(0);
8218 EVT TheVT = Op.getOperand(0).getValueType();
8219 // FIXME This causes a redundant load/store if the SSE-class value is already
8220 // in memory, such as if it is on the callstack.
8221 if (isScalarFPTypeInSSEReg(TheVT)) {
8222 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8223 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8224 MachinePointerInfo::getFixedStack(SSFI),
8226 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8228 Chain, StackSlot, DAG.getValueType(TheVT)
8231 MachineMemOperand *MMO =
8232 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8233 MachineMemOperand::MOLoad, MemSize, MemSize);
8234 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8236 Chain = Value.getValue(1);
8237 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8238 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8241 MachineMemOperand *MMO =
8242 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8243 MachineMemOperand::MOStore, MemSize, MemSize);
8245 if (Opc != X86ISD::WIN_FTOL) {
8246 // Build the FP_TO_INT*_IN_MEM
8247 SDValue Ops[] = { Chain, Value, StackSlot };
8248 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8249 Ops, 3, DstTy, MMO);
8250 return std::make_pair(FIST, StackSlot);
8252 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8253 DAG.getVTList(MVT::Other, MVT::Glue),
8255 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8256 MVT::i32, ftol.getValue(1));
8257 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8258 MVT::i32, eax.getValue(2));
8259 SDValue Ops[] = { eax, edx };
8260 SDValue pair = IsReplace
8261 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8262 : DAG.getMergeValues(Ops, 2, DL);
8263 return std::make_pair(pair, SDValue());
8267 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8268 DebugLoc DL = Op.getDebugLoc();
8269 EVT VT = Op.getValueType();
8270 EVT SVT = Op.getOperand(0).getValueType();
8272 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8273 VT.getVectorNumElements() != SVT.getVectorNumElements())
8276 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8278 unsigned NumElems = VT.getVectorNumElements();
8279 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8282 SDValue In = Op.getOperand(0);
8283 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8284 // Prepare truncation shuffle mask
8285 for (unsigned i = 0; i != NumElems; ++i)
8287 SDValue V = DAG.getVectorShuffle(NVT, DL,
8288 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8289 DAG.getUNDEF(NVT), &MaskVec[0]);
8290 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8291 DAG.getIntPtrConstant(0));
8294 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8295 SelectionDAG &DAG) const {
8296 if (Op.getValueType().isVector()) {
8297 if (Op.getValueType() == MVT::v8i16)
8298 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8299 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8300 MVT::v8i32, Op.getOperand(0)));
8304 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8305 /*IsSigned=*/ true, /*IsReplace=*/ false);
8306 SDValue FIST = Vals.first, StackSlot = Vals.second;
8307 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8308 if (FIST.getNode() == 0) return Op;
8310 if (StackSlot.getNode())
8312 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8313 FIST, StackSlot, MachinePointerInfo(),
8314 false, false, false, 0);
8316 // The node is the result.
8320 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8321 SelectionDAG &DAG) const {
8322 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8323 /*IsSigned=*/ false, /*IsReplace=*/ false);
8324 SDValue FIST = Vals.first, StackSlot = Vals.second;
8325 assert(FIST.getNode() && "Unexpected failure");
8327 if (StackSlot.getNode())
8329 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8330 FIST, StackSlot, MachinePointerInfo(),
8331 false, false, false, 0);
8333 // The node is the result.
8337 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8338 SelectionDAG &DAG) const {
8339 DebugLoc DL = Op.getDebugLoc();
8340 EVT VT = Op.getValueType();
8341 SDValue In = Op.getOperand(0);
8342 EVT SVT = In.getValueType();
8344 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8346 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8347 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8348 In, DAG.getUNDEF(SVT)));
8351 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8352 LLVMContext *Context = DAG.getContext();
8353 DebugLoc dl = Op.getDebugLoc();
8354 EVT VT = Op.getValueType();
8356 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8357 if (VT.isVector()) {
8358 EltVT = VT.getVectorElementType();
8359 NumElts = VT.getVectorNumElements();
8362 if (EltVT == MVT::f64)
8363 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8365 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8366 C = ConstantVector::getSplat(NumElts, C);
8367 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8368 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8369 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8370 MachinePointerInfo::getConstantPool(),
8371 false, false, false, Alignment);
8372 if (VT.isVector()) {
8373 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8374 return DAG.getNode(ISD::BITCAST, dl, VT,
8375 DAG.getNode(ISD::AND, dl, ANDVT,
8376 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8378 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8380 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8383 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8384 LLVMContext *Context = DAG.getContext();
8385 DebugLoc dl = Op.getDebugLoc();
8386 EVT VT = Op.getValueType();
8388 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8389 if (VT.isVector()) {
8390 EltVT = VT.getVectorElementType();
8391 NumElts = VT.getVectorNumElements();
8394 if (EltVT == MVT::f64)
8395 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8397 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8398 C = ConstantVector::getSplat(NumElts, C);
8399 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8400 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8401 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8402 MachinePointerInfo::getConstantPool(),
8403 false, false, false, Alignment);
8404 if (VT.isVector()) {
8405 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8406 return DAG.getNode(ISD::BITCAST, dl, VT,
8407 DAG.getNode(ISD::XOR, dl, XORVT,
8408 DAG.getNode(ISD::BITCAST, dl, XORVT,
8410 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8413 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8416 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8417 LLVMContext *Context = DAG.getContext();
8418 SDValue Op0 = Op.getOperand(0);
8419 SDValue Op1 = Op.getOperand(1);
8420 DebugLoc dl = Op.getDebugLoc();
8421 EVT VT = Op.getValueType();
8422 EVT SrcVT = Op1.getValueType();
8424 // If second operand is smaller, extend it first.
8425 if (SrcVT.bitsLT(VT)) {
8426 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8429 // And if it is bigger, shrink it first.
8430 if (SrcVT.bitsGT(VT)) {
8431 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8435 // At this point the operands and the result should have the same
8436 // type, and that won't be f80 since that is not custom lowered.
8438 // First get the sign bit of second operand.
8439 SmallVector<Constant*,4> CV;
8440 if (SrcVT == MVT::f64) {
8441 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8442 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8444 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8445 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8446 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8447 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8449 Constant *C = ConstantVector::get(CV);
8450 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8451 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8452 MachinePointerInfo::getConstantPool(),
8453 false, false, false, 16);
8454 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8456 // Shift sign bit right or left if the two operands have different types.
8457 if (SrcVT.bitsGT(VT)) {
8458 // Op0 is MVT::f32, Op1 is MVT::f64.
8459 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8460 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8461 DAG.getConstant(32, MVT::i32));
8462 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8463 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8464 DAG.getIntPtrConstant(0));
8467 // Clear first operand sign bit.
8469 if (VT == MVT::f64) {
8470 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8471 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8473 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8474 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8475 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8476 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8478 C = ConstantVector::get(CV);
8479 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8480 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8481 MachinePointerInfo::getConstantPool(),
8482 false, false, false, 16);
8483 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8485 // Or the value with the sign bit.
8486 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8489 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8490 SDValue N0 = Op.getOperand(0);
8491 DebugLoc dl = Op.getDebugLoc();
8492 EVT VT = Op.getValueType();
8494 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8495 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8496 DAG.getConstant(1, VT));
8497 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8500 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8502 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8503 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8505 if (!Subtarget->hasSSE41())
8508 if (!Op->hasOneUse())
8511 SDNode *N = Op.getNode();
8512 DebugLoc DL = N->getDebugLoc();
8514 SmallVector<SDValue, 8> Opnds;
8515 DenseMap<SDValue, unsigned> VecInMap;
8516 EVT VT = MVT::Other;
8518 // Recognize a special case where a vector is casted into wide integer to
8520 Opnds.push_back(N->getOperand(0));
8521 Opnds.push_back(N->getOperand(1));
8523 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8524 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8525 // BFS traverse all OR'd operands.
8526 if (I->getOpcode() == ISD::OR) {
8527 Opnds.push_back(I->getOperand(0));
8528 Opnds.push_back(I->getOperand(1));
8529 // Re-evaluate the number of nodes to be traversed.
8530 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8534 // Quit if a non-EXTRACT_VECTOR_ELT
8535 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8538 // Quit if without a constant index.
8539 SDValue Idx = I->getOperand(1);
8540 if (!isa<ConstantSDNode>(Idx))
8543 SDValue ExtractedFromVec = I->getOperand(0);
8544 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8545 if (M == VecInMap.end()) {
8546 VT = ExtractedFromVec.getValueType();
8547 // Quit if not 128/256-bit vector.
8548 if (!VT.is128BitVector() && !VT.is256BitVector())
8550 // Quit if not the same type.
8551 if (VecInMap.begin() != VecInMap.end() &&
8552 VT != VecInMap.begin()->first.getValueType())
8554 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8556 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8559 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8560 "Not extracted from 128-/256-bit vector.");
8562 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8563 SmallVector<SDValue, 8> VecIns;
8565 for (DenseMap<SDValue, unsigned>::const_iterator
8566 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8567 // Quit if not all elements are used.
8568 if (I->second != FullMask)
8570 VecIns.push_back(I->first);
8573 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8575 // Cast all vectors into TestVT for PTEST.
8576 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8577 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8579 // If more than one full vectors are evaluated, OR them first before PTEST.
8580 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8581 // Each iteration will OR 2 nodes and append the result until there is only
8582 // 1 node left, i.e. the final OR'd value of all vectors.
8583 SDValue LHS = VecIns[Slot];
8584 SDValue RHS = VecIns[Slot + 1];
8585 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8588 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8589 VecIns.back(), VecIns.back());
8592 /// Emit nodes that will be selected as "test Op0,Op0", or something
8594 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8595 SelectionDAG &DAG) const {
8596 DebugLoc dl = Op.getDebugLoc();
8598 // CF and OF aren't always set the way we want. Determine which
8599 // of these we need.
8600 bool NeedCF = false;
8601 bool NeedOF = false;
8604 case X86::COND_A: case X86::COND_AE:
8605 case X86::COND_B: case X86::COND_BE:
8608 case X86::COND_G: case X86::COND_GE:
8609 case X86::COND_L: case X86::COND_LE:
8610 case X86::COND_O: case X86::COND_NO:
8615 // See if we can use the EFLAGS value from the operand instead of
8616 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8617 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8618 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8619 // Emit a CMP with 0, which is the TEST pattern.
8620 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8621 DAG.getConstant(0, Op.getValueType()));
8623 unsigned Opcode = 0;
8624 unsigned NumOperands = 0;
8626 // Truncate operations may prevent the merge of the SETCC instruction
8627 // and the arithmetic intruction before it. Attempt to truncate the operands
8628 // of the arithmetic instruction and use a reduced bit-width instruction.
8629 bool NeedTruncation = false;
8630 SDValue ArithOp = Op;
8631 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8632 SDValue Arith = Op->getOperand(0);
8633 // Both the trunc and the arithmetic op need to have one user each.
8634 if (Arith->hasOneUse())
8635 switch (Arith.getOpcode()) {
8642 NeedTruncation = true;
8648 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8649 // which may be the result of a CAST. We use the variable 'Op', which is the
8650 // non-casted variable when we check for possible users.
8651 switch (ArithOp.getOpcode()) {
8653 // Due to an isel shortcoming, be conservative if this add is likely to be
8654 // selected as part of a load-modify-store instruction. When the root node
8655 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8656 // uses of other nodes in the match, such as the ADD in this case. This
8657 // leads to the ADD being left around and reselected, with the result being
8658 // two adds in the output. Alas, even if none our users are stores, that
8659 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8660 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8661 // climbing the DAG back to the root, and it doesn't seem to be worth the
8663 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8664 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8665 if (UI->getOpcode() != ISD::CopyToReg &&
8666 UI->getOpcode() != ISD::SETCC &&
8667 UI->getOpcode() != ISD::STORE)
8670 if (ConstantSDNode *C =
8671 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8672 // An add of one will be selected as an INC.
8673 if (C->getAPIntValue() == 1) {
8674 Opcode = X86ISD::INC;
8679 // An add of negative one (subtract of one) will be selected as a DEC.
8680 if (C->getAPIntValue().isAllOnesValue()) {
8681 Opcode = X86ISD::DEC;
8687 // Otherwise use a regular EFLAGS-setting add.
8688 Opcode = X86ISD::ADD;
8692 // If the primary and result isn't used, don't bother using X86ISD::AND,
8693 // because a TEST instruction will be better.
8694 bool NonFlagUse = false;
8695 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8696 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8698 unsigned UOpNo = UI.getOperandNo();
8699 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8700 // Look pass truncate.
8701 UOpNo = User->use_begin().getOperandNo();
8702 User = *User->use_begin();
8705 if (User->getOpcode() != ISD::BRCOND &&
8706 User->getOpcode() != ISD::SETCC &&
8707 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8720 // Due to the ISEL shortcoming noted above, be conservative if this op is
8721 // likely to be selected as part of a load-modify-store instruction.
8722 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8723 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8724 if (UI->getOpcode() == ISD::STORE)
8727 // Otherwise use a regular EFLAGS-setting instruction.
8728 switch (ArithOp.getOpcode()) {
8729 default: llvm_unreachable("unexpected operator!");
8730 case ISD::SUB: Opcode = X86ISD::SUB; break;
8731 case ISD::XOR: Opcode = X86ISD::XOR; break;
8732 case ISD::AND: Opcode = X86ISD::AND; break;
8734 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8735 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8736 if (EFLAGS.getNode())
8739 Opcode = X86ISD::OR;
8753 return SDValue(Op.getNode(), 1);
8759 // If we found that truncation is beneficial, perform the truncation and
8761 if (NeedTruncation) {
8762 EVT VT = Op.getValueType();
8763 SDValue WideVal = Op->getOperand(0);
8764 EVT WideVT = WideVal.getValueType();
8765 unsigned ConvertedOp = 0;
8766 // Use a target machine opcode to prevent further DAGCombine
8767 // optimizations that may separate the arithmetic operations
8768 // from the setcc node.
8769 switch (WideVal.getOpcode()) {
8771 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8772 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8773 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8774 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8775 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8779 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8780 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8781 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8782 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8783 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8789 // Emit a CMP with 0, which is the TEST pattern.
8790 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8791 DAG.getConstant(0, Op.getValueType()));
8793 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8794 SmallVector<SDValue, 4> Ops;
8795 for (unsigned i = 0; i != NumOperands; ++i)
8796 Ops.push_back(Op.getOperand(i));
8798 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8799 DAG.ReplaceAllUsesWith(Op, New);
8800 return SDValue(New.getNode(), 1);
8803 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8805 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8806 SelectionDAG &DAG) const {
8807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8808 if (C->getAPIntValue() == 0)
8809 return EmitTest(Op0, X86CC, DAG);
8811 DebugLoc dl = Op0.getDebugLoc();
8812 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8813 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8814 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8815 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8816 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8818 return SDValue(Sub.getNode(), 1);
8820 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8823 /// Convert a comparison if required by the subtarget.
8824 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8825 SelectionDAG &DAG) const {
8826 // If the subtarget does not support the FUCOMI instruction, floating-point
8827 // comparisons have to be converted.
8828 if (Subtarget->hasCMov() ||
8829 Cmp.getOpcode() != X86ISD::CMP ||
8830 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8831 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8834 // The instruction selector will select an FUCOM instruction instead of
8835 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8836 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8837 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8838 DebugLoc dl = Cmp.getDebugLoc();
8839 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8840 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8841 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8842 DAG.getConstant(8, MVT::i8));
8843 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8844 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8847 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8848 /// if it's possible.
8849 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8850 DebugLoc dl, SelectionDAG &DAG) const {
8851 SDValue Op0 = And.getOperand(0);
8852 SDValue Op1 = And.getOperand(1);
8853 if (Op0.getOpcode() == ISD::TRUNCATE)
8854 Op0 = Op0.getOperand(0);
8855 if (Op1.getOpcode() == ISD::TRUNCATE)
8856 Op1 = Op1.getOperand(0);
8859 if (Op1.getOpcode() == ISD::SHL)
8860 std::swap(Op0, Op1);
8861 if (Op0.getOpcode() == ISD::SHL) {
8862 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8863 if (And00C->getZExtValue() == 1) {
8864 // If we looked past a truncate, check that it's only truncating away
8866 unsigned BitWidth = Op0.getValueSizeInBits();
8867 unsigned AndBitWidth = And.getValueSizeInBits();
8868 if (BitWidth > AndBitWidth) {
8870 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8871 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8875 RHS = Op0.getOperand(1);
8877 } else if (Op1.getOpcode() == ISD::Constant) {
8878 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8879 uint64_t AndRHSVal = AndRHS->getZExtValue();
8880 SDValue AndLHS = Op0;
8882 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8883 LHS = AndLHS.getOperand(0);
8884 RHS = AndLHS.getOperand(1);
8887 // Use BT if the immediate can't be encoded in a TEST instruction.
8888 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8890 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8894 if (LHS.getNode()) {
8895 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8896 // instruction. Since the shift amount is in-range-or-undefined, we know
8897 // that doing a bittest on the i32 value is ok. We extend to i32 because
8898 // the encoding for the i16 version is larger than the i32 version.
8899 // Also promote i16 to i32 for performance / code size reason.
8900 if (LHS.getValueType() == MVT::i8 ||
8901 LHS.getValueType() == MVT::i16)
8902 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8904 // If the operand types disagree, extend the shift amount to match. Since
8905 // BT ignores high bits (like shifts) we can use anyextend.
8906 if (LHS.getValueType() != RHS.getValueType())
8907 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8909 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8910 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8911 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8912 DAG.getConstant(Cond, MVT::i8), BT);
8918 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8920 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8922 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8923 SDValue Op0 = Op.getOperand(0);
8924 SDValue Op1 = Op.getOperand(1);
8925 DebugLoc dl = Op.getDebugLoc();
8926 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8928 // Optimize to BT if possible.
8929 // Lower (X & (1 << N)) == 0 to BT(X, N).
8930 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8931 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8932 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8933 Op1.getOpcode() == ISD::Constant &&
8934 cast<ConstantSDNode>(Op1)->isNullValue() &&
8935 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8936 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8937 if (NewSetCC.getNode())
8941 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8943 if (Op1.getOpcode() == ISD::Constant &&
8944 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8945 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8946 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8948 // If the input is a setcc, then reuse the input setcc or use a new one with
8949 // the inverted condition.
8950 if (Op0.getOpcode() == X86ISD::SETCC) {
8951 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8952 bool Invert = (CC == ISD::SETNE) ^
8953 cast<ConstantSDNode>(Op1)->isNullValue();
8954 if (!Invert) return Op0;
8956 CCode = X86::GetOppositeBranchCondition(CCode);
8957 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8958 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8962 bool isFP = Op1.getValueType().isFloatingPoint();
8963 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8964 if (X86CC == X86::COND_INVALID)
8967 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8968 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8969 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8970 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8973 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8974 // ones, and then concatenate the result back.
8975 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8976 EVT VT = Op.getValueType();
8978 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8979 "Unsupported value type for operation");
8981 unsigned NumElems = VT.getVectorNumElements();
8982 DebugLoc dl = Op.getDebugLoc();
8983 SDValue CC = Op.getOperand(2);
8985 // Extract the LHS vectors
8986 SDValue LHS = Op.getOperand(0);
8987 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8988 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8990 // Extract the RHS vectors
8991 SDValue RHS = Op.getOperand(1);
8992 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8993 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8995 // Issue the operation on the smaller types and concatenate the result back
8996 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8997 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8998 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8999 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9000 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9004 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9006 SDValue Op0 = Op.getOperand(0);
9007 SDValue Op1 = Op.getOperand(1);
9008 SDValue CC = Op.getOperand(2);
9009 EVT VT = Op.getValueType();
9010 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9011 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9012 DebugLoc dl = Op.getDebugLoc();
9016 EVT EltVT = Op0.getValueType().getVectorElementType();
9017 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9023 // SSE Condition code mapping:
9032 switch (SetCCOpcode) {
9033 default: llvm_unreachable("Unexpected SETCC condition");
9035 case ISD::SETEQ: SSECC = 0; break;
9037 case ISD::SETGT: Swap = true; // Fallthrough
9039 case ISD::SETOLT: SSECC = 1; break;
9041 case ISD::SETGE: Swap = true; // Fallthrough
9043 case ISD::SETOLE: SSECC = 2; break;
9044 case ISD::SETUO: SSECC = 3; break;
9046 case ISD::SETNE: SSECC = 4; break;
9047 case ISD::SETULE: Swap = true; // Fallthrough
9048 case ISD::SETUGE: SSECC = 5; break;
9049 case ISD::SETULT: Swap = true; // Fallthrough
9050 case ISD::SETUGT: SSECC = 6; break;
9051 case ISD::SETO: SSECC = 7; break;
9053 case ISD::SETONE: SSECC = 8; break;
9056 std::swap(Op0, Op1);
9058 // In the two special cases we can't handle, emit two comparisons.
9061 unsigned CombineOpc;
9062 if (SetCCOpcode == ISD::SETUEQ) {
9063 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9065 assert(SetCCOpcode == ISD::SETONE);
9066 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9069 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9070 DAG.getConstant(CC0, MVT::i8));
9071 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9072 DAG.getConstant(CC1, MVT::i8));
9073 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9075 // Handle all other FP comparisons here.
9076 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9077 DAG.getConstant(SSECC, MVT::i8));
9080 // Break 256-bit integer vector compare into smaller ones.
9081 if (VT.is256BitVector() && !Subtarget->hasAVX2())
9082 return Lower256IntVSETCC(Op, DAG);
9084 // We are handling one of the integer comparisons here. Since SSE only has
9085 // GT and EQ comparisons for integer, swapping operands and multiple
9086 // operations may be required for some comparisons.
9088 bool Swap = false, Invert = false, FlipSigns = false;
9090 switch (SetCCOpcode) {
9091 default: llvm_unreachable("Unexpected SETCC condition");
9092 case ISD::SETNE: Invert = true;
9093 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9094 case ISD::SETLT: Swap = true;
9095 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9096 case ISD::SETGE: Swap = true;
9097 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9098 case ISD::SETULT: Swap = true;
9099 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9100 case ISD::SETUGE: Swap = true;
9101 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9104 std::swap(Op0, Op1);
9106 // Check that the operation in question is available (most are plain SSE2,
9107 // but PCMPGTQ and PCMPEQQ have different requirements).
9108 if (VT == MVT::v2i64) {
9109 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9111 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9115 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9116 // bits of the inputs before performing those operations.
9118 EVT EltVT = VT.getVectorElementType();
9119 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9121 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9122 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9124 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9125 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9128 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9130 // If the logical-not of the result is required, perform that now.
9132 Result = DAG.getNOT(dl, Result, VT);
9137 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9138 static bool isX86LogicalCmp(SDValue Op) {
9139 unsigned Opc = Op.getNode()->getOpcode();
9140 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9141 Opc == X86ISD::SAHF)
9143 if (Op.getResNo() == 1 &&
9144 (Opc == X86ISD::ADD ||
9145 Opc == X86ISD::SUB ||
9146 Opc == X86ISD::ADC ||
9147 Opc == X86ISD::SBB ||
9148 Opc == X86ISD::SMUL ||
9149 Opc == X86ISD::UMUL ||
9150 Opc == X86ISD::INC ||
9151 Opc == X86ISD::DEC ||
9152 Opc == X86ISD::OR ||
9153 Opc == X86ISD::XOR ||
9154 Opc == X86ISD::AND))
9157 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9163 static bool isZero(SDValue V) {
9164 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9165 return C && C->isNullValue();
9168 static bool isAllOnes(SDValue V) {
9169 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9170 return C && C->isAllOnesValue();
9173 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9174 if (V.getOpcode() != ISD::TRUNCATE)
9177 SDValue VOp0 = V.getOperand(0);
9178 unsigned InBits = VOp0.getValueSizeInBits();
9179 unsigned Bits = V.getValueSizeInBits();
9180 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9183 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9184 bool addTest = true;
9185 SDValue Cond = Op.getOperand(0);
9186 SDValue Op1 = Op.getOperand(1);
9187 SDValue Op2 = Op.getOperand(2);
9188 DebugLoc DL = Op.getDebugLoc();
9191 if (Cond.getOpcode() == ISD::SETCC) {
9192 SDValue NewCond = LowerSETCC(Cond, DAG);
9193 if (NewCond.getNode())
9197 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9198 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9199 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9200 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9201 if (Cond.getOpcode() == X86ISD::SETCC &&
9202 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9203 isZero(Cond.getOperand(1).getOperand(1))) {
9204 SDValue Cmp = Cond.getOperand(1);
9206 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9208 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9209 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9210 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9212 SDValue CmpOp0 = Cmp.getOperand(0);
9213 // Apply further optimizations for special cases
9214 // (select (x != 0), -1, 0) -> neg & sbb
9215 // (select (x == 0), 0, -1) -> neg & sbb
9216 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9217 if (YC->isNullValue() &&
9218 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9219 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9220 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9221 DAG.getConstant(0, CmpOp0.getValueType()),
9223 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9224 DAG.getConstant(X86::COND_B, MVT::i8),
9225 SDValue(Neg.getNode(), 1));
9229 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9230 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9231 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9233 SDValue Res = // Res = 0 or -1.
9234 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9235 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9237 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9238 Res = DAG.getNOT(DL, Res, Res.getValueType());
9240 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9241 if (N2C == 0 || !N2C->isNullValue())
9242 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9247 // Look past (and (setcc_carry (cmp ...)), 1).
9248 if (Cond.getOpcode() == ISD::AND &&
9249 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9250 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9251 if (C && C->getAPIntValue() == 1)
9252 Cond = Cond.getOperand(0);
9255 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9256 // setting operand in place of the X86ISD::SETCC.
9257 unsigned CondOpcode = Cond.getOpcode();
9258 if (CondOpcode == X86ISD::SETCC ||
9259 CondOpcode == X86ISD::SETCC_CARRY) {
9260 CC = Cond.getOperand(0);
9262 SDValue Cmp = Cond.getOperand(1);
9263 unsigned Opc = Cmp.getOpcode();
9264 EVT VT = Op.getValueType();
9266 bool IllegalFPCMov = false;
9267 if (VT.isFloatingPoint() && !VT.isVector() &&
9268 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9269 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9271 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9272 Opc == X86ISD::BT) { // FIXME
9276 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9277 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9278 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9279 Cond.getOperand(0).getValueType() != MVT::i8)) {
9280 SDValue LHS = Cond.getOperand(0);
9281 SDValue RHS = Cond.getOperand(1);
9285 switch (CondOpcode) {
9286 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9287 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9288 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9289 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9290 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9291 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9292 default: llvm_unreachable("unexpected overflowing operator");
9294 if (CondOpcode == ISD::UMULO)
9295 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9298 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9300 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9302 if (CondOpcode == ISD::UMULO)
9303 Cond = X86Op.getValue(2);
9305 Cond = X86Op.getValue(1);
9307 CC = DAG.getConstant(X86Cond, MVT::i8);
9312 // Look pass the truncate if the high bits are known zero.
9313 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9314 Cond = Cond.getOperand(0);
9316 // We know the result of AND is compared against zero. Try to match
9318 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9319 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9320 if (NewSetCC.getNode()) {
9321 CC = NewSetCC.getOperand(0);
9322 Cond = NewSetCC.getOperand(1);
9329 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9330 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9333 // a < b ? -1 : 0 -> RES = ~setcc_carry
9334 // a < b ? 0 : -1 -> RES = setcc_carry
9335 // a >= b ? -1 : 0 -> RES = setcc_carry
9336 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9337 if (Cond.getOpcode() == X86ISD::SUB) {
9338 Cond = ConvertCmpIfNecessary(Cond, DAG);
9339 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9341 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9342 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9343 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9344 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9345 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9346 return DAG.getNOT(DL, Res, Res.getValueType());
9351 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9352 // widen the cmov and push the truncate through. This avoids introducing a new
9353 // branch during isel and doesn't add any extensions.
9354 if (Op.getValueType() == MVT::i8 &&
9355 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9356 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9357 if (T1.getValueType() == T2.getValueType() &&
9358 // Blacklist CopyFromReg to avoid partial register stalls.
9359 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9360 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9361 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9362 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9366 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9367 // condition is true.
9368 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9369 SDValue Ops[] = { Op2, Op1, CC, Cond };
9370 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9373 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9374 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9375 // from the AND / OR.
9376 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9377 Opc = Op.getOpcode();
9378 if (Opc != ISD::OR && Opc != ISD::AND)
9380 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9381 Op.getOperand(0).hasOneUse() &&
9382 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9383 Op.getOperand(1).hasOneUse());
9386 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9387 // 1 and that the SETCC node has a single use.
9388 static bool isXor1OfSetCC(SDValue Op) {
9389 if (Op.getOpcode() != ISD::XOR)
9391 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9392 if (N1C && N1C->getAPIntValue() == 1) {
9393 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9394 Op.getOperand(0).hasOneUse();
9399 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9400 bool addTest = true;
9401 SDValue Chain = Op.getOperand(0);
9402 SDValue Cond = Op.getOperand(1);
9403 SDValue Dest = Op.getOperand(2);
9404 DebugLoc dl = Op.getDebugLoc();
9406 bool Inverted = false;
9408 if (Cond.getOpcode() == ISD::SETCC) {
9409 // Check for setcc([su]{add,sub,mul}o == 0).
9410 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9411 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9412 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9413 Cond.getOperand(0).getResNo() == 1 &&
9414 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9415 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9416 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9417 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9418 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9419 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9421 Cond = Cond.getOperand(0);
9423 SDValue NewCond = LowerSETCC(Cond, DAG);
9424 if (NewCond.getNode())
9429 // FIXME: LowerXALUO doesn't handle these!!
9430 else if (Cond.getOpcode() == X86ISD::ADD ||
9431 Cond.getOpcode() == X86ISD::SUB ||
9432 Cond.getOpcode() == X86ISD::SMUL ||
9433 Cond.getOpcode() == X86ISD::UMUL)
9434 Cond = LowerXALUO(Cond, DAG);
9437 // Look pass (and (setcc_carry (cmp ...)), 1).
9438 if (Cond.getOpcode() == ISD::AND &&
9439 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9440 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9441 if (C && C->getAPIntValue() == 1)
9442 Cond = Cond.getOperand(0);
9445 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9446 // setting operand in place of the X86ISD::SETCC.
9447 unsigned CondOpcode = Cond.getOpcode();
9448 if (CondOpcode == X86ISD::SETCC ||
9449 CondOpcode == X86ISD::SETCC_CARRY) {
9450 CC = Cond.getOperand(0);
9452 SDValue Cmp = Cond.getOperand(1);
9453 unsigned Opc = Cmp.getOpcode();
9454 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9455 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9459 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9463 // These can only come from an arithmetic instruction with overflow,
9464 // e.g. SADDO, UADDO.
9465 Cond = Cond.getNode()->getOperand(1);
9471 CondOpcode = Cond.getOpcode();
9472 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9473 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9474 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9475 Cond.getOperand(0).getValueType() != MVT::i8)) {
9476 SDValue LHS = Cond.getOperand(0);
9477 SDValue RHS = Cond.getOperand(1);
9481 switch (CondOpcode) {
9482 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9483 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9484 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9485 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9486 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9487 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9488 default: llvm_unreachable("unexpected overflowing operator");
9491 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9492 if (CondOpcode == ISD::UMULO)
9493 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9496 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9498 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9500 if (CondOpcode == ISD::UMULO)
9501 Cond = X86Op.getValue(2);
9503 Cond = X86Op.getValue(1);
9505 CC = DAG.getConstant(X86Cond, MVT::i8);
9509 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9510 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9511 if (CondOpc == ISD::OR) {
9512 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9513 // two branches instead of an explicit OR instruction with a
9515 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9516 isX86LogicalCmp(Cmp)) {
9517 CC = Cond.getOperand(0).getOperand(0);
9518 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9519 Chain, Dest, CC, Cmp);
9520 CC = Cond.getOperand(1).getOperand(0);
9524 } else { // ISD::AND
9525 // Also, recognize the pattern generated by an FCMP_OEQ. 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 (Cmp == Cond.getOperand(1).getOperand(1) &&
9531 isX86LogicalCmp(Cmp) &&
9532 Op.getNode()->hasOneUse()) {
9533 X86::CondCode CCode =
9534 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9535 CCode = X86::GetOppositeBranchCondition(CCode);
9536 CC = DAG.getConstant(CCode, MVT::i8);
9537 SDNode *User = *Op.getNode()->use_begin();
9538 // Look for an unconditional branch following this conditional branch.
9539 // We need this because we need to reverse the successors in order
9540 // to implement FCMP_OEQ.
9541 if (User->getOpcode() == ISD::BR) {
9542 SDValue FalseBB = User->getOperand(1);
9544 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9545 assert(NewBR == User);
9549 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9550 Chain, Dest, CC, Cmp);
9551 X86::CondCode CCode =
9552 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9553 CCode = X86::GetOppositeBranchCondition(CCode);
9554 CC = DAG.getConstant(CCode, MVT::i8);
9560 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9561 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9562 // It should be transformed during dag combiner except when the condition
9563 // is set by a arithmetics with overflow node.
9564 X86::CondCode CCode =
9565 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9566 CCode = X86::GetOppositeBranchCondition(CCode);
9567 CC = DAG.getConstant(CCode, MVT::i8);
9568 Cond = Cond.getOperand(0).getOperand(1);
9570 } else if (Cond.getOpcode() == ISD::SETCC &&
9571 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9572 // For FCMP_OEQ, we can emit
9573 // two branches instead of an explicit AND instruction with a
9574 // separate test. However, we only do this if this block doesn't
9575 // have a fall-through edge, because this requires an explicit
9576 // jmp when the condition is false.
9577 if (Op.getNode()->hasOneUse()) {
9578 SDNode *User = *Op.getNode()->use_begin();
9579 // Look for an unconditional branch following this conditional branch.
9580 // We need this because we need to reverse the successors in order
9581 // to implement FCMP_OEQ.
9582 if (User->getOpcode() == ISD::BR) {
9583 SDValue FalseBB = User->getOperand(1);
9585 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9586 assert(NewBR == User);
9590 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9591 Cond.getOperand(0), Cond.getOperand(1));
9592 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9593 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9594 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9595 Chain, Dest, CC, Cmp);
9596 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9601 } else if (Cond.getOpcode() == ISD::SETCC &&
9602 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9603 // For FCMP_UNE, we can emit
9604 // two branches instead of an explicit AND instruction with a
9605 // separate test. However, we only do this if this block doesn't
9606 // have a fall-through edge, because this requires an explicit
9607 // jmp when the condition is false.
9608 if (Op.getNode()->hasOneUse()) {
9609 SDNode *User = *Op.getNode()->use_begin();
9610 // Look for an unconditional branch following this conditional branch.
9611 // We need this because we need to reverse the successors in order
9612 // to implement FCMP_UNE.
9613 if (User->getOpcode() == ISD::BR) {
9614 SDValue FalseBB = User->getOperand(1);
9616 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9617 assert(NewBR == User);
9620 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9621 Cond.getOperand(0), Cond.getOperand(1));
9622 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9623 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9624 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9625 Chain, Dest, CC, Cmp);
9626 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9636 // Look pass the truncate if the high bits are known zero.
9637 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9638 Cond = Cond.getOperand(0);
9640 // We know the result of AND is compared against zero. Try to match
9642 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9643 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9644 if (NewSetCC.getNode()) {
9645 CC = NewSetCC.getOperand(0);
9646 Cond = NewSetCC.getOperand(1);
9653 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9654 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9656 Cond = ConvertCmpIfNecessary(Cond, DAG);
9657 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9658 Chain, Dest, CC, Cond);
9662 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9663 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9664 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9665 // that the guard pages used by the OS virtual memory manager are allocated in
9666 // correct sequence.
9668 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9669 SelectionDAG &DAG) const {
9670 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9671 getTargetMachine().Options.EnableSegmentedStacks) &&
9672 "This should be used only on Windows targets or when segmented stacks "
9674 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9675 DebugLoc dl = Op.getDebugLoc();
9678 SDValue Chain = Op.getOperand(0);
9679 SDValue Size = Op.getOperand(1);
9680 // FIXME: Ensure alignment here
9682 bool Is64Bit = Subtarget->is64Bit();
9683 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9685 if (getTargetMachine().Options.EnableSegmentedStacks) {
9686 MachineFunction &MF = DAG.getMachineFunction();
9687 MachineRegisterInfo &MRI = MF.getRegInfo();
9690 // The 64 bit implementation of segmented stacks needs to clobber both r10
9691 // r11. This makes it impossible to use it along with nested parameters.
9692 const Function *F = MF.getFunction();
9694 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9696 if (I->hasNestAttr())
9697 report_fatal_error("Cannot use segmented stacks with functions that "
9698 "have nested arguments.");
9701 const TargetRegisterClass *AddrRegClass =
9702 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9703 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9704 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9705 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9706 DAG.getRegister(Vreg, SPTy));
9707 SDValue Ops1[2] = { Value, Chain };
9708 return DAG.getMergeValues(Ops1, 2, dl);
9711 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9713 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9714 Flag = Chain.getValue(1);
9715 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9717 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9718 Flag = Chain.getValue(1);
9720 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9722 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9723 return DAG.getMergeValues(Ops1, 2, dl);
9727 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9728 MachineFunction &MF = DAG.getMachineFunction();
9729 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9731 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9732 DebugLoc DL = Op.getDebugLoc();
9734 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9735 // vastart just stores the address of the VarArgsFrameIndex slot into the
9736 // memory location argument.
9737 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9739 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9740 MachinePointerInfo(SV), false, false, 0);
9744 // gp_offset (0 - 6 * 8)
9745 // fp_offset (48 - 48 + 8 * 16)
9746 // overflow_arg_area (point to parameters coming in memory).
9748 SmallVector<SDValue, 8> MemOps;
9749 SDValue FIN = Op.getOperand(1);
9751 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9752 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9754 FIN, MachinePointerInfo(SV), false, false, 0);
9755 MemOps.push_back(Store);
9758 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9759 FIN, DAG.getIntPtrConstant(4));
9760 Store = DAG.getStore(Op.getOperand(0), DL,
9761 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9763 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9764 MemOps.push_back(Store);
9766 // Store ptr to overflow_arg_area
9767 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9768 FIN, DAG.getIntPtrConstant(4));
9769 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9771 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9772 MachinePointerInfo(SV, 8),
9774 MemOps.push_back(Store);
9776 // Store ptr to reg_save_area.
9777 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9778 FIN, DAG.getIntPtrConstant(8));
9779 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9781 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9782 MachinePointerInfo(SV, 16), false, false, 0);
9783 MemOps.push_back(Store);
9784 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9785 &MemOps[0], MemOps.size());
9788 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9789 assert(Subtarget->is64Bit() &&
9790 "LowerVAARG only handles 64-bit va_arg!");
9791 assert((Subtarget->isTargetLinux() ||
9792 Subtarget->isTargetDarwin()) &&
9793 "Unhandled target in LowerVAARG");
9794 assert(Op.getNode()->getNumOperands() == 4);
9795 SDValue Chain = Op.getOperand(0);
9796 SDValue SrcPtr = Op.getOperand(1);
9797 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9798 unsigned Align = Op.getConstantOperandVal(3);
9799 DebugLoc dl = Op.getDebugLoc();
9801 EVT ArgVT = Op.getNode()->getValueType(0);
9802 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9803 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9806 // Decide which area this value should be read from.
9807 // TODO: Implement the AMD64 ABI in its entirety. This simple
9808 // selection mechanism works only for the basic types.
9809 if (ArgVT == MVT::f80) {
9810 llvm_unreachable("va_arg for f80 not yet implemented");
9811 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9812 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9813 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9814 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9816 llvm_unreachable("Unhandled argument type in LowerVAARG");
9820 // Sanity Check: Make sure using fp_offset makes sense.
9821 assert(!getTargetMachine().Options.UseSoftFloat &&
9822 !(DAG.getMachineFunction()
9823 .getFunction()->getFnAttributes()
9824 .hasAttribute(Attributes::NoImplicitFloat)) &&
9825 Subtarget->hasSSE1());
9828 // Insert VAARG_64 node into the DAG
9829 // VAARG_64 returns two values: Variable Argument Address, Chain
9830 SmallVector<SDValue, 11> InstOps;
9831 InstOps.push_back(Chain);
9832 InstOps.push_back(SrcPtr);
9833 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9834 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9835 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9836 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9837 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9838 VTs, &InstOps[0], InstOps.size(),
9840 MachinePointerInfo(SV),
9845 Chain = VAARG.getValue(1);
9847 // Load the next argument and return it
9848 return DAG.getLoad(ArgVT, dl,
9851 MachinePointerInfo(),
9852 false, false, false, 0);
9855 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9856 SelectionDAG &DAG) {
9857 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9858 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9859 SDValue Chain = Op.getOperand(0);
9860 SDValue DstPtr = Op.getOperand(1);
9861 SDValue SrcPtr = Op.getOperand(2);
9862 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9863 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9864 DebugLoc DL = Op.getDebugLoc();
9866 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9867 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9869 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9872 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9873 // may or may not be a constant. Takes immediate version of shift as input.
9874 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9875 SDValue SrcOp, SDValue ShAmt,
9876 SelectionDAG &DAG) {
9877 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9879 if (isa<ConstantSDNode>(ShAmt)) {
9880 // Constant may be a TargetConstant. Use a regular constant.
9881 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9883 default: llvm_unreachable("Unknown target vector shift node");
9887 return DAG.getNode(Opc, dl, VT, SrcOp,
9888 DAG.getConstant(ShiftAmt, MVT::i32));
9892 // Change opcode to non-immediate version
9894 default: llvm_unreachable("Unknown target vector shift node");
9895 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9896 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9897 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9900 // Need to build a vector containing shift amount
9901 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9904 ShOps[1] = DAG.getConstant(0, MVT::i32);
9905 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9906 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9908 // The return type has to be a 128-bit type with the same element
9909 // type as the input type.
9910 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9911 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9913 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9914 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9917 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9918 DebugLoc dl = Op.getDebugLoc();
9919 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9921 default: return SDValue(); // Don't custom lower most intrinsics.
9922 // Comparison intrinsics.
9923 case Intrinsic::x86_sse_comieq_ss:
9924 case Intrinsic::x86_sse_comilt_ss:
9925 case Intrinsic::x86_sse_comile_ss:
9926 case Intrinsic::x86_sse_comigt_ss:
9927 case Intrinsic::x86_sse_comige_ss:
9928 case Intrinsic::x86_sse_comineq_ss:
9929 case Intrinsic::x86_sse_ucomieq_ss:
9930 case Intrinsic::x86_sse_ucomilt_ss:
9931 case Intrinsic::x86_sse_ucomile_ss:
9932 case Intrinsic::x86_sse_ucomigt_ss:
9933 case Intrinsic::x86_sse_ucomige_ss:
9934 case Intrinsic::x86_sse_ucomineq_ss:
9935 case Intrinsic::x86_sse2_comieq_sd:
9936 case Intrinsic::x86_sse2_comilt_sd:
9937 case Intrinsic::x86_sse2_comile_sd:
9938 case Intrinsic::x86_sse2_comigt_sd:
9939 case Intrinsic::x86_sse2_comige_sd:
9940 case Intrinsic::x86_sse2_comineq_sd:
9941 case Intrinsic::x86_sse2_ucomieq_sd:
9942 case Intrinsic::x86_sse2_ucomilt_sd:
9943 case Intrinsic::x86_sse2_ucomile_sd:
9944 case Intrinsic::x86_sse2_ucomigt_sd:
9945 case Intrinsic::x86_sse2_ucomige_sd:
9946 case Intrinsic::x86_sse2_ucomineq_sd: {
9950 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9951 case Intrinsic::x86_sse_comieq_ss:
9952 case Intrinsic::x86_sse2_comieq_sd:
9956 case Intrinsic::x86_sse_comilt_ss:
9957 case Intrinsic::x86_sse2_comilt_sd:
9961 case Intrinsic::x86_sse_comile_ss:
9962 case Intrinsic::x86_sse2_comile_sd:
9966 case Intrinsic::x86_sse_comigt_ss:
9967 case Intrinsic::x86_sse2_comigt_sd:
9971 case Intrinsic::x86_sse_comige_ss:
9972 case Intrinsic::x86_sse2_comige_sd:
9976 case Intrinsic::x86_sse_comineq_ss:
9977 case Intrinsic::x86_sse2_comineq_sd:
9981 case Intrinsic::x86_sse_ucomieq_ss:
9982 case Intrinsic::x86_sse2_ucomieq_sd:
9983 Opc = X86ISD::UCOMI;
9986 case Intrinsic::x86_sse_ucomilt_ss:
9987 case Intrinsic::x86_sse2_ucomilt_sd:
9988 Opc = X86ISD::UCOMI;
9991 case Intrinsic::x86_sse_ucomile_ss:
9992 case Intrinsic::x86_sse2_ucomile_sd:
9993 Opc = X86ISD::UCOMI;
9996 case Intrinsic::x86_sse_ucomigt_ss:
9997 case Intrinsic::x86_sse2_ucomigt_sd:
9998 Opc = X86ISD::UCOMI;
10001 case Intrinsic::x86_sse_ucomige_ss:
10002 case Intrinsic::x86_sse2_ucomige_sd:
10003 Opc = X86ISD::UCOMI;
10006 case Intrinsic::x86_sse_ucomineq_ss:
10007 case Intrinsic::x86_sse2_ucomineq_sd:
10008 Opc = X86ISD::UCOMI;
10013 SDValue LHS = Op.getOperand(1);
10014 SDValue RHS = Op.getOperand(2);
10015 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10016 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10017 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10018 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10019 DAG.getConstant(X86CC, MVT::i8), Cond);
10020 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10023 // Arithmetic intrinsics.
10024 case Intrinsic::x86_sse2_pmulu_dq:
10025 case Intrinsic::x86_avx2_pmulu_dq:
10026 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10027 Op.getOperand(1), Op.getOperand(2));
10029 // SSE3/AVX horizontal add/sub intrinsics
10030 case Intrinsic::x86_sse3_hadd_ps:
10031 case Intrinsic::x86_sse3_hadd_pd:
10032 case Intrinsic::x86_avx_hadd_ps_256:
10033 case Intrinsic::x86_avx_hadd_pd_256:
10034 case Intrinsic::x86_sse3_hsub_ps:
10035 case Intrinsic::x86_sse3_hsub_pd:
10036 case Intrinsic::x86_avx_hsub_ps_256:
10037 case Intrinsic::x86_avx_hsub_pd_256:
10038 case Intrinsic::x86_ssse3_phadd_w_128:
10039 case Intrinsic::x86_ssse3_phadd_d_128:
10040 case Intrinsic::x86_avx2_phadd_w:
10041 case Intrinsic::x86_avx2_phadd_d:
10042 case Intrinsic::x86_ssse3_phsub_w_128:
10043 case Intrinsic::x86_ssse3_phsub_d_128:
10044 case Intrinsic::x86_avx2_phsub_w:
10045 case Intrinsic::x86_avx2_phsub_d: {
10048 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10049 case Intrinsic::x86_sse3_hadd_ps:
10050 case Intrinsic::x86_sse3_hadd_pd:
10051 case Intrinsic::x86_avx_hadd_ps_256:
10052 case Intrinsic::x86_avx_hadd_pd_256:
10053 Opcode = X86ISD::FHADD;
10055 case Intrinsic::x86_sse3_hsub_ps:
10056 case Intrinsic::x86_sse3_hsub_pd:
10057 case Intrinsic::x86_avx_hsub_ps_256:
10058 case Intrinsic::x86_avx_hsub_pd_256:
10059 Opcode = X86ISD::FHSUB;
10061 case Intrinsic::x86_ssse3_phadd_w_128:
10062 case Intrinsic::x86_ssse3_phadd_d_128:
10063 case Intrinsic::x86_avx2_phadd_w:
10064 case Intrinsic::x86_avx2_phadd_d:
10065 Opcode = X86ISD::HADD;
10067 case Intrinsic::x86_ssse3_phsub_w_128:
10068 case Intrinsic::x86_ssse3_phsub_d_128:
10069 case Intrinsic::x86_avx2_phsub_w:
10070 case Intrinsic::x86_avx2_phsub_d:
10071 Opcode = X86ISD::HSUB;
10074 return DAG.getNode(Opcode, dl, Op.getValueType(),
10075 Op.getOperand(1), Op.getOperand(2));
10078 // AVX2 variable shift intrinsics
10079 case Intrinsic::x86_avx2_psllv_d:
10080 case Intrinsic::x86_avx2_psllv_q:
10081 case Intrinsic::x86_avx2_psllv_d_256:
10082 case Intrinsic::x86_avx2_psllv_q_256:
10083 case Intrinsic::x86_avx2_psrlv_d:
10084 case Intrinsic::x86_avx2_psrlv_q:
10085 case Intrinsic::x86_avx2_psrlv_d_256:
10086 case Intrinsic::x86_avx2_psrlv_q_256:
10087 case Intrinsic::x86_avx2_psrav_d:
10088 case Intrinsic::x86_avx2_psrav_d_256: {
10091 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10092 case Intrinsic::x86_avx2_psllv_d:
10093 case Intrinsic::x86_avx2_psllv_q:
10094 case Intrinsic::x86_avx2_psllv_d_256:
10095 case Intrinsic::x86_avx2_psllv_q_256:
10098 case Intrinsic::x86_avx2_psrlv_d:
10099 case Intrinsic::x86_avx2_psrlv_q:
10100 case Intrinsic::x86_avx2_psrlv_d_256:
10101 case Intrinsic::x86_avx2_psrlv_q_256:
10104 case Intrinsic::x86_avx2_psrav_d:
10105 case Intrinsic::x86_avx2_psrav_d_256:
10109 return DAG.getNode(Opcode, dl, Op.getValueType(),
10110 Op.getOperand(1), Op.getOperand(2));
10113 case Intrinsic::x86_ssse3_pshuf_b_128:
10114 case Intrinsic::x86_avx2_pshuf_b:
10115 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10116 Op.getOperand(1), Op.getOperand(2));
10118 case Intrinsic::x86_ssse3_psign_b_128:
10119 case Intrinsic::x86_ssse3_psign_w_128:
10120 case Intrinsic::x86_ssse3_psign_d_128:
10121 case Intrinsic::x86_avx2_psign_b:
10122 case Intrinsic::x86_avx2_psign_w:
10123 case Intrinsic::x86_avx2_psign_d:
10124 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10125 Op.getOperand(1), Op.getOperand(2));
10127 case Intrinsic::x86_sse41_insertps:
10128 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10129 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10131 case Intrinsic::x86_avx_vperm2f128_ps_256:
10132 case Intrinsic::x86_avx_vperm2f128_pd_256:
10133 case Intrinsic::x86_avx_vperm2f128_si_256:
10134 case Intrinsic::x86_avx2_vperm2i128:
10135 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10136 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10138 case Intrinsic::x86_avx2_permd:
10139 case Intrinsic::x86_avx2_permps:
10140 // Operands intentionally swapped. Mask is last operand to intrinsic,
10141 // but second operand for node/intruction.
10142 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10143 Op.getOperand(2), Op.getOperand(1));
10145 // ptest and testp intrinsics. The intrinsic these come from are designed to
10146 // return an integer value, not just an instruction so lower it to the ptest
10147 // or testp pattern and a setcc for the result.
10148 case Intrinsic::x86_sse41_ptestz:
10149 case Intrinsic::x86_sse41_ptestc:
10150 case Intrinsic::x86_sse41_ptestnzc:
10151 case Intrinsic::x86_avx_ptestz_256:
10152 case Intrinsic::x86_avx_ptestc_256:
10153 case Intrinsic::x86_avx_ptestnzc_256:
10154 case Intrinsic::x86_avx_vtestz_ps:
10155 case Intrinsic::x86_avx_vtestc_ps:
10156 case Intrinsic::x86_avx_vtestnzc_ps:
10157 case Intrinsic::x86_avx_vtestz_pd:
10158 case Intrinsic::x86_avx_vtestc_pd:
10159 case Intrinsic::x86_avx_vtestnzc_pd:
10160 case Intrinsic::x86_avx_vtestz_ps_256:
10161 case Intrinsic::x86_avx_vtestc_ps_256:
10162 case Intrinsic::x86_avx_vtestnzc_ps_256:
10163 case Intrinsic::x86_avx_vtestz_pd_256:
10164 case Intrinsic::x86_avx_vtestc_pd_256:
10165 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10166 bool IsTestPacked = false;
10169 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10170 case Intrinsic::x86_avx_vtestz_ps:
10171 case Intrinsic::x86_avx_vtestz_pd:
10172 case Intrinsic::x86_avx_vtestz_ps_256:
10173 case Intrinsic::x86_avx_vtestz_pd_256:
10174 IsTestPacked = true; // Fallthrough
10175 case Intrinsic::x86_sse41_ptestz:
10176 case Intrinsic::x86_avx_ptestz_256:
10178 X86CC = X86::COND_E;
10180 case Intrinsic::x86_avx_vtestc_ps:
10181 case Intrinsic::x86_avx_vtestc_pd:
10182 case Intrinsic::x86_avx_vtestc_ps_256:
10183 case Intrinsic::x86_avx_vtestc_pd_256:
10184 IsTestPacked = true; // Fallthrough
10185 case Intrinsic::x86_sse41_ptestc:
10186 case Intrinsic::x86_avx_ptestc_256:
10188 X86CC = X86::COND_B;
10190 case Intrinsic::x86_avx_vtestnzc_ps:
10191 case Intrinsic::x86_avx_vtestnzc_pd:
10192 case Intrinsic::x86_avx_vtestnzc_ps_256:
10193 case Intrinsic::x86_avx_vtestnzc_pd_256:
10194 IsTestPacked = true; // Fallthrough
10195 case Intrinsic::x86_sse41_ptestnzc:
10196 case Intrinsic::x86_avx_ptestnzc_256:
10198 X86CC = X86::COND_A;
10202 SDValue LHS = Op.getOperand(1);
10203 SDValue RHS = Op.getOperand(2);
10204 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10205 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10206 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10207 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10208 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10211 // SSE/AVX shift intrinsics
10212 case Intrinsic::x86_sse2_psll_w:
10213 case Intrinsic::x86_sse2_psll_d:
10214 case Intrinsic::x86_sse2_psll_q:
10215 case Intrinsic::x86_avx2_psll_w:
10216 case Intrinsic::x86_avx2_psll_d:
10217 case Intrinsic::x86_avx2_psll_q:
10218 case Intrinsic::x86_sse2_psrl_w:
10219 case Intrinsic::x86_sse2_psrl_d:
10220 case Intrinsic::x86_sse2_psrl_q:
10221 case Intrinsic::x86_avx2_psrl_w:
10222 case Intrinsic::x86_avx2_psrl_d:
10223 case Intrinsic::x86_avx2_psrl_q:
10224 case Intrinsic::x86_sse2_psra_w:
10225 case Intrinsic::x86_sse2_psra_d:
10226 case Intrinsic::x86_avx2_psra_w:
10227 case Intrinsic::x86_avx2_psra_d: {
10230 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10231 case Intrinsic::x86_sse2_psll_w:
10232 case Intrinsic::x86_sse2_psll_d:
10233 case Intrinsic::x86_sse2_psll_q:
10234 case Intrinsic::x86_avx2_psll_w:
10235 case Intrinsic::x86_avx2_psll_d:
10236 case Intrinsic::x86_avx2_psll_q:
10237 Opcode = X86ISD::VSHL;
10239 case Intrinsic::x86_sse2_psrl_w:
10240 case Intrinsic::x86_sse2_psrl_d:
10241 case Intrinsic::x86_sse2_psrl_q:
10242 case Intrinsic::x86_avx2_psrl_w:
10243 case Intrinsic::x86_avx2_psrl_d:
10244 case Intrinsic::x86_avx2_psrl_q:
10245 Opcode = X86ISD::VSRL;
10247 case Intrinsic::x86_sse2_psra_w:
10248 case Intrinsic::x86_sse2_psra_d:
10249 case Intrinsic::x86_avx2_psra_w:
10250 case Intrinsic::x86_avx2_psra_d:
10251 Opcode = X86ISD::VSRA;
10254 return DAG.getNode(Opcode, dl, Op.getValueType(),
10255 Op.getOperand(1), Op.getOperand(2));
10258 // SSE/AVX immediate shift intrinsics
10259 case Intrinsic::x86_sse2_pslli_w:
10260 case Intrinsic::x86_sse2_pslli_d:
10261 case Intrinsic::x86_sse2_pslli_q:
10262 case Intrinsic::x86_avx2_pslli_w:
10263 case Intrinsic::x86_avx2_pslli_d:
10264 case Intrinsic::x86_avx2_pslli_q:
10265 case Intrinsic::x86_sse2_psrli_w:
10266 case Intrinsic::x86_sse2_psrli_d:
10267 case Intrinsic::x86_sse2_psrli_q:
10268 case Intrinsic::x86_avx2_psrli_w:
10269 case Intrinsic::x86_avx2_psrli_d:
10270 case Intrinsic::x86_avx2_psrli_q:
10271 case Intrinsic::x86_sse2_psrai_w:
10272 case Intrinsic::x86_sse2_psrai_d:
10273 case Intrinsic::x86_avx2_psrai_w:
10274 case Intrinsic::x86_avx2_psrai_d: {
10277 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10278 case Intrinsic::x86_sse2_pslli_w:
10279 case Intrinsic::x86_sse2_pslli_d:
10280 case Intrinsic::x86_sse2_pslli_q:
10281 case Intrinsic::x86_avx2_pslli_w:
10282 case Intrinsic::x86_avx2_pslli_d:
10283 case Intrinsic::x86_avx2_pslli_q:
10284 Opcode = X86ISD::VSHLI;
10286 case Intrinsic::x86_sse2_psrli_w:
10287 case Intrinsic::x86_sse2_psrli_d:
10288 case Intrinsic::x86_sse2_psrli_q:
10289 case Intrinsic::x86_avx2_psrli_w:
10290 case Intrinsic::x86_avx2_psrli_d:
10291 case Intrinsic::x86_avx2_psrli_q:
10292 Opcode = X86ISD::VSRLI;
10294 case Intrinsic::x86_sse2_psrai_w:
10295 case Intrinsic::x86_sse2_psrai_d:
10296 case Intrinsic::x86_avx2_psrai_w:
10297 case Intrinsic::x86_avx2_psrai_d:
10298 Opcode = X86ISD::VSRAI;
10301 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10302 Op.getOperand(1), Op.getOperand(2), DAG);
10305 case Intrinsic::x86_sse42_pcmpistria128:
10306 case Intrinsic::x86_sse42_pcmpestria128:
10307 case Intrinsic::x86_sse42_pcmpistric128:
10308 case Intrinsic::x86_sse42_pcmpestric128:
10309 case Intrinsic::x86_sse42_pcmpistrio128:
10310 case Intrinsic::x86_sse42_pcmpestrio128:
10311 case Intrinsic::x86_sse42_pcmpistris128:
10312 case Intrinsic::x86_sse42_pcmpestris128:
10313 case Intrinsic::x86_sse42_pcmpistriz128:
10314 case Intrinsic::x86_sse42_pcmpestriz128: {
10318 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10319 case Intrinsic::x86_sse42_pcmpistria128:
10320 Opcode = X86ISD::PCMPISTRI;
10321 X86CC = X86::COND_A;
10323 case Intrinsic::x86_sse42_pcmpestria128:
10324 Opcode = X86ISD::PCMPESTRI;
10325 X86CC = X86::COND_A;
10327 case Intrinsic::x86_sse42_pcmpistric128:
10328 Opcode = X86ISD::PCMPISTRI;
10329 X86CC = X86::COND_B;
10331 case Intrinsic::x86_sse42_pcmpestric128:
10332 Opcode = X86ISD::PCMPESTRI;
10333 X86CC = X86::COND_B;
10335 case Intrinsic::x86_sse42_pcmpistrio128:
10336 Opcode = X86ISD::PCMPISTRI;
10337 X86CC = X86::COND_O;
10339 case Intrinsic::x86_sse42_pcmpestrio128:
10340 Opcode = X86ISD::PCMPESTRI;
10341 X86CC = X86::COND_O;
10343 case Intrinsic::x86_sse42_pcmpistris128:
10344 Opcode = X86ISD::PCMPISTRI;
10345 X86CC = X86::COND_S;
10347 case Intrinsic::x86_sse42_pcmpestris128:
10348 Opcode = X86ISD::PCMPESTRI;
10349 X86CC = X86::COND_S;
10351 case Intrinsic::x86_sse42_pcmpistriz128:
10352 Opcode = X86ISD::PCMPISTRI;
10353 X86CC = X86::COND_E;
10355 case Intrinsic::x86_sse42_pcmpestriz128:
10356 Opcode = X86ISD::PCMPESTRI;
10357 X86CC = X86::COND_E;
10360 SmallVector<SDValue, 5> NewOps;
10361 NewOps.append(Op->op_begin()+1, Op->op_end());
10362 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10363 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10364 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10365 DAG.getConstant(X86CC, MVT::i8),
10366 SDValue(PCMP.getNode(), 1));
10367 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10370 case Intrinsic::x86_sse42_pcmpistri128:
10371 case Intrinsic::x86_sse42_pcmpestri128: {
10373 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10374 Opcode = X86ISD::PCMPISTRI;
10376 Opcode = X86ISD::PCMPESTRI;
10378 SmallVector<SDValue, 5> NewOps;
10379 NewOps.append(Op->op_begin()+1, Op->op_end());
10380 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10381 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10383 case Intrinsic::x86_fma_vfmadd_ps:
10384 case Intrinsic::x86_fma_vfmadd_pd:
10385 case Intrinsic::x86_fma_vfmsub_ps:
10386 case Intrinsic::x86_fma_vfmsub_pd:
10387 case Intrinsic::x86_fma_vfnmadd_ps:
10388 case Intrinsic::x86_fma_vfnmadd_pd:
10389 case Intrinsic::x86_fma_vfnmsub_ps:
10390 case Intrinsic::x86_fma_vfnmsub_pd:
10391 case Intrinsic::x86_fma_vfmaddsub_ps:
10392 case Intrinsic::x86_fma_vfmaddsub_pd:
10393 case Intrinsic::x86_fma_vfmsubadd_ps:
10394 case Intrinsic::x86_fma_vfmsubadd_pd:
10395 case Intrinsic::x86_fma_vfmadd_ps_256:
10396 case Intrinsic::x86_fma_vfmadd_pd_256:
10397 case Intrinsic::x86_fma_vfmsub_ps_256:
10398 case Intrinsic::x86_fma_vfmsub_pd_256:
10399 case Intrinsic::x86_fma_vfnmadd_ps_256:
10400 case Intrinsic::x86_fma_vfnmadd_pd_256:
10401 case Intrinsic::x86_fma_vfnmsub_ps_256:
10402 case Intrinsic::x86_fma_vfnmsub_pd_256:
10403 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10404 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10405 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10406 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10409 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10410 case Intrinsic::x86_fma_vfmadd_ps:
10411 case Intrinsic::x86_fma_vfmadd_pd:
10412 case Intrinsic::x86_fma_vfmadd_ps_256:
10413 case Intrinsic::x86_fma_vfmadd_pd_256:
10414 Opc = X86ISD::FMADD;
10416 case Intrinsic::x86_fma_vfmsub_ps:
10417 case Intrinsic::x86_fma_vfmsub_pd:
10418 case Intrinsic::x86_fma_vfmsub_ps_256:
10419 case Intrinsic::x86_fma_vfmsub_pd_256:
10420 Opc = X86ISD::FMSUB;
10422 case Intrinsic::x86_fma_vfnmadd_ps:
10423 case Intrinsic::x86_fma_vfnmadd_pd:
10424 case Intrinsic::x86_fma_vfnmadd_ps_256:
10425 case Intrinsic::x86_fma_vfnmadd_pd_256:
10426 Opc = X86ISD::FNMADD;
10428 case Intrinsic::x86_fma_vfnmsub_ps:
10429 case Intrinsic::x86_fma_vfnmsub_pd:
10430 case Intrinsic::x86_fma_vfnmsub_ps_256:
10431 case Intrinsic::x86_fma_vfnmsub_pd_256:
10432 Opc = X86ISD::FNMSUB;
10434 case Intrinsic::x86_fma_vfmaddsub_ps:
10435 case Intrinsic::x86_fma_vfmaddsub_pd:
10436 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10437 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10438 Opc = X86ISD::FMADDSUB;
10440 case Intrinsic::x86_fma_vfmsubadd_ps:
10441 case Intrinsic::x86_fma_vfmsubadd_pd:
10442 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10443 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10444 Opc = X86ISD::FMSUBADD;
10448 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10449 Op.getOperand(2), Op.getOperand(3));
10454 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10455 DebugLoc dl = Op.getDebugLoc();
10456 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10458 default: return SDValue(); // Don't custom lower most intrinsics.
10460 // RDRAND intrinsics.
10461 case Intrinsic::x86_rdrand_16:
10462 case Intrinsic::x86_rdrand_32:
10463 case Intrinsic::x86_rdrand_64: {
10464 // Emit the node with the right value type.
10465 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10466 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10468 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10469 // return the value from Rand, which is always 0, casted to i32.
10470 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10471 DAG.getConstant(1, Op->getValueType(1)),
10472 DAG.getConstant(X86::COND_B, MVT::i32),
10473 SDValue(Result.getNode(), 1) };
10474 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10475 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10478 // Return { result, isValid, chain }.
10479 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10480 SDValue(Result.getNode(), 2));
10485 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10486 SelectionDAG &DAG) const {
10487 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10488 MFI->setReturnAddressIsTaken(true);
10490 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10491 DebugLoc dl = Op.getDebugLoc();
10494 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10496 DAG.getConstant(TD->getPointerSize(0),
10497 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10498 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10499 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10500 FrameAddr, Offset),
10501 MachinePointerInfo(), false, false, false, 0);
10504 // Just load the return address.
10505 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10506 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10507 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10510 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10511 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10512 MFI->setFrameAddressIsTaken(true);
10514 EVT VT = Op.getValueType();
10515 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10516 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10517 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10518 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10520 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10521 MachinePointerInfo(),
10522 false, false, false, 0);
10526 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10527 SelectionDAG &DAG) const {
10528 return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10531 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10532 SDValue Chain = Op.getOperand(0);
10533 SDValue Offset = Op.getOperand(1);
10534 SDValue Handler = Op.getOperand(2);
10535 DebugLoc dl = Op.getDebugLoc();
10537 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10538 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10540 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10542 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10543 DAG.getIntPtrConstant(TD->getPointerSize(0)));
10544 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10545 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10547 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10549 return DAG.getNode(X86ISD::EH_RETURN, dl,
10551 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10554 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10555 SelectionDAG &DAG) const {
10556 DebugLoc DL = Op.getDebugLoc();
10557 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10558 DAG.getVTList(MVT::i32, MVT::Other),
10559 Op.getOperand(0), Op.getOperand(1));
10562 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10563 SelectionDAG &DAG) const {
10564 DebugLoc DL = Op.getDebugLoc();
10565 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10566 Op.getOperand(0), Op.getOperand(1));
10569 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10570 return Op.getOperand(0);
10573 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10574 SelectionDAG &DAG) const {
10575 SDValue Root = Op.getOperand(0);
10576 SDValue Trmp = Op.getOperand(1); // trampoline
10577 SDValue FPtr = Op.getOperand(2); // nested function
10578 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10579 DebugLoc dl = Op.getDebugLoc();
10581 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10582 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10584 if (Subtarget->is64Bit()) {
10585 SDValue OutChains[6];
10587 // Large code-model.
10588 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10589 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10591 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10592 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10594 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10596 // Load the pointer to the nested function into R11.
10597 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10598 SDValue Addr = Trmp;
10599 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10600 Addr, MachinePointerInfo(TrmpAddr),
10603 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10604 DAG.getConstant(2, MVT::i64));
10605 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10606 MachinePointerInfo(TrmpAddr, 2),
10609 // Load the 'nest' parameter value into R10.
10610 // R10 is specified in X86CallingConv.td
10611 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10612 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10613 DAG.getConstant(10, MVT::i64));
10614 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10615 Addr, MachinePointerInfo(TrmpAddr, 10),
10618 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10619 DAG.getConstant(12, MVT::i64));
10620 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10621 MachinePointerInfo(TrmpAddr, 12),
10624 // Jump to the nested function.
10625 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10626 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10627 DAG.getConstant(20, MVT::i64));
10628 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10629 Addr, MachinePointerInfo(TrmpAddr, 20),
10632 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10633 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10634 DAG.getConstant(22, MVT::i64));
10635 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10636 MachinePointerInfo(TrmpAddr, 22),
10639 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10641 const Function *Func =
10642 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10643 CallingConv::ID CC = Func->getCallingConv();
10648 llvm_unreachable("Unsupported calling convention");
10649 case CallingConv::C:
10650 case CallingConv::X86_StdCall: {
10651 // Pass 'nest' parameter in ECX.
10652 // Must be kept in sync with X86CallingConv.td
10653 NestReg = X86::ECX;
10655 // Check that ECX wasn't needed by an 'inreg' parameter.
10656 FunctionType *FTy = Func->getFunctionType();
10657 const AttrListPtr &Attrs = Func->getAttributes();
10659 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10660 unsigned InRegCount = 0;
10663 for (FunctionType::param_iterator I = FTy->param_begin(),
10664 E = FTy->param_end(); I != E; ++I, ++Idx)
10665 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10666 // FIXME: should only count parameters that are lowered to integers.
10667 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10669 if (InRegCount > 2) {
10670 report_fatal_error("Nest register in use - reduce number of inreg"
10676 case CallingConv::X86_FastCall:
10677 case CallingConv::X86_ThisCall:
10678 case CallingConv::Fast:
10679 // Pass 'nest' parameter in EAX.
10680 // Must be kept in sync with X86CallingConv.td
10681 NestReg = X86::EAX;
10685 SDValue OutChains[4];
10686 SDValue Addr, Disp;
10688 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10689 DAG.getConstant(10, MVT::i32));
10690 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10692 // This is storing the opcode for MOV32ri.
10693 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10694 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10695 OutChains[0] = DAG.getStore(Root, dl,
10696 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10697 Trmp, MachinePointerInfo(TrmpAddr),
10700 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10701 DAG.getConstant(1, MVT::i32));
10702 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10703 MachinePointerInfo(TrmpAddr, 1),
10706 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10708 DAG.getConstant(5, MVT::i32));
10709 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10710 MachinePointerInfo(TrmpAddr, 5),
10713 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10714 DAG.getConstant(6, MVT::i32));
10715 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10716 MachinePointerInfo(TrmpAddr, 6),
10719 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10723 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10724 SelectionDAG &DAG) const {
10726 The rounding mode is in bits 11:10 of FPSR, and has the following
10728 00 Round to nearest
10733 FLT_ROUNDS, on the other hand, expects the following:
10740 To perform the conversion, we do:
10741 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10744 MachineFunction &MF = DAG.getMachineFunction();
10745 const TargetMachine &TM = MF.getTarget();
10746 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10747 unsigned StackAlignment = TFI.getStackAlignment();
10748 EVT VT = Op.getValueType();
10749 DebugLoc DL = Op.getDebugLoc();
10751 // Save FP Control Word to stack slot
10752 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10753 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10756 MachineMemOperand *MMO =
10757 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10758 MachineMemOperand::MOStore, 2, 2);
10760 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10761 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10762 DAG.getVTList(MVT::Other),
10763 Ops, 2, MVT::i16, MMO);
10765 // Load FP Control Word from stack slot
10766 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10767 MachinePointerInfo(), false, false, false, 0);
10769 // Transform as necessary
10771 DAG.getNode(ISD::SRL, DL, MVT::i16,
10772 DAG.getNode(ISD::AND, DL, MVT::i16,
10773 CWD, DAG.getConstant(0x800, MVT::i16)),
10774 DAG.getConstant(11, MVT::i8));
10776 DAG.getNode(ISD::SRL, DL, MVT::i16,
10777 DAG.getNode(ISD::AND, DL, MVT::i16,
10778 CWD, DAG.getConstant(0x400, MVT::i16)),
10779 DAG.getConstant(9, MVT::i8));
10782 DAG.getNode(ISD::AND, DL, MVT::i16,
10783 DAG.getNode(ISD::ADD, DL, MVT::i16,
10784 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10785 DAG.getConstant(1, MVT::i16)),
10786 DAG.getConstant(3, MVT::i16));
10789 return DAG.getNode((VT.getSizeInBits() < 16 ?
10790 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10793 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10794 EVT VT = Op.getValueType();
10796 unsigned NumBits = VT.getSizeInBits();
10797 DebugLoc dl = Op.getDebugLoc();
10799 Op = Op.getOperand(0);
10800 if (VT == MVT::i8) {
10801 // Zero extend to i32 since there is not an i8 bsr.
10803 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10806 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10807 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10808 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10810 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10813 DAG.getConstant(NumBits+NumBits-1, OpVT),
10814 DAG.getConstant(X86::COND_E, MVT::i8),
10817 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10819 // Finally xor with NumBits-1.
10820 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10823 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10827 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10828 EVT VT = Op.getValueType();
10830 unsigned NumBits = VT.getSizeInBits();
10831 DebugLoc dl = Op.getDebugLoc();
10833 Op = Op.getOperand(0);
10834 if (VT == MVT::i8) {
10835 // Zero extend to i32 since there is not an i8 bsr.
10837 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10840 // Issue a bsr (scan bits in reverse).
10841 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10842 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10844 // And xor with NumBits-1.
10845 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10848 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10852 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10853 EVT VT = Op.getValueType();
10854 unsigned NumBits = VT.getSizeInBits();
10855 DebugLoc dl = Op.getDebugLoc();
10856 Op = Op.getOperand(0);
10858 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10859 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10860 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10862 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10865 DAG.getConstant(NumBits, VT),
10866 DAG.getConstant(X86::COND_E, MVT::i8),
10869 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10872 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10873 // ones, and then concatenate the result back.
10874 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10875 EVT VT = Op.getValueType();
10877 assert(VT.is256BitVector() && VT.isInteger() &&
10878 "Unsupported value type for operation");
10880 unsigned NumElems = VT.getVectorNumElements();
10881 DebugLoc dl = Op.getDebugLoc();
10883 // Extract the LHS vectors
10884 SDValue LHS = Op.getOperand(0);
10885 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10886 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10888 // Extract the RHS vectors
10889 SDValue RHS = Op.getOperand(1);
10890 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10891 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10893 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10894 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10896 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10897 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10898 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10901 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10902 assert(Op.getValueType().is256BitVector() &&
10903 Op.getValueType().isInteger() &&
10904 "Only handle AVX 256-bit vector integer operation");
10905 return Lower256IntArith(Op, DAG);
10908 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10909 assert(Op.getValueType().is256BitVector() &&
10910 Op.getValueType().isInteger() &&
10911 "Only handle AVX 256-bit vector integer operation");
10912 return Lower256IntArith(Op, DAG);
10915 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10916 SelectionDAG &DAG) {
10917 EVT VT = Op.getValueType();
10919 // Decompose 256-bit ops into smaller 128-bit ops.
10920 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10921 return Lower256IntArith(Op, DAG);
10923 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10924 "Only know how to lower V2I64/V4I64 multiply");
10926 DebugLoc dl = Op.getDebugLoc();
10928 // Ahi = psrlqi(a, 32);
10929 // Bhi = psrlqi(b, 32);
10931 // AloBlo = pmuludq(a, b);
10932 // AloBhi = pmuludq(a, Bhi);
10933 // AhiBlo = pmuludq(Ahi, b);
10935 // AloBhi = psllqi(AloBhi, 32);
10936 // AhiBlo = psllqi(AhiBlo, 32);
10937 // return AloBlo + AloBhi + AhiBlo;
10939 SDValue A = Op.getOperand(0);
10940 SDValue B = Op.getOperand(1);
10942 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10944 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10945 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10947 // Bit cast to 32-bit vectors for MULUDQ
10948 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10949 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10950 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10951 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10952 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10954 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10955 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10956 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10958 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10959 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10961 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10962 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10965 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10967 EVT VT = Op.getValueType();
10968 DebugLoc dl = Op.getDebugLoc();
10969 SDValue R = Op.getOperand(0);
10970 SDValue Amt = Op.getOperand(1);
10971 LLVMContext *Context = DAG.getContext();
10973 if (!Subtarget->hasSSE2())
10976 // Optimize shl/srl/sra with constant shift amount.
10977 if (isSplatVector(Amt.getNode())) {
10978 SDValue SclrAmt = Amt->getOperand(0);
10979 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10980 uint64_t ShiftAmt = C->getZExtValue();
10982 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10983 (Subtarget->hasAVX2() &&
10984 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10985 if (Op.getOpcode() == ISD::SHL)
10986 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10987 DAG.getConstant(ShiftAmt, MVT::i32));
10988 if (Op.getOpcode() == ISD::SRL)
10989 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10990 DAG.getConstant(ShiftAmt, MVT::i32));
10991 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10992 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10993 DAG.getConstant(ShiftAmt, MVT::i32));
10996 if (VT == MVT::v16i8) {
10997 if (Op.getOpcode() == ISD::SHL) {
10998 // Make a large shift.
10999 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11000 DAG.getConstant(ShiftAmt, MVT::i32));
11001 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11002 // Zero out the rightmost bits.
11003 SmallVector<SDValue, 16> V(16,
11004 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11006 return DAG.getNode(ISD::AND, dl, VT, SHL,
11007 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11009 if (Op.getOpcode() == ISD::SRL) {
11010 // Make a large shift.
11011 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11012 DAG.getConstant(ShiftAmt, MVT::i32));
11013 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11014 // Zero out the leftmost bits.
11015 SmallVector<SDValue, 16> V(16,
11016 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11018 return DAG.getNode(ISD::AND, dl, VT, SRL,
11019 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11021 if (Op.getOpcode() == ISD::SRA) {
11022 if (ShiftAmt == 7) {
11023 // R s>> 7 === R s< 0
11024 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11025 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11028 // R s>> a === ((R u>> a) ^ m) - m
11029 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11030 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11032 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11033 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11034 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11037 llvm_unreachable("Unknown shift opcode.");
11040 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11041 if (Op.getOpcode() == ISD::SHL) {
11042 // Make a large shift.
11043 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11044 DAG.getConstant(ShiftAmt, MVT::i32));
11045 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11046 // Zero out the rightmost bits.
11047 SmallVector<SDValue, 32> V(32,
11048 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11050 return DAG.getNode(ISD::AND, dl, VT, SHL,
11051 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11053 if (Op.getOpcode() == ISD::SRL) {
11054 // Make a large shift.
11055 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11056 DAG.getConstant(ShiftAmt, MVT::i32));
11057 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11058 // Zero out the leftmost bits.
11059 SmallVector<SDValue, 32> V(32,
11060 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11062 return DAG.getNode(ISD::AND, dl, VT, SRL,
11063 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11065 if (Op.getOpcode() == ISD::SRA) {
11066 if (ShiftAmt == 7) {
11067 // R s>> 7 === R s< 0
11068 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11069 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11072 // R s>> a === ((R u>> a) ^ m) - m
11073 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11074 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11076 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11077 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11078 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11081 llvm_unreachable("Unknown shift opcode.");
11086 // Lower SHL with variable shift amount.
11087 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11088 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11089 DAG.getConstant(23, MVT::i32));
11091 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11092 Constant *C = ConstantDataVector::get(*Context, CV);
11093 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11094 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11095 MachinePointerInfo::getConstantPool(),
11096 false, false, false, 16);
11098 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11099 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11100 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11101 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11103 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11104 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11107 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11108 DAG.getConstant(5, MVT::i32));
11109 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11111 // Turn 'a' into a mask suitable for VSELECT
11112 SDValue VSelM = DAG.getConstant(0x80, VT);
11113 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11114 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11116 SDValue CM1 = DAG.getConstant(0x0f, VT);
11117 SDValue CM2 = DAG.getConstant(0x3f, VT);
11119 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11120 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11121 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11122 DAG.getConstant(4, MVT::i32), DAG);
11123 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11124 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11127 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11128 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11129 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11131 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11132 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11133 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11134 DAG.getConstant(2, MVT::i32), DAG);
11135 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11136 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11139 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11140 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11141 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11143 // return VSELECT(r, r+r, a);
11144 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11145 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11149 // Decompose 256-bit shifts into smaller 128-bit shifts.
11150 if (VT.is256BitVector()) {
11151 unsigned NumElems = VT.getVectorNumElements();
11152 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11153 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11155 // Extract the two vectors
11156 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11157 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11159 // Recreate the shift amount vectors
11160 SDValue Amt1, Amt2;
11161 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11162 // Constant shift amount
11163 SmallVector<SDValue, 4> Amt1Csts;
11164 SmallVector<SDValue, 4> Amt2Csts;
11165 for (unsigned i = 0; i != NumElems/2; ++i)
11166 Amt1Csts.push_back(Amt->getOperand(i));
11167 for (unsigned i = NumElems/2; i != NumElems; ++i)
11168 Amt2Csts.push_back(Amt->getOperand(i));
11170 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11171 &Amt1Csts[0], NumElems/2);
11172 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11173 &Amt2Csts[0], NumElems/2);
11175 // Variable shift amount
11176 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11177 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11180 // Issue new vector shifts for the smaller types
11181 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11182 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11184 // Concatenate the result back
11185 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11191 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11192 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11193 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11194 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11195 // has only one use.
11196 SDNode *N = Op.getNode();
11197 SDValue LHS = N->getOperand(0);
11198 SDValue RHS = N->getOperand(1);
11199 unsigned BaseOp = 0;
11201 DebugLoc DL = Op.getDebugLoc();
11202 switch (Op.getOpcode()) {
11203 default: llvm_unreachable("Unknown ovf instruction!");
11205 // A subtract of one will be selected as a INC. Note that INC doesn't
11206 // set CF, so we can't do this for UADDO.
11207 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11209 BaseOp = X86ISD::INC;
11210 Cond = X86::COND_O;
11213 BaseOp = X86ISD::ADD;
11214 Cond = X86::COND_O;
11217 BaseOp = X86ISD::ADD;
11218 Cond = X86::COND_B;
11221 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11222 // set CF, so we can't do this for USUBO.
11223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11225 BaseOp = X86ISD::DEC;
11226 Cond = X86::COND_O;
11229 BaseOp = X86ISD::SUB;
11230 Cond = X86::COND_O;
11233 BaseOp = X86ISD::SUB;
11234 Cond = X86::COND_B;
11237 BaseOp = X86ISD::SMUL;
11238 Cond = X86::COND_O;
11240 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11241 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11243 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11246 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11247 DAG.getConstant(X86::COND_O, MVT::i32),
11248 SDValue(Sum.getNode(), 2));
11250 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11254 // Also sets EFLAGS.
11255 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11256 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11259 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11260 DAG.getConstant(Cond, MVT::i32),
11261 SDValue(Sum.getNode(), 1));
11263 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11266 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11267 SelectionDAG &DAG) const {
11268 DebugLoc dl = Op.getDebugLoc();
11269 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11270 EVT VT = Op.getValueType();
11272 if (!Subtarget->hasSSE2() || !VT.isVector())
11275 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11276 ExtraVT.getScalarType().getSizeInBits();
11277 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11279 switch (VT.getSimpleVT().SimpleTy) {
11280 default: return SDValue();
11283 if (!Subtarget->hasAVX())
11285 if (!Subtarget->hasAVX2()) {
11286 // needs to be split
11287 unsigned NumElems = VT.getVectorNumElements();
11289 // Extract the LHS vectors
11290 SDValue LHS = Op.getOperand(0);
11291 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11292 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11294 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11295 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11297 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11298 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11299 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11301 SDValue Extra = DAG.getValueType(ExtraVT);
11303 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11304 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11306 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11311 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11312 Op.getOperand(0), ShAmt, DAG);
11313 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11319 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11320 SelectionDAG &DAG) {
11321 DebugLoc dl = Op.getDebugLoc();
11323 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11324 // There isn't any reason to disable it if the target processor supports it.
11325 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11326 SDValue Chain = Op.getOperand(0);
11327 SDValue Zero = DAG.getConstant(0, MVT::i32);
11329 DAG.getRegister(X86::ESP, MVT::i32), // Base
11330 DAG.getTargetConstant(1, MVT::i8), // Scale
11331 DAG.getRegister(0, MVT::i32), // Index
11332 DAG.getTargetConstant(0, MVT::i32), // Disp
11333 DAG.getRegister(0, MVT::i32), // Segment.
11338 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11339 array_lengthof(Ops));
11340 return SDValue(Res, 0);
11343 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11345 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11347 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11348 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11349 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11350 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11352 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11353 if (!Op1 && !Op2 && !Op3 && Op4)
11354 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11356 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11357 if (Op1 && !Op2 && !Op3 && !Op4)
11358 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11360 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11362 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11365 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11366 SelectionDAG &DAG) {
11367 DebugLoc dl = Op.getDebugLoc();
11368 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11369 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11370 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11371 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11373 // The only fence that needs an instruction is a sequentially-consistent
11374 // cross-thread fence.
11375 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11376 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11377 // no-sse2). There isn't any reason to disable it if the target processor
11379 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11380 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11382 SDValue Chain = Op.getOperand(0);
11383 SDValue Zero = DAG.getConstant(0, MVT::i32);
11385 DAG.getRegister(X86::ESP, MVT::i32), // Base
11386 DAG.getTargetConstant(1, MVT::i8), // Scale
11387 DAG.getRegister(0, MVT::i32), // Index
11388 DAG.getTargetConstant(0, MVT::i32), // Disp
11389 DAG.getRegister(0, MVT::i32), // Segment.
11394 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11395 array_lengthof(Ops));
11396 return SDValue(Res, 0);
11399 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11400 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11404 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11405 SelectionDAG &DAG) {
11406 EVT T = Op.getValueType();
11407 DebugLoc DL = Op.getDebugLoc();
11410 switch(T.getSimpleVT().SimpleTy) {
11411 default: llvm_unreachable("Invalid value type!");
11412 case MVT::i8: Reg = X86::AL; size = 1; break;
11413 case MVT::i16: Reg = X86::AX; size = 2; break;
11414 case MVT::i32: Reg = X86::EAX; size = 4; break;
11416 assert(Subtarget->is64Bit() && "Node not type legal!");
11417 Reg = X86::RAX; size = 8;
11420 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11421 Op.getOperand(2), SDValue());
11422 SDValue Ops[] = { cpIn.getValue(0),
11425 DAG.getTargetConstant(size, MVT::i8),
11426 cpIn.getValue(1) };
11427 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11428 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11429 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11432 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11436 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11437 SelectionDAG &DAG) {
11438 assert(Subtarget->is64Bit() && "Result not type legalized?");
11439 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11440 SDValue TheChain = Op.getOperand(0);
11441 DebugLoc dl = Op.getDebugLoc();
11442 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11443 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11444 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11446 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11447 DAG.getConstant(32, MVT::i8));
11449 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11452 return DAG.getMergeValues(Ops, 2, dl);
11455 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11456 EVT SrcVT = Op.getOperand(0).getValueType();
11457 EVT DstVT = Op.getValueType();
11458 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11459 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11460 assert((DstVT == MVT::i64 ||
11461 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11462 "Unexpected custom BITCAST");
11463 // i64 <=> MMX conversions are Legal.
11464 if (SrcVT==MVT::i64 && DstVT.isVector())
11466 if (DstVT==MVT::i64 && SrcVT.isVector())
11468 // MMX <=> MMX conversions are Legal.
11469 if (SrcVT.isVector() && DstVT.isVector())
11471 // All other conversions need to be expanded.
11475 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11476 SDNode *Node = Op.getNode();
11477 DebugLoc dl = Node->getDebugLoc();
11478 EVT T = Node->getValueType(0);
11479 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11480 DAG.getConstant(0, T), Node->getOperand(2));
11481 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11482 cast<AtomicSDNode>(Node)->getMemoryVT(),
11483 Node->getOperand(0),
11484 Node->getOperand(1), negOp,
11485 cast<AtomicSDNode>(Node)->getSrcValue(),
11486 cast<AtomicSDNode>(Node)->getAlignment(),
11487 cast<AtomicSDNode>(Node)->getOrdering(),
11488 cast<AtomicSDNode>(Node)->getSynchScope());
11491 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11492 SDNode *Node = Op.getNode();
11493 DebugLoc dl = Node->getDebugLoc();
11494 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11496 // Convert seq_cst store -> xchg
11497 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11498 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11499 // (The only way to get a 16-byte store is cmpxchg16b)
11500 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11501 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11502 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11503 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11504 cast<AtomicSDNode>(Node)->getMemoryVT(),
11505 Node->getOperand(0),
11506 Node->getOperand(1), Node->getOperand(2),
11507 cast<AtomicSDNode>(Node)->getMemOperand(),
11508 cast<AtomicSDNode>(Node)->getOrdering(),
11509 cast<AtomicSDNode>(Node)->getSynchScope());
11510 return Swap.getValue(1);
11512 // Other atomic stores have a simple pattern.
11516 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11517 EVT VT = Op.getNode()->getValueType(0);
11519 // Let legalize expand this if it isn't a legal type yet.
11520 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11523 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11526 bool ExtraOp = false;
11527 switch (Op.getOpcode()) {
11528 default: llvm_unreachable("Invalid code");
11529 case ISD::ADDC: Opc = X86ISD::ADD; break;
11530 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11531 case ISD::SUBC: Opc = X86ISD::SUB; break;
11532 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11536 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11538 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11539 Op.getOperand(1), Op.getOperand(2));
11542 /// LowerOperation - Provide custom lowering hooks for some operations.
11544 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11545 switch (Op.getOpcode()) {
11546 default: llvm_unreachable("Should not custom lower this!");
11547 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11548 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11549 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11550 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11551 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11552 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11553 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11554 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11555 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11556 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11557 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11558 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11559 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11560 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11561 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11562 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11563 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11564 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11565 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11566 case ISD::SHL_PARTS:
11567 case ISD::SRA_PARTS:
11568 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11569 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11570 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11571 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11572 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11573 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11574 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11575 case ISD::FABS: return LowerFABS(Op, DAG);
11576 case ISD::FNEG: return LowerFNEG(Op, DAG);
11577 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11578 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11579 case ISD::SETCC: return LowerSETCC(Op, DAG);
11580 case ISD::SELECT: return LowerSELECT(Op, DAG);
11581 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11582 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11583 case ISD::VASTART: return LowerVASTART(Op, DAG);
11584 case ISD::VAARG: return LowerVAARG(Op, DAG);
11585 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11586 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11587 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11588 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11589 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11590 case ISD::FRAME_TO_ARGS_OFFSET:
11591 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11592 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11593 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11594 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11595 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11596 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11597 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11598 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11599 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11600 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11601 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11602 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11605 case ISD::SHL: return LowerShift(Op, DAG);
11611 case ISD::UMULO: return LowerXALUO(Op, DAG);
11612 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11613 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11617 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11618 case ISD::ADD: return LowerADD(Op, DAG);
11619 case ISD::SUB: return LowerSUB(Op, DAG);
11623 static void ReplaceATOMIC_LOAD(SDNode *Node,
11624 SmallVectorImpl<SDValue> &Results,
11625 SelectionDAG &DAG) {
11626 DebugLoc dl = Node->getDebugLoc();
11627 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11629 // Convert wide load -> cmpxchg8b/cmpxchg16b
11630 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11631 // (The only way to get a 16-byte load is cmpxchg16b)
11632 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11633 SDValue Zero = DAG.getConstant(0, VT);
11634 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11635 Node->getOperand(0),
11636 Node->getOperand(1), Zero, Zero,
11637 cast<AtomicSDNode>(Node)->getMemOperand(),
11638 cast<AtomicSDNode>(Node)->getOrdering(),
11639 cast<AtomicSDNode>(Node)->getSynchScope());
11640 Results.push_back(Swap.getValue(0));
11641 Results.push_back(Swap.getValue(1));
11645 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11646 SelectionDAG &DAG, unsigned NewOp) {
11647 DebugLoc dl = Node->getDebugLoc();
11648 assert (Node->getValueType(0) == MVT::i64 &&
11649 "Only know how to expand i64 atomics");
11651 SDValue Chain = Node->getOperand(0);
11652 SDValue In1 = Node->getOperand(1);
11653 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11654 Node->getOperand(2), DAG.getIntPtrConstant(0));
11655 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11656 Node->getOperand(2), DAG.getIntPtrConstant(1));
11657 SDValue Ops[] = { Chain, In1, In2L, In2H };
11658 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11660 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11661 cast<MemSDNode>(Node)->getMemOperand());
11662 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11663 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11664 Results.push_back(Result.getValue(2));
11667 /// ReplaceNodeResults - Replace a node with an illegal result type
11668 /// with a new node built out of custom code.
11669 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11670 SmallVectorImpl<SDValue>&Results,
11671 SelectionDAG &DAG) const {
11672 DebugLoc dl = N->getDebugLoc();
11673 switch (N->getOpcode()) {
11675 llvm_unreachable("Do not know how to custom type legalize this operation!");
11676 case ISD::SIGN_EXTEND_INREG:
11681 // We don't want to expand or promote these.
11683 case ISD::FP_TO_SINT:
11684 case ISD::FP_TO_UINT: {
11685 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11687 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11690 std::pair<SDValue,SDValue> Vals =
11691 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11692 SDValue FIST = Vals.first, StackSlot = Vals.second;
11693 if (FIST.getNode() != 0) {
11694 EVT VT = N->getValueType(0);
11695 // Return a load from the stack slot.
11696 if (StackSlot.getNode() != 0)
11697 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11698 MachinePointerInfo(),
11699 false, false, false, 0));
11701 Results.push_back(FIST);
11705 case ISD::FP_ROUND: {
11706 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11707 Results.push_back(V);
11710 case ISD::READCYCLECOUNTER: {
11711 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11712 SDValue TheChain = N->getOperand(0);
11713 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11714 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11716 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11718 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11719 SDValue Ops[] = { eax, edx };
11720 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11721 Results.push_back(edx.getValue(1));
11724 case ISD::ATOMIC_CMP_SWAP: {
11725 EVT T = N->getValueType(0);
11726 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11727 bool Regs64bit = T == MVT::i128;
11728 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11729 SDValue cpInL, cpInH;
11730 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11731 DAG.getConstant(0, HalfT));
11732 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11733 DAG.getConstant(1, HalfT));
11734 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11735 Regs64bit ? X86::RAX : X86::EAX,
11737 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11738 Regs64bit ? X86::RDX : X86::EDX,
11739 cpInH, cpInL.getValue(1));
11740 SDValue swapInL, swapInH;
11741 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11742 DAG.getConstant(0, HalfT));
11743 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11744 DAG.getConstant(1, HalfT));
11745 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11746 Regs64bit ? X86::RBX : X86::EBX,
11747 swapInL, cpInH.getValue(1));
11748 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11749 Regs64bit ? X86::RCX : X86::ECX,
11750 swapInH, swapInL.getValue(1));
11751 SDValue Ops[] = { swapInH.getValue(0),
11753 swapInH.getValue(1) };
11754 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11755 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11756 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11757 X86ISD::LCMPXCHG8_DAG;
11758 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11760 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11761 Regs64bit ? X86::RAX : X86::EAX,
11762 HalfT, Result.getValue(1));
11763 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11764 Regs64bit ? X86::RDX : X86::EDX,
11765 HalfT, cpOutL.getValue(2));
11766 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11767 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11768 Results.push_back(cpOutH.getValue(1));
11771 case ISD::ATOMIC_LOAD_ADD:
11772 case ISD::ATOMIC_LOAD_AND:
11773 case ISD::ATOMIC_LOAD_NAND:
11774 case ISD::ATOMIC_LOAD_OR:
11775 case ISD::ATOMIC_LOAD_SUB:
11776 case ISD::ATOMIC_LOAD_XOR:
11777 case ISD::ATOMIC_LOAD_MAX:
11778 case ISD::ATOMIC_LOAD_MIN:
11779 case ISD::ATOMIC_LOAD_UMAX:
11780 case ISD::ATOMIC_LOAD_UMIN:
11781 case ISD::ATOMIC_SWAP: {
11783 switch (N->getOpcode()) {
11784 default: llvm_unreachable("Unexpected opcode");
11785 case ISD::ATOMIC_LOAD_ADD:
11786 Opc = X86ISD::ATOMADD64_DAG;
11788 case ISD::ATOMIC_LOAD_AND:
11789 Opc = X86ISD::ATOMAND64_DAG;
11791 case ISD::ATOMIC_LOAD_NAND:
11792 Opc = X86ISD::ATOMNAND64_DAG;
11794 case ISD::ATOMIC_LOAD_OR:
11795 Opc = X86ISD::ATOMOR64_DAG;
11797 case ISD::ATOMIC_LOAD_SUB:
11798 Opc = X86ISD::ATOMSUB64_DAG;
11800 case ISD::ATOMIC_LOAD_XOR:
11801 Opc = X86ISD::ATOMXOR64_DAG;
11803 case ISD::ATOMIC_LOAD_MAX:
11804 Opc = X86ISD::ATOMMAX64_DAG;
11806 case ISD::ATOMIC_LOAD_MIN:
11807 Opc = X86ISD::ATOMMIN64_DAG;
11809 case ISD::ATOMIC_LOAD_UMAX:
11810 Opc = X86ISD::ATOMUMAX64_DAG;
11812 case ISD::ATOMIC_LOAD_UMIN:
11813 Opc = X86ISD::ATOMUMIN64_DAG;
11815 case ISD::ATOMIC_SWAP:
11816 Opc = X86ISD::ATOMSWAP64_DAG;
11819 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11822 case ISD::ATOMIC_LOAD:
11823 ReplaceATOMIC_LOAD(N, Results, DAG);
11827 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11829 default: return NULL;
11830 case X86ISD::BSF: return "X86ISD::BSF";
11831 case X86ISD::BSR: return "X86ISD::BSR";
11832 case X86ISD::SHLD: return "X86ISD::SHLD";
11833 case X86ISD::SHRD: return "X86ISD::SHRD";
11834 case X86ISD::FAND: return "X86ISD::FAND";
11835 case X86ISD::FOR: return "X86ISD::FOR";
11836 case X86ISD::FXOR: return "X86ISD::FXOR";
11837 case X86ISD::FSRL: return "X86ISD::FSRL";
11838 case X86ISD::FILD: return "X86ISD::FILD";
11839 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11840 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11841 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11842 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11843 case X86ISD::FLD: return "X86ISD::FLD";
11844 case X86ISD::FST: return "X86ISD::FST";
11845 case X86ISD::CALL: return "X86ISD::CALL";
11846 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11847 case X86ISD::BT: return "X86ISD::BT";
11848 case X86ISD::CMP: return "X86ISD::CMP";
11849 case X86ISD::COMI: return "X86ISD::COMI";
11850 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11851 case X86ISD::SETCC: return "X86ISD::SETCC";
11852 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11853 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11854 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11855 case X86ISD::CMOV: return "X86ISD::CMOV";
11856 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11857 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11858 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11859 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11860 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11861 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11862 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11863 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11864 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11865 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11866 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11867 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11868 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11869 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11870 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11871 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11872 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11873 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11874 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11875 case X86ISD::HADD: return "X86ISD::HADD";
11876 case X86ISD::HSUB: return "X86ISD::HSUB";
11877 case X86ISD::FHADD: return "X86ISD::FHADD";
11878 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11879 case X86ISD::FMAX: return "X86ISD::FMAX";
11880 case X86ISD::FMIN: return "X86ISD::FMIN";
11881 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11882 case X86ISD::FMINC: return "X86ISD::FMINC";
11883 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11884 case X86ISD::FRCP: return "X86ISD::FRCP";
11885 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11886 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11887 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11888 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11889 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11890 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11891 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11892 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11893 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11894 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11895 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11896 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11897 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11898 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11899 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11900 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11901 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11902 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11903 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11904 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11905 case X86ISD::VZEXT: return "X86ISD::VZEXT";
11906 case X86ISD::VSEXT: return "X86ISD::VSEXT";
11907 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11908 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11909 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11910 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11911 case X86ISD::VSHL: return "X86ISD::VSHL";
11912 case X86ISD::VSRL: return "X86ISD::VSRL";
11913 case X86ISD::VSRA: return "X86ISD::VSRA";
11914 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11915 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11916 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11917 case X86ISD::CMPP: return "X86ISD::CMPP";
11918 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11919 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11920 case X86ISD::ADD: return "X86ISD::ADD";
11921 case X86ISD::SUB: return "X86ISD::SUB";
11922 case X86ISD::ADC: return "X86ISD::ADC";
11923 case X86ISD::SBB: return "X86ISD::SBB";
11924 case X86ISD::SMUL: return "X86ISD::SMUL";
11925 case X86ISD::UMUL: return "X86ISD::UMUL";
11926 case X86ISD::INC: return "X86ISD::INC";
11927 case X86ISD::DEC: return "X86ISD::DEC";
11928 case X86ISD::OR: return "X86ISD::OR";
11929 case X86ISD::XOR: return "X86ISD::XOR";
11930 case X86ISD::AND: return "X86ISD::AND";
11931 case X86ISD::ANDN: return "X86ISD::ANDN";
11932 case X86ISD::BLSI: return "X86ISD::BLSI";
11933 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11934 case X86ISD::BLSR: return "X86ISD::BLSR";
11935 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11936 case X86ISD::PTEST: return "X86ISD::PTEST";
11937 case X86ISD::TESTP: return "X86ISD::TESTP";
11938 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11939 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11940 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11941 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11942 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11943 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11944 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11945 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11946 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11947 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11948 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11949 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11950 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11951 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11952 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11953 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11954 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11955 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11956 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11957 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11958 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11959 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11960 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11961 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11962 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11963 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11964 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11965 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11966 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11967 case X86ISD::SAHF: return "X86ISD::SAHF";
11968 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11969 case X86ISD::FMADD: return "X86ISD::FMADD";
11970 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11971 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11972 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11973 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11974 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11978 // isLegalAddressingMode - Return true if the addressing mode represented
11979 // by AM is legal for this target, for a load/store of the specified type.
11980 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11982 // X86 supports extremely general addressing modes.
11983 CodeModel::Model M = getTargetMachine().getCodeModel();
11984 Reloc::Model R = getTargetMachine().getRelocationModel();
11986 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11987 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11992 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11994 // If a reference to this global requires an extra load, we can't fold it.
11995 if (isGlobalStubReference(GVFlags))
11998 // If BaseGV requires a register for the PIC base, we cannot also have a
11999 // BaseReg specified.
12000 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12003 // If lower 4G is not available, then we must use rip-relative addressing.
12004 if ((M != CodeModel::Small || R != Reloc::Static) &&
12005 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12009 switch (AM.Scale) {
12015 // These scales always work.
12020 // These scales are formed with basereg+scalereg. Only accept if there is
12025 default: // Other stuff never works.
12033 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12034 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12036 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12037 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12038 if (NumBits1 <= NumBits2)
12043 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12044 return Imm == (int32_t)Imm;
12047 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12048 // Can also use sub to handle negated immediates.
12049 return Imm == (int32_t)Imm;
12052 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12053 if (!VT1.isInteger() || !VT2.isInteger())
12055 unsigned NumBits1 = VT1.getSizeInBits();
12056 unsigned NumBits2 = VT2.getSizeInBits();
12057 if (NumBits1 <= NumBits2)
12062 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12063 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12064 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12067 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12068 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12069 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12072 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12073 // i16 instructions are longer (0x66 prefix) and potentially slower.
12074 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12077 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12078 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12079 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12080 /// are assumed to be legal.
12082 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12084 // Very little shuffling can be done for 64-bit vectors right now.
12085 if (VT.getSizeInBits() == 64)
12088 // FIXME: pshufb, blends, shifts.
12089 return (VT.getVectorNumElements() == 2 ||
12090 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12091 isMOVLMask(M, VT) ||
12092 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12093 isPSHUFDMask(M, VT) ||
12094 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12095 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12096 isPALIGNRMask(M, VT, Subtarget) ||
12097 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12098 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12099 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12100 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12104 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12106 unsigned NumElts = VT.getVectorNumElements();
12107 // FIXME: This collection of masks seems suspect.
12110 if (NumElts == 4 && VT.is128BitVector()) {
12111 return (isMOVLMask(Mask, VT) ||
12112 isCommutedMOVLMask(Mask, VT, true) ||
12113 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12114 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12119 //===----------------------------------------------------------------------===//
12120 // X86 Scheduler Hooks
12121 //===----------------------------------------------------------------------===//
12123 // private utility function
12125 // Get CMPXCHG opcode for the specified data type.
12126 static unsigned getCmpXChgOpcode(EVT VT) {
12127 switch (VT.getSimpleVT().SimpleTy) {
12128 case MVT::i8: return X86::LCMPXCHG8;
12129 case MVT::i16: return X86::LCMPXCHG16;
12130 case MVT::i32: return X86::LCMPXCHG32;
12131 case MVT::i64: return X86::LCMPXCHG64;
12135 llvm_unreachable("Invalid operand size!");
12138 // Get LOAD opcode for the specified data type.
12139 static unsigned getLoadOpcode(EVT VT) {
12140 switch (VT.getSimpleVT().SimpleTy) {
12141 case MVT::i8: return X86::MOV8rm;
12142 case MVT::i16: return X86::MOV16rm;
12143 case MVT::i32: return X86::MOV32rm;
12144 case MVT::i64: return X86::MOV64rm;
12148 llvm_unreachable("Invalid operand size!");
12151 // Get opcode of the non-atomic one from the specified atomic instruction.
12152 static unsigned getNonAtomicOpcode(unsigned Opc) {
12154 case X86::ATOMAND8: return X86::AND8rr;
12155 case X86::ATOMAND16: return X86::AND16rr;
12156 case X86::ATOMAND32: return X86::AND32rr;
12157 case X86::ATOMAND64: return X86::AND64rr;
12158 case X86::ATOMOR8: return X86::OR8rr;
12159 case X86::ATOMOR16: return X86::OR16rr;
12160 case X86::ATOMOR32: return X86::OR32rr;
12161 case X86::ATOMOR64: return X86::OR64rr;
12162 case X86::ATOMXOR8: return X86::XOR8rr;
12163 case X86::ATOMXOR16: return X86::XOR16rr;
12164 case X86::ATOMXOR32: return X86::XOR32rr;
12165 case X86::ATOMXOR64: return X86::XOR64rr;
12167 llvm_unreachable("Unhandled atomic-load-op opcode!");
12170 // Get opcode of the non-atomic one from the specified atomic instruction with
12172 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12173 unsigned &ExtraOpc) {
12175 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12176 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12177 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12178 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12179 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12180 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12181 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12182 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12183 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12184 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12185 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12186 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12187 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12188 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12189 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12190 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12191 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12192 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12193 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12194 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12196 llvm_unreachable("Unhandled atomic-load-op opcode!");
12199 // Get opcode of the non-atomic one from the specified atomic instruction for
12200 // 64-bit data type on 32-bit target.
12201 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12203 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12204 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12205 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12206 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12207 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12208 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12209 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12210 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12211 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12212 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12214 llvm_unreachable("Unhandled atomic-load-op opcode!");
12217 // Get opcode of the non-atomic one from the specified atomic instruction for
12218 // 64-bit data type on 32-bit target with extra opcode.
12219 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12221 unsigned &ExtraOpc) {
12223 case X86::ATOMNAND6432:
12224 ExtraOpc = X86::NOT32r;
12225 HiOpc = X86::AND32rr;
12226 return X86::AND32rr;
12228 llvm_unreachable("Unhandled atomic-load-op opcode!");
12231 // Get pseudo CMOV opcode from the specified data type.
12232 static unsigned getPseudoCMOVOpc(EVT VT) {
12233 switch (VT.getSimpleVT().SimpleTy) {
12234 case MVT::i8: return X86::CMOV_GR8;
12235 case MVT::i16: return X86::CMOV_GR16;
12236 case MVT::i32: return X86::CMOV_GR32;
12240 llvm_unreachable("Unknown CMOV opcode!");
12243 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12244 // They will be translated into a spin-loop or compare-exchange loop from
12247 // dst = atomic-fetch-op MI.addr, MI.val
12253 // EAX = LOAD MI.addr
12255 // t1 = OP MI.val, EAX
12256 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12261 MachineBasicBlock *
12262 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12263 MachineBasicBlock *MBB) const {
12264 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12265 DebugLoc DL = MI->getDebugLoc();
12267 MachineFunction *MF = MBB->getParent();
12268 MachineRegisterInfo &MRI = MF->getRegInfo();
12270 const BasicBlock *BB = MBB->getBasicBlock();
12271 MachineFunction::iterator I = MBB;
12274 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12275 "Unexpected number of operands");
12277 assert(MI->hasOneMemOperand() &&
12278 "Expected atomic-load-op to have one memoperand");
12280 // Memory Reference
12281 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12282 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12284 unsigned DstReg, SrcReg;
12285 unsigned MemOpndSlot;
12287 unsigned CurOp = 0;
12289 DstReg = MI->getOperand(CurOp++).getReg();
12290 MemOpndSlot = CurOp;
12291 CurOp += X86::AddrNumOperands;
12292 SrcReg = MI->getOperand(CurOp++).getReg();
12294 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12295 MVT::SimpleValueType VT = *RC->vt_begin();
12296 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12298 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12299 unsigned LOADOpc = getLoadOpcode(VT);
12301 // For the atomic load-arith operator, we generate
12304 // EAX = LOAD [MI.addr]
12306 // t1 = OP MI.val, EAX
12307 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12311 MachineBasicBlock *thisMBB = MBB;
12312 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12313 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12314 MF->insert(I, mainMBB);
12315 MF->insert(I, sinkMBB);
12317 MachineInstrBuilder MIB;
12319 // Transfer the remainder of BB and its successor edges to sinkMBB.
12320 sinkMBB->splice(sinkMBB->begin(), MBB,
12321 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12322 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12325 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12326 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12327 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12328 MIB.setMemRefs(MMOBegin, MMOEnd);
12330 thisMBB->addSuccessor(mainMBB);
12333 MachineBasicBlock *origMainMBB = mainMBB;
12334 mainMBB->addLiveIn(AccPhyReg);
12336 // Copy AccPhyReg as it is used more than once.
12337 unsigned AccReg = MRI.createVirtualRegister(RC);
12338 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12339 .addReg(AccPhyReg);
12341 unsigned t1 = MRI.createVirtualRegister(RC);
12342 unsigned Opc = MI->getOpcode();
12345 llvm_unreachable("Unhandled atomic-load-op opcode!");
12346 case X86::ATOMAND8:
12347 case X86::ATOMAND16:
12348 case X86::ATOMAND32:
12349 case X86::ATOMAND64:
12351 case X86::ATOMOR16:
12352 case X86::ATOMOR32:
12353 case X86::ATOMOR64:
12354 case X86::ATOMXOR8:
12355 case X86::ATOMXOR16:
12356 case X86::ATOMXOR32:
12357 case X86::ATOMXOR64: {
12358 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12359 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12363 case X86::ATOMNAND8:
12364 case X86::ATOMNAND16:
12365 case X86::ATOMNAND32:
12366 case X86::ATOMNAND64: {
12367 unsigned t2 = MRI.createVirtualRegister(RC);
12369 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12370 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12372 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12375 case X86::ATOMMAX8:
12376 case X86::ATOMMAX16:
12377 case X86::ATOMMAX32:
12378 case X86::ATOMMAX64:
12379 case X86::ATOMMIN8:
12380 case X86::ATOMMIN16:
12381 case X86::ATOMMIN32:
12382 case X86::ATOMMIN64:
12383 case X86::ATOMUMAX8:
12384 case X86::ATOMUMAX16:
12385 case X86::ATOMUMAX32:
12386 case X86::ATOMUMAX64:
12387 case X86::ATOMUMIN8:
12388 case X86::ATOMUMIN16:
12389 case X86::ATOMUMIN32:
12390 case X86::ATOMUMIN64: {
12392 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12394 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12398 if (Subtarget->hasCMov()) {
12399 if (VT != MVT::i8) {
12401 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12405 // Promote i8 to i32 to use CMOV32
12406 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12407 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12408 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12409 unsigned t2 = MRI.createVirtualRegister(RC32);
12411 unsigned Undef = MRI.createVirtualRegister(RC32);
12412 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12414 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12417 .addImm(X86::sub_8bit);
12418 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12421 .addImm(X86::sub_8bit);
12423 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12427 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12428 .addReg(t2, 0, X86::sub_8bit);
12431 // Use pseudo select and lower them.
12432 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12433 "Invalid atomic-load-op transformation!");
12434 unsigned SelOpc = getPseudoCMOVOpc(VT);
12435 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12436 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12437 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12438 .addReg(SrcReg).addReg(AccReg)
12440 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12446 // Copy AccPhyReg back from virtual register.
12447 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12450 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12451 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12452 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12454 MIB.setMemRefs(MMOBegin, MMOEnd);
12456 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12458 mainMBB->addSuccessor(origMainMBB);
12459 mainMBB->addSuccessor(sinkMBB);
12462 sinkMBB->addLiveIn(AccPhyReg);
12464 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12465 TII->get(TargetOpcode::COPY), DstReg)
12466 .addReg(AccPhyReg);
12468 MI->eraseFromParent();
12472 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12473 // instructions. They will be translated into a spin-loop or compare-exchange
12477 // dst = atomic-fetch-op MI.addr, MI.val
12483 // EAX = LOAD [MI.addr + 0]
12484 // EDX = LOAD [MI.addr + 4]
12486 // EBX = OP MI.val.lo, EAX
12487 // ECX = OP MI.val.hi, EDX
12488 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12493 MachineBasicBlock *
12494 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12495 MachineBasicBlock *MBB) const {
12496 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12497 DebugLoc DL = MI->getDebugLoc();
12499 MachineFunction *MF = MBB->getParent();
12500 MachineRegisterInfo &MRI = MF->getRegInfo();
12502 const BasicBlock *BB = MBB->getBasicBlock();
12503 MachineFunction::iterator I = MBB;
12506 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12507 "Unexpected number of operands");
12509 assert(MI->hasOneMemOperand() &&
12510 "Expected atomic-load-op32 to have one memoperand");
12512 // Memory Reference
12513 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12514 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12516 unsigned DstLoReg, DstHiReg;
12517 unsigned SrcLoReg, SrcHiReg;
12518 unsigned MemOpndSlot;
12520 unsigned CurOp = 0;
12522 DstLoReg = MI->getOperand(CurOp++).getReg();
12523 DstHiReg = MI->getOperand(CurOp++).getReg();
12524 MemOpndSlot = CurOp;
12525 CurOp += X86::AddrNumOperands;
12526 SrcLoReg = MI->getOperand(CurOp++).getReg();
12527 SrcHiReg = MI->getOperand(CurOp++).getReg();
12529 const TargetRegisterClass *RC = &X86::GR32RegClass;
12530 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12532 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12533 unsigned LOADOpc = X86::MOV32rm;
12535 // For the atomic load-arith operator, we generate
12538 // EAX = LOAD [MI.addr + 0]
12539 // EDX = LOAD [MI.addr + 4]
12541 // EBX = OP MI.vallo, EAX
12542 // ECX = OP MI.valhi, EDX
12543 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12547 MachineBasicBlock *thisMBB = MBB;
12548 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12549 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12550 MF->insert(I, mainMBB);
12551 MF->insert(I, sinkMBB);
12553 MachineInstrBuilder MIB;
12555 // Transfer the remainder of BB and its successor edges to sinkMBB.
12556 sinkMBB->splice(sinkMBB->begin(), MBB,
12557 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12558 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12562 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12563 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12564 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12565 MIB.setMemRefs(MMOBegin, MMOEnd);
12567 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12568 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12569 if (i == X86::AddrDisp)
12570 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12572 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12574 MIB.setMemRefs(MMOBegin, MMOEnd);
12576 thisMBB->addSuccessor(mainMBB);
12579 MachineBasicBlock *origMainMBB = mainMBB;
12580 mainMBB->addLiveIn(X86::EAX);
12581 mainMBB->addLiveIn(X86::EDX);
12583 // Copy EDX:EAX as they are used more than once.
12584 unsigned LoReg = MRI.createVirtualRegister(RC);
12585 unsigned HiReg = MRI.createVirtualRegister(RC);
12586 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12587 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12589 unsigned t1L = MRI.createVirtualRegister(RC);
12590 unsigned t1H = MRI.createVirtualRegister(RC);
12592 unsigned Opc = MI->getOpcode();
12595 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12596 case X86::ATOMAND6432:
12597 case X86::ATOMOR6432:
12598 case X86::ATOMXOR6432:
12599 case X86::ATOMADD6432:
12600 case X86::ATOMSUB6432: {
12602 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12603 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12604 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12607 case X86::ATOMNAND6432: {
12608 unsigned HiOpc, NOTOpc;
12609 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12610 unsigned t2L = MRI.createVirtualRegister(RC);
12611 unsigned t2H = MRI.createVirtualRegister(RC);
12612 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12613 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12614 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12615 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12618 case X86::ATOMMAX6432:
12619 case X86::ATOMMIN6432:
12620 case X86::ATOMUMAX6432:
12621 case X86::ATOMUMIN6432: {
12623 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12624 unsigned cL = MRI.createVirtualRegister(RC8);
12625 unsigned cH = MRI.createVirtualRegister(RC8);
12626 unsigned cL32 = MRI.createVirtualRegister(RC);
12627 unsigned cH32 = MRI.createVirtualRegister(RC);
12628 unsigned cc = MRI.createVirtualRegister(RC);
12629 // cl := cmp src_lo, lo
12630 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12631 .addReg(SrcLoReg).addReg(LoReg);
12632 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12633 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12634 // ch := cmp src_hi, hi
12635 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12636 .addReg(SrcHiReg).addReg(HiReg);
12637 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12638 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12639 // cc := if (src_hi == hi) ? cl : ch;
12640 if (Subtarget->hasCMov()) {
12641 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12642 .addReg(cH32).addReg(cL32);
12644 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12645 .addReg(cH32).addReg(cL32)
12646 .addImm(X86::COND_E);
12647 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12649 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12650 if (Subtarget->hasCMov()) {
12651 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12652 .addReg(SrcLoReg).addReg(LoReg);
12653 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12654 .addReg(SrcHiReg).addReg(HiReg);
12656 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12657 .addReg(SrcLoReg).addReg(LoReg)
12658 .addImm(X86::COND_NE);
12659 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12660 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12661 .addReg(SrcHiReg).addReg(HiReg)
12662 .addImm(X86::COND_NE);
12663 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12667 case X86::ATOMSWAP6432: {
12669 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12670 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12671 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12676 // Copy EDX:EAX back from HiReg:LoReg
12677 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12678 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12679 // Copy ECX:EBX from t1H:t1L
12680 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12681 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12683 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12684 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12685 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12686 MIB.setMemRefs(MMOBegin, MMOEnd);
12688 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12690 mainMBB->addSuccessor(origMainMBB);
12691 mainMBB->addSuccessor(sinkMBB);
12694 sinkMBB->addLiveIn(X86::EAX);
12695 sinkMBB->addLiveIn(X86::EDX);
12697 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12698 TII->get(TargetOpcode::COPY), DstLoReg)
12700 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12701 TII->get(TargetOpcode::COPY), DstHiReg)
12704 MI->eraseFromParent();
12708 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12709 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12710 // in the .td file.
12711 MachineBasicBlock *
12712 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12713 unsigned numArgs, bool memArg) const {
12714 assert(Subtarget->hasSSE42() &&
12715 "Target must have SSE4.2 or AVX features enabled");
12717 DebugLoc dl = MI->getDebugLoc();
12718 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12720 if (!Subtarget->hasAVX()) {
12722 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12724 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12727 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12729 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12732 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12733 for (unsigned i = 0; i < numArgs; ++i) {
12734 MachineOperand &Op = MI->getOperand(i+1);
12735 if (!(Op.isReg() && Op.isImplicit()))
12736 MIB.addOperand(Op);
12738 BuildMI(*BB, MI, dl,
12739 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12740 .addReg(X86::XMM0);
12742 MI->eraseFromParent();
12746 MachineBasicBlock *
12747 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12748 DebugLoc dl = MI->getDebugLoc();
12749 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12751 // Address into RAX/EAX, other two args into ECX, EDX.
12752 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12753 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12754 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12755 for (int i = 0; i < X86::AddrNumOperands; ++i)
12756 MIB.addOperand(MI->getOperand(i));
12758 unsigned ValOps = X86::AddrNumOperands;
12759 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12760 .addReg(MI->getOperand(ValOps).getReg());
12761 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12762 .addReg(MI->getOperand(ValOps+1).getReg());
12764 // The instruction doesn't actually take any operands though.
12765 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12767 MI->eraseFromParent(); // The pseudo is gone now.
12771 MachineBasicBlock *
12772 X86TargetLowering::EmitVAARG64WithCustomInserter(
12774 MachineBasicBlock *MBB) const {
12775 // Emit va_arg instruction on X86-64.
12777 // Operands to this pseudo-instruction:
12778 // 0 ) Output : destination address (reg)
12779 // 1-5) Input : va_list address (addr, i64mem)
12780 // 6 ) ArgSize : Size (in bytes) of vararg type
12781 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12782 // 8 ) Align : Alignment of type
12783 // 9 ) EFLAGS (implicit-def)
12785 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12786 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12788 unsigned DestReg = MI->getOperand(0).getReg();
12789 MachineOperand &Base = MI->getOperand(1);
12790 MachineOperand &Scale = MI->getOperand(2);
12791 MachineOperand &Index = MI->getOperand(3);
12792 MachineOperand &Disp = MI->getOperand(4);
12793 MachineOperand &Segment = MI->getOperand(5);
12794 unsigned ArgSize = MI->getOperand(6).getImm();
12795 unsigned ArgMode = MI->getOperand(7).getImm();
12796 unsigned Align = MI->getOperand(8).getImm();
12798 // Memory Reference
12799 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12800 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12801 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12803 // Machine Information
12804 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12805 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12806 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12807 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12808 DebugLoc DL = MI->getDebugLoc();
12810 // struct va_list {
12813 // i64 overflow_area (address)
12814 // i64 reg_save_area (address)
12816 // sizeof(va_list) = 24
12817 // alignment(va_list) = 8
12819 unsigned TotalNumIntRegs = 6;
12820 unsigned TotalNumXMMRegs = 8;
12821 bool UseGPOffset = (ArgMode == 1);
12822 bool UseFPOffset = (ArgMode == 2);
12823 unsigned MaxOffset = TotalNumIntRegs * 8 +
12824 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12826 /* Align ArgSize to a multiple of 8 */
12827 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12828 bool NeedsAlign = (Align > 8);
12830 MachineBasicBlock *thisMBB = MBB;
12831 MachineBasicBlock *overflowMBB;
12832 MachineBasicBlock *offsetMBB;
12833 MachineBasicBlock *endMBB;
12835 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12836 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12837 unsigned OffsetReg = 0;
12839 if (!UseGPOffset && !UseFPOffset) {
12840 // If we only pull from the overflow region, we don't create a branch.
12841 // We don't need to alter control flow.
12842 OffsetDestReg = 0; // unused
12843 OverflowDestReg = DestReg;
12846 overflowMBB = thisMBB;
12849 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12850 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12851 // If not, pull from overflow_area. (branch to overflowMBB)
12856 // offsetMBB overflowMBB
12861 // Registers for the PHI in endMBB
12862 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12863 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12865 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12866 MachineFunction *MF = MBB->getParent();
12867 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12868 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12869 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12871 MachineFunction::iterator MBBIter = MBB;
12874 // Insert the new basic blocks
12875 MF->insert(MBBIter, offsetMBB);
12876 MF->insert(MBBIter, overflowMBB);
12877 MF->insert(MBBIter, endMBB);
12879 // Transfer the remainder of MBB and its successor edges to endMBB.
12880 endMBB->splice(endMBB->begin(), thisMBB,
12881 llvm::next(MachineBasicBlock::iterator(MI)),
12883 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12885 // Make offsetMBB and overflowMBB successors of thisMBB
12886 thisMBB->addSuccessor(offsetMBB);
12887 thisMBB->addSuccessor(overflowMBB);
12889 // endMBB is a successor of both offsetMBB and overflowMBB
12890 offsetMBB->addSuccessor(endMBB);
12891 overflowMBB->addSuccessor(endMBB);
12893 // Load the offset value into a register
12894 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12895 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12899 .addDisp(Disp, UseFPOffset ? 4 : 0)
12900 .addOperand(Segment)
12901 .setMemRefs(MMOBegin, MMOEnd);
12903 // Check if there is enough room left to pull this argument.
12904 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12906 .addImm(MaxOffset + 8 - ArgSizeA8);
12908 // Branch to "overflowMBB" if offset >= max
12909 // Fall through to "offsetMBB" otherwise
12910 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12911 .addMBB(overflowMBB);
12914 // In offsetMBB, emit code to use the reg_save_area.
12916 assert(OffsetReg != 0);
12918 // Read the reg_save_area address.
12919 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12920 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12925 .addOperand(Segment)
12926 .setMemRefs(MMOBegin, MMOEnd);
12928 // Zero-extend the offset
12929 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12930 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12933 .addImm(X86::sub_32bit);
12935 // Add the offset to the reg_save_area to get the final address.
12936 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12937 .addReg(OffsetReg64)
12938 .addReg(RegSaveReg);
12940 // Compute the offset for the next argument
12941 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12942 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12944 .addImm(UseFPOffset ? 16 : 8);
12946 // Store it back into the va_list.
12947 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12951 .addDisp(Disp, UseFPOffset ? 4 : 0)
12952 .addOperand(Segment)
12953 .addReg(NextOffsetReg)
12954 .setMemRefs(MMOBegin, MMOEnd);
12957 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12962 // Emit code to use overflow area
12965 // Load the overflow_area address into a register.
12966 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12967 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12972 .addOperand(Segment)
12973 .setMemRefs(MMOBegin, MMOEnd);
12975 // If we need to align it, do so. Otherwise, just copy the address
12976 // to OverflowDestReg.
12978 // Align the overflow address
12979 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12980 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12982 // aligned_addr = (addr + (align-1)) & ~(align-1)
12983 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12984 .addReg(OverflowAddrReg)
12987 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12989 .addImm(~(uint64_t)(Align-1));
12991 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12992 .addReg(OverflowAddrReg);
12995 // Compute the next overflow address after this argument.
12996 // (the overflow address should be kept 8-byte aligned)
12997 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12998 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12999 .addReg(OverflowDestReg)
13000 .addImm(ArgSizeA8);
13002 // Store the new overflow address.
13003 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13008 .addOperand(Segment)
13009 .addReg(NextAddrReg)
13010 .setMemRefs(MMOBegin, MMOEnd);
13012 // If we branched, emit the PHI to the front of endMBB.
13014 BuildMI(*endMBB, endMBB->begin(), DL,
13015 TII->get(X86::PHI), DestReg)
13016 .addReg(OffsetDestReg).addMBB(offsetMBB)
13017 .addReg(OverflowDestReg).addMBB(overflowMBB);
13020 // Erase the pseudo instruction
13021 MI->eraseFromParent();
13026 MachineBasicBlock *
13027 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13029 MachineBasicBlock *MBB) const {
13030 // Emit code to save XMM registers to the stack. The ABI says that the
13031 // number of registers to save is given in %al, so it's theoretically
13032 // possible to do an indirect jump trick to avoid saving all of them,
13033 // however this code takes a simpler approach and just executes all
13034 // of the stores if %al is non-zero. It's less code, and it's probably
13035 // easier on the hardware branch predictor, and stores aren't all that
13036 // expensive anyway.
13038 // Create the new basic blocks. One block contains all the XMM stores,
13039 // and one block is the final destination regardless of whether any
13040 // stores were performed.
13041 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13042 MachineFunction *F = MBB->getParent();
13043 MachineFunction::iterator MBBIter = MBB;
13045 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13046 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13047 F->insert(MBBIter, XMMSaveMBB);
13048 F->insert(MBBIter, EndMBB);
13050 // Transfer the remainder of MBB and its successor edges to EndMBB.
13051 EndMBB->splice(EndMBB->begin(), MBB,
13052 llvm::next(MachineBasicBlock::iterator(MI)),
13054 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13056 // The original block will now fall through to the XMM save block.
13057 MBB->addSuccessor(XMMSaveMBB);
13058 // The XMMSaveMBB will fall through to the end block.
13059 XMMSaveMBB->addSuccessor(EndMBB);
13061 // Now add the instructions.
13062 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13063 DebugLoc DL = MI->getDebugLoc();
13065 unsigned CountReg = MI->getOperand(0).getReg();
13066 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13067 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13069 if (!Subtarget->isTargetWin64()) {
13070 // If %al is 0, branch around the XMM save block.
13071 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13072 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13073 MBB->addSuccessor(EndMBB);
13076 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13077 // In the XMM save block, save all the XMM argument registers.
13078 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13079 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13080 MachineMemOperand *MMO =
13081 F->getMachineMemOperand(
13082 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13083 MachineMemOperand::MOStore,
13084 /*Size=*/16, /*Align=*/16);
13085 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13086 .addFrameIndex(RegSaveFrameIndex)
13087 .addImm(/*Scale=*/1)
13088 .addReg(/*IndexReg=*/0)
13089 .addImm(/*Disp=*/Offset)
13090 .addReg(/*Segment=*/0)
13091 .addReg(MI->getOperand(i).getReg())
13092 .addMemOperand(MMO);
13095 MI->eraseFromParent(); // The pseudo instruction is gone now.
13100 // The EFLAGS operand of SelectItr might be missing a kill marker
13101 // because there were multiple uses of EFLAGS, and ISel didn't know
13102 // which to mark. Figure out whether SelectItr should have had a
13103 // kill marker, and set it if it should. Returns the correct kill
13105 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13106 MachineBasicBlock* BB,
13107 const TargetRegisterInfo* TRI) {
13108 // Scan forward through BB for a use/def of EFLAGS.
13109 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13110 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13111 const MachineInstr& mi = *miI;
13112 if (mi.readsRegister(X86::EFLAGS))
13114 if (mi.definesRegister(X86::EFLAGS))
13115 break; // Should have kill-flag - update below.
13118 // If we hit the end of the block, check whether EFLAGS is live into a
13120 if (miI == BB->end()) {
13121 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13122 sEnd = BB->succ_end();
13123 sItr != sEnd; ++sItr) {
13124 MachineBasicBlock* succ = *sItr;
13125 if (succ->isLiveIn(X86::EFLAGS))
13130 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13131 // out. SelectMI should have a kill flag on EFLAGS.
13132 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13136 MachineBasicBlock *
13137 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13138 MachineBasicBlock *BB) const {
13139 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13140 DebugLoc DL = MI->getDebugLoc();
13142 // To "insert" a SELECT_CC instruction, we actually have to insert the
13143 // diamond control-flow pattern. The incoming instruction knows the
13144 // destination vreg to set, the condition code register to branch on, the
13145 // true/false values to select between, and a branch opcode to use.
13146 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13147 MachineFunction::iterator It = BB;
13153 // cmpTY ccX, r1, r2
13155 // fallthrough --> copy0MBB
13156 MachineBasicBlock *thisMBB = BB;
13157 MachineFunction *F = BB->getParent();
13158 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13159 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13160 F->insert(It, copy0MBB);
13161 F->insert(It, sinkMBB);
13163 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13164 // live into the sink and copy blocks.
13165 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13166 if (!MI->killsRegister(X86::EFLAGS) &&
13167 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13168 copy0MBB->addLiveIn(X86::EFLAGS);
13169 sinkMBB->addLiveIn(X86::EFLAGS);
13172 // Transfer the remainder of BB and its successor edges to sinkMBB.
13173 sinkMBB->splice(sinkMBB->begin(), BB,
13174 llvm::next(MachineBasicBlock::iterator(MI)),
13176 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13178 // Add the true and fallthrough blocks as its successors.
13179 BB->addSuccessor(copy0MBB);
13180 BB->addSuccessor(sinkMBB);
13182 // Create the conditional branch instruction.
13184 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13185 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13188 // %FalseValue = ...
13189 // # fallthrough to sinkMBB
13190 copy0MBB->addSuccessor(sinkMBB);
13193 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13195 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13196 TII->get(X86::PHI), MI->getOperand(0).getReg())
13197 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13198 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13200 MI->eraseFromParent(); // The pseudo instruction is gone now.
13204 MachineBasicBlock *
13205 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13206 bool Is64Bit) const {
13207 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13208 DebugLoc DL = MI->getDebugLoc();
13209 MachineFunction *MF = BB->getParent();
13210 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13212 assert(getTargetMachine().Options.EnableSegmentedStacks);
13214 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13215 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13218 // ... [Till the alloca]
13219 // If stacklet is not large enough, jump to mallocMBB
13222 // Allocate by subtracting from RSP
13223 // Jump to continueMBB
13226 // Allocate by call to runtime
13230 // [rest of original BB]
13233 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13234 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13235 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13237 MachineRegisterInfo &MRI = MF->getRegInfo();
13238 const TargetRegisterClass *AddrRegClass =
13239 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13241 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13242 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13243 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13244 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13245 sizeVReg = MI->getOperand(1).getReg(),
13246 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13248 MachineFunction::iterator MBBIter = BB;
13251 MF->insert(MBBIter, bumpMBB);
13252 MF->insert(MBBIter, mallocMBB);
13253 MF->insert(MBBIter, continueMBB);
13255 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13256 (MachineBasicBlock::iterator(MI)), BB->end());
13257 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13259 // Add code to the main basic block to check if the stack limit has been hit,
13260 // and if so, jump to mallocMBB otherwise to bumpMBB.
13261 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13262 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13263 .addReg(tmpSPVReg).addReg(sizeVReg);
13264 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13265 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13266 .addReg(SPLimitVReg);
13267 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13269 // bumpMBB simply decreases the stack pointer, since we know the current
13270 // stacklet has enough space.
13271 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13272 .addReg(SPLimitVReg);
13273 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13274 .addReg(SPLimitVReg);
13275 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13277 // Calls into a routine in libgcc to allocate more space from the heap.
13278 const uint32_t *RegMask =
13279 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13281 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13283 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13284 .addExternalSymbol("__morestack_allocate_stack_space")
13285 .addRegMask(RegMask)
13286 .addReg(X86::RDI, RegState::Implicit)
13287 .addReg(X86::RAX, RegState::ImplicitDefine);
13289 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13291 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13292 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13293 .addExternalSymbol("__morestack_allocate_stack_space")
13294 .addRegMask(RegMask)
13295 .addReg(X86::EAX, RegState::ImplicitDefine);
13299 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13302 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13303 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13304 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13306 // Set up the CFG correctly.
13307 BB->addSuccessor(bumpMBB);
13308 BB->addSuccessor(mallocMBB);
13309 mallocMBB->addSuccessor(continueMBB);
13310 bumpMBB->addSuccessor(continueMBB);
13312 // Take care of the PHI nodes.
13313 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13314 MI->getOperand(0).getReg())
13315 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13316 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13318 // Delete the original pseudo instruction.
13319 MI->eraseFromParent();
13322 return continueMBB;
13325 MachineBasicBlock *
13326 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13327 MachineBasicBlock *BB) const {
13328 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13329 DebugLoc DL = MI->getDebugLoc();
13331 assert(!Subtarget->isTargetEnvMacho());
13333 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13334 // non-trivial part is impdef of ESP.
13336 if (Subtarget->isTargetWin64()) {
13337 if (Subtarget->isTargetCygMing()) {
13338 // ___chkstk(Mingw64):
13339 // Clobbers R10, R11, RAX and EFLAGS.
13341 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13342 .addExternalSymbol("___chkstk")
13343 .addReg(X86::RAX, RegState::Implicit)
13344 .addReg(X86::RSP, RegState::Implicit)
13345 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13346 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13347 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13349 // __chkstk(MSVCRT): does not update stack pointer.
13350 // Clobbers R10, R11 and EFLAGS.
13351 // FIXME: RAX(allocated size) might be reused and not killed.
13352 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13353 .addExternalSymbol("__chkstk")
13354 .addReg(X86::RAX, RegState::Implicit)
13355 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13356 // RAX has the offset to subtracted from RSP.
13357 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13362 const char *StackProbeSymbol =
13363 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13365 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13366 .addExternalSymbol(StackProbeSymbol)
13367 .addReg(X86::EAX, RegState::Implicit)
13368 .addReg(X86::ESP, RegState::Implicit)
13369 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13370 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13371 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13374 MI->eraseFromParent(); // The pseudo instruction is gone now.
13378 MachineBasicBlock *
13379 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13380 MachineBasicBlock *BB) const {
13381 // This is pretty easy. We're taking the value that we received from
13382 // our load from the relocation, sticking it in either RDI (x86-64)
13383 // or EAX and doing an indirect call. The return value will then
13384 // be in the normal return register.
13385 const X86InstrInfo *TII
13386 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13387 DebugLoc DL = MI->getDebugLoc();
13388 MachineFunction *F = BB->getParent();
13390 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13391 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13393 // Get a register mask for the lowered call.
13394 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13395 // proper register mask.
13396 const uint32_t *RegMask =
13397 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13398 if (Subtarget->is64Bit()) {
13399 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13400 TII->get(X86::MOV64rm), X86::RDI)
13402 .addImm(0).addReg(0)
13403 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13404 MI->getOperand(3).getTargetFlags())
13406 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13407 addDirectMem(MIB, X86::RDI);
13408 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13409 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13410 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13411 TII->get(X86::MOV32rm), X86::EAX)
13413 .addImm(0).addReg(0)
13414 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13415 MI->getOperand(3).getTargetFlags())
13417 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13418 addDirectMem(MIB, X86::EAX);
13419 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13421 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13422 TII->get(X86::MOV32rm), X86::EAX)
13423 .addReg(TII->getGlobalBaseReg(F))
13424 .addImm(0).addReg(0)
13425 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13426 MI->getOperand(3).getTargetFlags())
13428 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13429 addDirectMem(MIB, X86::EAX);
13430 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13433 MI->eraseFromParent(); // The pseudo instruction is gone now.
13437 MachineBasicBlock *
13438 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13439 MachineBasicBlock *MBB) const {
13440 DebugLoc DL = MI->getDebugLoc();
13441 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13443 MachineFunction *MF = MBB->getParent();
13444 MachineRegisterInfo &MRI = MF->getRegInfo();
13446 const BasicBlock *BB = MBB->getBasicBlock();
13447 MachineFunction::iterator I = MBB;
13450 // Memory Reference
13451 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13452 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13455 unsigned MemOpndSlot = 0;
13457 unsigned CurOp = 0;
13459 DstReg = MI->getOperand(CurOp++).getReg();
13460 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13461 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13462 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13463 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13465 MemOpndSlot = CurOp;
13467 MVT PVT = getPointerTy();
13468 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13469 "Invalid Pointer Size!");
13471 // For v = setjmp(buf), we generate
13474 // buf[LabelOffset] = restoreMBB
13475 // SjLjSetup restoreMBB
13481 // v = phi(main, restore)
13486 MachineBasicBlock *thisMBB = MBB;
13487 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13488 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13489 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13490 MF->insert(I, mainMBB);
13491 MF->insert(I, sinkMBB);
13492 MF->push_back(restoreMBB);
13494 MachineInstrBuilder MIB;
13496 // Transfer the remainder of BB and its successor edges to sinkMBB.
13497 sinkMBB->splice(sinkMBB->begin(), MBB,
13498 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13499 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13502 unsigned PtrStoreOpc = 0;
13503 unsigned LabelReg = 0;
13504 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13505 Reloc::Model RM = getTargetMachine().getRelocationModel();
13506 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13507 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13509 // Prepare IP either in reg or imm.
13510 if (!UseImmLabel) {
13511 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13512 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13513 LabelReg = MRI.createVirtualRegister(PtrRC);
13514 if (Subtarget->is64Bit()) {
13515 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13519 .addMBB(restoreMBB)
13522 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13523 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13524 .addReg(XII->getGlobalBaseReg(MF))
13527 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13531 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13533 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13534 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13535 if (i == X86::AddrDisp)
13536 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13538 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13541 MIB.addReg(LabelReg);
13543 MIB.addMBB(restoreMBB);
13544 MIB.setMemRefs(MMOBegin, MMOEnd);
13546 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13547 .addMBB(restoreMBB);
13548 MIB.addRegMask(RegInfo->getNoPreservedMask());
13549 thisMBB->addSuccessor(mainMBB);
13550 thisMBB->addSuccessor(restoreMBB);
13554 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13555 mainMBB->addSuccessor(sinkMBB);
13558 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13559 TII->get(X86::PHI), DstReg)
13560 .addReg(mainDstReg).addMBB(mainMBB)
13561 .addReg(restoreDstReg).addMBB(restoreMBB);
13564 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13565 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13566 restoreMBB->addSuccessor(sinkMBB);
13568 MI->eraseFromParent();
13572 MachineBasicBlock *
13573 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13574 MachineBasicBlock *MBB) const {
13575 DebugLoc DL = MI->getDebugLoc();
13576 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13578 MachineFunction *MF = MBB->getParent();
13579 MachineRegisterInfo &MRI = MF->getRegInfo();
13581 // Memory Reference
13582 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13583 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13585 MVT PVT = getPointerTy();
13586 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13587 "Invalid Pointer Size!");
13589 const TargetRegisterClass *RC =
13590 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13591 unsigned Tmp = MRI.createVirtualRegister(RC);
13592 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13593 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13594 unsigned SP = RegInfo->getStackRegister();
13596 MachineInstrBuilder MIB;
13598 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13599 const int64_t SPOffset = 2 * PVT.getStoreSize();
13601 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13602 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13605 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13606 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13607 MIB.addOperand(MI->getOperand(i));
13608 MIB.setMemRefs(MMOBegin, MMOEnd);
13610 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13611 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13612 if (i == X86::AddrDisp)
13613 MIB.addDisp(MI->getOperand(i), LabelOffset);
13615 MIB.addOperand(MI->getOperand(i));
13617 MIB.setMemRefs(MMOBegin, MMOEnd);
13619 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13620 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13621 if (i == X86::AddrDisp)
13622 MIB.addDisp(MI->getOperand(i), SPOffset);
13624 MIB.addOperand(MI->getOperand(i));
13626 MIB.setMemRefs(MMOBegin, MMOEnd);
13628 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13630 MI->eraseFromParent();
13634 MachineBasicBlock *
13635 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13636 MachineBasicBlock *BB) const {
13637 switch (MI->getOpcode()) {
13638 default: llvm_unreachable("Unexpected instr type to insert");
13639 case X86::TAILJMPd64:
13640 case X86::TAILJMPr64:
13641 case X86::TAILJMPm64:
13642 llvm_unreachable("TAILJMP64 would not be touched here.");
13643 case X86::TCRETURNdi64:
13644 case X86::TCRETURNri64:
13645 case X86::TCRETURNmi64:
13647 case X86::WIN_ALLOCA:
13648 return EmitLoweredWinAlloca(MI, BB);
13649 case X86::SEG_ALLOCA_32:
13650 return EmitLoweredSegAlloca(MI, BB, false);
13651 case X86::SEG_ALLOCA_64:
13652 return EmitLoweredSegAlloca(MI, BB, true);
13653 case X86::TLSCall_32:
13654 case X86::TLSCall_64:
13655 return EmitLoweredTLSCall(MI, BB);
13656 case X86::CMOV_GR8:
13657 case X86::CMOV_FR32:
13658 case X86::CMOV_FR64:
13659 case X86::CMOV_V4F32:
13660 case X86::CMOV_V2F64:
13661 case X86::CMOV_V2I64:
13662 case X86::CMOV_V8F32:
13663 case X86::CMOV_V4F64:
13664 case X86::CMOV_V4I64:
13665 case X86::CMOV_GR16:
13666 case X86::CMOV_GR32:
13667 case X86::CMOV_RFP32:
13668 case X86::CMOV_RFP64:
13669 case X86::CMOV_RFP80:
13670 return EmitLoweredSelect(MI, BB);
13672 case X86::FP32_TO_INT16_IN_MEM:
13673 case X86::FP32_TO_INT32_IN_MEM:
13674 case X86::FP32_TO_INT64_IN_MEM:
13675 case X86::FP64_TO_INT16_IN_MEM:
13676 case X86::FP64_TO_INT32_IN_MEM:
13677 case X86::FP64_TO_INT64_IN_MEM:
13678 case X86::FP80_TO_INT16_IN_MEM:
13679 case X86::FP80_TO_INT32_IN_MEM:
13680 case X86::FP80_TO_INT64_IN_MEM: {
13681 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13682 DebugLoc DL = MI->getDebugLoc();
13684 // Change the floating point control register to use "round towards zero"
13685 // mode when truncating to an integer value.
13686 MachineFunction *F = BB->getParent();
13687 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13688 addFrameReference(BuildMI(*BB, MI, DL,
13689 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13691 // Load the old value of the high byte of the control word...
13693 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13694 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13697 // Set the high part to be round to zero...
13698 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13701 // Reload the modified control word now...
13702 addFrameReference(BuildMI(*BB, MI, DL,
13703 TII->get(X86::FLDCW16m)), CWFrameIdx);
13705 // Restore the memory image of control word to original value
13706 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13709 // Get the X86 opcode to use.
13711 switch (MI->getOpcode()) {
13712 default: llvm_unreachable("illegal opcode!");
13713 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13714 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13715 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13716 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13717 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13718 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13719 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13720 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13721 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13725 MachineOperand &Op = MI->getOperand(0);
13727 AM.BaseType = X86AddressMode::RegBase;
13728 AM.Base.Reg = Op.getReg();
13730 AM.BaseType = X86AddressMode::FrameIndexBase;
13731 AM.Base.FrameIndex = Op.getIndex();
13733 Op = MI->getOperand(1);
13735 AM.Scale = Op.getImm();
13736 Op = MI->getOperand(2);
13738 AM.IndexReg = Op.getImm();
13739 Op = MI->getOperand(3);
13740 if (Op.isGlobal()) {
13741 AM.GV = Op.getGlobal();
13743 AM.Disp = Op.getImm();
13745 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13746 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13748 // Reload the original control word now.
13749 addFrameReference(BuildMI(*BB, MI, DL,
13750 TII->get(X86::FLDCW16m)), CWFrameIdx);
13752 MI->eraseFromParent(); // The pseudo instruction is gone now.
13755 // String/text processing lowering.
13756 case X86::PCMPISTRM128REG:
13757 case X86::VPCMPISTRM128REG:
13758 case X86::PCMPISTRM128MEM:
13759 case X86::VPCMPISTRM128MEM:
13760 case X86::PCMPESTRM128REG:
13761 case X86::VPCMPESTRM128REG:
13762 case X86::PCMPESTRM128MEM:
13763 case X86::VPCMPESTRM128MEM: {
13766 switch (MI->getOpcode()) {
13767 default: llvm_unreachable("illegal opcode!");
13768 case X86::PCMPISTRM128REG:
13769 case X86::VPCMPISTRM128REG:
13770 NumArgs = 3; MemArg = false; break;
13771 case X86::PCMPISTRM128MEM:
13772 case X86::VPCMPISTRM128MEM:
13773 NumArgs = 3; MemArg = true; break;
13774 case X86::PCMPESTRM128REG:
13775 case X86::VPCMPESTRM128REG:
13776 NumArgs = 5; MemArg = false; break;
13777 case X86::PCMPESTRM128MEM:
13778 case X86::VPCMPESTRM128MEM:
13779 NumArgs = 5; MemArg = true; break;
13781 return EmitPCMP(MI, BB, NumArgs, MemArg);
13784 // Thread synchronization.
13786 return EmitMonitor(MI, BB);
13788 // Atomic Lowering.
13789 case X86::ATOMAND8:
13790 case X86::ATOMAND16:
13791 case X86::ATOMAND32:
13792 case X86::ATOMAND64:
13795 case X86::ATOMOR16:
13796 case X86::ATOMOR32:
13797 case X86::ATOMOR64:
13799 case X86::ATOMXOR16:
13800 case X86::ATOMXOR8:
13801 case X86::ATOMXOR32:
13802 case X86::ATOMXOR64:
13804 case X86::ATOMNAND8:
13805 case X86::ATOMNAND16:
13806 case X86::ATOMNAND32:
13807 case X86::ATOMNAND64:
13809 case X86::ATOMMAX8:
13810 case X86::ATOMMAX16:
13811 case X86::ATOMMAX32:
13812 case X86::ATOMMAX64:
13814 case X86::ATOMMIN8:
13815 case X86::ATOMMIN16:
13816 case X86::ATOMMIN32:
13817 case X86::ATOMMIN64:
13819 case X86::ATOMUMAX8:
13820 case X86::ATOMUMAX16:
13821 case X86::ATOMUMAX32:
13822 case X86::ATOMUMAX64:
13824 case X86::ATOMUMIN8:
13825 case X86::ATOMUMIN16:
13826 case X86::ATOMUMIN32:
13827 case X86::ATOMUMIN64:
13828 return EmitAtomicLoadArith(MI, BB);
13830 // This group does 64-bit operations on a 32-bit host.
13831 case X86::ATOMAND6432:
13832 case X86::ATOMOR6432:
13833 case X86::ATOMXOR6432:
13834 case X86::ATOMNAND6432:
13835 case X86::ATOMADD6432:
13836 case X86::ATOMSUB6432:
13837 case X86::ATOMMAX6432:
13838 case X86::ATOMMIN6432:
13839 case X86::ATOMUMAX6432:
13840 case X86::ATOMUMIN6432:
13841 case X86::ATOMSWAP6432:
13842 return EmitAtomicLoadArith6432(MI, BB);
13844 case X86::VASTART_SAVE_XMM_REGS:
13845 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13847 case X86::VAARG_64:
13848 return EmitVAARG64WithCustomInserter(MI, BB);
13850 case X86::EH_SjLj_SetJmp32:
13851 case X86::EH_SjLj_SetJmp64:
13852 return emitEHSjLjSetJmp(MI, BB);
13854 case X86::EH_SjLj_LongJmp32:
13855 case X86::EH_SjLj_LongJmp64:
13856 return emitEHSjLjLongJmp(MI, BB);
13860 //===----------------------------------------------------------------------===//
13861 // X86 Optimization Hooks
13862 //===----------------------------------------------------------------------===//
13864 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13867 const SelectionDAG &DAG,
13868 unsigned Depth) const {
13869 unsigned BitWidth = KnownZero.getBitWidth();
13870 unsigned Opc = Op.getOpcode();
13871 assert((Opc >= ISD::BUILTIN_OP_END ||
13872 Opc == ISD::INTRINSIC_WO_CHAIN ||
13873 Opc == ISD::INTRINSIC_W_CHAIN ||
13874 Opc == ISD::INTRINSIC_VOID) &&
13875 "Should use MaskedValueIsZero if you don't know whether Op"
13876 " is a target node!");
13878 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13892 // These nodes' second result is a boolean.
13893 if (Op.getResNo() == 0)
13896 case X86ISD::SETCC:
13897 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13899 case ISD::INTRINSIC_WO_CHAIN: {
13900 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13901 unsigned NumLoBits = 0;
13904 case Intrinsic::x86_sse_movmsk_ps:
13905 case Intrinsic::x86_avx_movmsk_ps_256:
13906 case Intrinsic::x86_sse2_movmsk_pd:
13907 case Intrinsic::x86_avx_movmsk_pd_256:
13908 case Intrinsic::x86_mmx_pmovmskb:
13909 case Intrinsic::x86_sse2_pmovmskb_128:
13910 case Intrinsic::x86_avx2_pmovmskb: {
13911 // High bits of movmskp{s|d}, pmovmskb are known zero.
13913 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13914 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13915 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13916 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13917 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13918 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13919 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13920 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13922 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13931 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13932 unsigned Depth) const {
13933 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13934 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13935 return Op.getValueType().getScalarType().getSizeInBits();
13941 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13942 /// node is a GlobalAddress + offset.
13943 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13944 const GlobalValue* &GA,
13945 int64_t &Offset) const {
13946 if (N->getOpcode() == X86ISD::Wrapper) {
13947 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13948 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13949 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13953 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13956 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13957 /// same as extracting the high 128-bit part of 256-bit vector and then
13958 /// inserting the result into the low part of a new 256-bit vector
13959 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13960 EVT VT = SVOp->getValueType(0);
13961 unsigned NumElems = VT.getVectorNumElements();
13963 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13964 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13965 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13966 SVOp->getMaskElt(j) >= 0)
13972 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13973 /// same as extracting the low 128-bit part of 256-bit vector and then
13974 /// inserting the result into the high part of a new 256-bit vector
13975 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13976 EVT VT = SVOp->getValueType(0);
13977 unsigned NumElems = VT.getVectorNumElements();
13979 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13980 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13981 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13982 SVOp->getMaskElt(j) >= 0)
13988 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13989 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13990 TargetLowering::DAGCombinerInfo &DCI,
13991 const X86Subtarget* Subtarget) {
13992 DebugLoc dl = N->getDebugLoc();
13993 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13994 SDValue V1 = SVOp->getOperand(0);
13995 SDValue V2 = SVOp->getOperand(1);
13996 EVT VT = SVOp->getValueType(0);
13997 unsigned NumElems = VT.getVectorNumElements();
13999 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14000 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14004 // V UNDEF BUILD_VECTOR UNDEF
14006 // CONCAT_VECTOR CONCAT_VECTOR
14009 // RESULT: V + zero extended
14011 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14012 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14013 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14016 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14019 // To match the shuffle mask, the first half of the mask should
14020 // be exactly the first vector, and all the rest a splat with the
14021 // first element of the second one.
14022 for (unsigned i = 0; i != NumElems/2; ++i)
14023 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14024 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14027 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14028 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14029 if (Ld->hasNUsesOfValue(1, 0)) {
14030 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14031 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14033 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14035 Ld->getPointerInfo(),
14036 Ld->getAlignment(),
14037 false/*isVolatile*/, true/*ReadMem*/,
14038 false/*WriteMem*/);
14039 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14043 // Emit a zeroed vector and insert the desired subvector on its
14045 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14046 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14047 return DCI.CombineTo(N, InsV);
14050 //===--------------------------------------------------------------------===//
14051 // Combine some shuffles into subvector extracts and inserts:
14054 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14055 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14056 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14057 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14058 return DCI.CombineTo(N, InsV);
14061 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14062 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14063 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14064 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14065 return DCI.CombineTo(N, InsV);
14071 /// PerformShuffleCombine - Performs several different shuffle combines.
14072 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14073 TargetLowering::DAGCombinerInfo &DCI,
14074 const X86Subtarget *Subtarget) {
14075 DebugLoc dl = N->getDebugLoc();
14076 EVT VT = N->getValueType(0);
14078 // Don't create instructions with illegal types after legalize types has run.
14079 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14080 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14083 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14084 if (Subtarget->hasAVX() && VT.is256BitVector() &&
14085 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14086 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14088 // Only handle 128 wide vector from here on.
14089 if (!VT.is128BitVector())
14092 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14093 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14094 // consecutive, non-overlapping, and in the right order.
14095 SmallVector<SDValue, 16> Elts;
14096 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14097 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14099 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14103 /// PerformTruncateCombine - Converts truncate operation to
14104 /// a sequence of vector shuffle operations.
14105 /// It is possible when we truncate 256-bit vector to 128-bit vector
14106 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14107 TargetLowering::DAGCombinerInfo &DCI,
14108 const X86Subtarget *Subtarget) {
14109 if (!DCI.isBeforeLegalizeOps())
14112 if (!Subtarget->hasAVX())
14115 EVT VT = N->getValueType(0);
14116 SDValue Op = N->getOperand(0);
14117 EVT OpVT = Op.getValueType();
14118 DebugLoc dl = N->getDebugLoc();
14120 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14122 if (Subtarget->hasAVX2()) {
14123 // AVX2: v4i64 -> v4i32
14126 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14128 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14129 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14132 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14133 DAG.getIntPtrConstant(0));
14136 // AVX: v4i64 -> v4i32
14137 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14138 DAG.getIntPtrConstant(0));
14140 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14141 DAG.getIntPtrConstant(2));
14143 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14144 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14147 static const int ShufMask1[] = {0, 2, 0, 0};
14149 SDValue Undef = DAG.getUNDEF(VT);
14150 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14151 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14154 static const int ShufMask2[] = {0, 1, 4, 5};
14156 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14159 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14161 if (Subtarget->hasAVX2()) {
14162 // AVX2: v8i32 -> v8i16
14164 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14167 SmallVector<SDValue,32> pshufbMask;
14168 for (unsigned i = 0; i < 2; ++i) {
14169 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14170 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14171 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14172 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14173 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14174 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14175 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14176 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14177 for (unsigned j = 0; j < 8; ++j)
14178 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14180 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14181 &pshufbMask[0], 32);
14182 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14184 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14186 static const int ShufMask[] = {0, 2, -1, -1};
14187 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14190 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14191 DAG.getIntPtrConstant(0));
14193 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14196 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14197 DAG.getIntPtrConstant(0));
14199 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14200 DAG.getIntPtrConstant(4));
14202 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14203 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14206 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14207 -1, -1, -1, -1, -1, -1, -1, -1};
14209 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14210 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14211 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14213 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14214 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14217 static const int ShufMask2[] = {0, 1, 4, 5};
14219 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14220 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14226 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14227 /// specific shuffle of a load can be folded into a single element load.
14228 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14229 /// shuffles have been customed lowered so we need to handle those here.
14230 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14231 TargetLowering::DAGCombinerInfo &DCI) {
14232 if (DCI.isBeforeLegalizeOps())
14235 SDValue InVec = N->getOperand(0);
14236 SDValue EltNo = N->getOperand(1);
14238 if (!isa<ConstantSDNode>(EltNo))
14241 EVT VT = InVec.getValueType();
14243 bool HasShuffleIntoBitcast = false;
14244 if (InVec.getOpcode() == ISD::BITCAST) {
14245 // Don't duplicate a load with other uses.
14246 if (!InVec.hasOneUse())
14248 EVT BCVT = InVec.getOperand(0).getValueType();
14249 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14251 InVec = InVec.getOperand(0);
14252 HasShuffleIntoBitcast = true;
14255 if (!isTargetShuffle(InVec.getOpcode()))
14258 // Don't duplicate a load with other uses.
14259 if (!InVec.hasOneUse())
14262 SmallVector<int, 16> ShuffleMask;
14264 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14268 // Select the input vector, guarding against out of range extract vector.
14269 unsigned NumElems = VT.getVectorNumElements();
14270 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14271 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14272 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14273 : InVec.getOperand(1);
14275 // If inputs to shuffle are the same for both ops, then allow 2 uses
14276 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14278 if (LdNode.getOpcode() == ISD::BITCAST) {
14279 // Don't duplicate a load with other uses.
14280 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14283 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14284 LdNode = LdNode.getOperand(0);
14287 if (!ISD::isNormalLoad(LdNode.getNode()))
14290 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14292 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14295 if (HasShuffleIntoBitcast) {
14296 // If there's a bitcast before the shuffle, check if the load type and
14297 // alignment is valid.
14298 unsigned Align = LN0->getAlignment();
14299 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14300 unsigned NewAlign = TLI.getDataLayout()->
14301 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14303 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14307 // All checks match so transform back to vector_shuffle so that DAG combiner
14308 // can finish the job
14309 DebugLoc dl = N->getDebugLoc();
14311 // Create shuffle node taking into account the case that its a unary shuffle
14312 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14313 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14314 InVec.getOperand(0), Shuffle,
14316 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14317 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14321 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14322 /// generation and convert it from being a bunch of shuffles and extracts
14323 /// to a simple store and scalar loads to extract the elements.
14324 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14325 TargetLowering::DAGCombinerInfo &DCI) {
14326 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14327 if (NewOp.getNode())
14330 SDValue InputVector = N->getOperand(0);
14332 // Only operate on vectors of 4 elements, where the alternative shuffling
14333 // gets to be more expensive.
14334 if (InputVector.getValueType() != MVT::v4i32)
14337 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14338 // single use which is a sign-extend or zero-extend, and all elements are
14340 SmallVector<SDNode *, 4> Uses;
14341 unsigned ExtractedElements = 0;
14342 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14343 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14344 if (UI.getUse().getResNo() != InputVector.getResNo())
14347 SDNode *Extract = *UI;
14348 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14351 if (Extract->getValueType(0) != MVT::i32)
14353 if (!Extract->hasOneUse())
14355 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14356 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14358 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14361 // Record which element was extracted.
14362 ExtractedElements |=
14363 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14365 Uses.push_back(Extract);
14368 // If not all the elements were used, this may not be worthwhile.
14369 if (ExtractedElements != 15)
14372 // Ok, we've now decided to do the transformation.
14373 DebugLoc dl = InputVector.getDebugLoc();
14375 // Store the value to a temporary stack slot.
14376 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14377 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14378 MachinePointerInfo(), false, false, 0);
14380 // Replace each use (extract) with a load of the appropriate element.
14381 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14382 UE = Uses.end(); UI != UE; ++UI) {
14383 SDNode *Extract = *UI;
14385 // cOMpute the element's address.
14386 SDValue Idx = Extract->getOperand(1);
14388 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14389 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14390 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14391 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14393 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14394 StackPtr, OffsetVal);
14396 // Load the scalar.
14397 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14398 ScalarAddr, MachinePointerInfo(),
14399 false, false, false, 0);
14401 // Replace the exact with the load.
14402 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14405 // The replacement was made in place; don't return anything.
14409 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14411 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14412 TargetLowering::DAGCombinerInfo &DCI,
14413 const X86Subtarget *Subtarget) {
14414 DebugLoc DL = N->getDebugLoc();
14415 SDValue Cond = N->getOperand(0);
14416 // Get the LHS/RHS of the select.
14417 SDValue LHS = N->getOperand(1);
14418 SDValue RHS = N->getOperand(2);
14419 EVT VT = LHS.getValueType();
14421 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14422 // instructions match the semantics of the common C idiom x<y?x:y but not
14423 // x<=y?x:y, because of how they handle negative zero (which can be
14424 // ignored in unsafe-math mode).
14425 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14426 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14427 (Subtarget->hasSSE2() ||
14428 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14429 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14431 unsigned Opcode = 0;
14432 // Check for x CC y ? x : y.
14433 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14434 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14438 // Converting this to a min would handle NaNs incorrectly, and swapping
14439 // the operands would cause it to handle comparisons between positive
14440 // and negative zero incorrectly.
14441 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14442 if (!DAG.getTarget().Options.UnsafeFPMath &&
14443 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14445 std::swap(LHS, RHS);
14447 Opcode = X86ISD::FMIN;
14450 // Converting this to a min would handle comparisons between positive
14451 // and negative zero incorrectly.
14452 if (!DAG.getTarget().Options.UnsafeFPMath &&
14453 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14455 Opcode = X86ISD::FMIN;
14458 // Converting this to a min would handle both negative zeros and NaNs
14459 // incorrectly, but we can swap the operands to fix both.
14460 std::swap(LHS, RHS);
14464 Opcode = X86ISD::FMIN;
14468 // Converting this to a max would handle comparisons between positive
14469 // and negative zero incorrectly.
14470 if (!DAG.getTarget().Options.UnsafeFPMath &&
14471 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14473 Opcode = X86ISD::FMAX;
14476 // Converting this to a max would handle NaNs incorrectly, and swapping
14477 // the operands would cause it to handle comparisons between positive
14478 // and negative zero incorrectly.
14479 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14480 if (!DAG.getTarget().Options.UnsafeFPMath &&
14481 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14483 std::swap(LHS, RHS);
14485 Opcode = X86ISD::FMAX;
14488 // Converting this to a max would handle both negative zeros and NaNs
14489 // incorrectly, but we can swap the operands to fix both.
14490 std::swap(LHS, RHS);
14494 Opcode = X86ISD::FMAX;
14497 // Check for x CC y ? y : x -- a min/max with reversed arms.
14498 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14499 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14503 // Converting this to a min would handle comparisons between positive
14504 // and negative zero incorrectly, and swapping the operands would
14505 // cause it to handle NaNs incorrectly.
14506 if (!DAG.getTarget().Options.UnsafeFPMath &&
14507 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14508 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14510 std::swap(LHS, RHS);
14512 Opcode = X86ISD::FMIN;
14515 // Converting this to a min would handle NaNs incorrectly.
14516 if (!DAG.getTarget().Options.UnsafeFPMath &&
14517 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14519 Opcode = X86ISD::FMIN;
14522 // Converting this to a min would handle both negative zeros and NaNs
14523 // incorrectly, but we can swap the operands to fix both.
14524 std::swap(LHS, RHS);
14528 Opcode = X86ISD::FMIN;
14532 // Converting this to a max would handle NaNs incorrectly.
14533 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14535 Opcode = X86ISD::FMAX;
14538 // Converting this to a max would handle comparisons between positive
14539 // and negative zero incorrectly, and swapping the operands would
14540 // cause it to handle NaNs incorrectly.
14541 if (!DAG.getTarget().Options.UnsafeFPMath &&
14542 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14543 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14545 std::swap(LHS, RHS);
14547 Opcode = X86ISD::FMAX;
14550 // Converting this to a max would handle both negative zeros and NaNs
14551 // incorrectly, but we can swap the operands to fix both.
14552 std::swap(LHS, RHS);
14556 Opcode = X86ISD::FMAX;
14562 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14565 // If this is a select between two integer constants, try to do some
14567 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14568 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14569 // Don't do this for crazy integer types.
14570 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14571 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14572 // so that TrueC (the true value) is larger than FalseC.
14573 bool NeedsCondInvert = false;
14575 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14576 // Efficiently invertible.
14577 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14578 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14579 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14580 NeedsCondInvert = true;
14581 std::swap(TrueC, FalseC);
14584 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14585 if (FalseC->getAPIntValue() == 0 &&
14586 TrueC->getAPIntValue().isPowerOf2()) {
14587 if (NeedsCondInvert) // Invert the condition if needed.
14588 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14589 DAG.getConstant(1, Cond.getValueType()));
14591 // Zero extend the condition if needed.
14592 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14594 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14595 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14596 DAG.getConstant(ShAmt, MVT::i8));
14599 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14600 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14601 if (NeedsCondInvert) // Invert the condition if needed.
14602 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14603 DAG.getConstant(1, Cond.getValueType()));
14605 // Zero extend the condition if needed.
14606 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14607 FalseC->getValueType(0), Cond);
14608 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14609 SDValue(FalseC, 0));
14612 // Optimize cases that will turn into an LEA instruction. This requires
14613 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14614 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14615 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14616 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14618 bool isFastMultiplier = false;
14620 switch ((unsigned char)Diff) {
14622 case 1: // result = add base, cond
14623 case 2: // result = lea base( , cond*2)
14624 case 3: // result = lea base(cond, cond*2)
14625 case 4: // result = lea base( , cond*4)
14626 case 5: // result = lea base(cond, cond*4)
14627 case 8: // result = lea base( , cond*8)
14628 case 9: // result = lea base(cond, cond*8)
14629 isFastMultiplier = true;
14634 if (isFastMultiplier) {
14635 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14636 if (NeedsCondInvert) // Invert the condition if needed.
14637 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14638 DAG.getConstant(1, Cond.getValueType()));
14640 // Zero extend the condition if needed.
14641 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14643 // Scale the condition by the difference.
14645 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14646 DAG.getConstant(Diff, Cond.getValueType()));
14648 // Add the base if non-zero.
14649 if (FalseC->getAPIntValue() != 0)
14650 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14651 SDValue(FalseC, 0));
14658 // Canonicalize max and min:
14659 // (x > y) ? x : y -> (x >= y) ? x : y
14660 // (x < y) ? x : y -> (x <= y) ? x : y
14661 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14662 // the need for an extra compare
14663 // against zero. e.g.
14664 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14666 // testl %edi, %edi
14668 // cmovgl %edi, %eax
14672 // cmovsl %eax, %edi
14673 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14674 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14675 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14676 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14681 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14682 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14683 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14684 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14689 // If we know that this node is legal then we know that it is going to be
14690 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14691 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14692 // to simplify previous instructions.
14693 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14694 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14695 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14696 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14698 // Don't optimize vector selects that map to mask-registers.
14702 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14703 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14705 APInt KnownZero, KnownOne;
14706 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14707 DCI.isBeforeLegalizeOps());
14708 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14709 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14710 DCI.CommitTargetLoweringOpt(TLO);
14716 // Check whether a boolean test is testing a boolean value generated by
14717 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14720 // Simplify the following patterns:
14721 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14722 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14723 // to (Op EFLAGS Cond)
14725 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14726 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14727 // to (Op EFLAGS !Cond)
14729 // where Op could be BRCOND or CMOV.
14731 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14732 // Quit if not CMP and SUB with its value result used.
14733 if (Cmp.getOpcode() != X86ISD::CMP &&
14734 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14737 // Quit if not used as a boolean value.
14738 if (CC != X86::COND_E && CC != X86::COND_NE)
14741 // Check CMP operands. One of them should be 0 or 1 and the other should be
14742 // an SetCC or extended from it.
14743 SDValue Op1 = Cmp.getOperand(0);
14744 SDValue Op2 = Cmp.getOperand(1);
14747 const ConstantSDNode* C = 0;
14748 bool needOppositeCond = (CC == X86::COND_E);
14750 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14752 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14754 else // Quit if all operands are not constants.
14757 if (C->getZExtValue() == 1)
14758 needOppositeCond = !needOppositeCond;
14759 else if (C->getZExtValue() != 0)
14760 // Quit if the constant is neither 0 or 1.
14763 // Skip 'zext' node.
14764 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14765 SetCC = SetCC.getOperand(0);
14767 switch (SetCC.getOpcode()) {
14768 case X86ISD::SETCC:
14769 // Set the condition code or opposite one if necessary.
14770 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14771 if (needOppositeCond)
14772 CC = X86::GetOppositeBranchCondition(CC);
14773 return SetCC.getOperand(1);
14774 case X86ISD::CMOV: {
14775 // Check whether false/true value has canonical one, i.e. 0 or 1.
14776 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14777 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14778 // Quit if true value is not a constant.
14781 // Quit if false value is not a constant.
14783 // A special case for rdrand, where 0 is set if false cond is found.
14784 SDValue Op = SetCC.getOperand(0);
14785 if (Op.getOpcode() != X86ISD::RDRAND)
14788 // Quit if false value is not the constant 0 or 1.
14789 bool FValIsFalse = true;
14790 if (FVal && FVal->getZExtValue() != 0) {
14791 if (FVal->getZExtValue() != 1)
14793 // If FVal is 1, opposite cond is needed.
14794 needOppositeCond = !needOppositeCond;
14795 FValIsFalse = false;
14797 // Quit if TVal is not the constant opposite of FVal.
14798 if (FValIsFalse && TVal->getZExtValue() != 1)
14800 if (!FValIsFalse && TVal->getZExtValue() != 0)
14802 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14803 if (needOppositeCond)
14804 CC = X86::GetOppositeBranchCondition(CC);
14805 return SetCC.getOperand(3);
14812 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14813 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14814 TargetLowering::DAGCombinerInfo &DCI,
14815 const X86Subtarget *Subtarget) {
14816 DebugLoc DL = N->getDebugLoc();
14818 // If the flag operand isn't dead, don't touch this CMOV.
14819 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14822 SDValue FalseOp = N->getOperand(0);
14823 SDValue TrueOp = N->getOperand(1);
14824 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14825 SDValue Cond = N->getOperand(3);
14827 if (CC == X86::COND_E || CC == X86::COND_NE) {
14828 switch (Cond.getOpcode()) {
14832 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14833 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14834 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14840 Flags = checkBoolTestSetCCCombine(Cond, CC);
14841 if (Flags.getNode() &&
14842 // Extra check as FCMOV only supports a subset of X86 cond.
14843 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14844 SDValue Ops[] = { FalseOp, TrueOp,
14845 DAG.getConstant(CC, MVT::i8), Flags };
14846 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14847 Ops, array_lengthof(Ops));
14850 // If this is a select between two integer constants, try to do some
14851 // optimizations. Note that the operands are ordered the opposite of SELECT
14853 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14854 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14855 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14856 // larger than FalseC (the false value).
14857 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14858 CC = X86::GetOppositeBranchCondition(CC);
14859 std::swap(TrueC, FalseC);
14860 std::swap(TrueOp, FalseOp);
14863 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14864 // This is efficient for any integer data type (including i8/i16) and
14866 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14867 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14868 DAG.getConstant(CC, MVT::i8), Cond);
14870 // Zero extend the condition if needed.
14871 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14873 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14874 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14875 DAG.getConstant(ShAmt, MVT::i8));
14876 if (N->getNumValues() == 2) // Dead flag value?
14877 return DCI.CombineTo(N, Cond, SDValue());
14881 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14882 // for any integer data type, including i8/i16.
14883 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14884 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14885 DAG.getConstant(CC, MVT::i8), Cond);
14887 // Zero extend the condition if needed.
14888 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14889 FalseC->getValueType(0), Cond);
14890 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14891 SDValue(FalseC, 0));
14893 if (N->getNumValues() == 2) // Dead flag value?
14894 return DCI.CombineTo(N, Cond, SDValue());
14898 // Optimize cases that will turn into an LEA instruction. This requires
14899 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14900 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14901 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14902 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14904 bool isFastMultiplier = false;
14906 switch ((unsigned char)Diff) {
14908 case 1: // result = add base, cond
14909 case 2: // result = lea base( , cond*2)
14910 case 3: // result = lea base(cond, cond*2)
14911 case 4: // result = lea base( , cond*4)
14912 case 5: // result = lea base(cond, cond*4)
14913 case 8: // result = lea base( , cond*8)
14914 case 9: // result = lea base(cond, cond*8)
14915 isFastMultiplier = true;
14920 if (isFastMultiplier) {
14921 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14922 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14923 DAG.getConstant(CC, MVT::i8), Cond);
14924 // Zero extend the condition if needed.
14925 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14927 // Scale the condition by the difference.
14929 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14930 DAG.getConstant(Diff, Cond.getValueType()));
14932 // Add the base if non-zero.
14933 if (FalseC->getAPIntValue() != 0)
14934 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14935 SDValue(FalseC, 0));
14936 if (N->getNumValues() == 2) // Dead flag value?
14937 return DCI.CombineTo(N, Cond, SDValue());
14944 // Handle these cases:
14945 // (select (x != c), e, c) -> select (x != c), e, x),
14946 // (select (x == c), c, e) -> select (x == c), x, e)
14947 // where the c is an integer constant, and the "select" is the combination
14948 // of CMOV and CMP.
14950 // The rationale for this change is that the conditional-move from a constant
14951 // needs two instructions, however, conditional-move from a register needs
14952 // only one instruction.
14954 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14955 // some instruction-combining opportunities. This opt needs to be
14956 // postponed as late as possible.
14958 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14959 // the DCI.xxxx conditions are provided to postpone the optimization as
14960 // late as possible.
14962 ConstantSDNode *CmpAgainst = 0;
14963 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14964 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14965 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14967 if (CC == X86::COND_NE &&
14968 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14969 CC = X86::GetOppositeBranchCondition(CC);
14970 std::swap(TrueOp, FalseOp);
14973 if (CC == X86::COND_E &&
14974 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14975 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14976 DAG.getConstant(CC, MVT::i8), Cond };
14977 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14978 array_lengthof(Ops));
14987 /// PerformMulCombine - Optimize a single multiply with constant into two
14988 /// in order to implement it with two cheaper instructions, e.g.
14989 /// LEA + SHL, LEA + LEA.
14990 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14991 TargetLowering::DAGCombinerInfo &DCI) {
14992 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14995 EVT VT = N->getValueType(0);
14996 if (VT != MVT::i64)
14999 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15002 uint64_t MulAmt = C->getZExtValue();
15003 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15006 uint64_t MulAmt1 = 0;
15007 uint64_t MulAmt2 = 0;
15008 if ((MulAmt % 9) == 0) {
15010 MulAmt2 = MulAmt / 9;
15011 } else if ((MulAmt % 5) == 0) {
15013 MulAmt2 = MulAmt / 5;
15014 } else if ((MulAmt % 3) == 0) {
15016 MulAmt2 = MulAmt / 3;
15019 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15020 DebugLoc DL = N->getDebugLoc();
15022 if (isPowerOf2_64(MulAmt2) &&
15023 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15024 // If second multiplifer is pow2, issue it first. We want the multiply by
15025 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15027 std::swap(MulAmt1, MulAmt2);
15030 if (isPowerOf2_64(MulAmt1))
15031 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15032 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15034 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15035 DAG.getConstant(MulAmt1, VT));
15037 if (isPowerOf2_64(MulAmt2))
15038 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15039 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15041 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15042 DAG.getConstant(MulAmt2, VT));
15044 // Do not add new nodes to DAG combiner worklist.
15045 DCI.CombineTo(N, NewMul, false);
15050 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15051 SDValue N0 = N->getOperand(0);
15052 SDValue N1 = N->getOperand(1);
15053 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15054 EVT VT = N0.getValueType();
15056 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15057 // since the result of setcc_c is all zero's or all ones.
15058 if (VT.isInteger() && !VT.isVector() &&
15059 N1C && N0.getOpcode() == ISD::AND &&
15060 N0.getOperand(1).getOpcode() == ISD::Constant) {
15061 SDValue N00 = N0.getOperand(0);
15062 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15063 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15064 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15065 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15066 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15067 APInt ShAmt = N1C->getAPIntValue();
15068 Mask = Mask.shl(ShAmt);
15070 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15071 N00, DAG.getConstant(Mask, VT));
15076 // Hardware support for vector shifts is sparse which makes us scalarize the
15077 // vector operations in many cases. Also, on sandybridge ADD is faster than
15079 // (shl V, 1) -> add V,V
15080 if (isSplatVector(N1.getNode())) {
15081 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15082 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15083 // We shift all of the values by one. In many cases we do not have
15084 // hardware support for this operation. This is better expressed as an ADD
15086 if (N1C && (1 == N1C->getZExtValue())) {
15087 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15094 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15096 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15097 TargetLowering::DAGCombinerInfo &DCI,
15098 const X86Subtarget *Subtarget) {
15099 EVT VT = N->getValueType(0);
15100 if (N->getOpcode() == ISD::SHL) {
15101 SDValue V = PerformSHLCombine(N, DAG);
15102 if (V.getNode()) return V;
15105 // On X86 with SSE2 support, we can transform this to a vector shift if
15106 // all elements are shifted by the same amount. We can't do this in legalize
15107 // because the a constant vector is typically transformed to a constant pool
15108 // so we have no knowledge of the shift amount.
15109 if (!Subtarget->hasSSE2())
15112 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15113 (!Subtarget->hasAVX2() ||
15114 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15117 SDValue ShAmtOp = N->getOperand(1);
15118 EVT EltVT = VT.getVectorElementType();
15119 DebugLoc DL = N->getDebugLoc();
15120 SDValue BaseShAmt = SDValue();
15121 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15122 unsigned NumElts = VT.getVectorNumElements();
15124 for (; i != NumElts; ++i) {
15125 SDValue Arg = ShAmtOp.getOperand(i);
15126 if (Arg.getOpcode() == ISD::UNDEF) continue;
15130 // Handle the case where the build_vector is all undef
15131 // FIXME: Should DAG allow this?
15135 for (; i != NumElts; ++i) {
15136 SDValue Arg = ShAmtOp.getOperand(i);
15137 if (Arg.getOpcode() == ISD::UNDEF) continue;
15138 if (Arg != BaseShAmt) {
15142 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15143 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15144 SDValue InVec = ShAmtOp.getOperand(0);
15145 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15146 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15148 for (; i != NumElts; ++i) {
15149 SDValue Arg = InVec.getOperand(i);
15150 if (Arg.getOpcode() == ISD::UNDEF) continue;
15154 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15156 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15157 if (C->getZExtValue() == SplatIdx)
15158 BaseShAmt = InVec.getOperand(1);
15161 if (BaseShAmt.getNode() == 0) {
15162 // Don't create instructions with illegal types after legalize
15164 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15165 !DCI.isBeforeLegalize())
15168 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15169 DAG.getIntPtrConstant(0));
15174 // The shift amount is an i32.
15175 if (EltVT.bitsGT(MVT::i32))
15176 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15177 else if (EltVT.bitsLT(MVT::i32))
15178 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15180 // The shift amount is identical so we can do a vector shift.
15181 SDValue ValOp = N->getOperand(0);
15182 switch (N->getOpcode()) {
15184 llvm_unreachable("Unknown shift opcode!");
15186 switch (VT.getSimpleVT().SimpleTy) {
15187 default: return SDValue();
15194 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15197 switch (VT.getSimpleVT().SimpleTy) {
15198 default: return SDValue();
15203 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15206 switch (VT.getSimpleVT().SimpleTy) {
15207 default: return SDValue();
15214 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15220 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15221 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15222 // and friends. Likewise for OR -> CMPNEQSS.
15223 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15224 TargetLowering::DAGCombinerInfo &DCI,
15225 const X86Subtarget *Subtarget) {
15228 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15229 // we're requiring SSE2 for both.
15230 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15231 SDValue N0 = N->getOperand(0);
15232 SDValue N1 = N->getOperand(1);
15233 SDValue CMP0 = N0->getOperand(1);
15234 SDValue CMP1 = N1->getOperand(1);
15235 DebugLoc DL = N->getDebugLoc();
15237 // The SETCCs should both refer to the same CMP.
15238 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15241 SDValue CMP00 = CMP0->getOperand(0);
15242 SDValue CMP01 = CMP0->getOperand(1);
15243 EVT VT = CMP00.getValueType();
15245 if (VT == MVT::f32 || VT == MVT::f64) {
15246 bool ExpectingFlags = false;
15247 // Check for any users that want flags:
15248 for (SDNode::use_iterator UI = N->use_begin(),
15250 !ExpectingFlags && UI != UE; ++UI)
15251 switch (UI->getOpcode()) {
15256 ExpectingFlags = true;
15258 case ISD::CopyToReg:
15259 case ISD::SIGN_EXTEND:
15260 case ISD::ZERO_EXTEND:
15261 case ISD::ANY_EXTEND:
15265 if (!ExpectingFlags) {
15266 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15267 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15269 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15270 X86::CondCode tmp = cc0;
15275 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15276 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15277 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15278 X86ISD::NodeType NTOperator = is64BitFP ?
15279 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15280 // FIXME: need symbolic constants for these magic numbers.
15281 // See X86ATTInstPrinter.cpp:printSSECC().
15282 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15283 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15284 DAG.getConstant(x86cc, MVT::i8));
15285 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15287 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15288 DAG.getConstant(1, MVT::i32));
15289 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15290 return OneBitOfTruth;
15298 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15299 /// so it can be folded inside ANDNP.
15300 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15301 EVT VT = N->getValueType(0);
15303 // Match direct AllOnes for 128 and 256-bit vectors
15304 if (ISD::isBuildVectorAllOnes(N))
15307 // Look through a bit convert.
15308 if (N->getOpcode() == ISD::BITCAST)
15309 N = N->getOperand(0).getNode();
15311 // Sometimes the operand may come from a insert_subvector building a 256-bit
15313 if (VT.is256BitVector() &&
15314 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15315 SDValue V1 = N->getOperand(0);
15316 SDValue V2 = N->getOperand(1);
15318 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15319 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15320 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15321 ISD::isBuildVectorAllOnes(V2.getNode()))
15328 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15329 TargetLowering::DAGCombinerInfo &DCI,
15330 const X86Subtarget *Subtarget) {
15331 if (DCI.isBeforeLegalizeOps())
15334 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15338 EVT VT = N->getValueType(0);
15340 // Create ANDN, BLSI, and BLSR instructions
15341 // BLSI is X & (-X)
15342 // BLSR is X & (X-1)
15343 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15344 SDValue N0 = N->getOperand(0);
15345 SDValue N1 = N->getOperand(1);
15346 DebugLoc DL = N->getDebugLoc();
15348 // Check LHS for not
15349 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15350 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15351 // Check RHS for not
15352 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15353 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15355 // Check LHS for neg
15356 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15357 isZero(N0.getOperand(0)))
15358 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15360 // Check RHS for neg
15361 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15362 isZero(N1.getOperand(0)))
15363 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15365 // Check LHS for X-1
15366 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15367 isAllOnes(N0.getOperand(1)))
15368 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15370 // Check RHS for X-1
15371 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15372 isAllOnes(N1.getOperand(1)))
15373 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15378 // Want to form ANDNP nodes:
15379 // 1) In the hopes of then easily combining them with OR and AND nodes
15380 // to form PBLEND/PSIGN.
15381 // 2) To match ANDN packed intrinsics
15382 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15385 SDValue N0 = N->getOperand(0);
15386 SDValue N1 = N->getOperand(1);
15387 DebugLoc DL = N->getDebugLoc();
15389 // Check LHS for vnot
15390 if (N0.getOpcode() == ISD::XOR &&
15391 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15392 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15393 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15395 // Check RHS for vnot
15396 if (N1.getOpcode() == ISD::XOR &&
15397 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15398 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15399 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15404 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15405 TargetLowering::DAGCombinerInfo &DCI,
15406 const X86Subtarget *Subtarget) {
15407 if (DCI.isBeforeLegalizeOps())
15410 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15414 EVT VT = N->getValueType(0);
15416 SDValue N0 = N->getOperand(0);
15417 SDValue N1 = N->getOperand(1);
15419 // look for psign/blend
15420 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15421 if (!Subtarget->hasSSSE3() ||
15422 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15425 // Canonicalize pandn to RHS
15426 if (N0.getOpcode() == X86ISD::ANDNP)
15428 // or (and (m, y), (pandn m, x))
15429 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15430 SDValue Mask = N1.getOperand(0);
15431 SDValue X = N1.getOperand(1);
15433 if (N0.getOperand(0) == Mask)
15434 Y = N0.getOperand(1);
15435 if (N0.getOperand(1) == Mask)
15436 Y = N0.getOperand(0);
15438 // Check to see if the mask appeared in both the AND and ANDNP and
15442 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15443 // Look through mask bitcast.
15444 if (Mask.getOpcode() == ISD::BITCAST)
15445 Mask = Mask.getOperand(0);
15446 if (X.getOpcode() == ISD::BITCAST)
15447 X = X.getOperand(0);
15448 if (Y.getOpcode() == ISD::BITCAST)
15449 Y = Y.getOperand(0);
15451 EVT MaskVT = Mask.getValueType();
15453 // Validate that the Mask operand is a vector sra node.
15454 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15455 // there is no psrai.b
15456 if (Mask.getOpcode() != X86ISD::VSRAI)
15459 // Check that the SRA is all signbits.
15460 SDValue SraC = Mask.getOperand(1);
15461 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15462 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15463 if ((SraAmt + 1) != EltBits)
15466 DebugLoc DL = N->getDebugLoc();
15468 // Now we know we at least have a plendvb with the mask val. See if
15469 // we can form a psignb/w/d.
15470 // psign = x.type == y.type == mask.type && y = sub(0, x);
15471 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15472 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15473 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15474 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15475 "Unsupported VT for PSIGN");
15476 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15477 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15479 // PBLENDVB only available on SSE 4.1
15480 if (!Subtarget->hasSSE41())
15483 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15485 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15486 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15487 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15488 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15489 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15493 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15496 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15497 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15499 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15501 if (!N0.hasOneUse() || !N1.hasOneUse())
15504 SDValue ShAmt0 = N0.getOperand(1);
15505 if (ShAmt0.getValueType() != MVT::i8)
15507 SDValue ShAmt1 = N1.getOperand(1);
15508 if (ShAmt1.getValueType() != MVT::i8)
15510 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15511 ShAmt0 = ShAmt0.getOperand(0);
15512 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15513 ShAmt1 = ShAmt1.getOperand(0);
15515 DebugLoc DL = N->getDebugLoc();
15516 unsigned Opc = X86ISD::SHLD;
15517 SDValue Op0 = N0.getOperand(0);
15518 SDValue Op1 = N1.getOperand(0);
15519 if (ShAmt0.getOpcode() == ISD::SUB) {
15520 Opc = X86ISD::SHRD;
15521 std::swap(Op0, Op1);
15522 std::swap(ShAmt0, ShAmt1);
15525 unsigned Bits = VT.getSizeInBits();
15526 if (ShAmt1.getOpcode() == ISD::SUB) {
15527 SDValue Sum = ShAmt1.getOperand(0);
15528 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15529 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15530 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15531 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15532 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15533 return DAG.getNode(Opc, DL, VT,
15535 DAG.getNode(ISD::TRUNCATE, DL,
15538 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15539 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15541 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15542 return DAG.getNode(Opc, DL, VT,
15543 N0.getOperand(0), N1.getOperand(0),
15544 DAG.getNode(ISD::TRUNCATE, DL,
15551 // Generate NEG and CMOV for integer abs.
15552 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15553 EVT VT = N->getValueType(0);
15555 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15556 // 8-bit integer abs to NEG and CMOV.
15557 if (VT.isInteger() && VT.getSizeInBits() == 8)
15560 SDValue N0 = N->getOperand(0);
15561 SDValue N1 = N->getOperand(1);
15562 DebugLoc DL = N->getDebugLoc();
15564 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15565 // and change it to SUB and CMOV.
15566 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15567 N0.getOpcode() == ISD::ADD &&
15568 N0.getOperand(1) == N1 &&
15569 N1.getOpcode() == ISD::SRA &&
15570 N1.getOperand(0) == N0.getOperand(0))
15571 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15572 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15573 // Generate SUB & CMOV.
15574 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15575 DAG.getConstant(0, VT), N0.getOperand(0));
15577 SDValue Ops[] = { N0.getOperand(0), Neg,
15578 DAG.getConstant(X86::COND_GE, MVT::i8),
15579 SDValue(Neg.getNode(), 1) };
15580 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15581 Ops, array_lengthof(Ops));
15586 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15587 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15588 TargetLowering::DAGCombinerInfo &DCI,
15589 const X86Subtarget *Subtarget) {
15590 if (DCI.isBeforeLegalizeOps())
15593 if (Subtarget->hasCMov()) {
15594 SDValue RV = performIntegerAbsCombine(N, DAG);
15599 // Try forming BMI if it is available.
15600 if (!Subtarget->hasBMI())
15603 EVT VT = N->getValueType(0);
15605 if (VT != MVT::i32 && VT != MVT::i64)
15608 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15610 // Create BLSMSK instructions by finding X ^ (X-1)
15611 SDValue N0 = N->getOperand(0);
15612 SDValue N1 = N->getOperand(1);
15613 DebugLoc DL = N->getDebugLoc();
15615 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15616 isAllOnes(N0.getOperand(1)))
15617 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15619 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15620 isAllOnes(N1.getOperand(1)))
15621 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15626 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15627 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15628 TargetLowering::DAGCombinerInfo &DCI,
15629 const X86Subtarget *Subtarget) {
15630 LoadSDNode *Ld = cast<LoadSDNode>(N);
15631 EVT RegVT = Ld->getValueType(0);
15632 EVT MemVT = Ld->getMemoryVT();
15633 DebugLoc dl = Ld->getDebugLoc();
15634 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15636 ISD::LoadExtType Ext = Ld->getExtensionType();
15638 // If this is a vector EXT Load then attempt to optimize it using a
15639 // shuffle. We need SSSE3 shuffles.
15640 // TODO: It is possible to support ZExt by zeroing the undef values
15641 // during the shuffle phase or after the shuffle.
15642 if (RegVT.isVector() && RegVT.isInteger() &&
15643 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15644 assert(MemVT != RegVT && "Cannot extend to the same type");
15645 assert(MemVT.isVector() && "Must load a vector from memory");
15647 unsigned NumElems = RegVT.getVectorNumElements();
15648 unsigned RegSz = RegVT.getSizeInBits();
15649 unsigned MemSz = MemVT.getSizeInBits();
15650 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15652 // All sizes must be a power of two.
15653 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15656 // Attempt to load the original value using scalar loads.
15657 // Find the largest scalar type that divides the total loaded size.
15658 MVT SclrLoadTy = MVT::i8;
15659 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15660 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15661 MVT Tp = (MVT::SimpleValueType)tp;
15662 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15667 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15668 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15670 SclrLoadTy = MVT::f64;
15672 // Calculate the number of scalar loads that we need to perform
15673 // in order to load our vector from memory.
15674 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15676 // Represent our vector as a sequence of elements which are the
15677 // largest scalar that we can load.
15678 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15679 RegSz/SclrLoadTy.getSizeInBits());
15681 // Represent the data using the same element type that is stored in
15682 // memory. In practice, we ''widen'' MemVT.
15683 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15684 RegSz/MemVT.getScalarType().getSizeInBits());
15686 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15687 "Invalid vector type");
15689 // We can't shuffle using an illegal type.
15690 if (!TLI.isTypeLegal(WideVecVT))
15693 SmallVector<SDValue, 8> Chains;
15694 SDValue Ptr = Ld->getBasePtr();
15695 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15696 TLI.getPointerTy());
15697 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15699 for (unsigned i = 0; i < NumLoads; ++i) {
15700 // Perform a single load.
15701 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15702 Ptr, Ld->getPointerInfo(),
15703 Ld->isVolatile(), Ld->isNonTemporal(),
15704 Ld->isInvariant(), Ld->getAlignment());
15705 Chains.push_back(ScalarLoad.getValue(1));
15706 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15707 // another round of DAGCombining.
15709 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15711 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15712 ScalarLoad, DAG.getIntPtrConstant(i));
15714 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15717 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15720 // Bitcast the loaded value to a vector of the original element type, in
15721 // the size of the target vector type.
15722 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15723 unsigned SizeRatio = RegSz/MemSz;
15725 // Redistribute the loaded elements into the different locations.
15726 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15727 for (unsigned i = 0; i != NumElems; ++i)
15728 ShuffleVec[i*SizeRatio] = i;
15730 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15731 DAG.getUNDEF(WideVecVT),
15734 // Bitcast to the requested type.
15735 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15736 // Replace the original load with the new sequence
15737 // and return the new chain.
15738 return DCI.CombineTo(N, Shuff, TF, true);
15744 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15745 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15746 const X86Subtarget *Subtarget) {
15747 StoreSDNode *St = cast<StoreSDNode>(N);
15748 EVT VT = St->getValue().getValueType();
15749 EVT StVT = St->getMemoryVT();
15750 DebugLoc dl = St->getDebugLoc();
15751 SDValue StoredVal = St->getOperand(1);
15752 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15754 // If we are saving a concatenation of two XMM registers, perform two stores.
15755 // On Sandy Bridge, 256-bit memory operations are executed by two
15756 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15757 // memory operation.
15758 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15759 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15760 StoredVal.getNumOperands() == 2) {
15761 SDValue Value0 = StoredVal.getOperand(0);
15762 SDValue Value1 = StoredVal.getOperand(1);
15764 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15765 SDValue Ptr0 = St->getBasePtr();
15766 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15768 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15769 St->getPointerInfo(), St->isVolatile(),
15770 St->isNonTemporal(), St->getAlignment());
15771 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15772 St->getPointerInfo(), St->isVolatile(),
15773 St->isNonTemporal(), St->getAlignment());
15774 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15777 // Optimize trunc store (of multiple scalars) to shuffle and store.
15778 // First, pack all of the elements in one place. Next, store to memory
15779 // in fewer chunks.
15780 if (St->isTruncatingStore() && VT.isVector()) {
15781 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15782 unsigned NumElems = VT.getVectorNumElements();
15783 assert(StVT != VT && "Cannot truncate to the same type");
15784 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15785 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15787 // From, To sizes and ElemCount must be pow of two
15788 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15789 // We are going to use the original vector elt for storing.
15790 // Accumulated smaller vector elements must be a multiple of the store size.
15791 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15793 unsigned SizeRatio = FromSz / ToSz;
15795 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15797 // Create a type on which we perform the shuffle
15798 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15799 StVT.getScalarType(), NumElems*SizeRatio);
15801 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15803 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15804 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15805 for (unsigned i = 0; i != NumElems; ++i)
15806 ShuffleVec[i] = i * SizeRatio;
15808 // Can't shuffle using an illegal type.
15809 if (!TLI.isTypeLegal(WideVecVT))
15812 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15813 DAG.getUNDEF(WideVecVT),
15815 // At this point all of the data is stored at the bottom of the
15816 // register. We now need to save it to mem.
15818 // Find the largest store unit
15819 MVT StoreType = MVT::i8;
15820 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15821 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15822 MVT Tp = (MVT::SimpleValueType)tp;
15823 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15827 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15828 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15829 (64 <= NumElems * ToSz))
15830 StoreType = MVT::f64;
15832 // Bitcast the original vector into a vector of store-size units
15833 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15834 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15835 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15836 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15837 SmallVector<SDValue, 8> Chains;
15838 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15839 TLI.getPointerTy());
15840 SDValue Ptr = St->getBasePtr();
15842 // Perform one or more big stores into memory.
15843 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15844 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15845 StoreType, ShuffWide,
15846 DAG.getIntPtrConstant(i));
15847 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15848 St->getPointerInfo(), St->isVolatile(),
15849 St->isNonTemporal(), St->getAlignment());
15850 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15851 Chains.push_back(Ch);
15854 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15859 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15860 // the FP state in cases where an emms may be missing.
15861 // A preferable solution to the general problem is to figure out the right
15862 // places to insert EMMS. This qualifies as a quick hack.
15864 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15865 if (VT.getSizeInBits() != 64)
15868 const Function *F = DAG.getMachineFunction().getFunction();
15869 bool NoImplicitFloatOps = F->getFnAttributes().
15870 hasAttribute(Attributes::NoImplicitFloat);
15871 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15872 && Subtarget->hasSSE2();
15873 if ((VT.isVector() ||
15874 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15875 isa<LoadSDNode>(St->getValue()) &&
15876 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15877 St->getChain().hasOneUse() && !St->isVolatile()) {
15878 SDNode* LdVal = St->getValue().getNode();
15879 LoadSDNode *Ld = 0;
15880 int TokenFactorIndex = -1;
15881 SmallVector<SDValue, 8> Ops;
15882 SDNode* ChainVal = St->getChain().getNode();
15883 // Must be a store of a load. We currently handle two cases: the load
15884 // is a direct child, and it's under an intervening TokenFactor. It is
15885 // possible to dig deeper under nested TokenFactors.
15886 if (ChainVal == LdVal)
15887 Ld = cast<LoadSDNode>(St->getChain());
15888 else if (St->getValue().hasOneUse() &&
15889 ChainVal->getOpcode() == ISD::TokenFactor) {
15890 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15891 if (ChainVal->getOperand(i).getNode() == LdVal) {
15892 TokenFactorIndex = i;
15893 Ld = cast<LoadSDNode>(St->getValue());
15895 Ops.push_back(ChainVal->getOperand(i));
15899 if (!Ld || !ISD::isNormalLoad(Ld))
15902 // If this is not the MMX case, i.e. we are just turning i64 load/store
15903 // into f64 load/store, avoid the transformation if there are multiple
15904 // uses of the loaded value.
15905 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15908 DebugLoc LdDL = Ld->getDebugLoc();
15909 DebugLoc StDL = N->getDebugLoc();
15910 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15911 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15913 if (Subtarget->is64Bit() || F64IsLegal) {
15914 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15915 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15916 Ld->getPointerInfo(), Ld->isVolatile(),
15917 Ld->isNonTemporal(), Ld->isInvariant(),
15918 Ld->getAlignment());
15919 SDValue NewChain = NewLd.getValue(1);
15920 if (TokenFactorIndex != -1) {
15921 Ops.push_back(NewChain);
15922 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15925 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15926 St->getPointerInfo(),
15927 St->isVolatile(), St->isNonTemporal(),
15928 St->getAlignment());
15931 // Otherwise, lower to two pairs of 32-bit loads / stores.
15932 SDValue LoAddr = Ld->getBasePtr();
15933 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15934 DAG.getConstant(4, MVT::i32));
15936 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15937 Ld->getPointerInfo(),
15938 Ld->isVolatile(), Ld->isNonTemporal(),
15939 Ld->isInvariant(), Ld->getAlignment());
15940 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15941 Ld->getPointerInfo().getWithOffset(4),
15942 Ld->isVolatile(), Ld->isNonTemporal(),
15944 MinAlign(Ld->getAlignment(), 4));
15946 SDValue NewChain = LoLd.getValue(1);
15947 if (TokenFactorIndex != -1) {
15948 Ops.push_back(LoLd);
15949 Ops.push_back(HiLd);
15950 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15954 LoAddr = St->getBasePtr();
15955 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15956 DAG.getConstant(4, MVT::i32));
15958 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15959 St->getPointerInfo(),
15960 St->isVolatile(), St->isNonTemporal(),
15961 St->getAlignment());
15962 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15963 St->getPointerInfo().getWithOffset(4),
15965 St->isNonTemporal(),
15966 MinAlign(St->getAlignment(), 4));
15967 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15972 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15973 /// and return the operands for the horizontal operation in LHS and RHS. A
15974 /// horizontal operation performs the binary operation on successive elements
15975 /// of its first operand, then on successive elements of its second operand,
15976 /// returning the resulting values in a vector. For example, if
15977 /// A = < float a0, float a1, float a2, float a3 >
15979 /// B = < float b0, float b1, float b2, float b3 >
15980 /// then the result of doing a horizontal operation on A and B is
15981 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15982 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15983 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15984 /// set to A, RHS to B, and the routine returns 'true'.
15985 /// Note that the binary operation should have the property that if one of the
15986 /// operands is UNDEF then the result is UNDEF.
15987 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15988 // Look for the following pattern: if
15989 // A = < float a0, float a1, float a2, float a3 >
15990 // B = < float b0, float b1, float b2, float b3 >
15992 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15993 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15994 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15995 // which is A horizontal-op B.
15997 // At least one of the operands should be a vector shuffle.
15998 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15999 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16002 EVT VT = LHS.getValueType();
16004 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16005 "Unsupported vector type for horizontal add/sub");
16007 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16008 // operate independently on 128-bit lanes.
16009 unsigned NumElts = VT.getVectorNumElements();
16010 unsigned NumLanes = VT.getSizeInBits()/128;
16011 unsigned NumLaneElts = NumElts / NumLanes;
16012 assert((NumLaneElts % 2 == 0) &&
16013 "Vector type should have an even number of elements in each lane");
16014 unsigned HalfLaneElts = NumLaneElts/2;
16016 // View LHS in the form
16017 // LHS = VECTOR_SHUFFLE A, B, LMask
16018 // If LHS is not a shuffle then pretend it is the shuffle
16019 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16020 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16023 SmallVector<int, 16> LMask(NumElts);
16024 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16025 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16026 A = LHS.getOperand(0);
16027 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16028 B = LHS.getOperand(1);
16029 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16030 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16032 if (LHS.getOpcode() != ISD::UNDEF)
16034 for (unsigned i = 0; i != NumElts; ++i)
16038 // Likewise, view RHS in the form
16039 // RHS = VECTOR_SHUFFLE C, D, RMask
16041 SmallVector<int, 16> RMask(NumElts);
16042 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16043 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16044 C = RHS.getOperand(0);
16045 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16046 D = RHS.getOperand(1);
16047 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16048 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16050 if (RHS.getOpcode() != ISD::UNDEF)
16052 for (unsigned i = 0; i != NumElts; ++i)
16056 // Check that the shuffles are both shuffling the same vectors.
16057 if (!(A == C && B == D) && !(A == D && B == C))
16060 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16061 if (!A.getNode() && !B.getNode())
16064 // If A and B occur in reverse order in RHS, then "swap" them (which means
16065 // rewriting the mask).
16067 CommuteVectorShuffleMask(RMask, NumElts);
16069 // At this point LHS and RHS are equivalent to
16070 // LHS = VECTOR_SHUFFLE A, B, LMask
16071 // RHS = VECTOR_SHUFFLE A, B, RMask
16072 // Check that the masks correspond to performing a horizontal operation.
16073 for (unsigned i = 0; i != NumElts; ++i) {
16074 int LIdx = LMask[i], RIdx = RMask[i];
16076 // Ignore any UNDEF components.
16077 if (LIdx < 0 || RIdx < 0 ||
16078 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16079 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16082 // Check that successive elements are being operated on. If not, this is
16083 // not a horizontal operation.
16084 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16085 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16086 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16087 if (!(LIdx == Index && RIdx == Index + 1) &&
16088 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16092 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16093 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16097 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16098 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16099 const X86Subtarget *Subtarget) {
16100 EVT VT = N->getValueType(0);
16101 SDValue LHS = N->getOperand(0);
16102 SDValue RHS = N->getOperand(1);
16104 // Try to synthesize horizontal adds from adds of shuffles.
16105 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16106 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16107 isHorizontalBinOp(LHS, RHS, true))
16108 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16112 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16113 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16114 const X86Subtarget *Subtarget) {
16115 EVT VT = N->getValueType(0);
16116 SDValue LHS = N->getOperand(0);
16117 SDValue RHS = N->getOperand(1);
16119 // Try to synthesize horizontal subs from subs of shuffles.
16120 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16121 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16122 isHorizontalBinOp(LHS, RHS, false))
16123 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16127 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16128 /// X86ISD::FXOR nodes.
16129 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16130 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16131 // F[X]OR(0.0, x) -> x
16132 // F[X]OR(x, 0.0) -> x
16133 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16134 if (C->getValueAPF().isPosZero())
16135 return N->getOperand(1);
16136 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16137 if (C->getValueAPF().isPosZero())
16138 return N->getOperand(0);
16142 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16143 /// X86ISD::FMAX nodes.
16144 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16145 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16147 // Only perform optimizations if UnsafeMath is used.
16148 if (!DAG.getTarget().Options.UnsafeFPMath)
16151 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16152 // into FMINC and FMAXC, which are Commutative operations.
16153 unsigned NewOp = 0;
16154 switch (N->getOpcode()) {
16155 default: llvm_unreachable("unknown opcode");
16156 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16157 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16160 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16161 N->getOperand(0), N->getOperand(1));
16165 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16166 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16167 // FAND(0.0, x) -> 0.0
16168 // FAND(x, 0.0) -> 0.0
16169 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16170 if (C->getValueAPF().isPosZero())
16171 return N->getOperand(0);
16172 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16173 if (C->getValueAPF().isPosZero())
16174 return N->getOperand(1);
16178 static SDValue PerformBTCombine(SDNode *N,
16180 TargetLowering::DAGCombinerInfo &DCI) {
16181 // BT ignores high bits in the bit index operand.
16182 SDValue Op1 = N->getOperand(1);
16183 if (Op1.hasOneUse()) {
16184 unsigned BitWidth = Op1.getValueSizeInBits();
16185 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16186 APInt KnownZero, KnownOne;
16187 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16188 !DCI.isBeforeLegalizeOps());
16189 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16190 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16191 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16192 DCI.CommitTargetLoweringOpt(TLO);
16197 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16198 SDValue Op = N->getOperand(0);
16199 if (Op.getOpcode() == ISD::BITCAST)
16200 Op = Op.getOperand(0);
16201 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16202 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16203 VT.getVectorElementType().getSizeInBits() ==
16204 OpVT.getVectorElementType().getSizeInBits()) {
16205 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16210 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16211 TargetLowering::DAGCombinerInfo &DCI,
16212 const X86Subtarget *Subtarget) {
16213 if (!DCI.isBeforeLegalizeOps())
16216 if (!Subtarget->hasAVX())
16219 EVT VT = N->getValueType(0);
16220 SDValue Op = N->getOperand(0);
16221 EVT OpVT = Op.getValueType();
16222 DebugLoc dl = N->getDebugLoc();
16224 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16225 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16227 if (Subtarget->hasAVX2())
16228 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16230 // Optimize vectors in AVX mode
16231 // Sign extend v8i16 to v8i32 and
16234 // Divide input vector into two parts
16235 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16236 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16237 // concat the vectors to original VT
16239 unsigned NumElems = OpVT.getVectorNumElements();
16240 SDValue Undef = DAG.getUNDEF(OpVT);
16242 SmallVector<int,8> ShufMask1(NumElems, -1);
16243 for (unsigned i = 0; i != NumElems/2; ++i)
16246 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16248 SmallVector<int,8> ShufMask2(NumElems, -1);
16249 for (unsigned i = 0; i != NumElems/2; ++i)
16250 ShufMask2[i] = i + NumElems/2;
16252 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16254 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16255 VT.getVectorNumElements()/2);
16257 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16258 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16260 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16265 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16266 const X86Subtarget* Subtarget) {
16267 DebugLoc dl = N->getDebugLoc();
16268 EVT VT = N->getValueType(0);
16270 // Let legalize expand this if it isn't a legal type yet.
16271 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16274 EVT ScalarVT = VT.getScalarType();
16275 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16276 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16279 SDValue A = N->getOperand(0);
16280 SDValue B = N->getOperand(1);
16281 SDValue C = N->getOperand(2);
16283 bool NegA = (A.getOpcode() == ISD::FNEG);
16284 bool NegB = (B.getOpcode() == ISD::FNEG);
16285 bool NegC = (C.getOpcode() == ISD::FNEG);
16287 // Negative multiplication when NegA xor NegB
16288 bool NegMul = (NegA != NegB);
16290 A = A.getOperand(0);
16292 B = B.getOperand(0);
16294 C = C.getOperand(0);
16298 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16300 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16302 return DAG.getNode(Opcode, dl, VT, A, B, C);
16305 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16306 TargetLowering::DAGCombinerInfo &DCI,
16307 const X86Subtarget *Subtarget) {
16308 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16309 // (and (i32 x86isd::setcc_carry), 1)
16310 // This eliminates the zext. This transformation is necessary because
16311 // ISD::SETCC is always legalized to i8.
16312 DebugLoc dl = N->getDebugLoc();
16313 SDValue N0 = N->getOperand(0);
16314 EVT VT = N->getValueType(0);
16315 EVT OpVT = N0.getValueType();
16317 if (N0.getOpcode() == ISD::AND &&
16319 N0.getOperand(0).hasOneUse()) {
16320 SDValue N00 = N0.getOperand(0);
16321 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16323 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16324 if (!C || C->getZExtValue() != 1)
16326 return DAG.getNode(ISD::AND, dl, VT,
16327 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16328 N00.getOperand(0), N00.getOperand(1)),
16329 DAG.getConstant(1, VT));
16332 // Optimize vectors in AVX mode:
16335 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16336 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16337 // Concat upper and lower parts.
16340 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16341 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16342 // Concat upper and lower parts.
16344 if (!DCI.isBeforeLegalizeOps())
16347 if (!Subtarget->hasAVX())
16350 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16351 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16353 if (Subtarget->hasAVX2())
16354 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16356 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16357 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16358 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16360 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16361 VT.getVectorNumElements()/2);
16363 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16364 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16366 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16372 // Optimize x == -y --> x+y == 0
16373 // x != -y --> x+y != 0
16374 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16375 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16376 SDValue LHS = N->getOperand(0);
16377 SDValue RHS = N->getOperand(1);
16379 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16380 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16381 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16382 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16383 LHS.getValueType(), RHS, LHS.getOperand(1));
16384 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16385 addV, DAG.getConstant(0, addV.getValueType()), CC);
16387 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16389 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16390 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16391 RHS.getValueType(), LHS, RHS.getOperand(1));
16392 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16393 addV, DAG.getConstant(0, addV.getValueType()), CC);
16398 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16399 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16400 TargetLowering::DAGCombinerInfo &DCI,
16401 const X86Subtarget *Subtarget) {
16402 DebugLoc DL = N->getDebugLoc();
16403 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16404 SDValue EFLAGS = N->getOperand(1);
16406 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16407 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16409 if (CC == X86::COND_B)
16410 return DAG.getNode(ISD::AND, DL, MVT::i8,
16411 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16412 DAG.getConstant(CC, MVT::i8), EFLAGS),
16413 DAG.getConstant(1, MVT::i8));
16417 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16418 if (Flags.getNode()) {
16419 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16420 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16426 // Optimize branch condition evaluation.
16428 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16429 TargetLowering::DAGCombinerInfo &DCI,
16430 const X86Subtarget *Subtarget) {
16431 DebugLoc DL = N->getDebugLoc();
16432 SDValue Chain = N->getOperand(0);
16433 SDValue Dest = N->getOperand(1);
16434 SDValue EFLAGS = N->getOperand(3);
16435 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16439 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16440 if (Flags.getNode()) {
16441 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16442 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16449 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16450 SDValue Op0 = N->getOperand(0);
16451 EVT InVT = Op0->getValueType(0);
16453 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16454 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16455 DebugLoc dl = N->getDebugLoc();
16456 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16457 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16458 // Notice that we use SINT_TO_FP because we know that the high bits
16459 // are zero and SINT_TO_FP is better supported by the hardware.
16460 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16466 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16467 const X86TargetLowering *XTLI) {
16468 SDValue Op0 = N->getOperand(0);
16469 EVT InVT = Op0->getValueType(0);
16471 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16472 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16473 DebugLoc dl = N->getDebugLoc();
16474 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16475 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16476 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16479 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16480 // a 32-bit target where SSE doesn't support i64->FP operations.
16481 if (Op0.getOpcode() == ISD::LOAD) {
16482 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16483 EVT VT = Ld->getValueType(0);
16484 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16485 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16486 !XTLI->getSubtarget()->is64Bit() &&
16487 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16488 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16489 Ld->getChain(), Op0, DAG);
16490 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16497 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16498 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16499 X86TargetLowering::DAGCombinerInfo &DCI) {
16500 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16501 // the result is either zero or one (depending on the input carry bit).
16502 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16503 if (X86::isZeroNode(N->getOperand(0)) &&
16504 X86::isZeroNode(N->getOperand(1)) &&
16505 // We don't have a good way to replace an EFLAGS use, so only do this when
16507 SDValue(N, 1).use_empty()) {
16508 DebugLoc DL = N->getDebugLoc();
16509 EVT VT = N->getValueType(0);
16510 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16511 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16512 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16513 DAG.getConstant(X86::COND_B,MVT::i8),
16515 DAG.getConstant(1, VT));
16516 return DCI.CombineTo(N, Res1, CarryOut);
16522 // fold (add Y, (sete X, 0)) -> adc 0, Y
16523 // (add Y, (setne X, 0)) -> sbb -1, Y
16524 // (sub (sete X, 0), Y) -> sbb 0, Y
16525 // (sub (setne X, 0), Y) -> adc -1, Y
16526 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16527 DebugLoc DL = N->getDebugLoc();
16529 // Look through ZExts.
16530 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16531 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16534 SDValue SetCC = Ext.getOperand(0);
16535 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16538 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16539 if (CC != X86::COND_E && CC != X86::COND_NE)
16542 SDValue Cmp = SetCC.getOperand(1);
16543 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16544 !X86::isZeroNode(Cmp.getOperand(1)) ||
16545 !Cmp.getOperand(0).getValueType().isInteger())
16548 SDValue CmpOp0 = Cmp.getOperand(0);
16549 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16550 DAG.getConstant(1, CmpOp0.getValueType()));
16552 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16553 if (CC == X86::COND_NE)
16554 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16555 DL, OtherVal.getValueType(), OtherVal,
16556 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16557 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16558 DL, OtherVal.getValueType(), OtherVal,
16559 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16562 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16563 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16564 const X86Subtarget *Subtarget) {
16565 EVT VT = N->getValueType(0);
16566 SDValue Op0 = N->getOperand(0);
16567 SDValue Op1 = N->getOperand(1);
16569 // Try to synthesize horizontal adds from adds of shuffles.
16570 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16571 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16572 isHorizontalBinOp(Op0, Op1, true))
16573 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16575 return OptimizeConditionalInDecrement(N, DAG);
16578 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16579 const X86Subtarget *Subtarget) {
16580 SDValue Op0 = N->getOperand(0);
16581 SDValue Op1 = N->getOperand(1);
16583 // X86 can't encode an immediate LHS of a sub. See if we can push the
16584 // negation into a preceding instruction.
16585 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16586 // If the RHS of the sub is a XOR with one use and a constant, invert the
16587 // immediate. Then add one to the LHS of the sub so we can turn
16588 // X-Y -> X+~Y+1, saving one register.
16589 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16590 isa<ConstantSDNode>(Op1.getOperand(1))) {
16591 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16592 EVT VT = Op0.getValueType();
16593 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16595 DAG.getConstant(~XorC, VT));
16596 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16597 DAG.getConstant(C->getAPIntValue()+1, VT));
16601 // Try to synthesize horizontal adds from adds of shuffles.
16602 EVT VT = N->getValueType(0);
16603 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16604 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16605 isHorizontalBinOp(Op0, Op1, true))
16606 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16608 return OptimizeConditionalInDecrement(N, DAG);
16611 /// performVZEXTCombine - Performs build vector combines
16612 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16613 TargetLowering::DAGCombinerInfo &DCI,
16614 const X86Subtarget *Subtarget) {
16615 // (vzext (bitcast (vzext (x)) -> (vzext x)
16616 SDValue In = N->getOperand(0);
16617 while (In.getOpcode() == ISD::BITCAST)
16618 In = In.getOperand(0);
16620 if (In.getOpcode() != X86ISD::VZEXT)
16623 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16626 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16627 DAGCombinerInfo &DCI) const {
16628 SelectionDAG &DAG = DCI.DAG;
16629 switch (N->getOpcode()) {
16631 case ISD::EXTRACT_VECTOR_ELT:
16632 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16634 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16635 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16636 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16637 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16638 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16639 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16642 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16643 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16644 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16645 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16646 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16647 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16648 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16649 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16650 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16651 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16653 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16655 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16656 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16657 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16658 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16659 case ISD::ANY_EXTEND:
16660 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16661 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16662 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16663 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16664 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16665 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16666 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
16667 case X86ISD::SHUFP: // Handle all target specific shuffles
16668 case X86ISD::PALIGN:
16669 case X86ISD::UNPCKH:
16670 case X86ISD::UNPCKL:
16671 case X86ISD::MOVHLPS:
16672 case X86ISD::MOVLHPS:
16673 case X86ISD::PSHUFD:
16674 case X86ISD::PSHUFHW:
16675 case X86ISD::PSHUFLW:
16676 case X86ISD::MOVSS:
16677 case X86ISD::MOVSD:
16678 case X86ISD::VPERMILP:
16679 case X86ISD::VPERM2X128:
16680 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16681 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16687 /// isTypeDesirableForOp - Return true if the target has native support for
16688 /// the specified value type and it is 'desirable' to use the type for the
16689 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16690 /// instruction encodings are longer and some i16 instructions are slow.
16691 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16692 if (!isTypeLegal(VT))
16694 if (VT != MVT::i16)
16701 case ISD::SIGN_EXTEND:
16702 case ISD::ZERO_EXTEND:
16703 case ISD::ANY_EXTEND:
16716 /// IsDesirableToPromoteOp - This method query the target whether it is
16717 /// beneficial for dag combiner to promote the specified node. If true, it
16718 /// should return the desired promotion type by reference.
16719 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16720 EVT VT = Op.getValueType();
16721 if (VT != MVT::i16)
16724 bool Promote = false;
16725 bool Commute = false;
16726 switch (Op.getOpcode()) {
16729 LoadSDNode *LD = cast<LoadSDNode>(Op);
16730 // If the non-extending load has a single use and it's not live out, then it
16731 // might be folded.
16732 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16733 Op.hasOneUse()*/) {
16734 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16735 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16736 // The only case where we'd want to promote LOAD (rather then it being
16737 // promoted as an operand is when it's only use is liveout.
16738 if (UI->getOpcode() != ISD::CopyToReg)
16745 case ISD::SIGN_EXTEND:
16746 case ISD::ZERO_EXTEND:
16747 case ISD::ANY_EXTEND:
16752 SDValue N0 = Op.getOperand(0);
16753 // Look out for (store (shl (load), x)).
16754 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16767 SDValue N0 = Op.getOperand(0);
16768 SDValue N1 = Op.getOperand(1);
16769 if (!Commute && MayFoldLoad(N1))
16771 // Avoid disabling potential load folding opportunities.
16772 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16774 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16784 //===----------------------------------------------------------------------===//
16785 // X86 Inline Assembly Support
16786 //===----------------------------------------------------------------------===//
16789 // Helper to match a string separated by whitespace.
16790 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16791 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16793 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16794 StringRef piece(*args[i]);
16795 if (!s.startswith(piece)) // Check if the piece matches.
16798 s = s.substr(piece.size());
16799 StringRef::size_type pos = s.find_first_not_of(" \t");
16800 if (pos == 0) // We matched a prefix.
16808 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16811 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16812 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16814 std::string AsmStr = IA->getAsmString();
16816 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16817 if (!Ty || Ty->getBitWidth() % 16 != 0)
16820 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16821 SmallVector<StringRef, 4> AsmPieces;
16822 SplitString(AsmStr, AsmPieces, ";\n");
16824 switch (AsmPieces.size()) {
16825 default: return false;
16827 // FIXME: this should verify that we are targeting a 486 or better. If not,
16828 // we will turn this bswap into something that will be lowered to logical
16829 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16830 // lower so don't worry about this.
16832 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16833 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16834 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16835 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16836 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16837 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16838 // No need to check constraints, nothing other than the equivalent of
16839 // "=r,0" would be valid here.
16840 return IntrinsicLowering::LowerToByteSwap(CI);
16843 // rorw $$8, ${0:w} --> llvm.bswap.i16
16844 if (CI->getType()->isIntegerTy(16) &&
16845 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16846 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16847 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16849 const std::string &ConstraintsStr = IA->getConstraintString();
16850 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16851 std::sort(AsmPieces.begin(), AsmPieces.end());
16852 if (AsmPieces.size() == 4 &&
16853 AsmPieces[0] == "~{cc}" &&
16854 AsmPieces[1] == "~{dirflag}" &&
16855 AsmPieces[2] == "~{flags}" &&
16856 AsmPieces[3] == "~{fpsr}")
16857 return IntrinsicLowering::LowerToByteSwap(CI);
16861 if (CI->getType()->isIntegerTy(32) &&
16862 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16863 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16864 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16865 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16867 const std::string &ConstraintsStr = IA->getConstraintString();
16868 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16869 std::sort(AsmPieces.begin(), AsmPieces.end());
16870 if (AsmPieces.size() == 4 &&
16871 AsmPieces[0] == "~{cc}" &&
16872 AsmPieces[1] == "~{dirflag}" &&
16873 AsmPieces[2] == "~{flags}" &&
16874 AsmPieces[3] == "~{fpsr}")
16875 return IntrinsicLowering::LowerToByteSwap(CI);
16878 if (CI->getType()->isIntegerTy(64)) {
16879 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16880 if (Constraints.size() >= 2 &&
16881 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16882 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16883 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16884 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16885 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16886 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16887 return IntrinsicLowering::LowerToByteSwap(CI);
16897 /// getConstraintType - Given a constraint letter, return the type of
16898 /// constraint it is for this target.
16899 X86TargetLowering::ConstraintType
16900 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16901 if (Constraint.size() == 1) {
16902 switch (Constraint[0]) {
16913 return C_RegisterClass;
16937 return TargetLowering::getConstraintType(Constraint);
16940 /// Examine constraint type and operand type and determine a weight value.
16941 /// This object must already have been set up with the operand type
16942 /// and the current alternative constraint selected.
16943 TargetLowering::ConstraintWeight
16944 X86TargetLowering::getSingleConstraintMatchWeight(
16945 AsmOperandInfo &info, const char *constraint) const {
16946 ConstraintWeight weight = CW_Invalid;
16947 Value *CallOperandVal = info.CallOperandVal;
16948 // If we don't have a value, we can't do a match,
16949 // but allow it at the lowest weight.
16950 if (CallOperandVal == NULL)
16952 Type *type = CallOperandVal->getType();
16953 // Look at the constraint type.
16954 switch (*constraint) {
16956 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16967 if (CallOperandVal->getType()->isIntegerTy())
16968 weight = CW_SpecificReg;
16973 if (type->isFloatingPointTy())
16974 weight = CW_SpecificReg;
16977 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16978 weight = CW_SpecificReg;
16982 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16983 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16984 weight = CW_Register;
16987 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16988 if (C->getZExtValue() <= 31)
16989 weight = CW_Constant;
16993 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16994 if (C->getZExtValue() <= 63)
16995 weight = CW_Constant;
16999 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17000 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17001 weight = CW_Constant;
17005 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17006 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17007 weight = CW_Constant;
17011 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17012 if (C->getZExtValue() <= 3)
17013 weight = CW_Constant;
17017 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17018 if (C->getZExtValue() <= 0xff)
17019 weight = CW_Constant;
17024 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17025 weight = CW_Constant;
17029 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17030 if ((C->getSExtValue() >= -0x80000000LL) &&
17031 (C->getSExtValue() <= 0x7fffffffLL))
17032 weight = CW_Constant;
17036 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17037 if (C->getZExtValue() <= 0xffffffff)
17038 weight = CW_Constant;
17045 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17046 /// with another that has more specific requirements based on the type of the
17047 /// corresponding operand.
17048 const char *X86TargetLowering::
17049 LowerXConstraint(EVT ConstraintVT) const {
17050 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17051 // 'f' like normal targets.
17052 if (ConstraintVT.isFloatingPoint()) {
17053 if (Subtarget->hasSSE2())
17055 if (Subtarget->hasSSE1())
17059 return TargetLowering::LowerXConstraint(ConstraintVT);
17062 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17063 /// vector. If it is invalid, don't add anything to Ops.
17064 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17065 std::string &Constraint,
17066 std::vector<SDValue>&Ops,
17067 SelectionDAG &DAG) const {
17068 SDValue Result(0, 0);
17070 // Only support length 1 constraints for now.
17071 if (Constraint.length() > 1) return;
17073 char ConstraintLetter = Constraint[0];
17074 switch (ConstraintLetter) {
17077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17078 if (C->getZExtValue() <= 31) {
17079 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17085 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17086 if (C->getZExtValue() <= 63) {
17087 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17094 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17095 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17102 if (C->getZExtValue() <= 255) {
17103 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17109 // 32-bit signed value
17110 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17111 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17112 C->getSExtValue())) {
17113 // Widen to 64 bits here to get it sign extended.
17114 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17117 // FIXME gcc accepts some relocatable values here too, but only in certain
17118 // memory models; it's complicated.
17123 // 32-bit unsigned value
17124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17125 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17126 C->getZExtValue())) {
17127 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17131 // FIXME gcc accepts some relocatable values here too, but only in certain
17132 // memory models; it's complicated.
17136 // Literal immediates are always ok.
17137 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17138 // Widen to 64 bits here to get it sign extended.
17139 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17143 // In any sort of PIC mode addresses need to be computed at runtime by
17144 // adding in a register or some sort of table lookup. These can't
17145 // be used as immediates.
17146 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17149 // If we are in non-pic codegen mode, we allow the address of a global (with
17150 // an optional displacement) to be used with 'i'.
17151 GlobalAddressSDNode *GA = 0;
17152 int64_t Offset = 0;
17154 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17156 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17157 Offset += GA->getOffset();
17159 } else if (Op.getOpcode() == ISD::ADD) {
17160 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17161 Offset += C->getZExtValue();
17162 Op = Op.getOperand(0);
17165 } else if (Op.getOpcode() == ISD::SUB) {
17166 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17167 Offset += -C->getZExtValue();
17168 Op = Op.getOperand(0);
17173 // Otherwise, this isn't something we can handle, reject it.
17177 const GlobalValue *GV = GA->getGlobal();
17178 // If we require an extra load to get this address, as in PIC mode, we
17179 // can't accept it.
17180 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17181 getTargetMachine())))
17184 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17185 GA->getValueType(0), Offset);
17190 if (Result.getNode()) {
17191 Ops.push_back(Result);
17194 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17197 std::pair<unsigned, const TargetRegisterClass*>
17198 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17200 // First, see if this is a constraint that directly corresponds to an LLVM
17202 if (Constraint.size() == 1) {
17203 // GCC Constraint Letters
17204 switch (Constraint[0]) {
17206 // TODO: Slight differences here in allocation order and leaving
17207 // RIP in the class. Do they matter any more here than they do
17208 // in the normal allocation?
17209 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17210 if (Subtarget->is64Bit()) {
17211 if (VT == MVT::i32 || VT == MVT::f32)
17212 return std::make_pair(0U, &X86::GR32RegClass);
17213 if (VT == MVT::i16)
17214 return std::make_pair(0U, &X86::GR16RegClass);
17215 if (VT == MVT::i8 || VT == MVT::i1)
17216 return std::make_pair(0U, &X86::GR8RegClass);
17217 if (VT == MVT::i64 || VT == MVT::f64)
17218 return std::make_pair(0U, &X86::GR64RegClass);
17221 // 32-bit fallthrough
17222 case 'Q': // Q_REGS
17223 if (VT == MVT::i32 || VT == MVT::f32)
17224 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17225 if (VT == MVT::i16)
17226 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17227 if (VT == MVT::i8 || VT == MVT::i1)
17228 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17229 if (VT == MVT::i64)
17230 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17232 case 'r': // GENERAL_REGS
17233 case 'l': // INDEX_REGS
17234 if (VT == MVT::i8 || VT == MVT::i1)
17235 return std::make_pair(0U, &X86::GR8RegClass);
17236 if (VT == MVT::i16)
17237 return std::make_pair(0U, &X86::GR16RegClass);
17238 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17239 return std::make_pair(0U, &X86::GR32RegClass);
17240 return std::make_pair(0U, &X86::GR64RegClass);
17241 case 'R': // LEGACY_REGS
17242 if (VT == MVT::i8 || VT == MVT::i1)
17243 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17244 if (VT == MVT::i16)
17245 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17246 if (VT == MVT::i32 || !Subtarget->is64Bit())
17247 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17248 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17249 case 'f': // FP Stack registers.
17250 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17251 // value to the correct fpstack register class.
17252 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17253 return std::make_pair(0U, &X86::RFP32RegClass);
17254 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17255 return std::make_pair(0U, &X86::RFP64RegClass);
17256 return std::make_pair(0U, &X86::RFP80RegClass);
17257 case 'y': // MMX_REGS if MMX allowed.
17258 if (!Subtarget->hasMMX()) break;
17259 return std::make_pair(0U, &X86::VR64RegClass);
17260 case 'Y': // SSE_REGS if SSE2 allowed
17261 if (!Subtarget->hasSSE2()) break;
17263 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17264 if (!Subtarget->hasSSE1()) break;
17266 switch (VT.getSimpleVT().SimpleTy) {
17268 // Scalar SSE types.
17271 return std::make_pair(0U, &X86::FR32RegClass);
17274 return std::make_pair(0U, &X86::FR64RegClass);
17282 return std::make_pair(0U, &X86::VR128RegClass);
17290 return std::make_pair(0U, &X86::VR256RegClass);
17296 // Use the default implementation in TargetLowering to convert the register
17297 // constraint into a member of a register class.
17298 std::pair<unsigned, const TargetRegisterClass*> Res;
17299 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17301 // Not found as a standard register?
17302 if (Res.second == 0) {
17303 // Map st(0) -> st(7) -> ST0
17304 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17305 tolower(Constraint[1]) == 's' &&
17306 tolower(Constraint[2]) == 't' &&
17307 Constraint[3] == '(' &&
17308 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17309 Constraint[5] == ')' &&
17310 Constraint[6] == '}') {
17312 Res.first = X86::ST0+Constraint[4]-'0';
17313 Res.second = &X86::RFP80RegClass;
17317 // GCC allows "st(0)" to be called just plain "st".
17318 if (StringRef("{st}").equals_lower(Constraint)) {
17319 Res.first = X86::ST0;
17320 Res.second = &X86::RFP80RegClass;
17325 if (StringRef("{flags}").equals_lower(Constraint)) {
17326 Res.first = X86::EFLAGS;
17327 Res.second = &X86::CCRRegClass;
17331 // 'A' means EAX + EDX.
17332 if (Constraint == "A") {
17333 Res.first = X86::EAX;
17334 Res.second = &X86::GR32_ADRegClass;
17340 // Otherwise, check to see if this is a register class of the wrong value
17341 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17342 // turn into {ax},{dx}.
17343 if (Res.second->hasType(VT))
17344 return Res; // Correct type already, nothing to do.
17346 // All of the single-register GCC register classes map their values onto
17347 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17348 // really want an 8-bit or 32-bit register, map to the appropriate register
17349 // class and return the appropriate register.
17350 if (Res.second == &X86::GR16RegClass) {
17351 if (VT == MVT::i8) {
17352 unsigned DestReg = 0;
17353 switch (Res.first) {
17355 case X86::AX: DestReg = X86::AL; break;
17356 case X86::DX: DestReg = X86::DL; break;
17357 case X86::CX: DestReg = X86::CL; break;
17358 case X86::BX: DestReg = X86::BL; break;
17361 Res.first = DestReg;
17362 Res.second = &X86::GR8RegClass;
17364 } else if (VT == MVT::i32) {
17365 unsigned DestReg = 0;
17366 switch (Res.first) {
17368 case X86::AX: DestReg = X86::EAX; break;
17369 case X86::DX: DestReg = X86::EDX; break;
17370 case X86::CX: DestReg = X86::ECX; break;
17371 case X86::BX: DestReg = X86::EBX; break;
17372 case X86::SI: DestReg = X86::ESI; break;
17373 case X86::DI: DestReg = X86::EDI; break;
17374 case X86::BP: DestReg = X86::EBP; break;
17375 case X86::SP: DestReg = X86::ESP; break;
17378 Res.first = DestReg;
17379 Res.second = &X86::GR32RegClass;
17381 } else if (VT == MVT::i64) {
17382 unsigned DestReg = 0;
17383 switch (Res.first) {
17385 case X86::AX: DestReg = X86::RAX; break;
17386 case X86::DX: DestReg = X86::RDX; break;
17387 case X86::CX: DestReg = X86::RCX; break;
17388 case X86::BX: DestReg = X86::RBX; break;
17389 case X86::SI: DestReg = X86::RSI; break;
17390 case X86::DI: DestReg = X86::RDI; break;
17391 case X86::BP: DestReg = X86::RBP; break;
17392 case X86::SP: DestReg = X86::RSP; break;
17395 Res.first = DestReg;
17396 Res.second = &X86::GR64RegClass;
17399 } else if (Res.second == &X86::FR32RegClass ||
17400 Res.second == &X86::FR64RegClass ||
17401 Res.second == &X86::VR128RegClass) {
17402 // Handle references to XMM physical registers that got mapped into the
17403 // wrong class. This can happen with constraints like {xmm0} where the
17404 // target independent register mapper will just pick the first match it can
17405 // find, ignoring the required type.
17407 if (VT == MVT::f32 || VT == MVT::i32)
17408 Res.second = &X86::FR32RegClass;
17409 else if (VT == MVT::f64 || VT == MVT::i64)
17410 Res.second = &X86::FR64RegClass;
17411 else if (X86::VR128RegClass.hasType(VT))
17412 Res.second = &X86::VR128RegClass;
17413 else if (X86::VR256RegClass.hasType(VT))
17414 Res.second = &X86::VR256RegClass;