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::UINT_TO_FP, MVT::v4i8, Custom);
952 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
954 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
955 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
957 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
960 if (Subtarget->hasSSE41()) {
961 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
962 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
963 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
964 setOperationAction(ISD::FRINT, MVT::f32, Legal);
965 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
966 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
967 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
968 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
969 setOperationAction(ISD::FRINT, MVT::f64, Legal);
970 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
972 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
973 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
975 // FIXME: Do we need to handle scalar-to-vector here?
976 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
978 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
979 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
980 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
981 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
982 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
984 // i8 and i16 vectors are custom , because the source register and source
985 // source memory operand types are not the same width. f32 vectors are
986 // custom since the immediate controlling the insert encodes additional
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
989 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
990 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
994 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
995 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
998 // FIXME: these should be Legal but thats only for the case where
999 // the index is constant. For now custom expand to deal with that.
1000 if (Subtarget->is64Bit()) {
1001 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1002 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1006 if (Subtarget->hasSSE2()) {
1007 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1008 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1010 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1011 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1013 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1014 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1016 if (Subtarget->hasAVX2()) {
1017 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1018 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1020 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1023 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1026 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1028 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1029 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1031 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1035 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1036 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1038 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1039 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1040 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1043 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1045 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1047 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1050 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1051 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1054 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1056 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1059 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1060 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1063 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1065 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1067 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1069 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1070 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1071 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1073 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1075 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1077 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1079 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1080 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1082 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1083 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1085 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1086 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1088 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1089 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1091 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1093 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1094 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1095 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1097 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1098 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1099 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1100 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1102 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1103 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1104 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1105 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1106 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1107 setOperationAction(ISD::FMA, MVT::f32, Custom);
1108 setOperationAction(ISD::FMA, MVT::f64, Custom);
1111 if (Subtarget->hasAVX2()) {
1112 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1113 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1114 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1115 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1117 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1118 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1119 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1120 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1122 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1123 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1124 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1125 // Don't lower v32i8 because there is no 128-bit byte mul
1127 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1129 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1130 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1132 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1133 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1135 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1137 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1138 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1139 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1140 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1142 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1143 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1144 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1145 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1147 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1148 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1149 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1150 // Don't lower v32i8 because there is no 128-bit byte mul
1152 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1153 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1155 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1156 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1158 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1161 // Custom lower several nodes for 256-bit types.
1162 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1163 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1164 MVT VT = (MVT::SimpleValueType)i;
1166 // Extract subvector is special because the value type
1167 // (result) is 128-bit but the source is 256-bit wide.
1168 if (VT.is128BitVector())
1169 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1171 // Do not attempt to custom lower other non-256-bit vectors
1172 if (!VT.is256BitVector())
1175 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1176 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1177 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1178 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1179 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1180 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1181 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1184 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1185 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1186 MVT VT = (MVT::SimpleValueType)i;
1188 // Do not attempt to promote non-256-bit vectors
1189 if (!VT.is256BitVector())
1192 setOperationAction(ISD::AND, VT, Promote);
1193 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1194 setOperationAction(ISD::OR, VT, Promote);
1195 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1196 setOperationAction(ISD::XOR, VT, Promote);
1197 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1198 setOperationAction(ISD::LOAD, VT, Promote);
1199 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1200 setOperationAction(ISD::SELECT, VT, Promote);
1201 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1205 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1206 // of this type with custom code.
1207 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1208 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1209 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1213 // We want to custom lower some of our intrinsics.
1214 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1215 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1218 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1219 // handle type legalization for these operations here.
1221 // FIXME: We really should do custom legalization for addition and
1222 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1223 // than generic legalization for 64-bit multiplication-with-overflow, though.
1224 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1225 // Add/Sub/Mul with overflow operations are custom lowered.
1227 setOperationAction(ISD::SADDO, VT, Custom);
1228 setOperationAction(ISD::UADDO, VT, Custom);
1229 setOperationAction(ISD::SSUBO, VT, Custom);
1230 setOperationAction(ISD::USUBO, VT, Custom);
1231 setOperationAction(ISD::SMULO, VT, Custom);
1232 setOperationAction(ISD::UMULO, VT, Custom);
1235 // There are no 8-bit 3-address imul/mul instructions
1236 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1237 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1239 if (!Subtarget->is64Bit()) {
1240 // These libcalls are not available in 32-bit.
1241 setLibcallName(RTLIB::SHL_I128, 0);
1242 setLibcallName(RTLIB::SRL_I128, 0);
1243 setLibcallName(RTLIB::SRA_I128, 0);
1246 // We have target-specific dag combine patterns for the following nodes:
1247 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1248 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1249 setTargetDAGCombine(ISD::VSELECT);
1250 setTargetDAGCombine(ISD::SELECT);
1251 setTargetDAGCombine(ISD::SHL);
1252 setTargetDAGCombine(ISD::SRA);
1253 setTargetDAGCombine(ISD::SRL);
1254 setTargetDAGCombine(ISD::OR);
1255 setTargetDAGCombine(ISD::AND);
1256 setTargetDAGCombine(ISD::ADD);
1257 setTargetDAGCombine(ISD::FADD);
1258 setTargetDAGCombine(ISD::FSUB);
1259 setTargetDAGCombine(ISD::FMA);
1260 setTargetDAGCombine(ISD::SUB);
1261 setTargetDAGCombine(ISD::LOAD);
1262 setTargetDAGCombine(ISD::STORE);
1263 setTargetDAGCombine(ISD::ZERO_EXTEND);
1264 setTargetDAGCombine(ISD::ANY_EXTEND);
1265 setTargetDAGCombine(ISD::SIGN_EXTEND);
1266 setTargetDAGCombine(ISD::TRUNCATE);
1267 setTargetDAGCombine(ISD::SINT_TO_FP);
1268 setTargetDAGCombine(ISD::SETCC);
1269 if (Subtarget->is64Bit())
1270 setTargetDAGCombine(ISD::MUL);
1271 setTargetDAGCombine(ISD::XOR);
1273 computeRegisterProperties();
1275 // On Darwin, -Os means optimize for size without hurting performance,
1276 // do not reduce the limit.
1277 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1278 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1279 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1280 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1281 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1282 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1283 setPrefLoopAlignment(4); // 2^4 bytes.
1284 benefitFromCodePlacementOpt = true;
1286 // Predictable cmov don't hurt on atom because it's in-order.
1287 predictableSelectIsExpensive = !Subtarget->isAtom();
1289 setPrefFunctionAlignment(4); // 2^4 bytes.
1293 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1294 if (!VT.isVector()) return MVT::i8;
1295 return VT.changeVectorElementTypeToInteger();
1299 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1300 /// the desired ByVal argument alignment.
1301 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1304 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1305 if (VTy->getBitWidth() == 128)
1307 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1308 unsigned EltAlign = 0;
1309 getMaxByValAlign(ATy->getElementType(), EltAlign);
1310 if (EltAlign > MaxAlign)
1311 MaxAlign = EltAlign;
1312 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1313 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1314 unsigned EltAlign = 0;
1315 getMaxByValAlign(STy->getElementType(i), EltAlign);
1316 if (EltAlign > MaxAlign)
1317 MaxAlign = EltAlign;
1324 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1325 /// function arguments in the caller parameter area. For X86, aggregates
1326 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1327 /// are at 4-byte boundaries.
1328 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1329 if (Subtarget->is64Bit()) {
1330 // Max of 8 and alignment of type.
1331 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1338 if (Subtarget->hasSSE1())
1339 getMaxByValAlign(Ty, Align);
1343 /// getOptimalMemOpType - Returns the target specific optimal type for load
1344 /// and store operations as a result of memset, memcpy, and memmove
1345 /// lowering. If DstAlign is zero that means it's safe to destination
1346 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1347 /// means there isn't a need to check it against alignment requirement,
1348 /// probably because the source does not need to be loaded. If
1349 /// 'IsZeroVal' is true, that means it's safe to return a
1350 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1351 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1352 /// constant so it does not need to be loaded.
1353 /// It returns EVT::Other if the type should be determined using generic
1354 /// target-independent logic.
1356 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1357 unsigned DstAlign, unsigned SrcAlign,
1360 MachineFunction &MF) const {
1361 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1362 // linux. This is because the stack realignment code can't handle certain
1363 // cases like PR2962. This should be removed when PR2962 is fixed.
1364 const Function *F = MF.getFunction();
1366 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1368 (Subtarget->isUnalignedMemAccessFast() ||
1369 ((DstAlign == 0 || DstAlign >= 16) &&
1370 (SrcAlign == 0 || SrcAlign >= 16))) &&
1371 Subtarget->getStackAlignment() >= 16) {
1372 if (Subtarget->getStackAlignment() >= 32) {
1373 if (Subtarget->hasAVX2())
1375 if (Subtarget->hasAVX())
1378 if (Subtarget->hasSSE2())
1380 if (Subtarget->hasSSE1())
1382 } else if (!MemcpyStrSrc && Size >= 8 &&
1383 !Subtarget->is64Bit() &&
1384 Subtarget->getStackAlignment() >= 8 &&
1385 Subtarget->hasSSE2()) {
1386 // Do not use f64 to lower memcpy if source is string constant. It's
1387 // better to use i32 to avoid the loads.
1391 if (Subtarget->is64Bit() && Size >= 8)
1396 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1397 /// current function. The returned value is a member of the
1398 /// MachineJumpTableInfo::JTEntryKind enum.
1399 unsigned X86TargetLowering::getJumpTableEncoding() const {
1400 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1402 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1403 Subtarget->isPICStyleGOT())
1404 return MachineJumpTableInfo::EK_Custom32;
1406 // Otherwise, use the normal jump table encoding heuristics.
1407 return TargetLowering::getJumpTableEncoding();
1411 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1412 const MachineBasicBlock *MBB,
1413 unsigned uid,MCContext &Ctx) const{
1414 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1415 Subtarget->isPICStyleGOT());
1416 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1418 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1419 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1422 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1424 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1425 SelectionDAG &DAG) const {
1426 if (!Subtarget->is64Bit())
1427 // This doesn't have DebugLoc associated with it, but is not really the
1428 // same as a Register.
1429 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1433 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1434 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1436 const MCExpr *X86TargetLowering::
1437 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1438 MCContext &Ctx) const {
1439 // X86-64 uses RIP relative addressing based on the jump table label.
1440 if (Subtarget->isPICStyleRIPRel())
1441 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1443 // Otherwise, the reference is relative to the PIC base.
1444 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1447 // FIXME: Why this routine is here? Move to RegInfo!
1448 std::pair<const TargetRegisterClass*, uint8_t>
1449 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1450 const TargetRegisterClass *RRC = 0;
1452 switch (VT.getSimpleVT().SimpleTy) {
1454 return TargetLowering::findRepresentativeClass(VT);
1455 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1456 RRC = Subtarget->is64Bit() ?
1457 (const TargetRegisterClass*)&X86::GR64RegClass :
1458 (const TargetRegisterClass*)&X86::GR32RegClass;
1461 RRC = &X86::VR64RegClass;
1463 case MVT::f32: case MVT::f64:
1464 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1465 case MVT::v4f32: case MVT::v2f64:
1466 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1468 RRC = &X86::VR128RegClass;
1471 return std::make_pair(RRC, Cost);
1474 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1475 unsigned &Offset) const {
1476 if (!Subtarget->isTargetLinux())
1479 if (Subtarget->is64Bit()) {
1480 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1482 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1495 //===----------------------------------------------------------------------===//
1496 // Return Value Calling Convention Implementation
1497 //===----------------------------------------------------------------------===//
1499 #include "X86GenCallingConv.inc"
1502 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1503 MachineFunction &MF, bool isVarArg,
1504 const SmallVectorImpl<ISD::OutputArg> &Outs,
1505 LLVMContext &Context) const {
1506 SmallVector<CCValAssign, 16> RVLocs;
1507 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1509 return CCInfo.CheckReturn(Outs, RetCC_X86);
1513 X86TargetLowering::LowerReturn(SDValue Chain,
1514 CallingConv::ID CallConv, bool isVarArg,
1515 const SmallVectorImpl<ISD::OutputArg> &Outs,
1516 const SmallVectorImpl<SDValue> &OutVals,
1517 DebugLoc dl, SelectionDAG &DAG) const {
1518 MachineFunction &MF = DAG.getMachineFunction();
1519 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1521 SmallVector<CCValAssign, 16> RVLocs;
1522 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1523 RVLocs, *DAG.getContext());
1524 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1526 // Add the regs to the liveout set for the function.
1527 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1528 for (unsigned i = 0; i != RVLocs.size(); ++i)
1529 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1530 MRI.addLiveOut(RVLocs[i].getLocReg());
1534 SmallVector<SDValue, 6> RetOps;
1535 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1536 // Operand #1 = Bytes To Pop
1537 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1540 // Copy the result values into the output registers.
1541 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1542 CCValAssign &VA = RVLocs[i];
1543 assert(VA.isRegLoc() && "Can only return in registers!");
1544 SDValue ValToCopy = OutVals[i];
1545 EVT ValVT = ValToCopy.getValueType();
1547 // Promote values to the appropriate types
1548 if (VA.getLocInfo() == CCValAssign::SExt)
1549 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1550 else if (VA.getLocInfo() == CCValAssign::ZExt)
1551 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1552 else if (VA.getLocInfo() == CCValAssign::AExt)
1553 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1554 else if (VA.getLocInfo() == CCValAssign::BCvt)
1555 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1557 // If this is x86-64, and we disabled SSE, we can't return FP values,
1558 // or SSE or MMX vectors.
1559 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1560 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1561 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1562 report_fatal_error("SSE register return with SSE disabled");
1564 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1565 // llvm-gcc has never done it right and no one has noticed, so this
1566 // should be OK for now.
1567 if (ValVT == MVT::f64 &&
1568 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1569 report_fatal_error("SSE2 register return with SSE2 disabled");
1571 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1572 // the RET instruction and handled by the FP Stackifier.
1573 if (VA.getLocReg() == X86::ST0 ||
1574 VA.getLocReg() == X86::ST1) {
1575 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1576 // change the value to the FP stack register class.
1577 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1578 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1579 RetOps.push_back(ValToCopy);
1580 // Don't emit a copytoreg.
1584 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1585 // which is returned in RAX / RDX.
1586 if (Subtarget->is64Bit()) {
1587 if (ValVT == MVT::x86mmx) {
1588 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1589 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1590 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1592 // If we don't have SSE2 available, convert to v4f32 so the generated
1593 // register is legal.
1594 if (!Subtarget->hasSSE2())
1595 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1600 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1601 Flag = Chain.getValue(1);
1604 // The x86-64 ABI for returning structs by value requires that we copy
1605 // the sret argument into %rax for the return. We saved the argument into
1606 // a virtual register in the entry block, so now we copy the value out
1608 if (Subtarget->is64Bit() &&
1609 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1610 MachineFunction &MF = DAG.getMachineFunction();
1611 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1612 unsigned Reg = FuncInfo->getSRetReturnReg();
1614 "SRetReturnReg should have been set in LowerFormalArguments().");
1615 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1617 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1618 Flag = Chain.getValue(1);
1620 // RAX now acts like a return value.
1621 MRI.addLiveOut(X86::RAX);
1624 RetOps[0] = Chain; // Update chain.
1626 // Add the flag if we have it.
1628 RetOps.push_back(Flag);
1630 return DAG.getNode(X86ISD::RET_FLAG, dl,
1631 MVT::Other, &RetOps[0], RetOps.size());
1634 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1635 if (N->getNumValues() != 1)
1637 if (!N->hasNUsesOfValue(1, 0))
1640 SDValue TCChain = Chain;
1641 SDNode *Copy = *N->use_begin();
1642 if (Copy->getOpcode() == ISD::CopyToReg) {
1643 // If the copy has a glue operand, we conservatively assume it isn't safe to
1644 // perform a tail call.
1645 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1647 TCChain = Copy->getOperand(0);
1648 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1651 bool HasRet = false;
1652 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1654 if (UI->getOpcode() != X86ISD::RET_FLAG)
1667 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1668 ISD::NodeType ExtendKind) const {
1670 // TODO: Is this also valid on 32-bit?
1671 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1672 ReturnMVT = MVT::i8;
1674 ReturnMVT = MVT::i32;
1676 EVT MinVT = getRegisterType(Context, ReturnMVT);
1677 return VT.bitsLT(MinVT) ? MinVT : VT;
1680 /// LowerCallResult - Lower the result values of a call into the
1681 /// appropriate copies out of appropriate physical registers.
1684 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1685 CallingConv::ID CallConv, bool isVarArg,
1686 const SmallVectorImpl<ISD::InputArg> &Ins,
1687 DebugLoc dl, SelectionDAG &DAG,
1688 SmallVectorImpl<SDValue> &InVals) const {
1690 // Assign locations to each value returned by this call.
1691 SmallVector<CCValAssign, 16> RVLocs;
1692 bool Is64Bit = Subtarget->is64Bit();
1693 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1694 getTargetMachine(), RVLocs, *DAG.getContext());
1695 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1697 // Copy all of the result registers out of their specified physreg.
1698 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1699 CCValAssign &VA = RVLocs[i];
1700 EVT CopyVT = VA.getValVT();
1702 // If this is x86-64, and we disabled SSE, we can't return FP values
1703 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1704 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1705 report_fatal_error("SSE register return with SSE disabled");
1710 // If this is a call to a function that returns an fp value on the floating
1711 // point stack, we must guarantee the value is popped from the stack, so
1712 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1713 // if the return value is not used. We use the FpPOP_RETVAL instruction
1715 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1716 // If we prefer to use the value in xmm registers, copy it out as f80 and
1717 // use a truncate to move it from fp stack reg to xmm reg.
1718 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1719 SDValue Ops[] = { Chain, InFlag };
1720 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1721 MVT::Other, MVT::Glue, Ops, 2), 1);
1722 Val = Chain.getValue(0);
1724 // Round the f80 to the right size, which also moves it to the appropriate
1726 if (CopyVT != VA.getValVT())
1727 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1728 // This truncation won't change the value.
1729 DAG.getIntPtrConstant(1));
1731 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1732 CopyVT, InFlag).getValue(1);
1733 Val = Chain.getValue(0);
1735 InFlag = Chain.getValue(2);
1736 InVals.push_back(Val);
1743 //===----------------------------------------------------------------------===//
1744 // C & StdCall & Fast Calling Convention implementation
1745 //===----------------------------------------------------------------------===//
1746 // StdCall calling convention seems to be standard for many Windows' API
1747 // routines and around. It differs from C calling convention just a little:
1748 // callee should clean up the stack, not caller. Symbols should be also
1749 // decorated in some fancy way :) It doesn't support any vector arguments.
1750 // For info on fast calling convention see Fast Calling Convention (tail call)
1751 // implementation LowerX86_32FastCCCallTo.
1753 /// CallIsStructReturn - Determines whether a call uses struct return
1755 enum StructReturnType {
1760 static StructReturnType
1761 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1763 return NotStructReturn;
1765 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1766 if (!Flags.isSRet())
1767 return NotStructReturn;
1768 if (Flags.isInReg())
1769 return RegStructReturn;
1770 return StackStructReturn;
1773 /// ArgsAreStructReturn - Determines whether a function uses struct
1774 /// return semantics.
1775 static StructReturnType
1776 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1778 return NotStructReturn;
1780 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1781 if (!Flags.isSRet())
1782 return NotStructReturn;
1783 if (Flags.isInReg())
1784 return RegStructReturn;
1785 return StackStructReturn;
1788 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1789 /// by "Src" to address "Dst" with size and alignment information specified by
1790 /// the specific parameter attribute. The copy will be passed as a byval
1791 /// function parameter.
1793 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1794 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1796 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1798 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1799 /*isVolatile*/false, /*AlwaysInline=*/true,
1800 MachinePointerInfo(), MachinePointerInfo());
1803 /// IsTailCallConvention - Return true if the calling convention is one that
1804 /// supports tail call optimization.
1805 static bool IsTailCallConvention(CallingConv::ID CC) {
1806 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1809 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1810 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1814 CallingConv::ID CalleeCC = CS.getCallingConv();
1815 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1821 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1822 /// a tailcall target by changing its ABI.
1823 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1824 bool GuaranteedTailCallOpt) {
1825 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1829 X86TargetLowering::LowerMemArgument(SDValue Chain,
1830 CallingConv::ID CallConv,
1831 const SmallVectorImpl<ISD::InputArg> &Ins,
1832 DebugLoc dl, SelectionDAG &DAG,
1833 const CCValAssign &VA,
1834 MachineFrameInfo *MFI,
1836 // Create the nodes corresponding to a load from this parameter slot.
1837 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1838 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1839 getTargetMachine().Options.GuaranteedTailCallOpt);
1840 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1843 // If value is passed by pointer we have address passed instead of the value
1845 if (VA.getLocInfo() == CCValAssign::Indirect)
1846 ValVT = VA.getLocVT();
1848 ValVT = VA.getValVT();
1850 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1851 // changed with more analysis.
1852 // In case of tail call optimization mark all arguments mutable. Since they
1853 // could be overwritten by lowering of arguments in case of a tail call.
1854 if (Flags.isByVal()) {
1855 unsigned Bytes = Flags.getByValSize();
1856 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1857 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1858 return DAG.getFrameIndex(FI, getPointerTy());
1860 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1861 VA.getLocMemOffset(), isImmutable);
1862 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1863 return DAG.getLoad(ValVT, dl, Chain, FIN,
1864 MachinePointerInfo::getFixedStack(FI),
1865 false, false, false, 0);
1870 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1871 CallingConv::ID CallConv,
1873 const SmallVectorImpl<ISD::InputArg> &Ins,
1876 SmallVectorImpl<SDValue> &InVals)
1878 MachineFunction &MF = DAG.getMachineFunction();
1879 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1881 const Function* Fn = MF.getFunction();
1882 if (Fn->hasExternalLinkage() &&
1883 Subtarget->isTargetCygMing() &&
1884 Fn->getName() == "main")
1885 FuncInfo->setForceFramePointer(true);
1887 MachineFrameInfo *MFI = MF.getFrameInfo();
1888 bool Is64Bit = Subtarget->is64Bit();
1889 bool IsWindows = Subtarget->isTargetWindows();
1890 bool IsWin64 = Subtarget->isTargetWin64();
1892 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1893 "Var args not supported with calling convention fastcc or ghc");
1895 // Assign locations to all of the incoming arguments.
1896 SmallVector<CCValAssign, 16> ArgLocs;
1897 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1898 ArgLocs, *DAG.getContext());
1900 // Allocate shadow area for Win64
1902 CCInfo.AllocateStack(32, 8);
1905 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1907 unsigned LastVal = ~0U;
1909 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1910 CCValAssign &VA = ArgLocs[i];
1911 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1913 assert(VA.getValNo() != LastVal &&
1914 "Don't support value assigned to multiple locs yet");
1916 LastVal = VA.getValNo();
1918 if (VA.isRegLoc()) {
1919 EVT RegVT = VA.getLocVT();
1920 const TargetRegisterClass *RC;
1921 if (RegVT == MVT::i32)
1922 RC = &X86::GR32RegClass;
1923 else if (Is64Bit && RegVT == MVT::i64)
1924 RC = &X86::GR64RegClass;
1925 else if (RegVT == MVT::f32)
1926 RC = &X86::FR32RegClass;
1927 else if (RegVT == MVT::f64)
1928 RC = &X86::FR64RegClass;
1929 else if (RegVT.is256BitVector())
1930 RC = &X86::VR256RegClass;
1931 else if (RegVT.is128BitVector())
1932 RC = &X86::VR128RegClass;
1933 else if (RegVT == MVT::x86mmx)
1934 RC = &X86::VR64RegClass;
1936 llvm_unreachable("Unknown argument type!");
1938 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1939 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1941 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1942 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1944 if (VA.getLocInfo() == CCValAssign::SExt)
1945 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1946 DAG.getValueType(VA.getValVT()));
1947 else if (VA.getLocInfo() == CCValAssign::ZExt)
1948 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1949 DAG.getValueType(VA.getValVT()));
1950 else if (VA.getLocInfo() == CCValAssign::BCvt)
1951 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1953 if (VA.isExtInLoc()) {
1954 // Handle MMX values passed in XMM regs.
1955 if (RegVT.isVector()) {
1956 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1959 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1962 assert(VA.isMemLoc());
1963 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1966 // If value is passed via pointer - do a load.
1967 if (VA.getLocInfo() == CCValAssign::Indirect)
1968 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1969 MachinePointerInfo(), false, false, false, 0);
1971 InVals.push_back(ArgValue);
1974 // The x86-64 ABI for returning structs by value requires that we copy
1975 // the sret argument into %rax for the return. Save the argument into
1976 // a virtual register so that we can access it from the return points.
1977 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1978 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1979 unsigned Reg = FuncInfo->getSRetReturnReg();
1981 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1982 FuncInfo->setSRetReturnReg(Reg);
1984 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1985 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1988 unsigned StackSize = CCInfo.getNextStackOffset();
1989 // Align stack specially for tail calls.
1990 if (FuncIsMadeTailCallSafe(CallConv,
1991 MF.getTarget().Options.GuaranteedTailCallOpt))
1992 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1994 // If the function takes variable number of arguments, make a frame index for
1995 // the start of the first vararg value... for expansion of llvm.va_start.
1997 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1998 CallConv != CallingConv::X86_ThisCall)) {
1999 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2002 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2004 // FIXME: We should really autogenerate these arrays
2005 static const uint16_t GPR64ArgRegsWin64[] = {
2006 X86::RCX, X86::RDX, X86::R8, X86::R9
2008 static const uint16_t GPR64ArgRegs64Bit[] = {
2009 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2011 static const uint16_t XMMArgRegs64Bit[] = {
2012 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2013 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2015 const uint16_t *GPR64ArgRegs;
2016 unsigned NumXMMRegs = 0;
2019 // The XMM registers which might contain var arg parameters are shadowed
2020 // in their paired GPR. So we only need to save the GPR to their home
2022 TotalNumIntRegs = 4;
2023 GPR64ArgRegs = GPR64ArgRegsWin64;
2025 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2026 GPR64ArgRegs = GPR64ArgRegs64Bit;
2028 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2031 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2034 bool NoImplicitFloatOps = Fn->getFnAttributes().
2035 hasAttribute(Attributes::NoImplicitFloat);
2036 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2037 "SSE register cannot be used when SSE is disabled!");
2038 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2039 NoImplicitFloatOps) &&
2040 "SSE register cannot be used when SSE is disabled!");
2041 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2042 !Subtarget->hasSSE1())
2043 // Kernel mode asks for SSE to be disabled, so don't push them
2045 TotalNumXMMRegs = 0;
2048 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2049 // Get to the caller-allocated home save location. Add 8 to account
2050 // for the return address.
2051 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2052 FuncInfo->setRegSaveFrameIndex(
2053 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2054 // Fixup to set vararg frame on shadow area (4 x i64).
2056 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2058 // For X86-64, if there are vararg parameters that are passed via
2059 // registers, then we must store them to their spots on the stack so
2060 // they may be loaded by deferencing the result of va_next.
2061 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2062 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2063 FuncInfo->setRegSaveFrameIndex(
2064 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2068 // Store the integer parameter registers.
2069 SmallVector<SDValue, 8> MemOps;
2070 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2072 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2073 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2074 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2075 DAG.getIntPtrConstant(Offset));
2076 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2077 &X86::GR64RegClass);
2078 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2080 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2081 MachinePointerInfo::getFixedStack(
2082 FuncInfo->getRegSaveFrameIndex(), Offset),
2084 MemOps.push_back(Store);
2088 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2089 // Now store the XMM (fp + vector) parameter registers.
2090 SmallVector<SDValue, 11> SaveXMMOps;
2091 SaveXMMOps.push_back(Chain);
2093 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2094 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2095 SaveXMMOps.push_back(ALVal);
2097 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2098 FuncInfo->getRegSaveFrameIndex()));
2099 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2100 FuncInfo->getVarArgsFPOffset()));
2102 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2103 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2104 &X86::VR128RegClass);
2105 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2106 SaveXMMOps.push_back(Val);
2108 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2110 &SaveXMMOps[0], SaveXMMOps.size()));
2113 if (!MemOps.empty())
2114 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2115 &MemOps[0], MemOps.size());
2119 // Some CCs need callee pop.
2120 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2121 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2122 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2124 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2125 // If this is an sret function, the return should pop the hidden pointer.
2126 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2127 argsAreStructReturn(Ins) == StackStructReturn)
2128 FuncInfo->setBytesToPopOnReturn(4);
2132 // RegSaveFrameIndex is X86-64 only.
2133 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2134 if (CallConv == CallingConv::X86_FastCall ||
2135 CallConv == CallingConv::X86_ThisCall)
2136 // fastcc functions can't have varargs.
2137 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2140 FuncInfo->setArgumentStackSize(StackSize);
2146 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2147 SDValue StackPtr, SDValue Arg,
2148 DebugLoc dl, SelectionDAG &DAG,
2149 const CCValAssign &VA,
2150 ISD::ArgFlagsTy Flags) const {
2151 unsigned LocMemOffset = VA.getLocMemOffset();
2152 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2153 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2154 if (Flags.isByVal())
2155 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2157 return DAG.getStore(Chain, dl, Arg, PtrOff,
2158 MachinePointerInfo::getStack(LocMemOffset),
2162 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2163 /// optimization is performed and it is required.
2165 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2166 SDValue &OutRetAddr, SDValue Chain,
2167 bool IsTailCall, bool Is64Bit,
2168 int FPDiff, DebugLoc dl) const {
2169 // Adjust the Return address stack slot.
2170 EVT VT = getPointerTy();
2171 OutRetAddr = getReturnAddressFrameIndex(DAG);
2173 // Load the "old" Return address.
2174 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2175 false, false, false, 0);
2176 return SDValue(OutRetAddr.getNode(), 1);
2179 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2180 /// optimization is performed and it is required (FPDiff!=0).
2182 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2183 SDValue Chain, SDValue RetAddrFrIdx,
2184 bool Is64Bit, int FPDiff, DebugLoc dl) {
2185 // Store the return address to the appropriate stack slot.
2186 if (!FPDiff) return Chain;
2187 // Calculate the new stack slot for the return address.
2188 int SlotSize = Is64Bit ? 8 : 4;
2189 int NewReturnAddrFI =
2190 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2191 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2192 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2193 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2194 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2200 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2201 SmallVectorImpl<SDValue> &InVals) const {
2202 SelectionDAG &DAG = CLI.DAG;
2203 DebugLoc &dl = CLI.DL;
2204 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2205 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2206 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2207 SDValue Chain = CLI.Chain;
2208 SDValue Callee = CLI.Callee;
2209 CallingConv::ID CallConv = CLI.CallConv;
2210 bool &isTailCall = CLI.IsTailCall;
2211 bool isVarArg = CLI.IsVarArg;
2213 MachineFunction &MF = DAG.getMachineFunction();
2214 bool Is64Bit = Subtarget->is64Bit();
2215 bool IsWin64 = Subtarget->isTargetWin64();
2216 bool IsWindows = Subtarget->isTargetWindows();
2217 StructReturnType SR = callIsStructReturn(Outs);
2218 bool IsSibcall = false;
2220 if (MF.getTarget().Options.DisableTailCalls)
2224 // Check if it's really possible to do a tail call.
2225 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2226 isVarArg, SR != NotStructReturn,
2227 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2228 Outs, OutVals, Ins, DAG);
2230 // Sibcalls are automatically detected tailcalls which do not require
2232 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2239 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2240 "Var args not supported with calling convention fastcc or ghc");
2242 // Analyze operands of the call, assigning locations to each operand.
2243 SmallVector<CCValAssign, 16> ArgLocs;
2244 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2245 ArgLocs, *DAG.getContext());
2247 // Allocate shadow area for Win64
2249 CCInfo.AllocateStack(32, 8);
2252 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2254 // Get a count of how many bytes are to be pushed on the stack.
2255 unsigned NumBytes = CCInfo.getNextStackOffset();
2257 // This is a sibcall. The memory operands are available in caller's
2258 // own caller's stack.
2260 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2261 IsTailCallConvention(CallConv))
2262 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2265 if (isTailCall && !IsSibcall) {
2266 // Lower arguments at fp - stackoffset + fpdiff.
2267 unsigned NumBytesCallerPushed =
2268 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2269 FPDiff = NumBytesCallerPushed - NumBytes;
2271 // Set the delta of movement of the returnaddr stackslot.
2272 // But only set if delta is greater than previous delta.
2273 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2274 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2278 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2280 SDValue RetAddrFrIdx;
2281 // Load return address for tail calls.
2282 if (isTailCall && FPDiff)
2283 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2284 Is64Bit, FPDiff, dl);
2286 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2287 SmallVector<SDValue, 8> MemOpChains;
2290 // Walk the register/memloc assignments, inserting copies/loads. In the case
2291 // of tail call optimization arguments are handle later.
2292 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2293 CCValAssign &VA = ArgLocs[i];
2294 EVT RegVT = VA.getLocVT();
2295 SDValue Arg = OutVals[i];
2296 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2297 bool isByVal = Flags.isByVal();
2299 // Promote the value if needed.
2300 switch (VA.getLocInfo()) {
2301 default: llvm_unreachable("Unknown loc info!");
2302 case CCValAssign::Full: break;
2303 case CCValAssign::SExt:
2304 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2306 case CCValAssign::ZExt:
2307 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2309 case CCValAssign::AExt:
2310 if (RegVT.is128BitVector()) {
2311 // Special case: passing MMX values in XMM registers.
2312 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2313 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2314 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2316 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2318 case CCValAssign::BCvt:
2319 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2321 case CCValAssign::Indirect: {
2322 // Store the argument.
2323 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2324 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2325 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2326 MachinePointerInfo::getFixedStack(FI),
2333 if (VA.isRegLoc()) {
2334 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2335 if (isVarArg && IsWin64) {
2336 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2337 // shadow reg if callee is a varargs function.
2338 unsigned ShadowReg = 0;
2339 switch (VA.getLocReg()) {
2340 case X86::XMM0: ShadowReg = X86::RCX; break;
2341 case X86::XMM1: ShadowReg = X86::RDX; break;
2342 case X86::XMM2: ShadowReg = X86::R8; break;
2343 case X86::XMM3: ShadowReg = X86::R9; break;
2346 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2348 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2349 assert(VA.isMemLoc());
2350 if (StackPtr.getNode() == 0)
2351 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2352 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2353 dl, DAG, VA, Flags));
2357 if (!MemOpChains.empty())
2358 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2359 &MemOpChains[0], MemOpChains.size());
2361 if (Subtarget->isPICStyleGOT()) {
2362 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2365 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2366 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2368 // If we are tail calling and generating PIC/GOT style code load the
2369 // address of the callee into ECX. The value in ecx is used as target of
2370 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2371 // for tail calls on PIC/GOT architectures. Normally we would just put the
2372 // address of GOT into ebx and then call target@PLT. But for tail calls
2373 // ebx would be restored (since ebx is callee saved) before jumping to the
2376 // Note: The actual moving to ECX is done further down.
2377 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2378 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2379 !G->getGlobal()->hasProtectedVisibility())
2380 Callee = LowerGlobalAddress(Callee, DAG);
2381 else if (isa<ExternalSymbolSDNode>(Callee))
2382 Callee = LowerExternalSymbol(Callee, DAG);
2386 if (Is64Bit && isVarArg && !IsWin64) {
2387 // From AMD64 ABI document:
2388 // For calls that may call functions that use varargs or stdargs
2389 // (prototype-less calls or calls to functions containing ellipsis (...) in
2390 // the declaration) %al is used as hidden argument to specify the number
2391 // of SSE registers used. The contents of %al do not need to match exactly
2392 // the number of registers, but must be an ubound on the number of SSE
2393 // registers used and is in the range 0 - 8 inclusive.
2395 // Count the number of XMM registers allocated.
2396 static const uint16_t XMMArgRegs[] = {
2397 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2398 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2400 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2401 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2402 && "SSE registers cannot be used when SSE is disabled");
2404 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2405 DAG.getConstant(NumXMMRegs, MVT::i8)));
2408 // For tail calls lower the arguments to the 'real' stack slot.
2410 // Force all the incoming stack arguments to be loaded from the stack
2411 // before any new outgoing arguments are stored to the stack, because the
2412 // outgoing stack slots may alias the incoming argument stack slots, and
2413 // the alias isn't otherwise explicit. This is slightly more conservative
2414 // than necessary, because it means that each store effectively depends
2415 // on every argument instead of just those arguments it would clobber.
2416 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2418 SmallVector<SDValue, 8> MemOpChains2;
2421 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2422 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2423 CCValAssign &VA = ArgLocs[i];
2426 assert(VA.isMemLoc());
2427 SDValue Arg = OutVals[i];
2428 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2429 // Create frame index.
2430 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2431 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2432 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2433 FIN = DAG.getFrameIndex(FI, getPointerTy());
2435 if (Flags.isByVal()) {
2436 // Copy relative to framepointer.
2437 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2438 if (StackPtr.getNode() == 0)
2439 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2441 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2443 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2447 // Store relative to framepointer.
2448 MemOpChains2.push_back(
2449 DAG.getStore(ArgChain, dl, Arg, FIN,
2450 MachinePointerInfo::getFixedStack(FI),
2456 if (!MemOpChains2.empty())
2457 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2458 &MemOpChains2[0], MemOpChains2.size());
2460 // Store the return address to the appropriate stack slot.
2461 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2465 // Build a sequence of copy-to-reg nodes chained together with token chain
2466 // and flag operands which copy the outgoing args into registers.
2468 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2469 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2470 RegsToPass[i].second, InFlag);
2471 InFlag = Chain.getValue(1);
2474 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2475 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2476 // In the 64-bit large code model, we have to make all calls
2477 // through a register, since the call instruction's 32-bit
2478 // pc-relative offset may not be large enough to hold the whole
2480 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2481 // If the callee is a GlobalAddress node (quite common, every direct call
2482 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2485 // We should use extra load for direct calls to dllimported functions in
2487 const GlobalValue *GV = G->getGlobal();
2488 if (!GV->hasDLLImportLinkage()) {
2489 unsigned char OpFlags = 0;
2490 bool ExtraLoad = false;
2491 unsigned WrapperKind = ISD::DELETED_NODE;
2493 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2494 // external symbols most go through the PLT in PIC mode. If the symbol
2495 // has hidden or protected visibility, or if it is static or local, then
2496 // we don't need to use the PLT - we can directly call it.
2497 if (Subtarget->isTargetELF() &&
2498 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2499 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2500 OpFlags = X86II::MO_PLT;
2501 } else if (Subtarget->isPICStyleStubAny() &&
2502 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2503 (!Subtarget->getTargetTriple().isMacOSX() ||
2504 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2505 // PC-relative references to external symbols should go through $stub,
2506 // unless we're building with the leopard linker or later, which
2507 // automatically synthesizes these stubs.
2508 OpFlags = X86II::MO_DARWIN_STUB;
2509 } else if (Subtarget->isPICStyleRIPRel() &&
2510 isa<Function>(GV) &&
2511 cast<Function>(GV)->getFnAttributes().
2512 hasAttribute(Attributes::NonLazyBind)) {
2513 // If the function is marked as non-lazy, generate an indirect call
2514 // which loads from the GOT directly. This avoids runtime overhead
2515 // at the cost of eager binding (and one extra byte of encoding).
2516 OpFlags = X86II::MO_GOTPCREL;
2517 WrapperKind = X86ISD::WrapperRIP;
2521 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2522 G->getOffset(), OpFlags);
2524 // Add a wrapper if needed.
2525 if (WrapperKind != ISD::DELETED_NODE)
2526 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2527 // Add extra indirection if needed.
2529 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2530 MachinePointerInfo::getGOT(),
2531 false, false, false, 0);
2533 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2534 unsigned char OpFlags = 0;
2536 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2537 // external symbols should go through the PLT.
2538 if (Subtarget->isTargetELF() &&
2539 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2540 OpFlags = X86II::MO_PLT;
2541 } else if (Subtarget->isPICStyleStubAny() &&
2542 (!Subtarget->getTargetTriple().isMacOSX() ||
2543 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2544 // PC-relative references to external symbols should go through $stub,
2545 // unless we're building with the leopard linker or later, which
2546 // automatically synthesizes these stubs.
2547 OpFlags = X86II::MO_DARWIN_STUB;
2550 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2554 // Returns a chain & a flag for retval copy to use.
2555 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2556 SmallVector<SDValue, 8> Ops;
2558 if (!IsSibcall && isTailCall) {
2559 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2560 DAG.getIntPtrConstant(0, true), InFlag);
2561 InFlag = Chain.getValue(1);
2564 Ops.push_back(Chain);
2565 Ops.push_back(Callee);
2568 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2570 // Add argument registers to the end of the list so that they are known live
2572 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2573 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2574 RegsToPass[i].second.getValueType()));
2576 // Add a register mask operand representing the call-preserved registers.
2577 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2578 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2579 assert(Mask && "Missing call preserved mask for calling convention");
2580 Ops.push_back(DAG.getRegisterMask(Mask));
2582 if (InFlag.getNode())
2583 Ops.push_back(InFlag);
2587 //// If this is the first return lowered for this function, add the regs
2588 //// to the liveout set for the function.
2589 // This isn't right, although it's probably harmless on x86; liveouts
2590 // should be computed from returns not tail calls. Consider a void
2591 // function making a tail call to a function returning int.
2592 return DAG.getNode(X86ISD::TC_RETURN, dl,
2593 NodeTys, &Ops[0], Ops.size());
2596 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2597 InFlag = Chain.getValue(1);
2599 // Create the CALLSEQ_END node.
2600 unsigned NumBytesForCalleeToPush;
2601 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2602 getTargetMachine().Options.GuaranteedTailCallOpt))
2603 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2604 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2605 SR == StackStructReturn)
2606 // If this is a call to a struct-return function, the callee
2607 // pops the hidden struct pointer, so we have to push it back.
2608 // This is common for Darwin/X86, Linux & Mingw32 targets.
2609 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2610 NumBytesForCalleeToPush = 4;
2612 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2614 // Returns a flag for retval copy to use.
2616 Chain = DAG.getCALLSEQ_END(Chain,
2617 DAG.getIntPtrConstant(NumBytes, true),
2618 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2621 InFlag = Chain.getValue(1);
2624 // Handle result values, copying them out of physregs into vregs that we
2626 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2627 Ins, dl, DAG, InVals);
2631 //===----------------------------------------------------------------------===//
2632 // Fast Calling Convention (tail call) implementation
2633 //===----------------------------------------------------------------------===//
2635 // Like std call, callee cleans arguments, convention except that ECX is
2636 // reserved for storing the tail called function address. Only 2 registers are
2637 // free for argument passing (inreg). Tail call optimization is performed
2639 // * tailcallopt is enabled
2640 // * caller/callee are fastcc
2641 // On X86_64 architecture with GOT-style position independent code only local
2642 // (within module) calls are supported at the moment.
2643 // To keep the stack aligned according to platform abi the function
2644 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2645 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2646 // If a tail called function callee has more arguments than the caller the
2647 // caller needs to make sure that there is room to move the RETADDR to. This is
2648 // achieved by reserving an area the size of the argument delta right after the
2649 // original REtADDR, but before the saved framepointer or the spilled registers
2650 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2662 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2663 /// for a 16 byte align requirement.
2665 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2666 SelectionDAG& DAG) const {
2667 MachineFunction &MF = DAG.getMachineFunction();
2668 const TargetMachine &TM = MF.getTarget();
2669 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2670 unsigned StackAlignment = TFI.getStackAlignment();
2671 uint64_t AlignMask = StackAlignment - 1;
2672 int64_t Offset = StackSize;
2673 uint64_t SlotSize = TD->getPointerSize(0);
2674 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2675 // Number smaller than 12 so just add the difference.
2676 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2678 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2679 Offset = ((~AlignMask) & Offset) + StackAlignment +
2680 (StackAlignment-SlotSize);
2685 /// MatchingStackOffset - Return true if the given stack call argument is
2686 /// already available in the same position (relatively) of the caller's
2687 /// incoming argument stack.
2689 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2690 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2691 const X86InstrInfo *TII) {
2692 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2694 if (Arg.getOpcode() == ISD::CopyFromReg) {
2695 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2696 if (!TargetRegisterInfo::isVirtualRegister(VR))
2698 MachineInstr *Def = MRI->getVRegDef(VR);
2701 if (!Flags.isByVal()) {
2702 if (!TII->isLoadFromStackSlot(Def, FI))
2705 unsigned Opcode = Def->getOpcode();
2706 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2707 Def->getOperand(1).isFI()) {
2708 FI = Def->getOperand(1).getIndex();
2709 Bytes = Flags.getByValSize();
2713 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2714 if (Flags.isByVal())
2715 // ByVal argument is passed in as a pointer but it's now being
2716 // dereferenced. e.g.
2717 // define @foo(%struct.X* %A) {
2718 // tail call @bar(%struct.X* byval %A)
2721 SDValue Ptr = Ld->getBasePtr();
2722 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2725 FI = FINode->getIndex();
2726 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2727 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2728 FI = FINode->getIndex();
2729 Bytes = Flags.getByValSize();
2733 assert(FI != INT_MAX);
2734 if (!MFI->isFixedObjectIndex(FI))
2736 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2739 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2740 /// for tail call optimization. Targets which want to do tail call
2741 /// optimization should implement this function.
2743 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2744 CallingConv::ID CalleeCC,
2746 bool isCalleeStructRet,
2747 bool isCallerStructRet,
2749 const SmallVectorImpl<ISD::OutputArg> &Outs,
2750 const SmallVectorImpl<SDValue> &OutVals,
2751 const SmallVectorImpl<ISD::InputArg> &Ins,
2752 SelectionDAG& DAG) const {
2753 if (!IsTailCallConvention(CalleeCC) &&
2754 CalleeCC != CallingConv::C)
2757 // If -tailcallopt is specified, make fastcc functions tail-callable.
2758 const MachineFunction &MF = DAG.getMachineFunction();
2759 const Function *CallerF = DAG.getMachineFunction().getFunction();
2761 // If the function return type is x86_fp80 and the callee return type is not,
2762 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2763 // perform a tailcall optimization here.
2764 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2767 CallingConv::ID CallerCC = CallerF->getCallingConv();
2768 bool CCMatch = CallerCC == CalleeCC;
2770 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2771 if (IsTailCallConvention(CalleeCC) && CCMatch)
2776 // Look for obvious safe cases to perform tail call optimization that do not
2777 // require ABI changes. This is what gcc calls sibcall.
2779 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2780 // emit a special epilogue.
2781 if (RegInfo->needsStackRealignment(MF))
2784 // Also avoid sibcall optimization if either caller or callee uses struct
2785 // return semantics.
2786 if (isCalleeStructRet || isCallerStructRet)
2789 // An stdcall caller is expected to clean up its arguments; the callee
2790 // isn't going to do that.
2791 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2794 // Do not sibcall optimize vararg calls unless all arguments are passed via
2796 if (isVarArg && !Outs.empty()) {
2798 // Optimizing for varargs on Win64 is unlikely to be safe without
2799 // additional testing.
2800 if (Subtarget->isTargetWin64())
2803 SmallVector<CCValAssign, 16> ArgLocs;
2804 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2805 getTargetMachine(), ArgLocs, *DAG.getContext());
2807 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2808 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2809 if (!ArgLocs[i].isRegLoc())
2813 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2814 // stack. Therefore, if it's not used by the call it is not safe to optimize
2815 // this into a sibcall.
2816 bool Unused = false;
2817 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2824 SmallVector<CCValAssign, 16> RVLocs;
2825 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2826 getTargetMachine(), RVLocs, *DAG.getContext());
2827 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2828 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2829 CCValAssign &VA = RVLocs[i];
2830 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2835 // If the calling conventions do not match, then we'd better make sure the
2836 // results are returned in the same way as what the caller expects.
2838 SmallVector<CCValAssign, 16> RVLocs1;
2839 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2840 getTargetMachine(), RVLocs1, *DAG.getContext());
2841 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2843 SmallVector<CCValAssign, 16> RVLocs2;
2844 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2845 getTargetMachine(), RVLocs2, *DAG.getContext());
2846 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2848 if (RVLocs1.size() != RVLocs2.size())
2850 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2851 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2853 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2855 if (RVLocs1[i].isRegLoc()) {
2856 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2859 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2865 // If the callee takes no arguments then go on to check the results of the
2867 if (!Outs.empty()) {
2868 // Check if stack adjustment is needed. For now, do not do this if any
2869 // argument is passed on the stack.
2870 SmallVector<CCValAssign, 16> ArgLocs;
2871 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2872 getTargetMachine(), ArgLocs, *DAG.getContext());
2874 // Allocate shadow area for Win64
2875 if (Subtarget->isTargetWin64()) {
2876 CCInfo.AllocateStack(32, 8);
2879 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2880 if (CCInfo.getNextStackOffset()) {
2881 MachineFunction &MF = DAG.getMachineFunction();
2882 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2885 // Check if the arguments are already laid out in the right way as
2886 // the caller's fixed stack objects.
2887 MachineFrameInfo *MFI = MF.getFrameInfo();
2888 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2889 const X86InstrInfo *TII =
2890 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2891 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2892 CCValAssign &VA = ArgLocs[i];
2893 SDValue Arg = OutVals[i];
2894 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2895 if (VA.getLocInfo() == CCValAssign::Indirect)
2897 if (!VA.isRegLoc()) {
2898 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2905 // If the tailcall address may be in a register, then make sure it's
2906 // possible to register allocate for it. In 32-bit, the call address can
2907 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2908 // callee-saved registers are restored. These happen to be the same
2909 // registers used to pass 'inreg' arguments so watch out for those.
2910 if (!Subtarget->is64Bit() &&
2911 !isa<GlobalAddressSDNode>(Callee) &&
2912 !isa<ExternalSymbolSDNode>(Callee)) {
2913 unsigned NumInRegs = 0;
2914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2915 CCValAssign &VA = ArgLocs[i];
2918 unsigned Reg = VA.getLocReg();
2921 case X86::EAX: case X86::EDX: case X86::ECX:
2922 if (++NumInRegs == 3)
2934 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2935 const TargetLibraryInfo *libInfo) const {
2936 return X86::createFastISel(funcInfo, libInfo);
2940 //===----------------------------------------------------------------------===//
2941 // Other Lowering Hooks
2942 //===----------------------------------------------------------------------===//
2944 static bool MayFoldLoad(SDValue Op) {
2945 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2948 static bool MayFoldIntoStore(SDValue Op) {
2949 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2952 static bool isTargetShuffle(unsigned Opcode) {
2954 default: return false;
2955 case X86ISD::PSHUFD:
2956 case X86ISD::PSHUFHW:
2957 case X86ISD::PSHUFLW:
2959 case X86ISD::PALIGN:
2960 case X86ISD::MOVLHPS:
2961 case X86ISD::MOVLHPD:
2962 case X86ISD::MOVHLPS:
2963 case X86ISD::MOVLPS:
2964 case X86ISD::MOVLPD:
2965 case X86ISD::MOVSHDUP:
2966 case X86ISD::MOVSLDUP:
2967 case X86ISD::MOVDDUP:
2970 case X86ISD::UNPCKL:
2971 case X86ISD::UNPCKH:
2972 case X86ISD::VPERMILP:
2973 case X86ISD::VPERM2X128:
2974 case X86ISD::VPERMI:
2979 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2980 SDValue V1, SelectionDAG &DAG) {
2982 default: llvm_unreachable("Unknown x86 shuffle node");
2983 case X86ISD::MOVSHDUP:
2984 case X86ISD::MOVSLDUP:
2985 case X86ISD::MOVDDUP:
2986 return DAG.getNode(Opc, dl, VT, V1);
2990 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2991 SDValue V1, unsigned TargetMask,
2992 SelectionDAG &DAG) {
2994 default: llvm_unreachable("Unknown x86 shuffle node");
2995 case X86ISD::PSHUFD:
2996 case X86ISD::PSHUFHW:
2997 case X86ISD::PSHUFLW:
2998 case X86ISD::VPERMILP:
2999 case X86ISD::VPERMI:
3000 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3004 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3005 SDValue V1, SDValue V2, unsigned TargetMask,
3006 SelectionDAG &DAG) {
3008 default: llvm_unreachable("Unknown x86 shuffle node");
3009 case X86ISD::PALIGN:
3011 case X86ISD::VPERM2X128:
3012 return DAG.getNode(Opc, dl, VT, V1, V2,
3013 DAG.getConstant(TargetMask, MVT::i8));
3017 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3018 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3020 default: llvm_unreachable("Unknown x86 shuffle node");
3021 case X86ISD::MOVLHPS:
3022 case X86ISD::MOVLHPD:
3023 case X86ISD::MOVHLPS:
3024 case X86ISD::MOVLPS:
3025 case X86ISD::MOVLPD:
3028 case X86ISD::UNPCKL:
3029 case X86ISD::UNPCKH:
3030 return DAG.getNode(Opc, dl, VT, V1, V2);
3034 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3035 MachineFunction &MF = DAG.getMachineFunction();
3036 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3037 int ReturnAddrIndex = FuncInfo->getRAIndex();
3039 if (ReturnAddrIndex == 0) {
3040 // Set up a frame object for the return address.
3041 uint64_t SlotSize = TD->getPointerSize(0);
3042 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3044 FuncInfo->setRAIndex(ReturnAddrIndex);
3047 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3051 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3052 bool hasSymbolicDisplacement) {
3053 // Offset should fit into 32 bit immediate field.
3054 if (!isInt<32>(Offset))
3057 // If we don't have a symbolic displacement - we don't have any extra
3059 if (!hasSymbolicDisplacement)
3062 // FIXME: Some tweaks might be needed for medium code model.
3063 if (M != CodeModel::Small && M != CodeModel::Kernel)
3066 // For small code model we assume that latest object is 16MB before end of 31
3067 // bits boundary. We may also accept pretty large negative constants knowing
3068 // that all objects are in the positive half of address space.
3069 if (M == CodeModel::Small && Offset < 16*1024*1024)
3072 // For kernel code model we know that all object resist in the negative half
3073 // of 32bits address space. We may not accept negative offsets, since they may
3074 // be just off and we may accept pretty large positive ones.
3075 if (M == CodeModel::Kernel && Offset > 0)
3081 /// isCalleePop - Determines whether the callee is required to pop its
3082 /// own arguments. Callee pop is necessary to support tail calls.
3083 bool X86::isCalleePop(CallingConv::ID CallingConv,
3084 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3088 switch (CallingConv) {
3091 case CallingConv::X86_StdCall:
3093 case CallingConv::X86_FastCall:
3095 case CallingConv::X86_ThisCall:
3097 case CallingConv::Fast:
3099 case CallingConv::GHC:
3104 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3105 /// specific condition code, returning the condition code and the LHS/RHS of the
3106 /// comparison to make.
3107 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3108 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3110 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3111 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3112 // X > -1 -> X == 0, jump !sign.
3113 RHS = DAG.getConstant(0, RHS.getValueType());
3114 return X86::COND_NS;
3116 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3117 // X < 0 -> X == 0, jump on sign.
3120 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3122 RHS = DAG.getConstant(0, RHS.getValueType());
3123 return X86::COND_LE;
3127 switch (SetCCOpcode) {
3128 default: llvm_unreachable("Invalid integer condition!");
3129 case ISD::SETEQ: return X86::COND_E;
3130 case ISD::SETGT: return X86::COND_G;
3131 case ISD::SETGE: return X86::COND_GE;
3132 case ISD::SETLT: return X86::COND_L;
3133 case ISD::SETLE: return X86::COND_LE;
3134 case ISD::SETNE: return X86::COND_NE;
3135 case ISD::SETULT: return X86::COND_B;
3136 case ISD::SETUGT: return X86::COND_A;
3137 case ISD::SETULE: return X86::COND_BE;
3138 case ISD::SETUGE: return X86::COND_AE;
3142 // First determine if it is required or is profitable to flip the operands.
3144 // If LHS is a foldable load, but RHS is not, flip the condition.
3145 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3146 !ISD::isNON_EXTLoad(RHS.getNode())) {
3147 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3148 std::swap(LHS, RHS);
3151 switch (SetCCOpcode) {
3157 std::swap(LHS, RHS);
3161 // On a floating point condition, the flags are set as follows:
3163 // 0 | 0 | 0 | X > Y
3164 // 0 | 0 | 1 | X < Y
3165 // 1 | 0 | 0 | X == Y
3166 // 1 | 1 | 1 | unordered
3167 switch (SetCCOpcode) {
3168 default: llvm_unreachable("Condcode should be pre-legalized away");
3170 case ISD::SETEQ: return X86::COND_E;
3171 case ISD::SETOLT: // flipped
3173 case ISD::SETGT: return X86::COND_A;
3174 case ISD::SETOLE: // flipped
3176 case ISD::SETGE: return X86::COND_AE;
3177 case ISD::SETUGT: // flipped
3179 case ISD::SETLT: return X86::COND_B;
3180 case ISD::SETUGE: // flipped
3182 case ISD::SETLE: return X86::COND_BE;
3184 case ISD::SETNE: return X86::COND_NE;
3185 case ISD::SETUO: return X86::COND_P;
3186 case ISD::SETO: return X86::COND_NP;
3188 case ISD::SETUNE: return X86::COND_INVALID;
3192 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3193 /// code. Current x86 isa includes the following FP cmov instructions:
3194 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3195 static bool hasFPCMov(unsigned X86CC) {
3211 /// isFPImmLegal - Returns true if the target can instruction select the
3212 /// specified FP immediate natively. If false, the legalizer will
3213 /// materialize the FP immediate as a load from a constant pool.
3214 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3215 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3216 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3222 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3223 /// the specified range (L, H].
3224 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3225 return (Val < 0) || (Val >= Low && Val < Hi);
3228 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3229 /// specified value.
3230 static bool isUndefOrEqual(int Val, int CmpVal) {
3231 if (Val < 0 || Val == CmpVal)
3236 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3237 /// from position Pos and ending in Pos+Size, falls within the specified
3238 /// sequential range (L, L+Pos]. or is undef.
3239 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3240 unsigned Pos, unsigned Size, int Low) {
3241 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3242 if (!isUndefOrEqual(Mask[i], Low))
3247 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3248 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3249 /// the second operand.
3250 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3251 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3252 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3253 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3254 return (Mask[0] < 2 && Mask[1] < 2);
3258 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3259 /// is suitable for input to PSHUFHW.
3260 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3261 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3264 // Lower quadword copied in order or undef.
3265 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3268 // Upper quadword shuffled.
3269 for (unsigned i = 4; i != 8; ++i)
3270 if (!isUndefOrInRange(Mask[i], 4, 8))
3273 if (VT == MVT::v16i16) {
3274 // Lower quadword copied in order or undef.
3275 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3278 // Upper quadword shuffled.
3279 for (unsigned i = 12; i != 16; ++i)
3280 if (!isUndefOrInRange(Mask[i], 12, 16))
3287 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFLW.
3289 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3290 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3293 // Upper quadword copied in order.
3294 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3297 // Lower quadword shuffled.
3298 for (unsigned i = 0; i != 4; ++i)
3299 if (!isUndefOrInRange(Mask[i], 0, 4))
3302 if (VT == MVT::v16i16) {
3303 // Upper quadword copied in order.
3304 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3307 // Lower quadword shuffled.
3308 for (unsigned i = 8; i != 12; ++i)
3309 if (!isUndefOrInRange(Mask[i], 8, 12))
3316 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PALIGNR.
3318 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3319 const X86Subtarget *Subtarget) {
3320 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3321 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3324 unsigned NumElts = VT.getVectorNumElements();
3325 unsigned NumLanes = VT.getSizeInBits()/128;
3326 unsigned NumLaneElts = NumElts/NumLanes;
3328 // Do not handle 64-bit element shuffles with palignr.
3329 if (NumLaneElts == 2)
3332 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3334 for (i = 0; i != NumLaneElts; ++i) {
3339 // Lane is all undef, go to next lane
3340 if (i == NumLaneElts)
3343 int Start = Mask[i+l];
3345 // Make sure its in this lane in one of the sources
3346 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3347 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3350 // If not lane 0, then we must match lane 0
3351 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3354 // Correct second source to be contiguous with first source
3355 if (Start >= (int)NumElts)
3356 Start -= NumElts - NumLaneElts;
3358 // Make sure we're shifting in the right direction.
3359 if (Start <= (int)(i+l))
3364 // Check the rest of the elements to see if they are consecutive.
3365 for (++i; i != NumLaneElts; ++i) {
3366 int Idx = Mask[i+l];
3368 // Make sure its in this lane
3369 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3370 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3373 // If not lane 0, then we must match lane 0
3374 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3377 if (Idx >= (int)NumElts)
3378 Idx -= NumElts - NumLaneElts;
3380 if (!isUndefOrEqual(Idx, Start+i))
3389 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3390 /// the two vector operands have swapped position.
3391 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3392 unsigned NumElems) {
3393 for (unsigned i = 0; i != NumElems; ++i) {
3397 else if (idx < (int)NumElems)
3398 Mask[i] = idx + NumElems;
3400 Mask[i] = idx - NumElems;
3404 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3405 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3406 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3407 /// reverse of what x86 shuffles want.
3408 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3409 bool Commuted = false) {
3410 if (!HasAVX && VT.getSizeInBits() == 256)
3413 unsigned NumElems = VT.getVectorNumElements();
3414 unsigned NumLanes = VT.getSizeInBits()/128;
3415 unsigned NumLaneElems = NumElems/NumLanes;
3417 if (NumLaneElems != 2 && NumLaneElems != 4)
3420 // VSHUFPSY divides the resulting vector into 4 chunks.
3421 // The sources are also splitted into 4 chunks, and each destination
3422 // chunk must come from a different source chunk.
3424 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3425 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3427 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3428 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3430 // VSHUFPDY divides the resulting vector into 4 chunks.
3431 // The sources are also splitted into 4 chunks, and each destination
3432 // chunk must come from a different source chunk.
3434 // SRC1 => X3 X2 X1 X0
3435 // SRC2 => Y3 Y2 Y1 Y0
3437 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3439 unsigned HalfLaneElems = NumLaneElems/2;
3440 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3441 for (unsigned i = 0; i != NumLaneElems; ++i) {
3442 int Idx = Mask[i+l];
3443 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3444 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3446 // For VSHUFPSY, the mask of the second half must be the same as the
3447 // first but with the appropriate offsets. This works in the same way as
3448 // VPERMILPS works with masks.
3449 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3451 if (!isUndefOrEqual(Idx, Mask[i]+l))
3459 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3460 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3461 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3462 if (!VT.is128BitVector())
3465 unsigned NumElems = VT.getVectorNumElements();
3470 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3471 return isUndefOrEqual(Mask[0], 6) &&
3472 isUndefOrEqual(Mask[1], 7) &&
3473 isUndefOrEqual(Mask[2], 2) &&
3474 isUndefOrEqual(Mask[3], 3);
3477 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3478 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3480 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3481 if (!VT.is128BitVector())
3484 unsigned NumElems = VT.getVectorNumElements();
3489 return isUndefOrEqual(Mask[0], 2) &&
3490 isUndefOrEqual(Mask[1], 3) &&
3491 isUndefOrEqual(Mask[2], 2) &&
3492 isUndefOrEqual(Mask[3], 3);
3495 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3496 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3497 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3498 if (!VT.is128BitVector())
3501 unsigned NumElems = VT.getVectorNumElements();
3503 if (NumElems != 2 && NumElems != 4)
3506 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3507 if (!isUndefOrEqual(Mask[i], i + NumElems))
3510 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3511 if (!isUndefOrEqual(Mask[i], i))
3517 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3518 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3519 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3520 if (!VT.is128BitVector())
3523 unsigned NumElems = VT.getVectorNumElements();
3525 if (NumElems != 2 && NumElems != 4)
3528 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3529 if (!isUndefOrEqual(Mask[i], i))
3532 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3533 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3540 // Some special combinations that can be optimized.
3543 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3544 SelectionDAG &DAG) {
3545 EVT VT = SVOp->getValueType(0);
3546 DebugLoc dl = SVOp->getDebugLoc();
3548 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3551 ArrayRef<int> Mask = SVOp->getMask();
3553 // These are the special masks that may be optimized.
3554 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3555 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3556 bool MatchEvenMask = true;
3557 bool MatchOddMask = true;
3558 for (int i=0; i<8; ++i) {
3559 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3560 MatchEvenMask = false;
3561 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3562 MatchOddMask = false;
3565 if (!MatchEvenMask && !MatchOddMask)
3568 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3570 SDValue Op0 = SVOp->getOperand(0);
3571 SDValue Op1 = SVOp->getOperand(1);
3573 if (MatchEvenMask) {
3574 // Shift the second operand right to 32 bits.
3575 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3576 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3578 // Shift the first operand left to 32 bits.
3579 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3580 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3582 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3583 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3586 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3587 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3588 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3589 bool HasAVX2, bool V2IsSplat = false) {
3590 unsigned NumElts = VT.getVectorNumElements();
3592 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3593 "Unsupported vector type for unpckh");
3595 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3596 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3599 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3600 // independently on 128-bit lanes.
3601 unsigned NumLanes = VT.getSizeInBits()/128;
3602 unsigned NumLaneElts = NumElts/NumLanes;
3604 for (unsigned l = 0; l != NumLanes; ++l) {
3605 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3606 i != (l+1)*NumLaneElts;
3609 int BitI1 = Mask[i+1];
3610 if (!isUndefOrEqual(BitI, j))
3613 if (!isUndefOrEqual(BitI1, NumElts))
3616 if (!isUndefOrEqual(BitI1, j + NumElts))
3625 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3626 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3627 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3628 bool HasAVX2, bool V2IsSplat = false) {
3629 unsigned NumElts = VT.getVectorNumElements();
3631 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3632 "Unsupported vector type for unpckh");
3634 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3635 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3638 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3639 // independently on 128-bit lanes.
3640 unsigned NumLanes = VT.getSizeInBits()/128;
3641 unsigned NumLaneElts = NumElts/NumLanes;
3643 for (unsigned l = 0; l != NumLanes; ++l) {
3644 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3645 i != (l+1)*NumLaneElts; i += 2, ++j) {
3647 int BitI1 = Mask[i+1];
3648 if (!isUndefOrEqual(BitI, j))
3651 if (isUndefOrEqual(BitI1, NumElts))
3654 if (!isUndefOrEqual(BitI1, j+NumElts))
3662 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3663 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3665 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3667 unsigned NumElts = VT.getVectorNumElements();
3669 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3670 "Unsupported vector type for unpckh");
3672 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3673 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3676 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3677 // FIXME: Need a better way to get rid of this, there's no latency difference
3678 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3679 // the former later. We should also remove the "_undef" special mask.
3680 if (NumElts == 4 && VT.getSizeInBits() == 256)
3683 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3684 // independently on 128-bit lanes.
3685 unsigned NumLanes = VT.getSizeInBits()/128;
3686 unsigned NumLaneElts = NumElts/NumLanes;
3688 for (unsigned l = 0; l != NumLanes; ++l) {
3689 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3690 i != (l+1)*NumLaneElts;
3693 int BitI1 = Mask[i+1];
3695 if (!isUndefOrEqual(BitI, j))
3697 if (!isUndefOrEqual(BitI1, j))
3705 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3706 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3708 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3709 unsigned NumElts = VT.getVectorNumElements();
3711 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3712 "Unsupported vector type for unpckh");
3714 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3715 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3718 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3719 // independently on 128-bit lanes.
3720 unsigned NumLanes = VT.getSizeInBits()/128;
3721 unsigned NumLaneElts = NumElts/NumLanes;
3723 for (unsigned l = 0; l != NumLanes; ++l) {
3724 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3725 i != (l+1)*NumLaneElts; i += 2, ++j) {
3727 int BitI1 = Mask[i+1];
3728 if (!isUndefOrEqual(BitI, j))
3730 if (!isUndefOrEqual(BitI1, j))
3737 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3738 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3739 /// MOVSD, and MOVD, i.e. setting the lowest element.
3740 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3741 if (VT.getVectorElementType().getSizeInBits() < 32)
3743 if (!VT.is128BitVector())
3746 unsigned NumElts = VT.getVectorNumElements();
3748 if (!isUndefOrEqual(Mask[0], NumElts))
3751 for (unsigned i = 1; i != NumElts; ++i)
3752 if (!isUndefOrEqual(Mask[i], i))
3758 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3759 /// as permutations between 128-bit chunks or halves. As an example: this
3761 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3762 /// The first half comes from the second half of V1 and the second half from the
3763 /// the second half of V2.
3764 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3765 if (!HasAVX || !VT.is256BitVector())
3768 // The shuffle result is divided into half A and half B. In total the two
3769 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3770 // B must come from C, D, E or F.
3771 unsigned HalfSize = VT.getVectorNumElements()/2;
3772 bool MatchA = false, MatchB = false;
3774 // Check if A comes from one of C, D, E, F.
3775 for (unsigned Half = 0; Half != 4; ++Half) {
3776 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3782 // Check if B comes from one of C, D, E, F.
3783 for (unsigned Half = 0; Half != 4; ++Half) {
3784 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3790 return MatchA && MatchB;
3793 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3794 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3795 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3796 EVT VT = SVOp->getValueType(0);
3798 unsigned HalfSize = VT.getVectorNumElements()/2;
3800 unsigned FstHalf = 0, SndHalf = 0;
3801 for (unsigned i = 0; i < HalfSize; ++i) {
3802 if (SVOp->getMaskElt(i) > 0) {
3803 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3807 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3808 if (SVOp->getMaskElt(i) > 0) {
3809 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3814 return (FstHalf | (SndHalf << 4));
3817 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3818 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3819 /// Note that VPERMIL mask matching is different depending whether theunderlying
3820 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3821 /// to the same elements of the low, but to the higher half of the source.
3822 /// In VPERMILPD the two lanes could be shuffled independently of each other
3823 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3824 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3828 unsigned NumElts = VT.getVectorNumElements();
3829 // Only match 256-bit with 32/64-bit types
3830 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3833 unsigned NumLanes = VT.getSizeInBits()/128;
3834 unsigned LaneSize = NumElts/NumLanes;
3835 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3836 for (unsigned i = 0; i != LaneSize; ++i) {
3837 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3839 if (NumElts != 8 || l == 0)
3841 // VPERMILPS handling
3844 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3852 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3853 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3854 /// element of vector 2 and the other elements to come from vector 1 in order.
3855 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3856 bool V2IsSplat = false, bool V2IsUndef = false) {
3857 if (!VT.is128BitVector())
3860 unsigned NumOps = VT.getVectorNumElements();
3861 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3864 if (!isUndefOrEqual(Mask[0], 0))
3867 for (unsigned i = 1; i != NumOps; ++i)
3868 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3869 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3870 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3876 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3877 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3878 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3879 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3880 const X86Subtarget *Subtarget) {
3881 if (!Subtarget->hasSSE3())
3884 unsigned NumElems = VT.getVectorNumElements();
3886 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3887 (VT.getSizeInBits() == 256 && NumElems != 8))
3890 // "i+1" is the value the indexed mask element must have
3891 for (unsigned i = 0; i != NumElems; i += 2)
3892 if (!isUndefOrEqual(Mask[i], i+1) ||
3893 !isUndefOrEqual(Mask[i+1], i+1))
3899 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3900 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3901 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3902 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3903 const X86Subtarget *Subtarget) {
3904 if (!Subtarget->hasSSE3())
3907 unsigned NumElems = VT.getVectorNumElements();
3909 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3910 (VT.getSizeInBits() == 256 && NumElems != 8))
3913 // "i" is the value the indexed mask element must have
3914 for (unsigned i = 0; i != NumElems; i += 2)
3915 if (!isUndefOrEqual(Mask[i], i) ||
3916 !isUndefOrEqual(Mask[i+1], i))
3922 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3923 /// specifies a shuffle of elements that is suitable for input to 256-bit
3924 /// version of MOVDDUP.
3925 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3926 if (!HasAVX || !VT.is256BitVector())
3929 unsigned NumElts = VT.getVectorNumElements();
3933 for (unsigned i = 0; i != NumElts/2; ++i)
3934 if (!isUndefOrEqual(Mask[i], 0))
3936 for (unsigned i = NumElts/2; i != NumElts; ++i)
3937 if (!isUndefOrEqual(Mask[i], NumElts/2))
3942 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3943 /// specifies a shuffle of elements that is suitable for input to 128-bit
3944 /// version of MOVDDUP.
3945 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3946 if (!VT.is128BitVector())
3949 unsigned e = VT.getVectorNumElements() / 2;
3950 for (unsigned i = 0; i != e; ++i)
3951 if (!isUndefOrEqual(Mask[i], i))
3953 for (unsigned i = 0; i != e; ++i)
3954 if (!isUndefOrEqual(Mask[e+i], i))
3959 /// isVEXTRACTF128Index - Return true if the specified
3960 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3961 /// suitable for input to VEXTRACTF128.
3962 bool X86::isVEXTRACTF128Index(SDNode *N) {
3963 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3966 // The index should be aligned on a 128-bit boundary.
3968 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3970 unsigned VL = N->getValueType(0).getVectorNumElements();
3971 unsigned VBits = N->getValueType(0).getSizeInBits();
3972 unsigned ElSize = VBits / VL;
3973 bool Result = (Index * ElSize) % 128 == 0;
3978 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3979 /// operand specifies a subvector insert that is suitable for input to
3981 bool X86::isVINSERTF128Index(SDNode *N) {
3982 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3985 // The index should be aligned on a 128-bit boundary.
3987 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3989 unsigned VL = N->getValueType(0).getVectorNumElements();
3990 unsigned VBits = N->getValueType(0).getSizeInBits();
3991 unsigned ElSize = VBits / VL;
3992 bool Result = (Index * ElSize) % 128 == 0;
3997 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3998 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3999 /// Handles 128-bit and 256-bit.
4000 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4001 EVT VT = N->getValueType(0);
4003 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4004 "Unsupported vector type for PSHUF/SHUFP");
4006 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4007 // independently on 128-bit lanes.
4008 unsigned NumElts = VT.getVectorNumElements();
4009 unsigned NumLanes = VT.getSizeInBits()/128;
4010 unsigned NumLaneElts = NumElts/NumLanes;
4012 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4013 "Only supports 2 or 4 elements per lane");
4015 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4017 for (unsigned i = 0; i != NumElts; ++i) {
4018 int Elt = N->getMaskElt(i);
4019 if (Elt < 0) continue;
4020 Elt &= NumLaneElts - 1;
4021 unsigned ShAmt = (i << Shift) % 8;
4022 Mask |= Elt << ShAmt;
4028 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4029 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4030 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4031 EVT VT = N->getValueType(0);
4033 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4034 "Unsupported vector type for PSHUFHW");
4036 unsigned NumElts = VT.getVectorNumElements();
4039 for (unsigned l = 0; l != NumElts; l += 8) {
4040 // 8 nodes per lane, but we only care about the last 4.
4041 for (unsigned i = 0; i < 4; ++i) {
4042 int Elt = N->getMaskElt(l+i+4);
4043 if (Elt < 0) continue;
4044 Elt &= 0x3; // only 2-bits.
4045 Mask |= Elt << (i * 2);
4052 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4053 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4054 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4055 EVT VT = N->getValueType(0);
4057 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4058 "Unsupported vector type for PSHUFHW");
4060 unsigned NumElts = VT.getVectorNumElements();
4063 for (unsigned l = 0; l != NumElts; l += 8) {
4064 // 8 nodes per lane, but we only care about the first 4.
4065 for (unsigned i = 0; i < 4; ++i) {
4066 int Elt = N->getMaskElt(l+i);
4067 if (Elt < 0) continue;
4068 Elt &= 0x3; // only 2-bits
4069 Mask |= Elt << (i * 2);
4076 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4077 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4078 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4079 EVT VT = SVOp->getValueType(0);
4080 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4082 unsigned NumElts = VT.getVectorNumElements();
4083 unsigned NumLanes = VT.getSizeInBits()/128;
4084 unsigned NumLaneElts = NumElts/NumLanes;
4088 for (i = 0; i != NumElts; ++i) {
4089 Val = SVOp->getMaskElt(i);
4093 if (Val >= (int)NumElts)
4094 Val -= NumElts - NumLaneElts;
4096 assert(Val - i > 0 && "PALIGNR imm should be positive");
4097 return (Val - i) * EltSize;
4100 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4101 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4103 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4104 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4105 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4108 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4110 EVT VecVT = N->getOperand(0).getValueType();
4111 EVT ElVT = VecVT.getVectorElementType();
4113 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4114 return Index / NumElemsPerChunk;
4117 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4118 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4120 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4121 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4122 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4125 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4127 EVT VecVT = N->getValueType(0);
4128 EVT ElVT = VecVT.getVectorElementType();
4130 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4131 return Index / NumElemsPerChunk;
4134 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4135 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4136 /// Handles 256-bit.
4137 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4138 EVT VT = N->getValueType(0);
4140 unsigned NumElts = VT.getVectorNumElements();
4142 assert((VT.is256BitVector() && NumElts == 4) &&
4143 "Unsupported vector type for VPERMQ/VPERMPD");
4146 for (unsigned i = 0; i != NumElts; ++i) {
4147 int Elt = N->getMaskElt(i);
4150 Mask |= Elt << (i*2);
4155 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4157 bool X86::isZeroNode(SDValue Elt) {
4158 return ((isa<ConstantSDNode>(Elt) &&
4159 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4160 (isa<ConstantFPSDNode>(Elt) &&
4161 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4164 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4165 /// their permute mask.
4166 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4167 SelectionDAG &DAG) {
4168 EVT VT = SVOp->getValueType(0);
4169 unsigned NumElems = VT.getVectorNumElements();
4170 SmallVector<int, 8> MaskVec;
4172 for (unsigned i = 0; i != NumElems; ++i) {
4173 int Idx = SVOp->getMaskElt(i);
4175 if (Idx < (int)NumElems)
4180 MaskVec.push_back(Idx);
4182 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4183 SVOp->getOperand(0), &MaskVec[0]);
4186 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4187 /// match movhlps. The lower half elements should come from upper half of
4188 /// V1 (and in order), and the upper half elements should come from the upper
4189 /// half of V2 (and in order).
4190 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4191 if (!VT.is128BitVector())
4193 if (VT.getVectorNumElements() != 4)
4195 for (unsigned i = 0, e = 2; i != e; ++i)
4196 if (!isUndefOrEqual(Mask[i], i+2))
4198 for (unsigned i = 2; i != 4; ++i)
4199 if (!isUndefOrEqual(Mask[i], i+4))
4204 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4205 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4207 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4208 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4210 N = N->getOperand(0).getNode();
4211 if (!ISD::isNON_EXTLoad(N))
4214 *LD = cast<LoadSDNode>(N);
4218 // Test whether the given value is a vector value which will be legalized
4220 static bool WillBeConstantPoolLoad(SDNode *N) {
4221 if (N->getOpcode() != ISD::BUILD_VECTOR)
4224 // Check for any non-constant elements.
4225 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4226 switch (N->getOperand(i).getNode()->getOpcode()) {
4228 case ISD::ConstantFP:
4235 // Vectors of all-zeros and all-ones are materialized with special
4236 // instructions rather than being loaded.
4237 return !ISD::isBuildVectorAllZeros(N) &&
4238 !ISD::isBuildVectorAllOnes(N);
4241 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4242 /// match movlp{s|d}. The lower half elements should come from lower half of
4243 /// V1 (and in order), and the upper half elements should come from the upper
4244 /// half of V2 (and in order). And since V1 will become the source of the
4245 /// MOVLP, it must be either a vector load or a scalar load to vector.
4246 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4247 ArrayRef<int> Mask, EVT VT) {
4248 if (!VT.is128BitVector())
4251 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4253 // Is V2 is a vector load, don't do this transformation. We will try to use
4254 // load folding shufps op.
4255 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4258 unsigned NumElems = VT.getVectorNumElements();
4260 if (NumElems != 2 && NumElems != 4)
4262 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4263 if (!isUndefOrEqual(Mask[i], i))
4265 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4266 if (!isUndefOrEqual(Mask[i], i+NumElems))
4271 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4273 static bool isSplatVector(SDNode *N) {
4274 if (N->getOpcode() != ISD::BUILD_VECTOR)
4277 SDValue SplatValue = N->getOperand(0);
4278 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4279 if (N->getOperand(i) != SplatValue)
4284 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4285 /// to an zero vector.
4286 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4287 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4288 SDValue V1 = N->getOperand(0);
4289 SDValue V2 = N->getOperand(1);
4290 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4291 for (unsigned i = 0; i != NumElems; ++i) {
4292 int Idx = N->getMaskElt(i);
4293 if (Idx >= (int)NumElems) {
4294 unsigned Opc = V2.getOpcode();
4295 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4297 if (Opc != ISD::BUILD_VECTOR ||
4298 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4300 } else if (Idx >= 0) {
4301 unsigned Opc = V1.getOpcode();
4302 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4304 if (Opc != ISD::BUILD_VECTOR ||
4305 !X86::isZeroNode(V1.getOperand(Idx)))
4312 /// getZeroVector - Returns a vector of specified type with all zero elements.
4314 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4315 SelectionDAG &DAG, DebugLoc dl) {
4316 assert(VT.isVector() && "Expected a vector type");
4317 unsigned Size = VT.getSizeInBits();
4319 // Always build SSE zero vectors as <4 x i32> bitcasted
4320 // to their dest type. This ensures they get CSE'd.
4322 if (Size == 128) { // SSE
4323 if (Subtarget->hasSSE2()) { // SSE2
4324 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4325 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4327 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4328 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4330 } else if (Size == 256) { // AVX
4331 if (Subtarget->hasAVX2()) { // AVX2
4332 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4333 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4334 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4336 // 256-bit logic and arithmetic instructions in AVX are all
4337 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4338 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4339 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4340 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4343 llvm_unreachable("Unexpected vector type");
4345 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4348 /// getOnesVector - Returns a vector of specified type with all bits set.
4349 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4350 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4351 /// Then bitcast to their original type, ensuring they get CSE'd.
4352 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4354 assert(VT.isVector() && "Expected a vector type");
4355 unsigned Size = VT.getSizeInBits();
4357 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4360 if (HasAVX2) { // AVX2
4361 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4364 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4365 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4367 } else if (Size == 128) {
4368 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4370 llvm_unreachable("Unexpected vector type");
4372 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4375 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4376 /// that point to V2 points to its first element.
4377 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4378 for (unsigned i = 0; i != NumElems; ++i) {
4379 if (Mask[i] > (int)NumElems) {
4385 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4386 /// operation of specified width.
4387 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4389 unsigned NumElems = VT.getVectorNumElements();
4390 SmallVector<int, 8> Mask;
4391 Mask.push_back(NumElems);
4392 for (unsigned i = 1; i != NumElems; ++i)
4394 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4397 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4398 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4400 unsigned NumElems = VT.getVectorNumElements();
4401 SmallVector<int, 8> Mask;
4402 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4404 Mask.push_back(i + NumElems);
4406 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4409 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4410 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4412 unsigned NumElems = VT.getVectorNumElements();
4413 SmallVector<int, 8> Mask;
4414 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4415 Mask.push_back(i + Half);
4416 Mask.push_back(i + NumElems + Half);
4418 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4421 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4422 // a generic shuffle instruction because the target has no such instructions.
4423 // Generate shuffles which repeat i16 and i8 several times until they can be
4424 // represented by v4f32 and then be manipulated by target suported shuffles.
4425 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4426 EVT VT = V.getValueType();
4427 int NumElems = VT.getVectorNumElements();
4428 DebugLoc dl = V.getDebugLoc();
4430 while (NumElems > 4) {
4431 if (EltNo < NumElems/2) {
4432 V = getUnpackl(DAG, dl, VT, V, V);
4434 V = getUnpackh(DAG, dl, VT, V, V);
4435 EltNo -= NumElems/2;
4442 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4443 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4444 EVT VT = V.getValueType();
4445 DebugLoc dl = V.getDebugLoc();
4446 unsigned Size = VT.getSizeInBits();
4449 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4450 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4451 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4453 } else if (Size == 256) {
4454 // To use VPERMILPS to splat scalars, the second half of indicies must
4455 // refer to the higher part, which is a duplication of the lower one,
4456 // because VPERMILPS can only handle in-lane permutations.
4457 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4458 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4460 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4461 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4464 llvm_unreachable("Vector size not supported");
4466 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4469 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4470 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4471 EVT SrcVT = SV->getValueType(0);
4472 SDValue V1 = SV->getOperand(0);
4473 DebugLoc dl = SV->getDebugLoc();
4475 int EltNo = SV->getSplatIndex();
4476 int NumElems = SrcVT.getVectorNumElements();
4477 unsigned Size = SrcVT.getSizeInBits();
4479 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4480 "Unknown how to promote splat for type");
4482 // Extract the 128-bit part containing the splat element and update
4483 // the splat element index when it refers to the higher register.
4485 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4486 if (EltNo >= NumElems/2)
4487 EltNo -= NumElems/2;
4490 // All i16 and i8 vector types can't be used directly by a generic shuffle
4491 // instruction because the target has no such instruction. Generate shuffles
4492 // which repeat i16 and i8 several times until they fit in i32, and then can
4493 // be manipulated by target suported shuffles.
4494 EVT EltVT = SrcVT.getVectorElementType();
4495 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4496 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4498 // Recreate the 256-bit vector and place the same 128-bit vector
4499 // into the low and high part. This is necessary because we want
4500 // to use VPERM* to shuffle the vectors
4502 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4505 return getLegalSplat(DAG, V1, EltNo);
4508 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4509 /// vector of zero or undef vector. This produces a shuffle where the low
4510 /// element of V2 is swizzled into the zero/undef vector, landing at element
4511 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4512 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4514 const X86Subtarget *Subtarget,
4515 SelectionDAG &DAG) {
4516 EVT VT = V2.getValueType();
4518 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4519 unsigned NumElems = VT.getVectorNumElements();
4520 SmallVector<int, 16> MaskVec;
4521 for (unsigned i = 0; i != NumElems; ++i)
4522 // If this is the insertion idx, put the low elt of V2 here.
4523 MaskVec.push_back(i == Idx ? NumElems : i);
4524 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4527 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4528 /// target specific opcode. Returns true if the Mask could be calculated.
4529 /// Sets IsUnary to true if only uses one source.
4530 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4531 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4532 unsigned NumElems = VT.getVectorNumElements();
4536 switch(N->getOpcode()) {
4538 ImmN = N->getOperand(N->getNumOperands()-1);
4539 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4541 case X86ISD::UNPCKH:
4542 DecodeUNPCKHMask(VT, Mask);
4544 case X86ISD::UNPCKL:
4545 DecodeUNPCKLMask(VT, Mask);
4547 case X86ISD::MOVHLPS:
4548 DecodeMOVHLPSMask(NumElems, Mask);
4550 case X86ISD::MOVLHPS:
4551 DecodeMOVLHPSMask(NumElems, Mask);
4553 case X86ISD::PSHUFD:
4554 case X86ISD::VPERMILP:
4555 ImmN = N->getOperand(N->getNumOperands()-1);
4556 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4559 case X86ISD::PSHUFHW:
4560 ImmN = N->getOperand(N->getNumOperands()-1);
4561 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4564 case X86ISD::PSHUFLW:
4565 ImmN = N->getOperand(N->getNumOperands()-1);
4566 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4569 case X86ISD::VPERMI:
4570 ImmN = N->getOperand(N->getNumOperands()-1);
4571 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4575 case X86ISD::MOVSD: {
4576 // The index 0 always comes from the first element of the second source,
4577 // this is why MOVSS and MOVSD are used in the first place. The other
4578 // elements come from the other positions of the first source vector
4579 Mask.push_back(NumElems);
4580 for (unsigned i = 1; i != NumElems; ++i) {
4585 case X86ISD::VPERM2X128:
4586 ImmN = N->getOperand(N->getNumOperands()-1);
4587 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4588 if (Mask.empty()) return false;
4590 case X86ISD::MOVDDUP:
4591 case X86ISD::MOVLHPD:
4592 case X86ISD::MOVLPD:
4593 case X86ISD::MOVLPS:
4594 case X86ISD::MOVSHDUP:
4595 case X86ISD::MOVSLDUP:
4596 case X86ISD::PALIGN:
4597 // Not yet implemented
4599 default: llvm_unreachable("unknown target shuffle node");
4605 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4606 /// element of the result of the vector shuffle.
4607 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4610 return SDValue(); // Limit search depth.
4612 SDValue V = SDValue(N, 0);
4613 EVT VT = V.getValueType();
4614 unsigned Opcode = V.getOpcode();
4616 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4617 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4618 int Elt = SV->getMaskElt(Index);
4621 return DAG.getUNDEF(VT.getVectorElementType());
4623 unsigned NumElems = VT.getVectorNumElements();
4624 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4625 : SV->getOperand(1);
4626 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4629 // Recurse into target specific vector shuffles to find scalars.
4630 if (isTargetShuffle(Opcode)) {
4631 MVT ShufVT = V.getValueType().getSimpleVT();
4632 unsigned NumElems = ShufVT.getVectorNumElements();
4633 SmallVector<int, 16> ShuffleMask;
4637 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4640 int Elt = ShuffleMask[Index];
4642 return DAG.getUNDEF(ShufVT.getVectorElementType());
4644 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4646 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4650 // Actual nodes that may contain scalar elements
4651 if (Opcode == ISD::BITCAST) {
4652 V = V.getOperand(0);
4653 EVT SrcVT = V.getValueType();
4654 unsigned NumElems = VT.getVectorNumElements();
4656 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4660 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4661 return (Index == 0) ? V.getOperand(0)
4662 : DAG.getUNDEF(VT.getVectorElementType());
4664 if (V.getOpcode() == ISD::BUILD_VECTOR)
4665 return V.getOperand(Index);
4670 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4671 /// shuffle operation which come from a consecutively from a zero. The
4672 /// search can start in two different directions, from left or right.
4674 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4675 bool ZerosFromLeft, SelectionDAG &DAG) {
4677 for (i = 0; i != NumElems; ++i) {
4678 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4679 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4680 if (!(Elt.getNode() &&
4681 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4688 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4689 /// correspond consecutively to elements from one of the vector operands,
4690 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4692 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4693 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4694 unsigned NumElems, unsigned &OpNum) {
4695 bool SeenV1 = false;
4696 bool SeenV2 = false;
4698 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4699 int Idx = SVOp->getMaskElt(i);
4700 // Ignore undef indicies
4704 if (Idx < (int)NumElems)
4709 // Only accept consecutive elements from the same vector
4710 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4714 OpNum = SeenV1 ? 0 : 1;
4718 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4719 /// logical left shift of a vector.
4720 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4721 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4722 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4723 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4724 false /* check zeros from right */, DAG);
4730 // Considering the elements in the mask that are not consecutive zeros,
4731 // check if they consecutively come from only one of the source vectors.
4733 // V1 = {X, A, B, C} 0
4735 // vector_shuffle V1, V2 <1, 2, 3, X>
4737 if (!isShuffleMaskConsecutive(SVOp,
4738 0, // Mask Start Index
4739 NumElems-NumZeros, // Mask End Index(exclusive)
4740 NumZeros, // Where to start looking in the src vector
4741 NumElems, // Number of elements in vector
4742 OpSrc)) // Which source operand ?
4747 ShVal = SVOp->getOperand(OpSrc);
4751 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4752 /// logical left shift of a vector.
4753 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4754 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4755 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4756 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4757 true /* check zeros from left */, DAG);
4763 // Considering the elements in the mask that are not consecutive zeros,
4764 // check if they consecutively come from only one of the source vectors.
4766 // 0 { A, B, X, X } = V2
4768 // vector_shuffle V1, V2 <X, X, 4, 5>
4770 if (!isShuffleMaskConsecutive(SVOp,
4771 NumZeros, // Mask Start Index
4772 NumElems, // Mask End Index(exclusive)
4773 0, // Where to start looking in the src vector
4774 NumElems, // Number of elements in vector
4775 OpSrc)) // Which source operand ?
4780 ShVal = SVOp->getOperand(OpSrc);
4784 /// isVectorShift - Returns true if the shuffle can be implemented as a
4785 /// logical left or right shift of a vector.
4786 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4787 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4788 // Although the logic below support any bitwidth size, there are no
4789 // shift instructions which handle more than 128-bit vectors.
4790 if (!SVOp->getValueType(0).is128BitVector())
4793 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4794 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4800 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4802 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4803 unsigned NumNonZero, unsigned NumZero,
4805 const X86Subtarget* Subtarget,
4806 const TargetLowering &TLI) {
4810 DebugLoc dl = Op.getDebugLoc();
4813 for (unsigned i = 0; i < 16; ++i) {
4814 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4815 if (ThisIsNonZero && First) {
4817 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4819 V = DAG.getUNDEF(MVT::v8i16);
4824 SDValue ThisElt(0, 0), LastElt(0, 0);
4825 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4826 if (LastIsNonZero) {
4827 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4828 MVT::i16, Op.getOperand(i-1));
4830 if (ThisIsNonZero) {
4831 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4832 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4833 ThisElt, DAG.getConstant(8, MVT::i8));
4835 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4839 if (ThisElt.getNode())
4840 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4841 DAG.getIntPtrConstant(i/2));
4845 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4848 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4850 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4851 unsigned NumNonZero, unsigned NumZero,
4853 const X86Subtarget* Subtarget,
4854 const TargetLowering &TLI) {
4858 DebugLoc dl = Op.getDebugLoc();
4861 for (unsigned i = 0; i < 8; ++i) {
4862 bool isNonZero = (NonZeros & (1 << i)) != 0;
4866 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4868 V = DAG.getUNDEF(MVT::v8i16);
4871 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4872 MVT::v8i16, V, Op.getOperand(i),
4873 DAG.getIntPtrConstant(i));
4880 /// getVShift - Return a vector logical shift node.
4882 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4883 unsigned NumBits, SelectionDAG &DAG,
4884 const TargetLowering &TLI, DebugLoc dl) {
4885 assert(VT.is128BitVector() && "Unknown type for VShift");
4886 EVT ShVT = MVT::v2i64;
4887 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4888 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4889 return DAG.getNode(ISD::BITCAST, dl, VT,
4890 DAG.getNode(Opc, dl, ShVT, SrcOp,
4891 DAG.getConstant(NumBits,
4892 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4896 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4897 SelectionDAG &DAG) const {
4899 // Check if the scalar load can be widened into a vector load. And if
4900 // the address is "base + cst" see if the cst can be "absorbed" into
4901 // the shuffle mask.
4902 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4903 SDValue Ptr = LD->getBasePtr();
4904 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4906 EVT PVT = LD->getValueType(0);
4907 if (PVT != MVT::i32 && PVT != MVT::f32)
4912 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4913 FI = FINode->getIndex();
4915 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4916 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4917 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4918 Offset = Ptr.getConstantOperandVal(1);
4919 Ptr = Ptr.getOperand(0);
4924 // FIXME: 256-bit vector instructions don't require a strict alignment,
4925 // improve this code to support it better.
4926 unsigned RequiredAlign = VT.getSizeInBits()/8;
4927 SDValue Chain = LD->getChain();
4928 // Make sure the stack object alignment is at least 16 or 32.
4929 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4930 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4931 if (MFI->isFixedObjectIndex(FI)) {
4932 // Can't change the alignment. FIXME: It's possible to compute
4933 // the exact stack offset and reference FI + adjust offset instead.
4934 // If someone *really* cares about this. That's the way to implement it.
4937 MFI->setObjectAlignment(FI, RequiredAlign);
4941 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4942 // Ptr + (Offset & ~15).
4945 if ((Offset % RequiredAlign) & 3)
4947 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4949 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4950 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4952 int EltNo = (Offset - StartOffset) >> 2;
4953 unsigned NumElems = VT.getVectorNumElements();
4955 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4956 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4957 LD->getPointerInfo().getWithOffset(StartOffset),
4958 false, false, false, 0);
4960 SmallVector<int, 8> Mask;
4961 for (unsigned i = 0; i != NumElems; ++i)
4962 Mask.push_back(EltNo);
4964 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4970 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4971 /// vector of type 'VT', see if the elements can be replaced by a single large
4972 /// load which has the same value as a build_vector whose operands are 'elts'.
4974 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4976 /// FIXME: we'd also like to handle the case where the last elements are zero
4977 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4978 /// There's even a handy isZeroNode for that purpose.
4979 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4980 DebugLoc &DL, SelectionDAG &DAG) {
4981 EVT EltVT = VT.getVectorElementType();
4982 unsigned NumElems = Elts.size();
4984 LoadSDNode *LDBase = NULL;
4985 unsigned LastLoadedElt = -1U;
4987 // For each element in the initializer, see if we've found a load or an undef.
4988 // If we don't find an initial load element, or later load elements are
4989 // non-consecutive, bail out.
4990 for (unsigned i = 0; i < NumElems; ++i) {
4991 SDValue Elt = Elts[i];
4993 if (!Elt.getNode() ||
4994 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4997 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4999 LDBase = cast<LoadSDNode>(Elt.getNode());
5003 if (Elt.getOpcode() == ISD::UNDEF)
5006 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5007 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5012 // If we have found an entire vector of loads and undefs, then return a large
5013 // load of the entire vector width starting at the base pointer. If we found
5014 // consecutive loads for the low half, generate a vzext_load node.
5015 if (LastLoadedElt == NumElems - 1) {
5016 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5017 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5018 LDBase->getPointerInfo(),
5019 LDBase->isVolatile(), LDBase->isNonTemporal(),
5020 LDBase->isInvariant(), 0);
5021 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5022 LDBase->getPointerInfo(),
5023 LDBase->isVolatile(), LDBase->isNonTemporal(),
5024 LDBase->isInvariant(), LDBase->getAlignment());
5026 if (NumElems == 4 && LastLoadedElt == 1 &&
5027 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5028 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5029 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5031 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5032 LDBase->getPointerInfo(),
5033 LDBase->getAlignment(),
5034 false/*isVolatile*/, true/*ReadMem*/,
5037 // Make sure the newly-created LOAD is in the same position as LDBase in
5038 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5039 // update uses of LDBase's output chain to use the TokenFactor.
5040 if (LDBase->hasAnyUseOfValue(1)) {
5041 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5042 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5043 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5044 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5045 SDValue(ResNode.getNode(), 1));
5048 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5053 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5054 /// to generate a splat value for the following cases:
5055 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5056 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5057 /// a scalar load, or a constant.
5058 /// The VBROADCAST node is returned when a pattern is found,
5059 /// or SDValue() otherwise.
5061 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5062 if (!Subtarget->hasAVX())
5065 EVT VT = Op.getValueType();
5066 DebugLoc dl = Op.getDebugLoc();
5068 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5069 "Unsupported vector type for broadcast.");
5074 switch (Op.getOpcode()) {
5076 // Unknown pattern found.
5079 case ISD::BUILD_VECTOR: {
5080 // The BUILD_VECTOR node must be a splat.
5081 if (!isSplatVector(Op.getNode()))
5084 Ld = Op.getOperand(0);
5085 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5086 Ld.getOpcode() == ISD::ConstantFP);
5088 // The suspected load node has several users. Make sure that all
5089 // of its users are from the BUILD_VECTOR node.
5090 // Constants may have multiple users.
5091 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5096 case ISD::VECTOR_SHUFFLE: {
5097 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5099 // Shuffles must have a splat mask where the first element is
5101 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5104 SDValue Sc = Op.getOperand(0);
5105 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5106 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5108 if (!Subtarget->hasAVX2())
5111 // Use the register form of the broadcast instruction available on AVX2.
5112 if (VT.is256BitVector())
5113 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5114 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5117 Ld = Sc.getOperand(0);
5118 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5119 Ld.getOpcode() == ISD::ConstantFP);
5121 // The scalar_to_vector node and the suspected
5122 // load node must have exactly one user.
5123 // Constants may have multiple users.
5124 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5130 bool Is256 = VT.is256BitVector();
5132 // Handle the broadcasting a single constant scalar from the constant pool
5133 // into a vector. On Sandybridge it is still better to load a constant vector
5134 // from the constant pool and not to broadcast it from a scalar.
5135 if (ConstSplatVal && Subtarget->hasAVX2()) {
5136 EVT CVT = Ld.getValueType();
5137 assert(!CVT.isVector() && "Must not broadcast a vector type");
5138 unsigned ScalarSize = CVT.getSizeInBits();
5140 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5141 const Constant *C = 0;
5142 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5143 C = CI->getConstantIntValue();
5144 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5145 C = CF->getConstantFPValue();
5147 assert(C && "Invalid constant type");
5149 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5150 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5151 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5152 MachinePointerInfo::getConstantPool(),
5153 false, false, false, Alignment);
5155 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5159 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5160 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5162 // Handle AVX2 in-register broadcasts.
5163 if (!IsLoad && Subtarget->hasAVX2() &&
5164 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5165 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5167 // The scalar source must be a normal load.
5171 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5172 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5174 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5175 // double since there is no vbroadcastsd xmm
5176 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5177 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5178 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5181 // Unsupported broadcast.
5186 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5187 EVT VT = Op.getValueType();
5189 // Skip if insert_vec_elt is not supported.
5190 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5193 DebugLoc DL = Op.getDebugLoc();
5194 unsigned NumElems = Op.getNumOperands();
5198 SmallVector<unsigned, 4> InsertIndices;
5199 SmallVector<int, 8> Mask(NumElems, -1);
5201 for (unsigned i = 0; i != NumElems; ++i) {
5202 unsigned Opc = Op.getOperand(i).getOpcode();
5204 if (Opc == ISD::UNDEF)
5207 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5208 // Quit if more than 1 elements need inserting.
5209 if (InsertIndices.size() > 1)
5212 InsertIndices.push_back(i);
5216 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5217 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5219 // Quit if extracted from vector of different type.
5220 if (ExtractedFromVec.getValueType() != VT)
5223 // Quit if non-constant index.
5224 if (!isa<ConstantSDNode>(ExtIdx))
5227 if (VecIn1.getNode() == 0)
5228 VecIn1 = ExtractedFromVec;
5229 else if (VecIn1 != ExtractedFromVec) {
5230 if (VecIn2.getNode() == 0)
5231 VecIn2 = ExtractedFromVec;
5232 else if (VecIn2 != ExtractedFromVec)
5233 // Quit if more than 2 vectors to shuffle
5237 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5239 if (ExtractedFromVec == VecIn1)
5241 else if (ExtractedFromVec == VecIn2)
5242 Mask[i] = Idx + NumElems;
5245 if (VecIn1.getNode() == 0)
5248 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5249 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5250 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5251 unsigned Idx = InsertIndices[i];
5252 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5253 DAG.getIntPtrConstant(Idx));
5260 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5261 DebugLoc dl = Op.getDebugLoc();
5263 EVT VT = Op.getValueType();
5264 EVT ExtVT = VT.getVectorElementType();
5265 unsigned NumElems = Op.getNumOperands();
5267 // Vectors containing all zeros can be matched by pxor and xorps later
5268 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5269 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5270 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5271 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5274 return getZeroVector(VT, Subtarget, DAG, dl);
5277 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5278 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5279 // vpcmpeqd on 256-bit vectors.
5280 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5281 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5284 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5287 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5288 if (Broadcast.getNode())
5291 unsigned EVTBits = ExtVT.getSizeInBits();
5293 unsigned NumZero = 0;
5294 unsigned NumNonZero = 0;
5295 unsigned NonZeros = 0;
5296 bool IsAllConstants = true;
5297 SmallSet<SDValue, 8> Values;
5298 for (unsigned i = 0; i < NumElems; ++i) {
5299 SDValue Elt = Op.getOperand(i);
5300 if (Elt.getOpcode() == ISD::UNDEF)
5303 if (Elt.getOpcode() != ISD::Constant &&
5304 Elt.getOpcode() != ISD::ConstantFP)
5305 IsAllConstants = false;
5306 if (X86::isZeroNode(Elt))
5309 NonZeros |= (1 << i);
5314 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5315 if (NumNonZero == 0)
5316 return DAG.getUNDEF(VT);
5318 // Special case for single non-zero, non-undef, element.
5319 if (NumNonZero == 1) {
5320 unsigned Idx = CountTrailingZeros_32(NonZeros);
5321 SDValue Item = Op.getOperand(Idx);
5323 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5324 // the value are obviously zero, truncate the value to i32 and do the
5325 // insertion that way. Only do this if the value is non-constant or if the
5326 // value is a constant being inserted into element 0. It is cheaper to do
5327 // a constant pool load than it is to do a movd + shuffle.
5328 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5329 (!IsAllConstants || Idx == 0)) {
5330 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5332 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5333 EVT VecVT = MVT::v4i32;
5334 unsigned VecElts = 4;
5336 // Truncate the value (which may itself be a constant) to i32, and
5337 // convert it to a vector with movd (S2V+shuffle to zero extend).
5338 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5339 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5340 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5342 // Now we have our 32-bit value zero extended in the low element of
5343 // a vector. If Idx != 0, swizzle it into place.
5345 SmallVector<int, 4> Mask;
5346 Mask.push_back(Idx);
5347 for (unsigned i = 1; i != VecElts; ++i)
5349 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5352 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5356 // If we have a constant or non-constant insertion into the low element of
5357 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5358 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5359 // depending on what the source datatype is.
5362 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5364 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5365 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5366 if (VT.is256BitVector()) {
5367 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5368 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5369 Item, DAG.getIntPtrConstant(0));
5371 assert(VT.is128BitVector() && "Expected an SSE value type!");
5372 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5373 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5374 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5377 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5378 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5379 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5380 if (VT.is256BitVector()) {
5381 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5382 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5384 assert(VT.is128BitVector() && "Expected an SSE value type!");
5385 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5387 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5391 // Is it a vector logical left shift?
5392 if (NumElems == 2 && Idx == 1 &&
5393 X86::isZeroNode(Op.getOperand(0)) &&
5394 !X86::isZeroNode(Op.getOperand(1))) {
5395 unsigned NumBits = VT.getSizeInBits();
5396 return getVShift(true, VT,
5397 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5398 VT, Op.getOperand(1)),
5399 NumBits/2, DAG, *this, dl);
5402 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5405 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5406 // is a non-constant being inserted into an element other than the low one,
5407 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5408 // movd/movss) to move this into the low element, then shuffle it into
5410 if (EVTBits == 32) {
5411 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5413 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5414 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5415 SmallVector<int, 8> MaskVec;
5416 for (unsigned i = 0; i != NumElems; ++i)
5417 MaskVec.push_back(i == Idx ? 0 : 1);
5418 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5422 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5423 if (Values.size() == 1) {
5424 if (EVTBits == 32) {
5425 // Instead of a shuffle like this:
5426 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5427 // Check if it's possible to issue this instead.
5428 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5429 unsigned Idx = CountTrailingZeros_32(NonZeros);
5430 SDValue Item = Op.getOperand(Idx);
5431 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5432 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5437 // A vector full of immediates; various special cases are already
5438 // handled, so this is best done with a single constant-pool load.
5442 // For AVX-length vectors, build the individual 128-bit pieces and use
5443 // shuffles to put them in place.
5444 if (VT.is256BitVector()) {
5445 SmallVector<SDValue, 32> V;
5446 for (unsigned i = 0; i != NumElems; ++i)
5447 V.push_back(Op.getOperand(i));
5449 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5451 // Build both the lower and upper subvector.
5452 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5453 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5456 // Recreate the wider vector with the lower and upper part.
5457 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5460 // Let legalizer expand 2-wide build_vectors.
5461 if (EVTBits == 64) {
5462 if (NumNonZero == 1) {
5463 // One half is zero or undef.
5464 unsigned Idx = CountTrailingZeros_32(NonZeros);
5465 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5466 Op.getOperand(Idx));
5467 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5472 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5473 if (EVTBits == 8 && NumElems == 16) {
5474 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5476 if (V.getNode()) return V;
5479 if (EVTBits == 16 && NumElems == 8) {
5480 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5482 if (V.getNode()) return V;
5485 // If element VT is == 32 bits, turn it into a number of shuffles.
5486 SmallVector<SDValue, 8> V(NumElems);
5487 if (NumElems == 4 && NumZero > 0) {
5488 for (unsigned i = 0; i < 4; ++i) {
5489 bool isZero = !(NonZeros & (1 << i));
5491 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5493 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5496 for (unsigned i = 0; i < 2; ++i) {
5497 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5500 V[i] = V[i*2]; // Must be a zero vector.
5503 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5506 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5509 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5514 bool Reverse1 = (NonZeros & 0x3) == 2;
5515 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5519 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5520 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5522 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5525 if (Values.size() > 1 && VT.is128BitVector()) {
5526 // Check for a build vector of consecutive loads.
5527 for (unsigned i = 0; i < NumElems; ++i)
5528 V[i] = Op.getOperand(i);
5530 // Check for elements which are consecutive loads.
5531 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5535 // Check for a build vector from mostly shuffle plus few inserting.
5536 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5540 // For SSE 4.1, use insertps to put the high elements into the low element.
5541 if (getSubtarget()->hasSSE41()) {
5543 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5544 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5546 Result = DAG.getUNDEF(VT);
5548 for (unsigned i = 1; i < NumElems; ++i) {
5549 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5550 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5551 Op.getOperand(i), DAG.getIntPtrConstant(i));
5556 // Otherwise, expand into a number of unpckl*, start by extending each of
5557 // our (non-undef) elements to the full vector width with the element in the
5558 // bottom slot of the vector (which generates no code for SSE).
5559 for (unsigned i = 0; i < NumElems; ++i) {
5560 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5561 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5563 V[i] = DAG.getUNDEF(VT);
5566 // Next, we iteratively mix elements, e.g. for v4f32:
5567 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5568 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5569 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5570 unsigned EltStride = NumElems >> 1;
5571 while (EltStride != 0) {
5572 for (unsigned i = 0; i < EltStride; ++i) {
5573 // If V[i+EltStride] is undef and this is the first round of mixing,
5574 // then it is safe to just drop this shuffle: V[i] is already in the
5575 // right place, the one element (since it's the first round) being
5576 // inserted as undef can be dropped. This isn't safe for successive
5577 // rounds because they will permute elements within both vectors.
5578 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5579 EltStride == NumElems/2)
5582 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5591 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5592 // to create 256-bit vectors from two other 128-bit ones.
5593 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5594 DebugLoc dl = Op.getDebugLoc();
5595 EVT ResVT = Op.getValueType();
5597 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5599 SDValue V1 = Op.getOperand(0);
5600 SDValue V2 = Op.getOperand(1);
5601 unsigned NumElems = ResVT.getVectorNumElements();
5603 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5606 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5607 assert(Op.getNumOperands() == 2);
5609 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5610 // from two other 128-bit ones.
5611 return LowerAVXCONCAT_VECTORS(Op, DAG);
5614 // Try to lower a shuffle node into a simple blend instruction.
5616 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5617 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5618 SDValue V1 = SVOp->getOperand(0);
5619 SDValue V2 = SVOp->getOperand(1);
5620 DebugLoc dl = SVOp->getDebugLoc();
5621 MVT VT = SVOp->getValueType(0).getSimpleVT();
5622 unsigned NumElems = VT.getVectorNumElements();
5624 if (!Subtarget->hasSSE41())
5630 switch (VT.SimpleTy) {
5631 default: return SDValue();
5633 ISDNo = X86ISD::BLENDPW;
5638 ISDNo = X86ISD::BLENDPS;
5643 ISDNo = X86ISD::BLENDPD;
5648 if (!Subtarget->hasAVX())
5650 ISDNo = X86ISD::BLENDPS;
5655 if (!Subtarget->hasAVX())
5657 ISDNo = X86ISD::BLENDPD;
5661 assert(ISDNo && "Invalid Op Number");
5663 unsigned MaskVals = 0;
5665 for (unsigned i = 0; i != NumElems; ++i) {
5666 int EltIdx = SVOp->getMaskElt(i);
5667 if (EltIdx == (int)i || EltIdx < 0)
5669 else if (EltIdx == (int)(i + NumElems))
5670 continue; // Bit is set to zero;
5675 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5676 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5677 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5678 DAG.getConstant(MaskVals, MVT::i32));
5679 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5682 // v8i16 shuffles - Prefer shuffles in the following order:
5683 // 1. [all] pshuflw, pshufhw, optional move
5684 // 2. [ssse3] 1 x pshufb
5685 // 3. [ssse3] 2 x pshufb + 1 x por
5686 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5688 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5689 SelectionDAG &DAG) {
5690 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5691 SDValue V1 = SVOp->getOperand(0);
5692 SDValue V2 = SVOp->getOperand(1);
5693 DebugLoc dl = SVOp->getDebugLoc();
5694 SmallVector<int, 8> MaskVals;
5696 // Determine if more than 1 of the words in each of the low and high quadwords
5697 // of the result come from the same quadword of one of the two inputs. Undef
5698 // mask values count as coming from any quadword, for better codegen.
5699 unsigned LoQuad[] = { 0, 0, 0, 0 };
5700 unsigned HiQuad[] = { 0, 0, 0, 0 };
5701 std::bitset<4> InputQuads;
5702 for (unsigned i = 0; i < 8; ++i) {
5703 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5704 int EltIdx = SVOp->getMaskElt(i);
5705 MaskVals.push_back(EltIdx);
5714 InputQuads.set(EltIdx / 4);
5717 int BestLoQuad = -1;
5718 unsigned MaxQuad = 1;
5719 for (unsigned i = 0; i < 4; ++i) {
5720 if (LoQuad[i] > MaxQuad) {
5722 MaxQuad = LoQuad[i];
5726 int BestHiQuad = -1;
5728 for (unsigned i = 0; i < 4; ++i) {
5729 if (HiQuad[i] > MaxQuad) {
5731 MaxQuad = HiQuad[i];
5735 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5736 // of the two input vectors, shuffle them into one input vector so only a
5737 // single pshufb instruction is necessary. If There are more than 2 input
5738 // quads, disable the next transformation since it does not help SSSE3.
5739 bool V1Used = InputQuads[0] || InputQuads[1];
5740 bool V2Used = InputQuads[2] || InputQuads[3];
5741 if (Subtarget->hasSSSE3()) {
5742 if (InputQuads.count() == 2 && V1Used && V2Used) {
5743 BestLoQuad = InputQuads[0] ? 0 : 1;
5744 BestHiQuad = InputQuads[2] ? 2 : 3;
5746 if (InputQuads.count() > 2) {
5752 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5753 // the shuffle mask. If a quad is scored as -1, that means that it contains
5754 // words from all 4 input quadwords.
5756 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5758 BestLoQuad < 0 ? 0 : BestLoQuad,
5759 BestHiQuad < 0 ? 1 : BestHiQuad
5761 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5762 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5763 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5764 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5766 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5767 // source words for the shuffle, to aid later transformations.
5768 bool AllWordsInNewV = true;
5769 bool InOrder[2] = { true, true };
5770 for (unsigned i = 0; i != 8; ++i) {
5771 int idx = MaskVals[i];
5773 InOrder[i/4] = false;
5774 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5776 AllWordsInNewV = false;
5780 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5781 if (AllWordsInNewV) {
5782 for (int i = 0; i != 8; ++i) {
5783 int idx = MaskVals[i];
5786 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5787 if ((idx != i) && idx < 4)
5789 if ((idx != i) && idx > 3)
5798 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5799 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5800 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5801 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5802 unsigned TargetMask = 0;
5803 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5804 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5805 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5806 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5807 getShufflePSHUFLWImmediate(SVOp);
5808 V1 = NewV.getOperand(0);
5809 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5813 // If we have SSSE3, and all words of the result are from 1 input vector,
5814 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5815 // is present, fall back to case 4.
5816 if (Subtarget->hasSSSE3()) {
5817 SmallVector<SDValue,16> pshufbMask;
5819 // If we have elements from both input vectors, set the high bit of the
5820 // shuffle mask element to zero out elements that come from V2 in the V1
5821 // mask, and elements that come from V1 in the V2 mask, so that the two
5822 // results can be OR'd together.
5823 bool TwoInputs = V1Used && V2Used;
5824 for (unsigned i = 0; i != 8; ++i) {
5825 int EltIdx = MaskVals[i] * 2;
5826 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5827 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5828 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5829 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5831 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5832 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5833 DAG.getNode(ISD::BUILD_VECTOR, dl,
5834 MVT::v16i8, &pshufbMask[0], 16));
5836 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5838 // Calculate the shuffle mask for the second input, shuffle it, and
5839 // OR it with the first shuffled input.
5841 for (unsigned i = 0; i != 8; ++i) {
5842 int EltIdx = MaskVals[i] * 2;
5843 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5844 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5845 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5846 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5848 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5849 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5850 DAG.getNode(ISD::BUILD_VECTOR, dl,
5851 MVT::v16i8, &pshufbMask[0], 16));
5852 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5853 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5856 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5857 // and update MaskVals with new element order.
5858 std::bitset<8> InOrder;
5859 if (BestLoQuad >= 0) {
5860 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5861 for (int i = 0; i != 4; ++i) {
5862 int idx = MaskVals[i];
5865 } else if ((idx / 4) == BestLoQuad) {
5870 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5873 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5874 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5875 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5877 getShufflePSHUFLWImmediate(SVOp), DAG);
5881 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5882 // and update MaskVals with the new element order.
5883 if (BestHiQuad >= 0) {
5884 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5885 for (unsigned i = 4; i != 8; ++i) {
5886 int idx = MaskVals[i];
5889 } else if ((idx / 4) == BestHiQuad) {
5890 MaskV[i] = (idx & 3) + 4;
5894 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5897 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5898 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5899 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5901 getShufflePSHUFHWImmediate(SVOp), DAG);
5905 // In case BestHi & BestLo were both -1, which means each quadword has a word
5906 // from each of the four input quadwords, calculate the InOrder bitvector now
5907 // before falling through to the insert/extract cleanup.
5908 if (BestLoQuad == -1 && BestHiQuad == -1) {
5910 for (int i = 0; i != 8; ++i)
5911 if (MaskVals[i] < 0 || MaskVals[i] == i)
5915 // The other elements are put in the right place using pextrw and pinsrw.
5916 for (unsigned i = 0; i != 8; ++i) {
5919 int EltIdx = MaskVals[i];
5922 SDValue ExtOp = (EltIdx < 8) ?
5923 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5924 DAG.getIntPtrConstant(EltIdx)) :
5925 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5926 DAG.getIntPtrConstant(EltIdx - 8));
5927 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5928 DAG.getIntPtrConstant(i));
5933 // v16i8 shuffles - Prefer shuffles in the following order:
5934 // 1. [ssse3] 1 x pshufb
5935 // 2. [ssse3] 2 x pshufb + 1 x por
5936 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5938 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5940 const X86TargetLowering &TLI) {
5941 SDValue V1 = SVOp->getOperand(0);
5942 SDValue V2 = SVOp->getOperand(1);
5943 DebugLoc dl = SVOp->getDebugLoc();
5944 ArrayRef<int> MaskVals = SVOp->getMask();
5946 // If we have SSSE3, case 1 is generated when all result bytes come from
5947 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5948 // present, fall back to case 3.
5950 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5951 if (TLI.getSubtarget()->hasSSSE3()) {
5952 SmallVector<SDValue,16> pshufbMask;
5954 // If all result elements are from one input vector, then only translate
5955 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5957 // Otherwise, we have elements from both input vectors, and must zero out
5958 // elements that come from V2 in the first mask, and V1 in the second mask
5959 // so that we can OR them together.
5960 for (unsigned i = 0; i != 16; ++i) {
5961 int EltIdx = MaskVals[i];
5962 if (EltIdx < 0 || EltIdx >= 16)
5964 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5966 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5967 DAG.getNode(ISD::BUILD_VECTOR, dl,
5968 MVT::v16i8, &pshufbMask[0], 16));
5970 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5971 // the 2nd operand if it's undefined or zero.
5972 if (V2.getOpcode() == ISD::UNDEF ||
5973 ISD::isBuildVectorAllZeros(V2.getNode()))
5976 // Calculate the shuffle mask for the second input, shuffle it, and
5977 // OR it with the first shuffled input.
5979 for (unsigned i = 0; i != 16; ++i) {
5980 int EltIdx = MaskVals[i];
5981 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5982 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5984 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5985 DAG.getNode(ISD::BUILD_VECTOR, dl,
5986 MVT::v16i8, &pshufbMask[0], 16));
5987 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5990 // No SSSE3 - Calculate in place words and then fix all out of place words
5991 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5992 // the 16 different words that comprise the two doublequadword input vectors.
5993 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5994 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5996 for (int i = 0; i != 8; ++i) {
5997 int Elt0 = MaskVals[i*2];
5998 int Elt1 = MaskVals[i*2+1];
6000 // This word of the result is all undef, skip it.
6001 if (Elt0 < 0 && Elt1 < 0)
6004 // This word of the result is already in the correct place, skip it.
6005 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6008 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6009 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6012 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6013 // using a single extract together, load it and store it.
6014 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6015 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6016 DAG.getIntPtrConstant(Elt1 / 2));
6017 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6018 DAG.getIntPtrConstant(i));
6022 // If Elt1 is defined, extract it from the appropriate source. If the
6023 // source byte is not also odd, shift the extracted word left 8 bits
6024 // otherwise clear the bottom 8 bits if we need to do an or.
6026 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6027 DAG.getIntPtrConstant(Elt1 / 2));
6028 if ((Elt1 & 1) == 0)
6029 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6031 TLI.getShiftAmountTy(InsElt.getValueType())));
6033 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6034 DAG.getConstant(0xFF00, MVT::i16));
6036 // If Elt0 is defined, extract it from the appropriate source. If the
6037 // source byte is not also even, shift the extracted word right 8 bits. If
6038 // Elt1 was also defined, OR the extracted values together before
6039 // inserting them in the result.
6041 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6042 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6043 if ((Elt0 & 1) != 0)
6044 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6046 TLI.getShiftAmountTy(InsElt0.getValueType())));
6048 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6049 DAG.getConstant(0x00FF, MVT::i16));
6050 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6053 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6054 DAG.getIntPtrConstant(i));
6056 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6059 // v32i8 shuffles - Translate to VPSHUFB if possible.
6061 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6062 const X86Subtarget *Subtarget,
6063 SelectionDAG &DAG) {
6064 EVT VT = SVOp->getValueType(0);
6065 SDValue V1 = SVOp->getOperand(0);
6066 SDValue V2 = SVOp->getOperand(1);
6067 DebugLoc dl = SVOp->getDebugLoc();
6068 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6070 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6071 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6072 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6074 // VPSHUFB may be generated if
6075 // (1) one of input vector is undefined or zeroinitializer.
6076 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6077 // And (2) the mask indexes don't cross the 128-bit lane.
6078 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6079 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6082 if (V1IsAllZero && !V2IsAllZero) {
6083 CommuteVectorShuffleMask(MaskVals, 32);
6086 SmallVector<SDValue, 32> pshufbMask;
6087 for (unsigned i = 0; i != 32; i++) {
6088 int EltIdx = MaskVals[i];
6089 if (EltIdx < 0 || EltIdx >= 32)
6092 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6093 // Cross lane is not allowed.
6097 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6099 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6100 DAG.getNode(ISD::BUILD_VECTOR, dl,
6101 MVT::v32i8, &pshufbMask[0], 32));
6104 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6105 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6106 /// done when every pair / quad of shuffle mask elements point to elements in
6107 /// the right sequence. e.g.
6108 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6110 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6111 SelectionDAG &DAG, DebugLoc dl) {
6112 MVT VT = SVOp->getValueType(0).getSimpleVT();
6113 unsigned NumElems = VT.getVectorNumElements();
6116 switch (VT.SimpleTy) {
6117 default: llvm_unreachable("Unexpected!");
6118 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6119 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6120 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6121 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6122 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6123 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6126 SmallVector<int, 8> MaskVec;
6127 for (unsigned i = 0; i != NumElems; i += Scale) {
6129 for (unsigned j = 0; j != Scale; ++j) {
6130 int EltIdx = SVOp->getMaskElt(i+j);
6134 StartIdx = (EltIdx / Scale);
6135 if (EltIdx != (int)(StartIdx*Scale + j))
6138 MaskVec.push_back(StartIdx);
6141 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6142 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6143 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6146 /// getVZextMovL - Return a zero-extending vector move low node.
6148 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6149 SDValue SrcOp, SelectionDAG &DAG,
6150 const X86Subtarget *Subtarget, DebugLoc dl) {
6151 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6152 LoadSDNode *LD = NULL;
6153 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6154 LD = dyn_cast<LoadSDNode>(SrcOp);
6156 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6158 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6159 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6160 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6161 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6162 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6164 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6165 return DAG.getNode(ISD::BITCAST, dl, VT,
6166 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6167 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6175 return DAG.getNode(ISD::BITCAST, dl, VT,
6176 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6177 DAG.getNode(ISD::BITCAST, dl,
6181 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6182 /// which could not be matched by any known target speficic shuffle
6184 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6186 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6187 if (NewOp.getNode())
6190 EVT VT = SVOp->getValueType(0);
6192 unsigned NumElems = VT.getVectorNumElements();
6193 unsigned NumLaneElems = NumElems / 2;
6195 DebugLoc dl = SVOp->getDebugLoc();
6196 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6197 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6200 SmallVector<int, 16> Mask;
6201 for (unsigned l = 0; l < 2; ++l) {
6202 // Build a shuffle mask for the output, discovering on the fly which
6203 // input vectors to use as shuffle operands (recorded in InputUsed).
6204 // If building a suitable shuffle vector proves too hard, then bail
6205 // out with UseBuildVector set.
6206 bool UseBuildVector = false;
6207 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6208 unsigned LaneStart = l * NumLaneElems;
6209 for (unsigned i = 0; i != NumLaneElems; ++i) {
6210 // The mask element. This indexes into the input.
6211 int Idx = SVOp->getMaskElt(i+LaneStart);
6213 // the mask element does not index into any input vector.
6218 // The input vector this mask element indexes into.
6219 int Input = Idx / NumLaneElems;
6221 // Turn the index into an offset from the start of the input vector.
6222 Idx -= Input * NumLaneElems;
6224 // Find or create a shuffle vector operand to hold this input.
6226 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6227 if (InputUsed[OpNo] == Input)
6228 // This input vector is already an operand.
6230 if (InputUsed[OpNo] < 0) {
6231 // Create a new operand for this input vector.
6232 InputUsed[OpNo] = Input;
6237 if (OpNo >= array_lengthof(InputUsed)) {
6238 // More than two input vectors used! Give up on trying to create a
6239 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6240 UseBuildVector = true;
6244 // Add the mask index for the new shuffle vector.
6245 Mask.push_back(Idx + OpNo * NumLaneElems);
6248 if (UseBuildVector) {
6249 SmallVector<SDValue, 16> SVOps;
6250 for (unsigned i = 0; i != NumLaneElems; ++i) {
6251 // The mask element. This indexes into the input.
6252 int Idx = SVOp->getMaskElt(i+LaneStart);
6254 SVOps.push_back(DAG.getUNDEF(EltVT));
6258 // The input vector this mask element indexes into.
6259 int Input = Idx / NumElems;
6261 // Turn the index into an offset from the start of the input vector.
6262 Idx -= Input * NumElems;
6264 // Extract the vector element by hand.
6265 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6266 SVOp->getOperand(Input),
6267 DAG.getIntPtrConstant(Idx)));
6270 // Construct the output using a BUILD_VECTOR.
6271 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6273 } else if (InputUsed[0] < 0) {
6274 // No input vectors were used! The result is undefined.
6275 Output[l] = DAG.getUNDEF(NVT);
6277 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6278 (InputUsed[0] % 2) * NumLaneElems,
6280 // If only one input was used, use an undefined vector for the other.
6281 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6282 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6283 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6284 // At least one input vector was used. Create a new shuffle vector.
6285 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6291 // Concatenate the result back
6292 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6295 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6296 /// 4 elements, and match them with several different shuffle types.
6298 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6299 SDValue V1 = SVOp->getOperand(0);
6300 SDValue V2 = SVOp->getOperand(1);
6301 DebugLoc dl = SVOp->getDebugLoc();
6302 EVT VT = SVOp->getValueType(0);
6304 assert(VT.is128BitVector() && "Unsupported vector size");
6306 std::pair<int, int> Locs[4];
6307 int Mask1[] = { -1, -1, -1, -1 };
6308 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6312 for (unsigned i = 0; i != 4; ++i) {
6313 int Idx = PermMask[i];
6315 Locs[i] = std::make_pair(-1, -1);
6317 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6319 Locs[i] = std::make_pair(0, NumLo);
6323 Locs[i] = std::make_pair(1, NumHi);
6325 Mask1[2+NumHi] = Idx;
6331 if (NumLo <= 2 && NumHi <= 2) {
6332 // If no more than two elements come from either vector. This can be
6333 // implemented with two shuffles. First shuffle gather the elements.
6334 // The second shuffle, which takes the first shuffle as both of its
6335 // vector operands, put the elements into the right order.
6336 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6338 int Mask2[] = { -1, -1, -1, -1 };
6340 for (unsigned i = 0; i != 4; ++i)
6341 if (Locs[i].first != -1) {
6342 unsigned Idx = (i < 2) ? 0 : 4;
6343 Idx += Locs[i].first * 2 + Locs[i].second;
6347 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6350 if (NumLo == 3 || NumHi == 3) {
6351 // Otherwise, we must have three elements from one vector, call it X, and
6352 // one element from the other, call it Y. First, use a shufps to build an
6353 // intermediate vector with the one element from Y and the element from X
6354 // that will be in the same half in the final destination (the indexes don't
6355 // matter). Then, use a shufps to build the final vector, taking the half
6356 // containing the element from Y from the intermediate, and the other half
6359 // Normalize it so the 3 elements come from V1.
6360 CommuteVectorShuffleMask(PermMask, 4);
6364 // Find the element from V2.
6366 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6367 int Val = PermMask[HiIndex];
6374 Mask1[0] = PermMask[HiIndex];
6376 Mask1[2] = PermMask[HiIndex^1];
6378 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6381 Mask1[0] = PermMask[0];
6382 Mask1[1] = PermMask[1];
6383 Mask1[2] = HiIndex & 1 ? 6 : 4;
6384 Mask1[3] = HiIndex & 1 ? 4 : 6;
6385 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6388 Mask1[0] = HiIndex & 1 ? 2 : 0;
6389 Mask1[1] = HiIndex & 1 ? 0 : 2;
6390 Mask1[2] = PermMask[2];
6391 Mask1[3] = PermMask[3];
6396 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6399 // Break it into (shuffle shuffle_hi, shuffle_lo).
6400 int LoMask[] = { -1, -1, -1, -1 };
6401 int HiMask[] = { -1, -1, -1, -1 };
6403 int *MaskPtr = LoMask;
6404 unsigned MaskIdx = 0;
6407 for (unsigned i = 0; i != 4; ++i) {
6414 int Idx = PermMask[i];
6416 Locs[i] = std::make_pair(-1, -1);
6417 } else if (Idx < 4) {
6418 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6419 MaskPtr[LoIdx] = Idx;
6422 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6423 MaskPtr[HiIdx] = Idx;
6428 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6429 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6430 int MaskOps[] = { -1, -1, -1, -1 };
6431 for (unsigned i = 0; i != 4; ++i)
6432 if (Locs[i].first != -1)
6433 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6434 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6437 static bool MayFoldVectorLoad(SDValue V) {
6438 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6439 V = V.getOperand(0);
6440 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6441 V = V.getOperand(0);
6442 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6443 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6444 // BUILD_VECTOR (load), undef
6445 V = V.getOperand(0);
6451 // FIXME: the version above should always be used. Since there's
6452 // a bug where several vector shuffles can't be folded because the
6453 // DAG is not updated during lowering and a node claims to have two
6454 // uses while it only has one, use this version, and let isel match
6455 // another instruction if the load really happens to have more than
6456 // one use. Remove this version after this bug get fixed.
6457 // rdar://8434668, PR8156
6458 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6459 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6460 V = V.getOperand(0);
6461 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6462 V = V.getOperand(0);
6463 if (ISD::isNormalLoad(V.getNode()))
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470 EVT VT = Op.getValueType();
6472 // Canonizalize to v2f64.
6473 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474 return DAG.getNode(ISD::BITCAST, dl, VT,
6475 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6482 SDValue V1 = Op.getOperand(0);
6483 SDValue V2 = Op.getOperand(1);
6484 EVT VT = Op.getValueType();
6486 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6488 if (HasSSE2 && VT == MVT::v2f64)
6489 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6491 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492 return DAG.getNode(ISD::BITCAST, dl, VT,
6493 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500 SDValue V1 = Op.getOperand(0);
6501 SDValue V2 = Op.getOperand(1);
6502 EVT VT = Op.getValueType();
6504 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505 "unsupported shuffle type");
6507 if (V2.getOpcode() == ISD::UNDEF)
6511 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516 SDValue V1 = Op.getOperand(0);
6517 SDValue V2 = Op.getOperand(1);
6518 EVT VT = Op.getValueType();
6519 unsigned NumElems = VT.getVectorNumElements();
6521 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522 // operand of these instructions is only memory, so check if there's a
6523 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6525 bool CanFoldLoad = false;
6527 // Trivial case, when V2 comes from a load.
6528 if (MayFoldVectorLoad(V2))
6531 // When V1 is a load, it can be folded later into a store in isel, example:
6532 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6534 // (MOVLPSmr addr:$src1, VR128:$src2)
6535 // So, recognize this potential and also use MOVLPS or MOVLPD
6536 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6539 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6541 if (HasSSE2 && NumElems == 2)
6542 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6545 // If we don't care about the second element, proceed to use movss.
6546 if (SVOp->getMaskElt(1) != -1)
6547 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6550 // movl and movlp will both match v2i64, but v2i64 is never matched by
6551 // movl earlier because we make it strict to avoid messing with the movlp load
6552 // folding logic (see the code above getMOVLP call). Match it here then,
6553 // this is horrible, but will stay like this until we move all shuffle
6554 // matching to x86 specific nodes. Note that for the 1st condition all
6555 // types are matched with movsd.
6557 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558 // as to remove this logic from here, as much as possible
6559 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6564 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6566 // Invert the operand order and use SHUFPS to match it.
6567 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568 getShuffleSHUFImmediate(SVOp), DAG);
6571 // Reduce a vector shuffle to zext.
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574 // PMOVZX is only available from SSE41.
6575 if (!Subtarget->hasSSE41())
6578 EVT VT = Op.getValueType();
6580 // Only AVX2 support 256-bit vector integer extending.
6581 if (!Subtarget->hasAVX2() && VT.is256BitVector())
6584 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585 DebugLoc DL = Op.getDebugLoc();
6586 SDValue V1 = Op.getOperand(0);
6587 SDValue V2 = Op.getOperand(1);
6588 unsigned NumElems = VT.getVectorNumElements();
6590 // Extending is an unary operation and the element type of the source vector
6591 // won't be equal to or larger than i64.
6592 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593 VT.getVectorElementType() == MVT::i64)
6596 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598 while ((1 << Shift) < NumElems) {
6599 if (SVOp->getMaskElt(1 << Shift) == 1)
6602 // The maximal ratio is 8, i.e. from i8 to i64.
6607 // Check the shuffle mask.
6608 unsigned Mask = (1U << Shift) - 1;
6609 for (unsigned i = 0; i != NumElems; ++i) {
6610 int EltIdx = SVOp->getMaskElt(i);
6611 if ((i & Mask) != 0 && EltIdx != -1)
6613 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6617 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6621 if (!isTypeLegal(NVT))
6624 // Simplify the operand as it's prepared to be fed into shuffle.
6625 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626 if (V1.getOpcode() == ISD::BITCAST &&
6627 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6630 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633 // If it's foldable, i.e. normal load with single use, we will let code
6634 // selection to fold it. Otherwise, we will short the conversion sequence.
6635 if (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())
6636 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6639 return DAG.getNode(ISD::BITCAST, DL, VT,
6640 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6644 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6645 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6646 EVT VT = Op.getValueType();
6647 DebugLoc dl = Op.getDebugLoc();
6648 SDValue V1 = Op.getOperand(0);
6649 SDValue V2 = Op.getOperand(1);
6651 if (isZeroShuffle(SVOp))
6652 return getZeroVector(VT, Subtarget, DAG, dl);
6654 // Handle splat operations
6655 if (SVOp->isSplat()) {
6656 unsigned NumElem = VT.getVectorNumElements();
6657 int Size = VT.getSizeInBits();
6659 // Use vbroadcast whenever the splat comes from a foldable load
6660 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6661 if (Broadcast.getNode())
6664 // Handle splats by matching through known shuffle masks
6665 if ((Size == 128 && NumElem <= 4) ||
6666 (Size == 256 && NumElem < 8))
6669 // All remaning splats are promoted to target supported vector shuffles.
6670 return PromoteSplat(SVOp, DAG);
6673 // Check integer expanding shuffles.
6674 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6675 if (NewOp.getNode())
6678 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6680 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6681 VT == MVT::v16i16 || VT == MVT::v32i8) {
6682 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6683 if (NewOp.getNode())
6684 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6685 } else if ((VT == MVT::v4i32 ||
6686 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6687 // FIXME: Figure out a cleaner way to do this.
6688 // Try to make use of movq to zero out the top part.
6689 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6690 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6691 if (NewOp.getNode()) {
6692 EVT NewVT = NewOp.getValueType();
6693 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6694 NewVT, true, false))
6695 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6696 DAG, Subtarget, dl);
6698 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6699 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6700 if (NewOp.getNode()) {
6701 EVT NewVT = NewOp.getValueType();
6702 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6703 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6704 DAG, Subtarget, dl);
6712 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6713 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6714 SDValue V1 = Op.getOperand(0);
6715 SDValue V2 = Op.getOperand(1);
6716 EVT VT = Op.getValueType();
6717 DebugLoc dl = Op.getDebugLoc();
6718 unsigned NumElems = VT.getVectorNumElements();
6719 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6720 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6721 bool V1IsSplat = false;
6722 bool V2IsSplat = false;
6723 bool HasSSE2 = Subtarget->hasSSE2();
6724 bool HasAVX = Subtarget->hasAVX();
6725 bool HasAVX2 = Subtarget->hasAVX2();
6726 MachineFunction &MF = DAG.getMachineFunction();
6727 bool OptForSize = MF.getFunction()->getFnAttributes().
6728 hasAttribute(Attributes::OptimizeForSize);
6730 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6732 if (V1IsUndef && V2IsUndef)
6733 return DAG.getUNDEF(VT);
6735 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6737 // Vector shuffle lowering takes 3 steps:
6739 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6740 // narrowing and commutation of operands should be handled.
6741 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6743 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6744 // so the shuffle can be broken into other shuffles and the legalizer can
6745 // try the lowering again.
6747 // The general idea is that no vector_shuffle operation should be left to
6748 // be matched during isel, all of them must be converted to a target specific
6751 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6752 // narrowing and commutation of operands should be handled. The actual code
6753 // doesn't include all of those, work in progress...
6754 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6755 if (NewOp.getNode())
6758 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6760 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6761 // unpckh_undef). Only use pshufd if speed is more important than size.
6762 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6763 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6764 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6765 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6767 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6768 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6769 return getMOVDDup(Op, dl, V1, DAG);
6771 if (isMOVHLPS_v_undef_Mask(M, VT))
6772 return getMOVHighToLow(Op, dl, DAG);
6774 // Use to match splats
6775 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6776 (VT == MVT::v2f64 || VT == MVT::v2i64))
6777 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6779 if (isPSHUFDMask(M, VT)) {
6780 // The actual implementation will match the mask in the if above and then
6781 // during isel it can match several different instructions, not only pshufd
6782 // as its name says, sad but true, emulate the behavior for now...
6783 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6784 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6786 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6788 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6789 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6791 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6792 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6794 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6798 // Check if this can be converted into a logical shift.
6799 bool isLeft = false;
6802 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6803 if (isShift && ShVal.hasOneUse()) {
6804 // If the shifted value has multiple uses, it may be cheaper to use
6805 // v_set0 + movlhps or movhlps, etc.
6806 EVT EltVT = VT.getVectorElementType();
6807 ShAmt *= EltVT.getSizeInBits();
6808 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6811 if (isMOVLMask(M, VT)) {
6812 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6813 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6814 if (!isMOVLPMask(M, VT)) {
6815 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6816 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6818 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6819 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6823 // FIXME: fold these into legal mask.
6824 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6825 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6827 if (isMOVHLPSMask(M, VT))
6828 return getMOVHighToLow(Op, dl, DAG);
6830 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6831 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6833 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6834 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6836 if (isMOVLPMask(M, VT))
6837 return getMOVLP(Op, dl, DAG, HasSSE2);
6839 if (ShouldXformToMOVHLPS(M, VT) ||
6840 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6841 return CommuteVectorShuffle(SVOp, DAG);
6844 // No better options. Use a vshldq / vsrldq.
6845 EVT EltVT = VT.getVectorElementType();
6846 ShAmt *= EltVT.getSizeInBits();
6847 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6850 bool Commuted = false;
6851 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6852 // 1,1,1,1 -> v8i16 though.
6853 V1IsSplat = isSplatVector(V1.getNode());
6854 V2IsSplat = isSplatVector(V2.getNode());
6856 // Canonicalize the splat or undef, if present, to be on the RHS.
6857 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6858 CommuteVectorShuffleMask(M, NumElems);
6860 std::swap(V1IsSplat, V2IsSplat);
6864 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6865 // Shuffling low element of v1 into undef, just return v1.
6868 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6869 // the instruction selector will not match, so get a canonical MOVL with
6870 // swapped operands to undo the commute.
6871 return getMOVL(DAG, dl, VT, V2, V1);
6874 if (isUNPCKLMask(M, VT, HasAVX2))
6875 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6877 if (isUNPCKHMask(M, VT, HasAVX2))
6878 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6881 // Normalize mask so all entries that point to V2 points to its first
6882 // element then try to match unpck{h|l} again. If match, return a
6883 // new vector_shuffle with the corrected mask.p
6884 SmallVector<int, 8> NewMask(M.begin(), M.end());
6885 NormalizeMask(NewMask, NumElems);
6886 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6887 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6888 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6889 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6893 // Commute is back and try unpck* again.
6894 // FIXME: this seems wrong.
6895 CommuteVectorShuffleMask(M, NumElems);
6897 std::swap(V1IsSplat, V2IsSplat);
6900 if (isUNPCKLMask(M, VT, HasAVX2))
6901 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6903 if (isUNPCKHMask(M, VT, HasAVX2))
6904 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6907 // Normalize the node to match x86 shuffle ops if needed
6908 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6909 return CommuteVectorShuffle(SVOp, DAG);
6911 // The checks below are all present in isShuffleMaskLegal, but they are
6912 // inlined here right now to enable us to directly emit target specific
6913 // nodes, and remove one by one until they don't return Op anymore.
6915 if (isPALIGNRMask(M, VT, Subtarget))
6916 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6917 getShufflePALIGNRImmediate(SVOp),
6920 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6921 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6922 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6923 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6926 if (isPSHUFHWMask(M, VT, HasAVX2))
6927 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6928 getShufflePSHUFHWImmediate(SVOp),
6931 if (isPSHUFLWMask(M, VT, HasAVX2))
6932 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6933 getShufflePSHUFLWImmediate(SVOp),
6936 if (isSHUFPMask(M, VT, HasAVX))
6937 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6938 getShuffleSHUFImmediate(SVOp), DAG);
6940 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6941 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6942 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6943 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6945 //===--------------------------------------------------------------------===//
6946 // Generate target specific nodes for 128 or 256-bit shuffles only
6947 // supported in the AVX instruction set.
6950 // Handle VMOVDDUPY permutations
6951 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6952 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6954 // Handle VPERMILPS/D* permutations
6955 if (isVPERMILPMask(M, VT, HasAVX)) {
6956 if (HasAVX2 && VT == MVT::v8i32)
6957 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6958 getShuffleSHUFImmediate(SVOp), DAG);
6959 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6960 getShuffleSHUFImmediate(SVOp), DAG);
6963 // Handle VPERM2F128/VPERM2I128 permutations
6964 if (isVPERM2X128Mask(M, VT, HasAVX))
6965 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6966 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6968 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6969 if (BlendOp.getNode())
6972 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6973 SmallVector<SDValue, 8> permclMask;
6974 for (unsigned i = 0; i != 8; ++i) {
6975 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6977 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6979 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6980 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6981 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6984 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6985 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6986 getShuffleCLImmediate(SVOp), DAG);
6989 //===--------------------------------------------------------------------===//
6990 // Since no target specific shuffle was selected for this generic one,
6991 // lower it into other known shuffles. FIXME: this isn't true yet, but
6992 // this is the plan.
6995 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6996 if (VT == MVT::v8i16) {
6997 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6998 if (NewOp.getNode())
7002 if (VT == MVT::v16i8) {
7003 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7004 if (NewOp.getNode())
7008 if (VT == MVT::v32i8) {
7009 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7010 if (NewOp.getNode())
7014 // Handle all 128-bit wide vectors with 4 elements, and match them with
7015 // several different shuffle types.
7016 if (NumElems == 4 && VT.is128BitVector())
7017 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7019 // Handle general 256-bit shuffles
7020 if (VT.is256BitVector())
7021 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7027 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7028 SelectionDAG &DAG) const {
7029 EVT VT = Op.getValueType();
7030 DebugLoc dl = Op.getDebugLoc();
7032 if (!Op.getOperand(0).getValueType().is128BitVector())
7035 if (VT.getSizeInBits() == 8) {
7036 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7037 Op.getOperand(0), Op.getOperand(1));
7038 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7039 DAG.getValueType(VT));
7040 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7043 if (VT.getSizeInBits() == 16) {
7044 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7045 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7047 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7048 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7049 DAG.getNode(ISD::BITCAST, dl,
7053 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7054 Op.getOperand(0), Op.getOperand(1));
7055 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7056 DAG.getValueType(VT));
7057 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7060 if (VT == MVT::f32) {
7061 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7062 // the result back to FR32 register. It's only worth matching if the
7063 // result has a single use which is a store or a bitcast to i32. And in
7064 // the case of a store, it's not worth it if the index is a constant 0,
7065 // because a MOVSSmr can be used instead, which is smaller and faster.
7066 if (!Op.hasOneUse())
7068 SDNode *User = *Op.getNode()->use_begin();
7069 if ((User->getOpcode() != ISD::STORE ||
7070 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7071 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7072 (User->getOpcode() != ISD::BITCAST ||
7073 User->getValueType(0) != MVT::i32))
7075 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7076 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7079 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7082 if (VT == MVT::i32 || VT == MVT::i64) {
7083 // ExtractPS/pextrq works with constant index.
7084 if (isa<ConstantSDNode>(Op.getOperand(1)))
7092 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7093 SelectionDAG &DAG) const {
7094 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7097 SDValue Vec = Op.getOperand(0);
7098 EVT VecVT = Vec.getValueType();
7100 // If this is a 256-bit vector result, first extract the 128-bit vector and
7101 // then extract the element from the 128-bit vector.
7102 if (VecVT.is256BitVector()) {
7103 DebugLoc dl = Op.getNode()->getDebugLoc();
7104 unsigned NumElems = VecVT.getVectorNumElements();
7105 SDValue Idx = Op.getOperand(1);
7106 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7108 // Get the 128-bit vector.
7109 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7111 if (IdxVal >= NumElems/2)
7112 IdxVal -= NumElems/2;
7113 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7114 DAG.getConstant(IdxVal, MVT::i32));
7117 assert(VecVT.is128BitVector() && "Unexpected vector length");
7119 if (Subtarget->hasSSE41()) {
7120 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7125 EVT VT = Op.getValueType();
7126 DebugLoc dl = Op.getDebugLoc();
7127 // TODO: handle v16i8.
7128 if (VT.getSizeInBits() == 16) {
7129 SDValue Vec = Op.getOperand(0);
7130 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7132 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7133 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7134 DAG.getNode(ISD::BITCAST, dl,
7137 // Transform it so it match pextrw which produces a 32-bit result.
7138 EVT EltVT = MVT::i32;
7139 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7140 Op.getOperand(0), Op.getOperand(1));
7141 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7142 DAG.getValueType(VT));
7143 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7146 if (VT.getSizeInBits() == 32) {
7147 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7151 // SHUFPS the element to the lowest double word, then movss.
7152 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7153 EVT VVT = Op.getOperand(0).getValueType();
7154 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7155 DAG.getUNDEF(VVT), Mask);
7156 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7157 DAG.getIntPtrConstant(0));
7160 if (VT.getSizeInBits() == 64) {
7161 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7162 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7163 // to match extract_elt for f64.
7164 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7168 // UNPCKHPD the element to the lowest double word, then movsd.
7169 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7170 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7171 int Mask[2] = { 1, -1 };
7172 EVT VVT = Op.getOperand(0).getValueType();
7173 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7174 DAG.getUNDEF(VVT), Mask);
7175 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7176 DAG.getIntPtrConstant(0));
7183 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7184 SelectionDAG &DAG) const {
7185 EVT VT = Op.getValueType();
7186 EVT EltVT = VT.getVectorElementType();
7187 DebugLoc dl = Op.getDebugLoc();
7189 SDValue N0 = Op.getOperand(0);
7190 SDValue N1 = Op.getOperand(1);
7191 SDValue N2 = Op.getOperand(2);
7193 if (!VT.is128BitVector())
7196 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7197 isa<ConstantSDNode>(N2)) {
7199 if (VT == MVT::v8i16)
7200 Opc = X86ISD::PINSRW;
7201 else if (VT == MVT::v16i8)
7202 Opc = X86ISD::PINSRB;
7204 Opc = X86ISD::PINSRB;
7206 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7208 if (N1.getValueType() != MVT::i32)
7209 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7210 if (N2.getValueType() != MVT::i32)
7211 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7212 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7215 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7216 // Bits [7:6] of the constant are the source select. This will always be
7217 // zero here. The DAG Combiner may combine an extract_elt index into these
7218 // bits. For example (insert (extract, 3), 2) could be matched by putting
7219 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7220 // Bits [5:4] of the constant are the destination select. This is the
7221 // value of the incoming immediate.
7222 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7223 // combine either bitwise AND or insert of float 0.0 to set these bits.
7224 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7225 // Create this as a scalar to vector..
7226 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7227 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7230 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7231 // PINSR* works with constant index.
7238 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7239 EVT VT = Op.getValueType();
7240 EVT EltVT = VT.getVectorElementType();
7242 DebugLoc dl = Op.getDebugLoc();
7243 SDValue N0 = Op.getOperand(0);
7244 SDValue N1 = Op.getOperand(1);
7245 SDValue N2 = Op.getOperand(2);
7247 // If this is a 256-bit vector result, first extract the 128-bit vector,
7248 // insert the element into the extracted half and then place it back.
7249 if (VT.is256BitVector()) {
7250 if (!isa<ConstantSDNode>(N2))
7253 // Get the desired 128-bit vector half.
7254 unsigned NumElems = VT.getVectorNumElements();
7255 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7256 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7258 // Insert the element into the desired half.
7259 bool Upper = IdxVal >= NumElems/2;
7260 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7261 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7263 // Insert the changed part back to the 256-bit vector
7264 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7267 if (Subtarget->hasSSE41())
7268 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7270 if (EltVT == MVT::i8)
7273 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7274 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7275 // as its second argument.
7276 if (N1.getValueType() != MVT::i32)
7277 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7278 if (N2.getValueType() != MVT::i32)
7279 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7280 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7285 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7286 LLVMContext *Context = DAG.getContext();
7287 DebugLoc dl = Op.getDebugLoc();
7288 EVT OpVT = Op.getValueType();
7290 // If this is a 256-bit vector result, first insert into a 128-bit
7291 // vector and then insert into the 256-bit vector.
7292 if (!OpVT.is128BitVector()) {
7293 // Insert into a 128-bit vector.
7294 EVT VT128 = EVT::getVectorVT(*Context,
7295 OpVT.getVectorElementType(),
7296 OpVT.getVectorNumElements() / 2);
7298 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7300 // Insert the 128-bit vector.
7301 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7304 if (OpVT == MVT::v1i64 &&
7305 Op.getOperand(0).getValueType() == MVT::i64)
7306 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7308 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7309 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7310 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7311 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7314 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7315 // a simple subregister reference or explicit instructions to grab
7316 // upper bits of a vector.
7317 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7318 SelectionDAG &DAG) {
7319 if (Subtarget->hasAVX()) {
7320 DebugLoc dl = Op.getNode()->getDebugLoc();
7321 SDValue Vec = Op.getNode()->getOperand(0);
7322 SDValue Idx = Op.getNode()->getOperand(1);
7324 if (Op.getNode()->getValueType(0).is128BitVector() &&
7325 Vec.getNode()->getValueType(0).is256BitVector() &&
7326 isa<ConstantSDNode>(Idx)) {
7327 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7328 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7334 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7335 // simple superregister reference or explicit instructions to insert
7336 // the upper bits of a vector.
7337 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7338 SelectionDAG &DAG) {
7339 if (Subtarget->hasAVX()) {
7340 DebugLoc dl = Op.getNode()->getDebugLoc();
7341 SDValue Vec = Op.getNode()->getOperand(0);
7342 SDValue SubVec = Op.getNode()->getOperand(1);
7343 SDValue Idx = Op.getNode()->getOperand(2);
7345 if (Op.getNode()->getValueType(0).is256BitVector() &&
7346 SubVec.getNode()->getValueType(0).is128BitVector() &&
7347 isa<ConstantSDNode>(Idx)) {
7348 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7349 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7355 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7356 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7357 // one of the above mentioned nodes. It has to be wrapped because otherwise
7358 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7359 // be used to form addressing mode. These wrapped nodes will be selected
7362 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7363 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7365 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7367 unsigned char OpFlag = 0;
7368 unsigned WrapperKind = X86ISD::Wrapper;
7369 CodeModel::Model M = getTargetMachine().getCodeModel();
7371 if (Subtarget->isPICStyleRIPRel() &&
7372 (M == CodeModel::Small || M == CodeModel::Kernel))
7373 WrapperKind = X86ISD::WrapperRIP;
7374 else if (Subtarget->isPICStyleGOT())
7375 OpFlag = X86II::MO_GOTOFF;
7376 else if (Subtarget->isPICStyleStubPIC())
7377 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7379 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7381 CP->getOffset(), OpFlag);
7382 DebugLoc DL = CP->getDebugLoc();
7383 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7384 // With PIC, the address is actually $g + Offset.
7386 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7387 DAG.getNode(X86ISD::GlobalBaseReg,
7388 DebugLoc(), getPointerTy()),
7395 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7396 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7398 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7400 unsigned char OpFlag = 0;
7401 unsigned WrapperKind = X86ISD::Wrapper;
7402 CodeModel::Model M = getTargetMachine().getCodeModel();
7404 if (Subtarget->isPICStyleRIPRel() &&
7405 (M == CodeModel::Small || M == CodeModel::Kernel))
7406 WrapperKind = X86ISD::WrapperRIP;
7407 else if (Subtarget->isPICStyleGOT())
7408 OpFlag = X86II::MO_GOTOFF;
7409 else if (Subtarget->isPICStyleStubPIC())
7410 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7412 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7414 DebugLoc DL = JT->getDebugLoc();
7415 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7417 // With PIC, the address is actually $g + Offset.
7419 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7420 DAG.getNode(X86ISD::GlobalBaseReg,
7421 DebugLoc(), getPointerTy()),
7428 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7429 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7431 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7433 unsigned char OpFlag = 0;
7434 unsigned WrapperKind = X86ISD::Wrapper;
7435 CodeModel::Model M = getTargetMachine().getCodeModel();
7437 if (Subtarget->isPICStyleRIPRel() &&
7438 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7439 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7440 OpFlag = X86II::MO_GOTPCREL;
7441 WrapperKind = X86ISD::WrapperRIP;
7442 } else if (Subtarget->isPICStyleGOT()) {
7443 OpFlag = X86II::MO_GOT;
7444 } else if (Subtarget->isPICStyleStubPIC()) {
7445 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7446 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7447 OpFlag = X86II::MO_DARWIN_NONLAZY;
7450 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7452 DebugLoc DL = Op.getDebugLoc();
7453 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7456 // With PIC, the address is actually $g + Offset.
7457 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7458 !Subtarget->is64Bit()) {
7459 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7460 DAG.getNode(X86ISD::GlobalBaseReg,
7461 DebugLoc(), getPointerTy()),
7465 // For symbols that require a load from a stub to get the address, emit the
7467 if (isGlobalStubReference(OpFlag))
7468 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7469 MachinePointerInfo::getGOT(), false, false, false, 0);
7475 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7476 // Create the TargetBlockAddressAddress node.
7477 unsigned char OpFlags =
7478 Subtarget->ClassifyBlockAddressReference();
7479 CodeModel::Model M = getTargetMachine().getCodeModel();
7480 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7481 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7482 DebugLoc dl = Op.getDebugLoc();
7483 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7486 if (Subtarget->isPICStyleRIPRel() &&
7487 (M == CodeModel::Small || M == CodeModel::Kernel))
7488 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7490 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7492 // With PIC, the address is actually $g + Offset.
7493 if (isGlobalRelativeToPICBase(OpFlags)) {
7494 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7495 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7503 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7505 SelectionDAG &DAG) const {
7506 // Create the TargetGlobalAddress node, folding in the constant
7507 // offset if it is legal.
7508 unsigned char OpFlags =
7509 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7510 CodeModel::Model M = getTargetMachine().getCodeModel();
7512 if (OpFlags == X86II::MO_NO_FLAG &&
7513 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7514 // A direct static reference to a global.
7515 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7518 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7521 if (Subtarget->isPICStyleRIPRel() &&
7522 (M == CodeModel::Small || M == CodeModel::Kernel))
7523 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7525 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7527 // With PIC, the address is actually $g + Offset.
7528 if (isGlobalRelativeToPICBase(OpFlags)) {
7529 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7530 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7534 // For globals that require a load from a stub to get the address, emit the
7536 if (isGlobalStubReference(OpFlags))
7537 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7538 MachinePointerInfo::getGOT(), false, false, false, 0);
7540 // If there was a non-zero offset that we didn't fold, create an explicit
7543 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7544 DAG.getConstant(Offset, getPointerTy()));
7550 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7551 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7552 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7553 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7557 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7558 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7559 unsigned char OperandFlags, bool LocalDynamic = false) {
7560 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7561 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7562 DebugLoc dl = GA->getDebugLoc();
7563 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7564 GA->getValueType(0),
7568 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7572 SDValue Ops[] = { Chain, TGA, *InFlag };
7573 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7575 SDValue Ops[] = { Chain, TGA };
7576 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7579 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7580 MFI->setAdjustsStack(true);
7582 SDValue Flag = Chain.getValue(1);
7583 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7586 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7588 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7591 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7592 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7593 DAG.getNode(X86ISD::GlobalBaseReg,
7594 DebugLoc(), PtrVT), InFlag);
7595 InFlag = Chain.getValue(1);
7597 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7600 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7602 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7604 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7605 X86::RAX, X86II::MO_TLSGD);
7608 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7612 DebugLoc dl = GA->getDebugLoc();
7614 // Get the start address of the TLS block for this module.
7615 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7616 .getInfo<X86MachineFunctionInfo>();
7617 MFI->incNumLocalDynamicTLSAccesses();
7621 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7622 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7625 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7626 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7627 InFlag = Chain.getValue(1);
7628 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7629 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7632 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7636 unsigned char OperandFlags = X86II::MO_DTPOFF;
7637 unsigned WrapperKind = X86ISD::Wrapper;
7638 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7639 GA->getValueType(0),
7640 GA->getOffset(), OperandFlags);
7641 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7643 // Add x@dtpoff with the base.
7644 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7647 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7648 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7649 const EVT PtrVT, TLSModel::Model model,
7650 bool is64Bit, bool isPIC) {
7651 DebugLoc dl = GA->getDebugLoc();
7653 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7654 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7655 is64Bit ? 257 : 256));
7657 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7658 DAG.getIntPtrConstant(0),
7659 MachinePointerInfo(Ptr),
7660 false, false, false, 0);
7662 unsigned char OperandFlags = 0;
7663 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7665 unsigned WrapperKind = X86ISD::Wrapper;
7666 if (model == TLSModel::LocalExec) {
7667 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7668 } else if (model == TLSModel::InitialExec) {
7670 OperandFlags = X86II::MO_GOTTPOFF;
7671 WrapperKind = X86ISD::WrapperRIP;
7673 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7676 llvm_unreachable("Unexpected model");
7679 // emit "addl x@ntpoff,%eax" (local exec)
7680 // or "addl x@indntpoff,%eax" (initial exec)
7681 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7682 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7683 GA->getValueType(0),
7684 GA->getOffset(), OperandFlags);
7685 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7687 if (model == TLSModel::InitialExec) {
7688 if (isPIC && !is64Bit) {
7689 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7690 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7694 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7695 MachinePointerInfo::getGOT(), false, false, false,
7699 // The address of the thread local variable is the add of the thread
7700 // pointer with the offset of the variable.
7701 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7705 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7707 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7708 const GlobalValue *GV = GA->getGlobal();
7710 if (Subtarget->isTargetELF()) {
7711 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7714 case TLSModel::GeneralDynamic:
7715 if (Subtarget->is64Bit())
7716 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7717 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7718 case TLSModel::LocalDynamic:
7719 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7720 Subtarget->is64Bit());
7721 case TLSModel::InitialExec:
7722 case TLSModel::LocalExec:
7723 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7724 Subtarget->is64Bit(),
7725 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7727 llvm_unreachable("Unknown TLS model.");
7730 if (Subtarget->isTargetDarwin()) {
7731 // Darwin only has one model of TLS. Lower to that.
7732 unsigned char OpFlag = 0;
7733 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7734 X86ISD::WrapperRIP : X86ISD::Wrapper;
7736 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7738 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7739 !Subtarget->is64Bit();
7741 OpFlag = X86II::MO_TLVP_PIC_BASE;
7743 OpFlag = X86II::MO_TLVP;
7744 DebugLoc DL = Op.getDebugLoc();
7745 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7746 GA->getValueType(0),
7747 GA->getOffset(), OpFlag);
7748 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7750 // With PIC32, the address is actually $g + Offset.
7752 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7753 DAG.getNode(X86ISD::GlobalBaseReg,
7754 DebugLoc(), getPointerTy()),
7757 // Lowering the machine isd will make sure everything is in the right
7759 SDValue Chain = DAG.getEntryNode();
7760 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7761 SDValue Args[] = { Chain, Offset };
7762 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7764 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7765 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7766 MFI->setAdjustsStack(true);
7768 // And our return value (tls address) is in the standard call return value
7770 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7771 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7775 if (Subtarget->isTargetWindows()) {
7776 // Just use the implicit TLS architecture
7777 // Need to generate someting similar to:
7778 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7780 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7781 // mov rcx, qword [rdx+rcx*8]
7782 // mov eax, .tls$:tlsvar
7783 // [rax+rcx] contains the address
7784 // Windows 64bit: gs:0x58
7785 // Windows 32bit: fs:__tls_array
7787 // If GV is an alias then use the aliasee for determining
7788 // thread-localness.
7789 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7790 GV = GA->resolveAliasedGlobal(false);
7791 DebugLoc dl = GA->getDebugLoc();
7792 SDValue Chain = DAG.getEntryNode();
7794 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7795 // %gs:0x58 (64-bit).
7796 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7797 ? Type::getInt8PtrTy(*DAG.getContext(),
7799 : Type::getInt32PtrTy(*DAG.getContext(),
7802 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7803 Subtarget->is64Bit()
7804 ? DAG.getIntPtrConstant(0x58)
7805 : DAG.getExternalSymbol("_tls_array",
7807 MachinePointerInfo(Ptr),
7808 false, false, false, 0);
7810 // Load the _tls_index variable
7811 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7812 if (Subtarget->is64Bit())
7813 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7814 IDX, MachinePointerInfo(), MVT::i32,
7817 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7818 false, false, false, 0);
7820 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7822 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7824 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7825 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7826 false, false, false, 0);
7828 // Get the offset of start of .tls section
7829 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7830 GA->getValueType(0),
7831 GA->getOffset(), X86II::MO_SECREL);
7832 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7834 // The address of the thread local variable is the add of the thread
7835 // pointer with the offset of the variable.
7836 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7839 llvm_unreachable("TLS not implemented for this target.");
7843 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7844 /// and take a 2 x i32 value to shift plus a shift amount.
7845 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7846 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7847 EVT VT = Op.getValueType();
7848 unsigned VTBits = VT.getSizeInBits();
7849 DebugLoc dl = Op.getDebugLoc();
7850 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7851 SDValue ShOpLo = Op.getOperand(0);
7852 SDValue ShOpHi = Op.getOperand(1);
7853 SDValue ShAmt = Op.getOperand(2);
7854 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7855 DAG.getConstant(VTBits - 1, MVT::i8))
7856 : DAG.getConstant(0, VT);
7859 if (Op.getOpcode() == ISD::SHL_PARTS) {
7860 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7861 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7863 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7864 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7867 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7868 DAG.getConstant(VTBits, MVT::i8));
7869 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7870 AndNode, DAG.getConstant(0, MVT::i8));
7873 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7874 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7875 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7877 if (Op.getOpcode() == ISD::SHL_PARTS) {
7878 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7881 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7885 SDValue Ops[2] = { Lo, Hi };
7886 return DAG.getMergeValues(Ops, 2, dl);
7889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7890 SelectionDAG &DAG) const {
7891 EVT SrcVT = Op.getOperand(0).getValueType();
7893 if (SrcVT.isVector())
7896 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7897 "Unknown SINT_TO_FP to lower!");
7899 // These are really Legal; return the operand so the caller accepts it as
7901 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7903 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7904 Subtarget->is64Bit()) {
7908 DebugLoc dl = Op.getDebugLoc();
7909 unsigned Size = SrcVT.getSizeInBits()/8;
7910 MachineFunction &MF = DAG.getMachineFunction();
7911 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7912 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7915 MachinePointerInfo::getFixedStack(SSFI),
7917 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7920 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7922 SelectionDAG &DAG) const {
7924 DebugLoc DL = Op.getDebugLoc();
7926 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7928 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7930 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7932 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7934 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7935 MachineMemOperand *MMO;
7937 int SSFI = FI->getIndex();
7939 DAG.getMachineFunction()
7940 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7941 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7943 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7944 StackSlot = StackSlot.getOperand(1);
7946 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7947 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7949 Tys, Ops, array_lengthof(Ops),
7953 Chain = Result.getValue(1);
7954 SDValue InFlag = Result.getValue(2);
7956 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7957 // shouldn't be necessary except that RFP cannot be live across
7958 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7959 MachineFunction &MF = DAG.getMachineFunction();
7960 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7961 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963 Tys = DAG.getVTList(MVT::Other);
7965 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7967 MachineMemOperand *MMO =
7968 DAG.getMachineFunction()
7969 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970 MachineMemOperand::MOStore, SSFISize, SSFISize);
7972 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7973 Ops, array_lengthof(Ops),
7974 Op.getValueType(), MMO);
7975 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7976 MachinePointerInfo::getFixedStack(SSFI),
7977 false, false, false, 0);
7983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7985 SelectionDAG &DAG) const {
7986 // This algorithm is not obvious. Here it is what we're trying to output:
7989 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7990 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7994 pshufd $0x4e, %xmm0, %xmm1
7999 DebugLoc dl = Op.getDebugLoc();
8000 LLVMContext *Context = DAG.getContext();
8002 // Build some magic constants.
8003 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8004 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8005 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8007 SmallVector<Constant*,2> CV1;
8009 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8011 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8012 Constant *C1 = ConstantVector::get(CV1);
8013 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8015 // Load the 64-bit value into an XMM register.
8016 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8018 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8019 MachinePointerInfo::getConstantPool(),
8020 false, false, false, 16);
8021 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8022 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8025 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8026 MachinePointerInfo::getConstantPool(),
8027 false, false, false, 16);
8028 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8029 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8032 if (Subtarget->hasSSE3()) {
8033 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8034 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8036 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8037 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8039 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8040 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8044 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8045 DAG.getIntPtrConstant(0));
8048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8050 SelectionDAG &DAG) const {
8051 DebugLoc dl = Op.getDebugLoc();
8052 // FP constant to bias correct the final result.
8053 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8056 // Load the 32-bit value into an XMM register.
8057 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8060 // Zero out the upper parts of the register.
8061 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8063 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8064 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8065 DAG.getIntPtrConstant(0));
8067 // Or the load with the bias.
8068 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8069 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8072 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074 MVT::v2f64, Bias)));
8075 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8077 DAG.getIntPtrConstant(0));
8079 // Subtract the bias.
8080 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8082 // Handle final rounding.
8083 EVT DestVT = Op.getValueType();
8085 if (DestVT.bitsLT(MVT::f64))
8086 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8087 DAG.getIntPtrConstant(0));
8088 if (DestVT.bitsGT(MVT::f64))
8089 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8091 // Handle final rounding.
8095 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8096 SelectionDAG &DAG) const {
8097 SDValue N0 = Op.getOperand(0);
8098 EVT SVT = N0.getValueType();
8099 DebugLoc dl = Op.getDebugLoc();
8101 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8102 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8103 "Custom UINT_TO_FP is not supported!");
8105 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8106 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8107 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8110 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8111 SelectionDAG &DAG) const {
8112 SDValue N0 = Op.getOperand(0);
8113 DebugLoc dl = Op.getDebugLoc();
8115 if (Op.getValueType().isVector())
8116 return lowerUINT_TO_FP_vec(Op, DAG);
8118 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8119 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8120 // the optimization here.
8121 if (DAG.SignBitIsZero(N0))
8122 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8124 EVT SrcVT = N0.getValueType();
8125 EVT DstVT = Op.getValueType();
8126 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8127 return LowerUINT_TO_FP_i64(Op, DAG);
8128 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8129 return LowerUINT_TO_FP_i32(Op, DAG);
8130 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8133 // Make a 64-bit buffer, and use it to build an FILD.
8134 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8135 if (SrcVT == MVT::i32) {
8136 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8137 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8138 getPointerTy(), StackSlot, WordOff);
8139 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8140 StackSlot, MachinePointerInfo(),
8142 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8143 OffsetSlot, MachinePointerInfo(),
8145 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8149 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8150 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8151 StackSlot, MachinePointerInfo(),
8153 // For i64 source, we need to add the appropriate power of 2 if the input
8154 // was negative. This is the same as the optimization in
8155 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8156 // we must be careful to do the computation in x87 extended precision, not
8157 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8158 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8159 MachineMemOperand *MMO =
8160 DAG.getMachineFunction()
8161 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8162 MachineMemOperand::MOLoad, 8, 8);
8164 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8165 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8166 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8169 APInt FF(32, 0x5F800000ULL);
8171 // Check whether the sign bit is set.
8172 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8173 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8176 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8177 SDValue FudgePtr = DAG.getConstantPool(
8178 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8181 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8182 SDValue Zero = DAG.getIntPtrConstant(0);
8183 SDValue Four = DAG.getIntPtrConstant(4);
8184 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8186 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8188 // Load the value out, extending it from f32 to f80.
8189 // FIXME: Avoid the extend by constructing the right constant pool?
8190 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8191 FudgePtr, MachinePointerInfo::getConstantPool(),
8192 MVT::f32, false, false, 4);
8193 // Extend everything to 80 bits to force it to be done on x87.
8194 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8195 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8198 std::pair<SDValue,SDValue> X86TargetLowering::
8199 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8200 DebugLoc DL = Op.getDebugLoc();
8202 EVT DstTy = Op.getValueType();
8204 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8205 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8209 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8210 DstTy.getSimpleVT() >= MVT::i16 &&
8211 "Unknown FP_TO_INT to lower!");
8213 // These are really Legal.
8214 if (DstTy == MVT::i32 &&
8215 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8216 return std::make_pair(SDValue(), SDValue());
8217 if (Subtarget->is64Bit() &&
8218 DstTy == MVT::i64 &&
8219 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8220 return std::make_pair(SDValue(), SDValue());
8222 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8223 // stack slot, or into the FTOL runtime function.
8224 MachineFunction &MF = DAG.getMachineFunction();
8225 unsigned MemSize = DstTy.getSizeInBits()/8;
8226 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8227 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8230 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8231 Opc = X86ISD::WIN_FTOL;
8233 switch (DstTy.getSimpleVT().SimpleTy) {
8234 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8235 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8236 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8237 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8240 SDValue Chain = DAG.getEntryNode();
8241 SDValue Value = Op.getOperand(0);
8242 EVT TheVT = Op.getOperand(0).getValueType();
8243 // FIXME This causes a redundant load/store if the SSE-class value is already
8244 // in memory, such as if it is on the callstack.
8245 if (isScalarFPTypeInSSEReg(TheVT)) {
8246 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8247 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8248 MachinePointerInfo::getFixedStack(SSFI),
8250 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8252 Chain, StackSlot, DAG.getValueType(TheVT)
8255 MachineMemOperand *MMO =
8256 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8257 MachineMemOperand::MOLoad, MemSize, MemSize);
8258 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8260 Chain = Value.getValue(1);
8261 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8262 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8265 MachineMemOperand *MMO =
8266 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8267 MachineMemOperand::MOStore, MemSize, MemSize);
8269 if (Opc != X86ISD::WIN_FTOL) {
8270 // Build the FP_TO_INT*_IN_MEM
8271 SDValue Ops[] = { Chain, Value, StackSlot };
8272 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8273 Ops, 3, DstTy, MMO);
8274 return std::make_pair(FIST, StackSlot);
8276 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8277 DAG.getVTList(MVT::Other, MVT::Glue),
8279 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8280 MVT::i32, ftol.getValue(1));
8281 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8282 MVT::i32, eax.getValue(2));
8283 SDValue Ops[] = { eax, edx };
8284 SDValue pair = IsReplace
8285 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8286 : DAG.getMergeValues(Ops, 2, DL);
8287 return std::make_pair(pair, SDValue());
8291 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8292 DebugLoc DL = Op.getDebugLoc();
8293 EVT VT = Op.getValueType();
8294 SDValue In = Op.getOperand(0);
8295 EVT SVT = In.getValueType();
8297 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8298 VT.getVectorNumElements() != SVT.getVectorNumElements())
8301 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8303 // AVX2 has better support of integer extending.
8304 if (Subtarget->hasAVX2())
8305 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8307 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8308 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8309 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8310 DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8312 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8315 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8316 DebugLoc DL = Op.getDebugLoc();
8317 EVT VT = Op.getValueType();
8318 EVT SVT = Op.getOperand(0).getValueType();
8320 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8321 VT.getVectorNumElements() != SVT.getVectorNumElements())
8324 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8326 unsigned NumElems = VT.getVectorNumElements();
8327 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8330 SDValue In = Op.getOperand(0);
8331 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8332 // Prepare truncation shuffle mask
8333 for (unsigned i = 0; i != NumElems; ++i)
8335 SDValue V = DAG.getVectorShuffle(NVT, DL,
8336 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8337 DAG.getUNDEF(NVT), &MaskVec[0]);
8338 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8339 DAG.getIntPtrConstant(0));
8342 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8343 SelectionDAG &DAG) const {
8344 if (Op.getValueType().isVector()) {
8345 if (Op.getValueType() == MVT::v8i16)
8346 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8347 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8348 MVT::v8i32, Op.getOperand(0)));
8352 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8353 /*IsSigned=*/ true, /*IsReplace=*/ false);
8354 SDValue FIST = Vals.first, StackSlot = Vals.second;
8355 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8356 if (FIST.getNode() == 0) return Op;
8358 if (StackSlot.getNode())
8360 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8361 FIST, StackSlot, MachinePointerInfo(),
8362 false, false, false, 0);
8364 // The node is the result.
8368 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8369 SelectionDAG &DAG) const {
8370 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8371 /*IsSigned=*/ false, /*IsReplace=*/ false);
8372 SDValue FIST = Vals.first, StackSlot = Vals.second;
8373 assert(FIST.getNode() && "Unexpected failure");
8375 if (StackSlot.getNode())
8377 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8378 FIST, StackSlot, MachinePointerInfo(),
8379 false, false, false, 0);
8381 // The node is the result.
8385 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8386 SelectionDAG &DAG) const {
8387 DebugLoc DL = Op.getDebugLoc();
8388 EVT VT = Op.getValueType();
8389 SDValue In = Op.getOperand(0);
8390 EVT SVT = In.getValueType();
8392 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8394 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8395 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8396 In, DAG.getUNDEF(SVT)));
8399 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8400 LLVMContext *Context = DAG.getContext();
8401 DebugLoc dl = Op.getDebugLoc();
8402 EVT VT = Op.getValueType();
8404 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8405 if (VT.isVector()) {
8406 EltVT = VT.getVectorElementType();
8407 NumElts = VT.getVectorNumElements();
8410 if (EltVT == MVT::f64)
8411 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8413 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8414 C = ConstantVector::getSplat(NumElts, C);
8415 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8416 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8417 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8418 MachinePointerInfo::getConstantPool(),
8419 false, false, false, Alignment);
8420 if (VT.isVector()) {
8421 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8422 return DAG.getNode(ISD::BITCAST, dl, VT,
8423 DAG.getNode(ISD::AND, dl, ANDVT,
8424 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8426 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8428 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8431 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8432 LLVMContext *Context = DAG.getContext();
8433 DebugLoc dl = Op.getDebugLoc();
8434 EVT VT = Op.getValueType();
8436 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8437 if (VT.isVector()) {
8438 EltVT = VT.getVectorElementType();
8439 NumElts = VT.getVectorNumElements();
8442 if (EltVT == MVT::f64)
8443 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8445 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8446 C = ConstantVector::getSplat(NumElts, C);
8447 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8448 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8449 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8450 MachinePointerInfo::getConstantPool(),
8451 false, false, false, Alignment);
8452 if (VT.isVector()) {
8453 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8454 return DAG.getNode(ISD::BITCAST, dl, VT,
8455 DAG.getNode(ISD::XOR, dl, XORVT,
8456 DAG.getNode(ISD::BITCAST, dl, XORVT,
8458 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8461 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8464 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8465 LLVMContext *Context = DAG.getContext();
8466 SDValue Op0 = Op.getOperand(0);
8467 SDValue Op1 = Op.getOperand(1);
8468 DebugLoc dl = Op.getDebugLoc();
8469 EVT VT = Op.getValueType();
8470 EVT SrcVT = Op1.getValueType();
8472 // If second operand is smaller, extend it first.
8473 if (SrcVT.bitsLT(VT)) {
8474 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8477 // And if it is bigger, shrink it first.
8478 if (SrcVT.bitsGT(VT)) {
8479 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8483 // At this point the operands and the result should have the same
8484 // type, and that won't be f80 since that is not custom lowered.
8486 // First get the sign bit of second operand.
8487 SmallVector<Constant*,4> CV;
8488 if (SrcVT == MVT::f64) {
8489 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8490 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8492 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8493 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8495 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8497 Constant *C = ConstantVector::get(CV);
8498 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8499 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8500 MachinePointerInfo::getConstantPool(),
8501 false, false, false, 16);
8502 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8504 // Shift sign bit right or left if the two operands have different types.
8505 if (SrcVT.bitsGT(VT)) {
8506 // Op0 is MVT::f32, Op1 is MVT::f64.
8507 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8508 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8509 DAG.getConstant(32, MVT::i32));
8510 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8511 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8512 DAG.getIntPtrConstant(0));
8515 // Clear first operand sign bit.
8517 if (VT == MVT::f64) {
8518 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8519 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8521 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8522 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8524 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8526 C = ConstantVector::get(CV);
8527 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8528 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8529 MachinePointerInfo::getConstantPool(),
8530 false, false, false, 16);
8531 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8533 // Or the value with the sign bit.
8534 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8538 SDValue N0 = Op.getOperand(0);
8539 DebugLoc dl = Op.getDebugLoc();
8540 EVT VT = Op.getValueType();
8542 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8543 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8544 DAG.getConstant(1, VT));
8545 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8550 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8551 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8553 if (!Subtarget->hasSSE41())
8556 if (!Op->hasOneUse())
8559 SDNode *N = Op.getNode();
8560 DebugLoc DL = N->getDebugLoc();
8562 SmallVector<SDValue, 8> Opnds;
8563 DenseMap<SDValue, unsigned> VecInMap;
8564 EVT VT = MVT::Other;
8566 // Recognize a special case where a vector is casted into wide integer to
8568 Opnds.push_back(N->getOperand(0));
8569 Opnds.push_back(N->getOperand(1));
8571 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8572 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8573 // BFS traverse all OR'd operands.
8574 if (I->getOpcode() == ISD::OR) {
8575 Opnds.push_back(I->getOperand(0));
8576 Opnds.push_back(I->getOperand(1));
8577 // Re-evaluate the number of nodes to be traversed.
8578 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8582 // Quit if a non-EXTRACT_VECTOR_ELT
8583 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8586 // Quit if without a constant index.
8587 SDValue Idx = I->getOperand(1);
8588 if (!isa<ConstantSDNode>(Idx))
8591 SDValue ExtractedFromVec = I->getOperand(0);
8592 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8593 if (M == VecInMap.end()) {
8594 VT = ExtractedFromVec.getValueType();
8595 // Quit if not 128/256-bit vector.
8596 if (!VT.is128BitVector() && !VT.is256BitVector())
8598 // Quit if not the same type.
8599 if (VecInMap.begin() != VecInMap.end() &&
8600 VT != VecInMap.begin()->first.getValueType())
8602 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8604 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8607 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8608 "Not extracted from 128-/256-bit vector.");
8610 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8611 SmallVector<SDValue, 8> VecIns;
8613 for (DenseMap<SDValue, unsigned>::const_iterator
8614 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8615 // Quit if not all elements are used.
8616 if (I->second != FullMask)
8618 VecIns.push_back(I->first);
8621 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8623 // Cast all vectors into TestVT for PTEST.
8624 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8625 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8627 // If more than one full vectors are evaluated, OR them first before PTEST.
8628 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8629 // Each iteration will OR 2 nodes and append the result until there is only
8630 // 1 node left, i.e. the final OR'd value of all vectors.
8631 SDValue LHS = VecIns[Slot];
8632 SDValue RHS = VecIns[Slot + 1];
8633 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8636 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8637 VecIns.back(), VecIns.back());
8640 /// Emit nodes that will be selected as "test Op0,Op0", or something
8642 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8643 SelectionDAG &DAG) const {
8644 DebugLoc dl = Op.getDebugLoc();
8646 // CF and OF aren't always set the way we want. Determine which
8647 // of these we need.
8648 bool NeedCF = false;
8649 bool NeedOF = false;
8652 case X86::COND_A: case X86::COND_AE:
8653 case X86::COND_B: case X86::COND_BE:
8656 case X86::COND_G: case X86::COND_GE:
8657 case X86::COND_L: case X86::COND_LE:
8658 case X86::COND_O: case X86::COND_NO:
8663 // See if we can use the EFLAGS value from the operand instead of
8664 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8665 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8666 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8667 // Emit a CMP with 0, which is the TEST pattern.
8668 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8669 DAG.getConstant(0, Op.getValueType()));
8671 unsigned Opcode = 0;
8672 unsigned NumOperands = 0;
8674 // Truncate operations may prevent the merge of the SETCC instruction
8675 // and the arithmetic intruction before it. Attempt to truncate the operands
8676 // of the arithmetic instruction and use a reduced bit-width instruction.
8677 bool NeedTruncation = false;
8678 SDValue ArithOp = Op;
8679 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8680 SDValue Arith = Op->getOperand(0);
8681 // Both the trunc and the arithmetic op need to have one user each.
8682 if (Arith->hasOneUse())
8683 switch (Arith.getOpcode()) {
8690 NeedTruncation = true;
8696 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8697 // which may be the result of a CAST. We use the variable 'Op', which is the
8698 // non-casted variable when we check for possible users.
8699 switch (ArithOp.getOpcode()) {
8701 // Due to an isel shortcoming, be conservative if this add is likely to be
8702 // selected as part of a load-modify-store instruction. When the root node
8703 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8704 // uses of other nodes in the match, such as the ADD in this case. This
8705 // leads to the ADD being left around and reselected, with the result being
8706 // two adds in the output. Alas, even if none our users are stores, that
8707 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8708 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8709 // climbing the DAG back to the root, and it doesn't seem to be worth the
8711 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8712 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8713 if (UI->getOpcode() != ISD::CopyToReg &&
8714 UI->getOpcode() != ISD::SETCC &&
8715 UI->getOpcode() != ISD::STORE)
8718 if (ConstantSDNode *C =
8719 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8720 // An add of one will be selected as an INC.
8721 if (C->getAPIntValue() == 1) {
8722 Opcode = X86ISD::INC;
8727 // An add of negative one (subtract of one) will be selected as a DEC.
8728 if (C->getAPIntValue().isAllOnesValue()) {
8729 Opcode = X86ISD::DEC;
8735 // Otherwise use a regular EFLAGS-setting add.
8736 Opcode = X86ISD::ADD;
8740 // If the primary and result isn't used, don't bother using X86ISD::AND,
8741 // because a TEST instruction will be better.
8742 bool NonFlagUse = false;
8743 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8744 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8746 unsigned UOpNo = UI.getOperandNo();
8747 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8748 // Look pass truncate.
8749 UOpNo = User->use_begin().getOperandNo();
8750 User = *User->use_begin();
8753 if (User->getOpcode() != ISD::BRCOND &&
8754 User->getOpcode() != ISD::SETCC &&
8755 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8768 // Due to the ISEL shortcoming noted above, be conservative if this op is
8769 // likely to be selected as part of a load-modify-store instruction.
8770 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8771 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8772 if (UI->getOpcode() == ISD::STORE)
8775 // Otherwise use a regular EFLAGS-setting instruction.
8776 switch (ArithOp.getOpcode()) {
8777 default: llvm_unreachable("unexpected operator!");
8778 case ISD::SUB: Opcode = X86ISD::SUB; break;
8779 case ISD::XOR: Opcode = X86ISD::XOR; break;
8780 case ISD::AND: Opcode = X86ISD::AND; break;
8782 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8783 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8784 if (EFLAGS.getNode())
8787 Opcode = X86ISD::OR;
8801 return SDValue(Op.getNode(), 1);
8807 // If we found that truncation is beneficial, perform the truncation and
8809 if (NeedTruncation) {
8810 EVT VT = Op.getValueType();
8811 SDValue WideVal = Op->getOperand(0);
8812 EVT WideVT = WideVal.getValueType();
8813 unsigned ConvertedOp = 0;
8814 // Use a target machine opcode to prevent further DAGCombine
8815 // optimizations that may separate the arithmetic operations
8816 // from the setcc node.
8817 switch (WideVal.getOpcode()) {
8819 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8820 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8821 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8822 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8823 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8828 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8829 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8830 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8831 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8837 // Emit a CMP with 0, which is the TEST pattern.
8838 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839 DAG.getConstant(0, Op.getValueType()));
8841 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8842 SmallVector<SDValue, 4> Ops;
8843 for (unsigned i = 0; i != NumOperands; ++i)
8844 Ops.push_back(Op.getOperand(i));
8846 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8847 DAG.ReplaceAllUsesWith(Op, New);
8848 return SDValue(New.getNode(), 1);
8851 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8853 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8854 SelectionDAG &DAG) const {
8855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8856 if (C->getAPIntValue() == 0)
8857 return EmitTest(Op0, X86CC, DAG);
8859 DebugLoc dl = Op0.getDebugLoc();
8860 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8861 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8862 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8863 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8864 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8866 return SDValue(Sub.getNode(), 1);
8868 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8871 /// Convert a comparison if required by the subtarget.
8872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8873 SelectionDAG &DAG) const {
8874 // If the subtarget does not support the FUCOMI instruction, floating-point
8875 // comparisons have to be converted.
8876 if (Subtarget->hasCMov() ||
8877 Cmp.getOpcode() != X86ISD::CMP ||
8878 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8879 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8882 // The instruction selector will select an FUCOM instruction instead of
8883 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8884 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8885 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8886 DebugLoc dl = Cmp.getDebugLoc();
8887 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8888 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8889 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8890 DAG.getConstant(8, MVT::i8));
8891 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8892 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8895 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8896 /// if it's possible.
8897 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8898 DebugLoc dl, SelectionDAG &DAG) const {
8899 SDValue Op0 = And.getOperand(0);
8900 SDValue Op1 = And.getOperand(1);
8901 if (Op0.getOpcode() == ISD::TRUNCATE)
8902 Op0 = Op0.getOperand(0);
8903 if (Op1.getOpcode() == ISD::TRUNCATE)
8904 Op1 = Op1.getOperand(0);
8907 if (Op1.getOpcode() == ISD::SHL)
8908 std::swap(Op0, Op1);
8909 if (Op0.getOpcode() == ISD::SHL) {
8910 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8911 if (And00C->getZExtValue() == 1) {
8912 // If we looked past a truncate, check that it's only truncating away
8914 unsigned BitWidth = Op0.getValueSizeInBits();
8915 unsigned AndBitWidth = And.getValueSizeInBits();
8916 if (BitWidth > AndBitWidth) {
8918 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8919 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8923 RHS = Op0.getOperand(1);
8925 } else if (Op1.getOpcode() == ISD::Constant) {
8926 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8927 uint64_t AndRHSVal = AndRHS->getZExtValue();
8928 SDValue AndLHS = Op0;
8930 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8931 LHS = AndLHS.getOperand(0);
8932 RHS = AndLHS.getOperand(1);
8935 // Use BT if the immediate can't be encoded in a TEST instruction.
8936 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8938 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8942 if (LHS.getNode()) {
8943 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8944 // instruction. Since the shift amount is in-range-or-undefined, we know
8945 // that doing a bittest on the i32 value is ok. We extend to i32 because
8946 // the encoding for the i16 version is larger than the i32 version.
8947 // Also promote i16 to i32 for performance / code size reason.
8948 if (LHS.getValueType() == MVT::i8 ||
8949 LHS.getValueType() == MVT::i16)
8950 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8952 // If the operand types disagree, extend the shift amount to match. Since
8953 // BT ignores high bits (like shifts) we can use anyextend.
8954 if (LHS.getValueType() != RHS.getValueType())
8955 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8957 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8958 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8959 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8960 DAG.getConstant(Cond, MVT::i8), BT);
8966 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8968 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8970 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8971 SDValue Op0 = Op.getOperand(0);
8972 SDValue Op1 = Op.getOperand(1);
8973 DebugLoc dl = Op.getDebugLoc();
8974 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8976 // Optimize to BT if possible.
8977 // Lower (X & (1 << N)) == 0 to BT(X, N).
8978 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8979 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8980 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8981 Op1.getOpcode() == ISD::Constant &&
8982 cast<ConstantSDNode>(Op1)->isNullValue() &&
8983 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8984 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8985 if (NewSetCC.getNode())
8989 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8991 if (Op1.getOpcode() == ISD::Constant &&
8992 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8993 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8994 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8996 // If the input is a setcc, then reuse the input setcc or use a new one with
8997 // the inverted condition.
8998 if (Op0.getOpcode() == X86ISD::SETCC) {
8999 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9000 bool Invert = (CC == ISD::SETNE) ^
9001 cast<ConstantSDNode>(Op1)->isNullValue();
9002 if (!Invert) return Op0;
9004 CCode = X86::GetOppositeBranchCondition(CCode);
9005 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9006 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9010 bool isFP = Op1.getValueType().isFloatingPoint();
9011 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9012 if (X86CC == X86::COND_INVALID)
9015 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9016 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9017 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9018 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9021 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9022 // ones, and then concatenate the result back.
9023 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9024 EVT VT = Op.getValueType();
9026 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9027 "Unsupported value type for operation");
9029 unsigned NumElems = VT.getVectorNumElements();
9030 DebugLoc dl = Op.getDebugLoc();
9031 SDValue CC = Op.getOperand(2);
9033 // Extract the LHS vectors
9034 SDValue LHS = Op.getOperand(0);
9035 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9036 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9038 // Extract the RHS vectors
9039 SDValue RHS = Op.getOperand(1);
9040 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9041 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9043 // Issue the operation on the smaller types and concatenate the result back
9044 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9045 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9046 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9047 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9048 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9052 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9054 SDValue Op0 = Op.getOperand(0);
9055 SDValue Op1 = Op.getOperand(1);
9056 SDValue CC = Op.getOperand(2);
9057 EVT VT = Op.getValueType();
9058 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9059 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9060 DebugLoc dl = Op.getDebugLoc();
9064 EVT EltVT = Op0.getValueType().getVectorElementType();
9065 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9071 // SSE Condition code mapping:
9080 switch (SetCCOpcode) {
9081 default: llvm_unreachable("Unexpected SETCC condition");
9083 case ISD::SETEQ: SSECC = 0; break;
9085 case ISD::SETGT: Swap = true; // Fallthrough
9087 case ISD::SETOLT: SSECC = 1; break;
9089 case ISD::SETGE: Swap = true; // Fallthrough
9091 case ISD::SETOLE: SSECC = 2; break;
9092 case ISD::SETUO: SSECC = 3; break;
9094 case ISD::SETNE: SSECC = 4; break;
9095 case ISD::SETULE: Swap = true; // Fallthrough
9096 case ISD::SETUGE: SSECC = 5; break;
9097 case ISD::SETULT: Swap = true; // Fallthrough
9098 case ISD::SETUGT: SSECC = 6; break;
9099 case ISD::SETO: SSECC = 7; break;
9101 case ISD::SETONE: SSECC = 8; break;
9104 std::swap(Op0, Op1);
9106 // In the two special cases we can't handle, emit two comparisons.
9109 unsigned CombineOpc;
9110 if (SetCCOpcode == ISD::SETUEQ) {
9111 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9113 assert(SetCCOpcode == ISD::SETONE);
9114 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9117 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9118 DAG.getConstant(CC0, MVT::i8));
9119 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9120 DAG.getConstant(CC1, MVT::i8));
9121 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9123 // Handle all other FP comparisons here.
9124 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9125 DAG.getConstant(SSECC, MVT::i8));
9128 // Break 256-bit integer vector compare into smaller ones.
9129 if (VT.is256BitVector() && !Subtarget->hasAVX2())
9130 return Lower256IntVSETCC(Op, DAG);
9132 // We are handling one of the integer comparisons here. Since SSE only has
9133 // GT and EQ comparisons for integer, swapping operands and multiple
9134 // operations may be required for some comparisons.
9136 bool Swap = false, Invert = false, FlipSigns = false;
9138 switch (SetCCOpcode) {
9139 default: llvm_unreachable("Unexpected SETCC condition");
9140 case ISD::SETNE: Invert = true;
9141 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9142 case ISD::SETLT: Swap = true;
9143 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9144 case ISD::SETGE: Swap = true;
9145 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9146 case ISD::SETULT: Swap = true;
9147 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9148 case ISD::SETUGE: Swap = true;
9149 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9152 std::swap(Op0, Op1);
9154 // Check that the operation in question is available (most are plain SSE2,
9155 // but PCMPGTQ and PCMPEQQ have different requirements).
9156 if (VT == MVT::v2i64) {
9157 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9159 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9163 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9164 // bits of the inputs before performing those operations.
9166 EVT EltVT = VT.getVectorElementType();
9167 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9169 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9170 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9172 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9173 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9176 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9178 // If the logical-not of the result is required, perform that now.
9180 Result = DAG.getNOT(dl, Result, VT);
9185 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9186 static bool isX86LogicalCmp(SDValue Op) {
9187 unsigned Opc = Op.getNode()->getOpcode();
9188 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9189 Opc == X86ISD::SAHF)
9191 if (Op.getResNo() == 1 &&
9192 (Opc == X86ISD::ADD ||
9193 Opc == X86ISD::SUB ||
9194 Opc == X86ISD::ADC ||
9195 Opc == X86ISD::SBB ||
9196 Opc == X86ISD::SMUL ||
9197 Opc == X86ISD::UMUL ||
9198 Opc == X86ISD::INC ||
9199 Opc == X86ISD::DEC ||
9200 Opc == X86ISD::OR ||
9201 Opc == X86ISD::XOR ||
9202 Opc == X86ISD::AND))
9205 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9211 static bool isZero(SDValue V) {
9212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9213 return C && C->isNullValue();
9216 static bool isAllOnes(SDValue V) {
9217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9218 return C && C->isAllOnesValue();
9221 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9222 if (V.getOpcode() != ISD::TRUNCATE)
9225 SDValue VOp0 = V.getOperand(0);
9226 unsigned InBits = VOp0.getValueSizeInBits();
9227 unsigned Bits = V.getValueSizeInBits();
9228 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9231 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9232 bool addTest = true;
9233 SDValue Cond = Op.getOperand(0);
9234 SDValue Op1 = Op.getOperand(1);
9235 SDValue Op2 = Op.getOperand(2);
9236 DebugLoc DL = Op.getDebugLoc();
9239 if (Cond.getOpcode() == ISD::SETCC) {
9240 SDValue NewCond = LowerSETCC(Cond, DAG);
9241 if (NewCond.getNode())
9245 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9246 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9247 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9248 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9249 if (Cond.getOpcode() == X86ISD::SETCC &&
9250 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9251 isZero(Cond.getOperand(1).getOperand(1))) {
9252 SDValue Cmp = Cond.getOperand(1);
9254 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9256 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9257 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9258 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9260 SDValue CmpOp0 = Cmp.getOperand(0);
9261 // Apply further optimizations for special cases
9262 // (select (x != 0), -1, 0) -> neg & sbb
9263 // (select (x == 0), 0, -1) -> neg & sbb
9264 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9265 if (YC->isNullValue() &&
9266 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9267 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9268 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9269 DAG.getConstant(0, CmpOp0.getValueType()),
9271 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9272 DAG.getConstant(X86::COND_B, MVT::i8),
9273 SDValue(Neg.getNode(), 1));
9277 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9278 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9279 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9281 SDValue Res = // Res = 0 or -1.
9282 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9283 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9285 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9286 Res = DAG.getNOT(DL, Res, Res.getValueType());
9288 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9289 if (N2C == 0 || !N2C->isNullValue())
9290 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9295 // Look past (and (setcc_carry (cmp ...)), 1).
9296 if (Cond.getOpcode() == ISD::AND &&
9297 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9298 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9299 if (C && C->getAPIntValue() == 1)
9300 Cond = Cond.getOperand(0);
9303 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9304 // setting operand in place of the X86ISD::SETCC.
9305 unsigned CondOpcode = Cond.getOpcode();
9306 if (CondOpcode == X86ISD::SETCC ||
9307 CondOpcode == X86ISD::SETCC_CARRY) {
9308 CC = Cond.getOperand(0);
9310 SDValue Cmp = Cond.getOperand(1);
9311 unsigned Opc = Cmp.getOpcode();
9312 EVT VT = Op.getValueType();
9314 bool IllegalFPCMov = false;
9315 if (VT.isFloatingPoint() && !VT.isVector() &&
9316 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9317 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9319 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9320 Opc == X86ISD::BT) { // FIXME
9324 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9325 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9326 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9327 Cond.getOperand(0).getValueType() != MVT::i8)) {
9328 SDValue LHS = Cond.getOperand(0);
9329 SDValue RHS = Cond.getOperand(1);
9333 switch (CondOpcode) {
9334 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9335 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9336 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9337 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9338 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9339 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9340 default: llvm_unreachable("unexpected overflowing operator");
9342 if (CondOpcode == ISD::UMULO)
9343 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9346 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9348 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9350 if (CondOpcode == ISD::UMULO)
9351 Cond = X86Op.getValue(2);
9353 Cond = X86Op.getValue(1);
9355 CC = DAG.getConstant(X86Cond, MVT::i8);
9360 // Look pass the truncate if the high bits are known zero.
9361 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9362 Cond = Cond.getOperand(0);
9364 // We know the result of AND is compared against zero. Try to match
9366 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9367 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9368 if (NewSetCC.getNode()) {
9369 CC = NewSetCC.getOperand(0);
9370 Cond = NewSetCC.getOperand(1);
9377 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9378 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9381 // a < b ? -1 : 0 -> RES = ~setcc_carry
9382 // a < b ? 0 : -1 -> RES = setcc_carry
9383 // a >= b ? -1 : 0 -> RES = setcc_carry
9384 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9385 if (Cond.getOpcode() == X86ISD::SUB) {
9386 Cond = ConvertCmpIfNecessary(Cond, DAG);
9387 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9389 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9390 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9391 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9392 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9393 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9394 return DAG.getNOT(DL, Res, Res.getValueType());
9399 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9400 // widen the cmov and push the truncate through. This avoids introducing a new
9401 // branch during isel and doesn't add any extensions.
9402 if (Op.getValueType() == MVT::i8 &&
9403 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9404 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9405 if (T1.getValueType() == T2.getValueType() &&
9406 // Blacklist CopyFromReg to avoid partial register stalls.
9407 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9408 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9409 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9410 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9414 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9415 // condition is true.
9416 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9417 SDValue Ops[] = { Op2, Op1, CC, Cond };
9418 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9421 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9422 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9423 // from the AND / OR.
9424 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9425 Opc = Op.getOpcode();
9426 if (Opc != ISD::OR && Opc != ISD::AND)
9428 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9429 Op.getOperand(0).hasOneUse() &&
9430 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9431 Op.getOperand(1).hasOneUse());
9434 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9435 // 1 and that the SETCC node has a single use.
9436 static bool isXor1OfSetCC(SDValue Op) {
9437 if (Op.getOpcode() != ISD::XOR)
9439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9440 if (N1C && N1C->getAPIntValue() == 1) {
9441 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9442 Op.getOperand(0).hasOneUse();
9447 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9448 bool addTest = true;
9449 SDValue Chain = Op.getOperand(0);
9450 SDValue Cond = Op.getOperand(1);
9451 SDValue Dest = Op.getOperand(2);
9452 DebugLoc dl = Op.getDebugLoc();
9454 bool Inverted = false;
9456 if (Cond.getOpcode() == ISD::SETCC) {
9457 // Check for setcc([su]{add,sub,mul}o == 0).
9458 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9459 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9460 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9461 Cond.getOperand(0).getResNo() == 1 &&
9462 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9463 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9464 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9465 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9466 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9467 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9469 Cond = Cond.getOperand(0);
9471 SDValue NewCond = LowerSETCC(Cond, DAG);
9472 if (NewCond.getNode())
9477 // FIXME: LowerXALUO doesn't handle these!!
9478 else if (Cond.getOpcode() == X86ISD::ADD ||
9479 Cond.getOpcode() == X86ISD::SUB ||
9480 Cond.getOpcode() == X86ISD::SMUL ||
9481 Cond.getOpcode() == X86ISD::UMUL)
9482 Cond = LowerXALUO(Cond, DAG);
9485 // Look pass (and (setcc_carry (cmp ...)), 1).
9486 if (Cond.getOpcode() == ISD::AND &&
9487 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9488 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9489 if (C && C->getAPIntValue() == 1)
9490 Cond = Cond.getOperand(0);
9493 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9494 // setting operand in place of the X86ISD::SETCC.
9495 unsigned CondOpcode = Cond.getOpcode();
9496 if (CondOpcode == X86ISD::SETCC ||
9497 CondOpcode == X86ISD::SETCC_CARRY) {
9498 CC = Cond.getOperand(0);
9500 SDValue Cmp = Cond.getOperand(1);
9501 unsigned Opc = Cmp.getOpcode();
9502 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9503 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9507 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9511 // These can only come from an arithmetic instruction with overflow,
9512 // e.g. SADDO, UADDO.
9513 Cond = Cond.getNode()->getOperand(1);
9519 CondOpcode = Cond.getOpcode();
9520 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9521 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9522 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9523 Cond.getOperand(0).getValueType() != MVT::i8)) {
9524 SDValue LHS = Cond.getOperand(0);
9525 SDValue RHS = Cond.getOperand(1);
9529 switch (CondOpcode) {
9530 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9531 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9532 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9533 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9534 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9535 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9536 default: llvm_unreachable("unexpected overflowing operator");
9539 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9540 if (CondOpcode == ISD::UMULO)
9541 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9544 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9546 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9548 if (CondOpcode == ISD::UMULO)
9549 Cond = X86Op.getValue(2);
9551 Cond = X86Op.getValue(1);
9553 CC = DAG.getConstant(X86Cond, MVT::i8);
9557 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9558 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9559 if (CondOpc == ISD::OR) {
9560 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9561 // two branches instead of an explicit OR instruction with a
9563 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9564 isX86LogicalCmp(Cmp)) {
9565 CC = Cond.getOperand(0).getOperand(0);
9566 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9567 Chain, Dest, CC, Cmp);
9568 CC = Cond.getOperand(1).getOperand(0);
9572 } else { // ISD::AND
9573 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9574 // two branches instead of an explicit AND instruction with a
9575 // separate test. However, we only do this if this block doesn't
9576 // have a fall-through edge, because this requires an explicit
9577 // jmp when the condition is false.
9578 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9579 isX86LogicalCmp(Cmp) &&
9580 Op.getNode()->hasOneUse()) {
9581 X86::CondCode CCode =
9582 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9583 CCode = X86::GetOppositeBranchCondition(CCode);
9584 CC = DAG.getConstant(CCode, MVT::i8);
9585 SDNode *User = *Op.getNode()->use_begin();
9586 // Look for an unconditional branch following this conditional branch.
9587 // We need this because we need to reverse the successors in order
9588 // to implement FCMP_OEQ.
9589 if (User->getOpcode() == ISD::BR) {
9590 SDValue FalseBB = User->getOperand(1);
9592 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9593 assert(NewBR == User);
9597 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9598 Chain, Dest, CC, Cmp);
9599 X86::CondCode CCode =
9600 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9601 CCode = X86::GetOppositeBranchCondition(CCode);
9602 CC = DAG.getConstant(CCode, MVT::i8);
9608 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9609 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9610 // It should be transformed during dag combiner except when the condition
9611 // is set by a arithmetics with overflow node.
9612 X86::CondCode CCode =
9613 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9614 CCode = X86::GetOppositeBranchCondition(CCode);
9615 CC = DAG.getConstant(CCode, MVT::i8);
9616 Cond = Cond.getOperand(0).getOperand(1);
9618 } else if (Cond.getOpcode() == ISD::SETCC &&
9619 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9620 // For FCMP_OEQ, we can emit
9621 // two branches instead of an explicit AND instruction with a
9622 // separate test. However, we only do this if this block doesn't
9623 // have a fall-through edge, because this requires an explicit
9624 // jmp when the condition is false.
9625 if (Op.getNode()->hasOneUse()) {
9626 SDNode *User = *Op.getNode()->use_begin();
9627 // Look for an unconditional branch following this conditional branch.
9628 // We need this because we need to reverse the successors in order
9629 // to implement FCMP_OEQ.
9630 if (User->getOpcode() == ISD::BR) {
9631 SDValue FalseBB = User->getOperand(1);
9633 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9634 assert(NewBR == User);
9638 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9639 Cond.getOperand(0), Cond.getOperand(1));
9640 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9641 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9642 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9643 Chain, Dest, CC, Cmp);
9644 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9649 } else if (Cond.getOpcode() == ISD::SETCC &&
9650 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9651 // For FCMP_UNE, we can emit
9652 // two branches instead of an explicit AND instruction with a
9653 // separate test. However, we only do this if this block doesn't
9654 // have a fall-through edge, because this requires an explicit
9655 // jmp when the condition is false.
9656 if (Op.getNode()->hasOneUse()) {
9657 SDNode *User = *Op.getNode()->use_begin();
9658 // Look for an unconditional branch following this conditional branch.
9659 // We need this because we need to reverse the successors in order
9660 // to implement FCMP_UNE.
9661 if (User->getOpcode() == ISD::BR) {
9662 SDValue FalseBB = User->getOperand(1);
9664 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9665 assert(NewBR == User);
9668 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9669 Cond.getOperand(0), Cond.getOperand(1));
9670 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9671 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9672 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9673 Chain, Dest, CC, Cmp);
9674 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9684 // Look pass the truncate if the high bits are known zero.
9685 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9686 Cond = Cond.getOperand(0);
9688 // We know the result of AND is compared against zero. Try to match
9690 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9691 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9692 if (NewSetCC.getNode()) {
9693 CC = NewSetCC.getOperand(0);
9694 Cond = NewSetCC.getOperand(1);
9701 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9702 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9704 Cond = ConvertCmpIfNecessary(Cond, DAG);
9705 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9706 Chain, Dest, CC, Cond);
9710 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9711 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9712 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9713 // that the guard pages used by the OS virtual memory manager are allocated in
9714 // correct sequence.
9716 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9717 SelectionDAG &DAG) const {
9718 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9719 getTargetMachine().Options.EnableSegmentedStacks) &&
9720 "This should be used only on Windows targets or when segmented stacks "
9722 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9723 DebugLoc dl = Op.getDebugLoc();
9726 SDValue Chain = Op.getOperand(0);
9727 SDValue Size = Op.getOperand(1);
9728 // FIXME: Ensure alignment here
9730 bool Is64Bit = Subtarget->is64Bit();
9731 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9733 if (getTargetMachine().Options.EnableSegmentedStacks) {
9734 MachineFunction &MF = DAG.getMachineFunction();
9735 MachineRegisterInfo &MRI = MF.getRegInfo();
9738 // The 64 bit implementation of segmented stacks needs to clobber both r10
9739 // r11. This makes it impossible to use it along with nested parameters.
9740 const Function *F = MF.getFunction();
9742 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9744 if (I->hasNestAttr())
9745 report_fatal_error("Cannot use segmented stacks with functions that "
9746 "have nested arguments.");
9749 const TargetRegisterClass *AddrRegClass =
9750 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9751 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9752 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9753 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9754 DAG.getRegister(Vreg, SPTy));
9755 SDValue Ops1[2] = { Value, Chain };
9756 return DAG.getMergeValues(Ops1, 2, dl);
9759 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9761 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9762 Flag = Chain.getValue(1);
9763 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9765 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9766 Flag = Chain.getValue(1);
9768 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9770 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9771 return DAG.getMergeValues(Ops1, 2, dl);
9775 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9776 MachineFunction &MF = DAG.getMachineFunction();
9777 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9779 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9780 DebugLoc DL = Op.getDebugLoc();
9782 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9783 // vastart just stores the address of the VarArgsFrameIndex slot into the
9784 // memory location argument.
9785 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9787 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9788 MachinePointerInfo(SV), false, false, 0);
9792 // gp_offset (0 - 6 * 8)
9793 // fp_offset (48 - 48 + 8 * 16)
9794 // overflow_arg_area (point to parameters coming in memory).
9796 SmallVector<SDValue, 8> MemOps;
9797 SDValue FIN = Op.getOperand(1);
9799 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9800 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9802 FIN, MachinePointerInfo(SV), false, false, 0);
9803 MemOps.push_back(Store);
9806 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9807 FIN, DAG.getIntPtrConstant(4));
9808 Store = DAG.getStore(Op.getOperand(0), DL,
9809 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9811 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9812 MemOps.push_back(Store);
9814 // Store ptr to overflow_arg_area
9815 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9816 FIN, DAG.getIntPtrConstant(4));
9817 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9819 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9820 MachinePointerInfo(SV, 8),
9822 MemOps.push_back(Store);
9824 // Store ptr to reg_save_area.
9825 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9826 FIN, DAG.getIntPtrConstant(8));
9827 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9829 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9830 MachinePointerInfo(SV, 16), false, false, 0);
9831 MemOps.push_back(Store);
9832 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9833 &MemOps[0], MemOps.size());
9836 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9837 assert(Subtarget->is64Bit() &&
9838 "LowerVAARG only handles 64-bit va_arg!");
9839 assert((Subtarget->isTargetLinux() ||
9840 Subtarget->isTargetDarwin()) &&
9841 "Unhandled target in LowerVAARG");
9842 assert(Op.getNode()->getNumOperands() == 4);
9843 SDValue Chain = Op.getOperand(0);
9844 SDValue SrcPtr = Op.getOperand(1);
9845 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9846 unsigned Align = Op.getConstantOperandVal(3);
9847 DebugLoc dl = Op.getDebugLoc();
9849 EVT ArgVT = Op.getNode()->getValueType(0);
9850 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9851 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9854 // Decide which area this value should be read from.
9855 // TODO: Implement the AMD64 ABI in its entirety. This simple
9856 // selection mechanism works only for the basic types.
9857 if (ArgVT == MVT::f80) {
9858 llvm_unreachable("va_arg for f80 not yet implemented");
9859 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9860 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9861 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9862 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9864 llvm_unreachable("Unhandled argument type in LowerVAARG");
9868 // Sanity Check: Make sure using fp_offset makes sense.
9869 assert(!getTargetMachine().Options.UseSoftFloat &&
9870 !(DAG.getMachineFunction()
9871 .getFunction()->getFnAttributes()
9872 .hasAttribute(Attributes::NoImplicitFloat)) &&
9873 Subtarget->hasSSE1());
9876 // Insert VAARG_64 node into the DAG
9877 // VAARG_64 returns two values: Variable Argument Address, Chain
9878 SmallVector<SDValue, 11> InstOps;
9879 InstOps.push_back(Chain);
9880 InstOps.push_back(SrcPtr);
9881 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9882 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9883 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9884 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9885 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9886 VTs, &InstOps[0], InstOps.size(),
9888 MachinePointerInfo(SV),
9893 Chain = VAARG.getValue(1);
9895 // Load the next argument and return it
9896 return DAG.getLoad(ArgVT, dl,
9899 MachinePointerInfo(),
9900 false, false, false, 0);
9903 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9904 SelectionDAG &DAG) {
9905 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9906 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9907 SDValue Chain = Op.getOperand(0);
9908 SDValue DstPtr = Op.getOperand(1);
9909 SDValue SrcPtr = Op.getOperand(2);
9910 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9911 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9912 DebugLoc DL = Op.getDebugLoc();
9914 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9915 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9917 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9920 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9921 // may or may not be a constant. Takes immediate version of shift as input.
9922 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9923 SDValue SrcOp, SDValue ShAmt,
9924 SelectionDAG &DAG) {
9925 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9927 if (isa<ConstantSDNode>(ShAmt)) {
9928 // Constant may be a TargetConstant. Use a regular constant.
9929 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9931 default: llvm_unreachable("Unknown target vector shift node");
9935 return DAG.getNode(Opc, dl, VT, SrcOp,
9936 DAG.getConstant(ShiftAmt, MVT::i32));
9940 // Change opcode to non-immediate version
9942 default: llvm_unreachable("Unknown target vector shift node");
9943 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9944 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9945 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9948 // Need to build a vector containing shift amount
9949 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9952 ShOps[1] = DAG.getConstant(0, MVT::i32);
9953 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9954 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9956 // The return type has to be a 128-bit type with the same element
9957 // type as the input type.
9958 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9959 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9961 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9962 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9965 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9966 DebugLoc dl = Op.getDebugLoc();
9967 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9969 default: return SDValue(); // Don't custom lower most intrinsics.
9970 // Comparison intrinsics.
9971 case Intrinsic::x86_sse_comieq_ss:
9972 case Intrinsic::x86_sse_comilt_ss:
9973 case Intrinsic::x86_sse_comile_ss:
9974 case Intrinsic::x86_sse_comigt_ss:
9975 case Intrinsic::x86_sse_comige_ss:
9976 case Intrinsic::x86_sse_comineq_ss:
9977 case Intrinsic::x86_sse_ucomieq_ss:
9978 case Intrinsic::x86_sse_ucomilt_ss:
9979 case Intrinsic::x86_sse_ucomile_ss:
9980 case Intrinsic::x86_sse_ucomigt_ss:
9981 case Intrinsic::x86_sse_ucomige_ss:
9982 case Intrinsic::x86_sse_ucomineq_ss:
9983 case Intrinsic::x86_sse2_comieq_sd:
9984 case Intrinsic::x86_sse2_comilt_sd:
9985 case Intrinsic::x86_sse2_comile_sd:
9986 case Intrinsic::x86_sse2_comigt_sd:
9987 case Intrinsic::x86_sse2_comige_sd:
9988 case Intrinsic::x86_sse2_comineq_sd:
9989 case Intrinsic::x86_sse2_ucomieq_sd:
9990 case Intrinsic::x86_sse2_ucomilt_sd:
9991 case Intrinsic::x86_sse2_ucomile_sd:
9992 case Intrinsic::x86_sse2_ucomigt_sd:
9993 case Intrinsic::x86_sse2_ucomige_sd:
9994 case Intrinsic::x86_sse2_ucomineq_sd: {
9998 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9999 case Intrinsic::x86_sse_comieq_ss:
10000 case Intrinsic::x86_sse2_comieq_sd:
10001 Opc = X86ISD::COMI;
10004 case Intrinsic::x86_sse_comilt_ss:
10005 case Intrinsic::x86_sse2_comilt_sd:
10006 Opc = X86ISD::COMI;
10009 case Intrinsic::x86_sse_comile_ss:
10010 case Intrinsic::x86_sse2_comile_sd:
10011 Opc = X86ISD::COMI;
10014 case Intrinsic::x86_sse_comigt_ss:
10015 case Intrinsic::x86_sse2_comigt_sd:
10016 Opc = X86ISD::COMI;
10019 case Intrinsic::x86_sse_comige_ss:
10020 case Intrinsic::x86_sse2_comige_sd:
10021 Opc = X86ISD::COMI;
10024 case Intrinsic::x86_sse_comineq_ss:
10025 case Intrinsic::x86_sse2_comineq_sd:
10026 Opc = X86ISD::COMI;
10029 case Intrinsic::x86_sse_ucomieq_ss:
10030 case Intrinsic::x86_sse2_ucomieq_sd:
10031 Opc = X86ISD::UCOMI;
10034 case Intrinsic::x86_sse_ucomilt_ss:
10035 case Intrinsic::x86_sse2_ucomilt_sd:
10036 Opc = X86ISD::UCOMI;
10039 case Intrinsic::x86_sse_ucomile_ss:
10040 case Intrinsic::x86_sse2_ucomile_sd:
10041 Opc = X86ISD::UCOMI;
10044 case Intrinsic::x86_sse_ucomigt_ss:
10045 case Intrinsic::x86_sse2_ucomigt_sd:
10046 Opc = X86ISD::UCOMI;
10049 case Intrinsic::x86_sse_ucomige_ss:
10050 case Intrinsic::x86_sse2_ucomige_sd:
10051 Opc = X86ISD::UCOMI;
10054 case Intrinsic::x86_sse_ucomineq_ss:
10055 case Intrinsic::x86_sse2_ucomineq_sd:
10056 Opc = X86ISD::UCOMI;
10061 SDValue LHS = Op.getOperand(1);
10062 SDValue RHS = Op.getOperand(2);
10063 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10064 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10065 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10066 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10067 DAG.getConstant(X86CC, MVT::i8), Cond);
10068 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10071 // Arithmetic intrinsics.
10072 case Intrinsic::x86_sse2_pmulu_dq:
10073 case Intrinsic::x86_avx2_pmulu_dq:
10074 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10075 Op.getOperand(1), Op.getOperand(2));
10077 // SSE3/AVX horizontal add/sub intrinsics
10078 case Intrinsic::x86_sse3_hadd_ps:
10079 case Intrinsic::x86_sse3_hadd_pd:
10080 case Intrinsic::x86_avx_hadd_ps_256:
10081 case Intrinsic::x86_avx_hadd_pd_256:
10082 case Intrinsic::x86_sse3_hsub_ps:
10083 case Intrinsic::x86_sse3_hsub_pd:
10084 case Intrinsic::x86_avx_hsub_ps_256:
10085 case Intrinsic::x86_avx_hsub_pd_256:
10086 case Intrinsic::x86_ssse3_phadd_w_128:
10087 case Intrinsic::x86_ssse3_phadd_d_128:
10088 case Intrinsic::x86_avx2_phadd_w:
10089 case Intrinsic::x86_avx2_phadd_d:
10090 case Intrinsic::x86_ssse3_phsub_w_128:
10091 case Intrinsic::x86_ssse3_phsub_d_128:
10092 case Intrinsic::x86_avx2_phsub_w:
10093 case Intrinsic::x86_avx2_phsub_d: {
10096 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10097 case Intrinsic::x86_sse3_hadd_ps:
10098 case Intrinsic::x86_sse3_hadd_pd:
10099 case Intrinsic::x86_avx_hadd_ps_256:
10100 case Intrinsic::x86_avx_hadd_pd_256:
10101 Opcode = X86ISD::FHADD;
10103 case Intrinsic::x86_sse3_hsub_ps:
10104 case Intrinsic::x86_sse3_hsub_pd:
10105 case Intrinsic::x86_avx_hsub_ps_256:
10106 case Intrinsic::x86_avx_hsub_pd_256:
10107 Opcode = X86ISD::FHSUB;
10109 case Intrinsic::x86_ssse3_phadd_w_128:
10110 case Intrinsic::x86_ssse3_phadd_d_128:
10111 case Intrinsic::x86_avx2_phadd_w:
10112 case Intrinsic::x86_avx2_phadd_d:
10113 Opcode = X86ISD::HADD;
10115 case Intrinsic::x86_ssse3_phsub_w_128:
10116 case Intrinsic::x86_ssse3_phsub_d_128:
10117 case Intrinsic::x86_avx2_phsub_w:
10118 case Intrinsic::x86_avx2_phsub_d:
10119 Opcode = X86ISD::HSUB;
10122 return DAG.getNode(Opcode, dl, Op.getValueType(),
10123 Op.getOperand(1), Op.getOperand(2));
10126 // AVX2 variable shift intrinsics
10127 case Intrinsic::x86_avx2_psllv_d:
10128 case Intrinsic::x86_avx2_psllv_q:
10129 case Intrinsic::x86_avx2_psllv_d_256:
10130 case Intrinsic::x86_avx2_psllv_q_256:
10131 case Intrinsic::x86_avx2_psrlv_d:
10132 case Intrinsic::x86_avx2_psrlv_q:
10133 case Intrinsic::x86_avx2_psrlv_d_256:
10134 case Intrinsic::x86_avx2_psrlv_q_256:
10135 case Intrinsic::x86_avx2_psrav_d:
10136 case Intrinsic::x86_avx2_psrav_d_256: {
10139 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10140 case Intrinsic::x86_avx2_psllv_d:
10141 case Intrinsic::x86_avx2_psllv_q:
10142 case Intrinsic::x86_avx2_psllv_d_256:
10143 case Intrinsic::x86_avx2_psllv_q_256:
10146 case Intrinsic::x86_avx2_psrlv_d:
10147 case Intrinsic::x86_avx2_psrlv_q:
10148 case Intrinsic::x86_avx2_psrlv_d_256:
10149 case Intrinsic::x86_avx2_psrlv_q_256:
10152 case Intrinsic::x86_avx2_psrav_d:
10153 case Intrinsic::x86_avx2_psrav_d_256:
10157 return DAG.getNode(Opcode, dl, Op.getValueType(),
10158 Op.getOperand(1), Op.getOperand(2));
10161 case Intrinsic::x86_ssse3_pshuf_b_128:
10162 case Intrinsic::x86_avx2_pshuf_b:
10163 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10164 Op.getOperand(1), Op.getOperand(2));
10166 case Intrinsic::x86_ssse3_psign_b_128:
10167 case Intrinsic::x86_ssse3_psign_w_128:
10168 case Intrinsic::x86_ssse3_psign_d_128:
10169 case Intrinsic::x86_avx2_psign_b:
10170 case Intrinsic::x86_avx2_psign_w:
10171 case Intrinsic::x86_avx2_psign_d:
10172 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10173 Op.getOperand(1), Op.getOperand(2));
10175 case Intrinsic::x86_sse41_insertps:
10176 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10177 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10179 case Intrinsic::x86_avx_vperm2f128_ps_256:
10180 case Intrinsic::x86_avx_vperm2f128_pd_256:
10181 case Intrinsic::x86_avx_vperm2f128_si_256:
10182 case Intrinsic::x86_avx2_vperm2i128:
10183 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10184 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10186 case Intrinsic::x86_avx2_permd:
10187 case Intrinsic::x86_avx2_permps:
10188 // Operands intentionally swapped. Mask is last operand to intrinsic,
10189 // but second operand for node/intruction.
10190 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10191 Op.getOperand(2), Op.getOperand(1));
10193 // ptest and testp intrinsics. The intrinsic these come from are designed to
10194 // return an integer value, not just an instruction so lower it to the ptest
10195 // or testp pattern and a setcc for the result.
10196 case Intrinsic::x86_sse41_ptestz:
10197 case Intrinsic::x86_sse41_ptestc:
10198 case Intrinsic::x86_sse41_ptestnzc:
10199 case Intrinsic::x86_avx_ptestz_256:
10200 case Intrinsic::x86_avx_ptestc_256:
10201 case Intrinsic::x86_avx_ptestnzc_256:
10202 case Intrinsic::x86_avx_vtestz_ps:
10203 case Intrinsic::x86_avx_vtestc_ps:
10204 case Intrinsic::x86_avx_vtestnzc_ps:
10205 case Intrinsic::x86_avx_vtestz_pd:
10206 case Intrinsic::x86_avx_vtestc_pd:
10207 case Intrinsic::x86_avx_vtestnzc_pd:
10208 case Intrinsic::x86_avx_vtestz_ps_256:
10209 case Intrinsic::x86_avx_vtestc_ps_256:
10210 case Intrinsic::x86_avx_vtestnzc_ps_256:
10211 case Intrinsic::x86_avx_vtestz_pd_256:
10212 case Intrinsic::x86_avx_vtestc_pd_256:
10213 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10214 bool IsTestPacked = false;
10217 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10218 case Intrinsic::x86_avx_vtestz_ps:
10219 case Intrinsic::x86_avx_vtestz_pd:
10220 case Intrinsic::x86_avx_vtestz_ps_256:
10221 case Intrinsic::x86_avx_vtestz_pd_256:
10222 IsTestPacked = true; // Fallthrough
10223 case Intrinsic::x86_sse41_ptestz:
10224 case Intrinsic::x86_avx_ptestz_256:
10226 X86CC = X86::COND_E;
10228 case Intrinsic::x86_avx_vtestc_ps:
10229 case Intrinsic::x86_avx_vtestc_pd:
10230 case Intrinsic::x86_avx_vtestc_ps_256:
10231 case Intrinsic::x86_avx_vtestc_pd_256:
10232 IsTestPacked = true; // Fallthrough
10233 case Intrinsic::x86_sse41_ptestc:
10234 case Intrinsic::x86_avx_ptestc_256:
10236 X86CC = X86::COND_B;
10238 case Intrinsic::x86_avx_vtestnzc_ps:
10239 case Intrinsic::x86_avx_vtestnzc_pd:
10240 case Intrinsic::x86_avx_vtestnzc_ps_256:
10241 case Intrinsic::x86_avx_vtestnzc_pd_256:
10242 IsTestPacked = true; // Fallthrough
10243 case Intrinsic::x86_sse41_ptestnzc:
10244 case Intrinsic::x86_avx_ptestnzc_256:
10246 X86CC = X86::COND_A;
10250 SDValue LHS = Op.getOperand(1);
10251 SDValue RHS = Op.getOperand(2);
10252 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10253 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10254 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10255 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10256 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10259 // SSE/AVX shift intrinsics
10260 case Intrinsic::x86_sse2_psll_w:
10261 case Intrinsic::x86_sse2_psll_d:
10262 case Intrinsic::x86_sse2_psll_q:
10263 case Intrinsic::x86_avx2_psll_w:
10264 case Intrinsic::x86_avx2_psll_d:
10265 case Intrinsic::x86_avx2_psll_q:
10266 case Intrinsic::x86_sse2_psrl_w:
10267 case Intrinsic::x86_sse2_psrl_d:
10268 case Intrinsic::x86_sse2_psrl_q:
10269 case Intrinsic::x86_avx2_psrl_w:
10270 case Intrinsic::x86_avx2_psrl_d:
10271 case Intrinsic::x86_avx2_psrl_q:
10272 case Intrinsic::x86_sse2_psra_w:
10273 case Intrinsic::x86_sse2_psra_d:
10274 case Intrinsic::x86_avx2_psra_w:
10275 case Intrinsic::x86_avx2_psra_d: {
10278 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10279 case Intrinsic::x86_sse2_psll_w:
10280 case Intrinsic::x86_sse2_psll_d:
10281 case Intrinsic::x86_sse2_psll_q:
10282 case Intrinsic::x86_avx2_psll_w:
10283 case Intrinsic::x86_avx2_psll_d:
10284 case Intrinsic::x86_avx2_psll_q:
10285 Opcode = X86ISD::VSHL;
10287 case Intrinsic::x86_sse2_psrl_w:
10288 case Intrinsic::x86_sse2_psrl_d:
10289 case Intrinsic::x86_sse2_psrl_q:
10290 case Intrinsic::x86_avx2_psrl_w:
10291 case Intrinsic::x86_avx2_psrl_d:
10292 case Intrinsic::x86_avx2_psrl_q:
10293 Opcode = X86ISD::VSRL;
10295 case Intrinsic::x86_sse2_psra_w:
10296 case Intrinsic::x86_sse2_psra_d:
10297 case Intrinsic::x86_avx2_psra_w:
10298 case Intrinsic::x86_avx2_psra_d:
10299 Opcode = X86ISD::VSRA;
10302 return DAG.getNode(Opcode, dl, Op.getValueType(),
10303 Op.getOperand(1), Op.getOperand(2));
10306 // SSE/AVX immediate shift intrinsics
10307 case Intrinsic::x86_sse2_pslli_w:
10308 case Intrinsic::x86_sse2_pslli_d:
10309 case Intrinsic::x86_sse2_pslli_q:
10310 case Intrinsic::x86_avx2_pslli_w:
10311 case Intrinsic::x86_avx2_pslli_d:
10312 case Intrinsic::x86_avx2_pslli_q:
10313 case Intrinsic::x86_sse2_psrli_w:
10314 case Intrinsic::x86_sse2_psrli_d:
10315 case Intrinsic::x86_sse2_psrli_q:
10316 case Intrinsic::x86_avx2_psrli_w:
10317 case Intrinsic::x86_avx2_psrli_d:
10318 case Intrinsic::x86_avx2_psrli_q:
10319 case Intrinsic::x86_sse2_psrai_w:
10320 case Intrinsic::x86_sse2_psrai_d:
10321 case Intrinsic::x86_avx2_psrai_w:
10322 case Intrinsic::x86_avx2_psrai_d: {
10325 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10326 case Intrinsic::x86_sse2_pslli_w:
10327 case Intrinsic::x86_sse2_pslli_d:
10328 case Intrinsic::x86_sse2_pslli_q:
10329 case Intrinsic::x86_avx2_pslli_w:
10330 case Intrinsic::x86_avx2_pslli_d:
10331 case Intrinsic::x86_avx2_pslli_q:
10332 Opcode = X86ISD::VSHLI;
10334 case Intrinsic::x86_sse2_psrli_w:
10335 case Intrinsic::x86_sse2_psrli_d:
10336 case Intrinsic::x86_sse2_psrli_q:
10337 case Intrinsic::x86_avx2_psrli_w:
10338 case Intrinsic::x86_avx2_psrli_d:
10339 case Intrinsic::x86_avx2_psrli_q:
10340 Opcode = X86ISD::VSRLI;
10342 case Intrinsic::x86_sse2_psrai_w:
10343 case Intrinsic::x86_sse2_psrai_d:
10344 case Intrinsic::x86_avx2_psrai_w:
10345 case Intrinsic::x86_avx2_psrai_d:
10346 Opcode = X86ISD::VSRAI;
10349 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10350 Op.getOperand(1), Op.getOperand(2), DAG);
10353 case Intrinsic::x86_sse42_pcmpistria128:
10354 case Intrinsic::x86_sse42_pcmpestria128:
10355 case Intrinsic::x86_sse42_pcmpistric128:
10356 case Intrinsic::x86_sse42_pcmpestric128:
10357 case Intrinsic::x86_sse42_pcmpistrio128:
10358 case Intrinsic::x86_sse42_pcmpestrio128:
10359 case Intrinsic::x86_sse42_pcmpistris128:
10360 case Intrinsic::x86_sse42_pcmpestris128:
10361 case Intrinsic::x86_sse42_pcmpistriz128:
10362 case Intrinsic::x86_sse42_pcmpestriz128: {
10366 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10367 case Intrinsic::x86_sse42_pcmpistria128:
10368 Opcode = X86ISD::PCMPISTRI;
10369 X86CC = X86::COND_A;
10371 case Intrinsic::x86_sse42_pcmpestria128:
10372 Opcode = X86ISD::PCMPESTRI;
10373 X86CC = X86::COND_A;
10375 case Intrinsic::x86_sse42_pcmpistric128:
10376 Opcode = X86ISD::PCMPISTRI;
10377 X86CC = X86::COND_B;
10379 case Intrinsic::x86_sse42_pcmpestric128:
10380 Opcode = X86ISD::PCMPESTRI;
10381 X86CC = X86::COND_B;
10383 case Intrinsic::x86_sse42_pcmpistrio128:
10384 Opcode = X86ISD::PCMPISTRI;
10385 X86CC = X86::COND_O;
10387 case Intrinsic::x86_sse42_pcmpestrio128:
10388 Opcode = X86ISD::PCMPESTRI;
10389 X86CC = X86::COND_O;
10391 case Intrinsic::x86_sse42_pcmpistris128:
10392 Opcode = X86ISD::PCMPISTRI;
10393 X86CC = X86::COND_S;
10395 case Intrinsic::x86_sse42_pcmpestris128:
10396 Opcode = X86ISD::PCMPESTRI;
10397 X86CC = X86::COND_S;
10399 case Intrinsic::x86_sse42_pcmpistriz128:
10400 Opcode = X86ISD::PCMPISTRI;
10401 X86CC = X86::COND_E;
10403 case Intrinsic::x86_sse42_pcmpestriz128:
10404 Opcode = X86ISD::PCMPESTRI;
10405 X86CC = X86::COND_E;
10408 SmallVector<SDValue, 5> NewOps;
10409 NewOps.append(Op->op_begin()+1, Op->op_end());
10410 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10411 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10412 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10413 DAG.getConstant(X86CC, MVT::i8),
10414 SDValue(PCMP.getNode(), 1));
10415 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10418 case Intrinsic::x86_sse42_pcmpistri128:
10419 case Intrinsic::x86_sse42_pcmpestri128: {
10421 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10422 Opcode = X86ISD::PCMPISTRI;
10424 Opcode = X86ISD::PCMPESTRI;
10426 SmallVector<SDValue, 5> NewOps;
10427 NewOps.append(Op->op_begin()+1, Op->op_end());
10428 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10429 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10431 case Intrinsic::x86_fma_vfmadd_ps:
10432 case Intrinsic::x86_fma_vfmadd_pd:
10433 case Intrinsic::x86_fma_vfmsub_ps:
10434 case Intrinsic::x86_fma_vfmsub_pd:
10435 case Intrinsic::x86_fma_vfnmadd_ps:
10436 case Intrinsic::x86_fma_vfnmadd_pd:
10437 case Intrinsic::x86_fma_vfnmsub_ps:
10438 case Intrinsic::x86_fma_vfnmsub_pd:
10439 case Intrinsic::x86_fma_vfmaddsub_ps:
10440 case Intrinsic::x86_fma_vfmaddsub_pd:
10441 case Intrinsic::x86_fma_vfmsubadd_ps:
10442 case Intrinsic::x86_fma_vfmsubadd_pd:
10443 case Intrinsic::x86_fma_vfmadd_ps_256:
10444 case Intrinsic::x86_fma_vfmadd_pd_256:
10445 case Intrinsic::x86_fma_vfmsub_ps_256:
10446 case Intrinsic::x86_fma_vfmsub_pd_256:
10447 case Intrinsic::x86_fma_vfnmadd_ps_256:
10448 case Intrinsic::x86_fma_vfnmadd_pd_256:
10449 case Intrinsic::x86_fma_vfnmsub_ps_256:
10450 case Intrinsic::x86_fma_vfnmsub_pd_256:
10451 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10452 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10453 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10454 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10457 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10458 case Intrinsic::x86_fma_vfmadd_ps:
10459 case Intrinsic::x86_fma_vfmadd_pd:
10460 case Intrinsic::x86_fma_vfmadd_ps_256:
10461 case Intrinsic::x86_fma_vfmadd_pd_256:
10462 Opc = X86ISD::FMADD;
10464 case Intrinsic::x86_fma_vfmsub_ps:
10465 case Intrinsic::x86_fma_vfmsub_pd:
10466 case Intrinsic::x86_fma_vfmsub_ps_256:
10467 case Intrinsic::x86_fma_vfmsub_pd_256:
10468 Opc = X86ISD::FMSUB;
10470 case Intrinsic::x86_fma_vfnmadd_ps:
10471 case Intrinsic::x86_fma_vfnmadd_pd:
10472 case Intrinsic::x86_fma_vfnmadd_ps_256:
10473 case Intrinsic::x86_fma_vfnmadd_pd_256:
10474 Opc = X86ISD::FNMADD;
10476 case Intrinsic::x86_fma_vfnmsub_ps:
10477 case Intrinsic::x86_fma_vfnmsub_pd:
10478 case Intrinsic::x86_fma_vfnmsub_ps_256:
10479 case Intrinsic::x86_fma_vfnmsub_pd_256:
10480 Opc = X86ISD::FNMSUB;
10482 case Intrinsic::x86_fma_vfmaddsub_ps:
10483 case Intrinsic::x86_fma_vfmaddsub_pd:
10484 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10485 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10486 Opc = X86ISD::FMADDSUB;
10488 case Intrinsic::x86_fma_vfmsubadd_ps:
10489 case Intrinsic::x86_fma_vfmsubadd_pd:
10490 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10491 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10492 Opc = X86ISD::FMSUBADD;
10496 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10497 Op.getOperand(2), Op.getOperand(3));
10502 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10503 DebugLoc dl = Op.getDebugLoc();
10504 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10506 default: return SDValue(); // Don't custom lower most intrinsics.
10508 // RDRAND intrinsics.
10509 case Intrinsic::x86_rdrand_16:
10510 case Intrinsic::x86_rdrand_32:
10511 case Intrinsic::x86_rdrand_64: {
10512 // Emit the node with the right value type.
10513 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10514 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10516 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10517 // return the value from Rand, which is always 0, casted to i32.
10518 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10519 DAG.getConstant(1, Op->getValueType(1)),
10520 DAG.getConstant(X86::COND_B, MVT::i32),
10521 SDValue(Result.getNode(), 1) };
10522 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10523 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10526 // Return { result, isValid, chain }.
10527 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10528 SDValue(Result.getNode(), 2));
10533 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10534 SelectionDAG &DAG) const {
10535 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10536 MFI->setReturnAddressIsTaken(true);
10538 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10539 DebugLoc dl = Op.getDebugLoc();
10542 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10544 DAG.getConstant(TD->getPointerSize(0),
10545 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10546 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10547 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10548 FrameAddr, Offset),
10549 MachinePointerInfo(), false, false, false, 0);
10552 // Just load the return address.
10553 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10554 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10555 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10558 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10559 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10560 MFI->setFrameAddressIsTaken(true);
10562 EVT VT = Op.getValueType();
10563 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10564 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10565 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10566 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10568 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10569 MachinePointerInfo(),
10570 false, false, false, 0);
10574 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10575 SelectionDAG &DAG) const {
10576 return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10579 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10580 SDValue Chain = Op.getOperand(0);
10581 SDValue Offset = Op.getOperand(1);
10582 SDValue Handler = Op.getOperand(2);
10583 DebugLoc dl = Op.getDebugLoc();
10585 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10586 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10588 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10590 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10591 DAG.getIntPtrConstant(TD->getPointerSize(0)));
10592 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10593 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10595 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10597 return DAG.getNode(X86ISD::EH_RETURN, dl,
10599 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10602 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10603 SelectionDAG &DAG) const {
10604 DebugLoc DL = Op.getDebugLoc();
10605 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10606 DAG.getVTList(MVT::i32, MVT::Other),
10607 Op.getOperand(0), Op.getOperand(1));
10610 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10611 SelectionDAG &DAG) const {
10612 DebugLoc DL = Op.getDebugLoc();
10613 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10614 Op.getOperand(0), Op.getOperand(1));
10617 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10618 return Op.getOperand(0);
10621 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10622 SelectionDAG &DAG) const {
10623 SDValue Root = Op.getOperand(0);
10624 SDValue Trmp = Op.getOperand(1); // trampoline
10625 SDValue FPtr = Op.getOperand(2); // nested function
10626 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10627 DebugLoc dl = Op.getDebugLoc();
10629 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10630 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10632 if (Subtarget->is64Bit()) {
10633 SDValue OutChains[6];
10635 // Large code-model.
10636 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10637 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10639 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10640 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10642 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10644 // Load the pointer to the nested function into R11.
10645 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10646 SDValue Addr = Trmp;
10647 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10648 Addr, MachinePointerInfo(TrmpAddr),
10651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10652 DAG.getConstant(2, MVT::i64));
10653 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10654 MachinePointerInfo(TrmpAddr, 2),
10657 // Load the 'nest' parameter value into R10.
10658 // R10 is specified in X86CallingConv.td
10659 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10660 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10661 DAG.getConstant(10, MVT::i64));
10662 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10663 Addr, MachinePointerInfo(TrmpAddr, 10),
10666 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10667 DAG.getConstant(12, MVT::i64));
10668 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10669 MachinePointerInfo(TrmpAddr, 12),
10672 // Jump to the nested function.
10673 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10674 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10675 DAG.getConstant(20, MVT::i64));
10676 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10677 Addr, MachinePointerInfo(TrmpAddr, 20),
10680 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10681 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10682 DAG.getConstant(22, MVT::i64));
10683 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10684 MachinePointerInfo(TrmpAddr, 22),
10687 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10689 const Function *Func =
10690 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10691 CallingConv::ID CC = Func->getCallingConv();
10696 llvm_unreachable("Unsupported calling convention");
10697 case CallingConv::C:
10698 case CallingConv::X86_StdCall: {
10699 // Pass 'nest' parameter in ECX.
10700 // Must be kept in sync with X86CallingConv.td
10701 NestReg = X86::ECX;
10703 // Check that ECX wasn't needed by an 'inreg' parameter.
10704 FunctionType *FTy = Func->getFunctionType();
10705 const AttrListPtr &Attrs = Func->getAttributes();
10707 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10708 unsigned InRegCount = 0;
10711 for (FunctionType::param_iterator I = FTy->param_begin(),
10712 E = FTy->param_end(); I != E; ++I, ++Idx)
10713 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10714 // FIXME: should only count parameters that are lowered to integers.
10715 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10717 if (InRegCount > 2) {
10718 report_fatal_error("Nest register in use - reduce number of inreg"
10724 case CallingConv::X86_FastCall:
10725 case CallingConv::X86_ThisCall:
10726 case CallingConv::Fast:
10727 // Pass 'nest' parameter in EAX.
10728 // Must be kept in sync with X86CallingConv.td
10729 NestReg = X86::EAX;
10733 SDValue OutChains[4];
10734 SDValue Addr, Disp;
10736 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10737 DAG.getConstant(10, MVT::i32));
10738 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10740 // This is storing the opcode for MOV32ri.
10741 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10742 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10743 OutChains[0] = DAG.getStore(Root, dl,
10744 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10745 Trmp, MachinePointerInfo(TrmpAddr),
10748 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10749 DAG.getConstant(1, MVT::i32));
10750 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10751 MachinePointerInfo(TrmpAddr, 1),
10754 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10755 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10756 DAG.getConstant(5, MVT::i32));
10757 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10758 MachinePointerInfo(TrmpAddr, 5),
10761 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10762 DAG.getConstant(6, MVT::i32));
10763 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10764 MachinePointerInfo(TrmpAddr, 6),
10767 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10771 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10772 SelectionDAG &DAG) const {
10774 The rounding mode is in bits 11:10 of FPSR, and has the following
10776 00 Round to nearest
10781 FLT_ROUNDS, on the other hand, expects the following:
10788 To perform the conversion, we do:
10789 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10792 MachineFunction &MF = DAG.getMachineFunction();
10793 const TargetMachine &TM = MF.getTarget();
10794 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10795 unsigned StackAlignment = TFI.getStackAlignment();
10796 EVT VT = Op.getValueType();
10797 DebugLoc DL = Op.getDebugLoc();
10799 // Save FP Control Word to stack slot
10800 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10801 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10804 MachineMemOperand *MMO =
10805 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10806 MachineMemOperand::MOStore, 2, 2);
10808 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10809 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10810 DAG.getVTList(MVT::Other),
10811 Ops, 2, MVT::i16, MMO);
10813 // Load FP Control Word from stack slot
10814 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10815 MachinePointerInfo(), false, false, false, 0);
10817 // Transform as necessary
10819 DAG.getNode(ISD::SRL, DL, MVT::i16,
10820 DAG.getNode(ISD::AND, DL, MVT::i16,
10821 CWD, DAG.getConstant(0x800, MVT::i16)),
10822 DAG.getConstant(11, MVT::i8));
10824 DAG.getNode(ISD::SRL, DL, MVT::i16,
10825 DAG.getNode(ISD::AND, DL, MVT::i16,
10826 CWD, DAG.getConstant(0x400, MVT::i16)),
10827 DAG.getConstant(9, MVT::i8));
10830 DAG.getNode(ISD::AND, DL, MVT::i16,
10831 DAG.getNode(ISD::ADD, DL, MVT::i16,
10832 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10833 DAG.getConstant(1, MVT::i16)),
10834 DAG.getConstant(3, MVT::i16));
10837 return DAG.getNode((VT.getSizeInBits() < 16 ?
10838 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10841 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10842 EVT VT = Op.getValueType();
10844 unsigned NumBits = VT.getSizeInBits();
10845 DebugLoc dl = Op.getDebugLoc();
10847 Op = Op.getOperand(0);
10848 if (VT == MVT::i8) {
10849 // Zero extend to i32 since there is not an i8 bsr.
10851 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10854 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10855 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10856 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10858 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10861 DAG.getConstant(NumBits+NumBits-1, OpVT),
10862 DAG.getConstant(X86::COND_E, MVT::i8),
10865 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10867 // Finally xor with NumBits-1.
10868 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10871 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10875 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10876 EVT VT = Op.getValueType();
10878 unsigned NumBits = VT.getSizeInBits();
10879 DebugLoc dl = Op.getDebugLoc();
10881 Op = Op.getOperand(0);
10882 if (VT == MVT::i8) {
10883 // Zero extend to i32 since there is not an i8 bsr.
10885 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10888 // Issue a bsr (scan bits in reverse).
10889 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10890 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10892 // And xor with NumBits-1.
10893 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10896 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10900 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10901 EVT VT = Op.getValueType();
10902 unsigned NumBits = VT.getSizeInBits();
10903 DebugLoc dl = Op.getDebugLoc();
10904 Op = Op.getOperand(0);
10906 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10907 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10908 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10910 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10913 DAG.getConstant(NumBits, VT),
10914 DAG.getConstant(X86::COND_E, MVT::i8),
10917 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10920 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10921 // ones, and then concatenate the result back.
10922 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10923 EVT VT = Op.getValueType();
10925 assert(VT.is256BitVector() && VT.isInteger() &&
10926 "Unsupported value type for operation");
10928 unsigned NumElems = VT.getVectorNumElements();
10929 DebugLoc dl = Op.getDebugLoc();
10931 // Extract the LHS vectors
10932 SDValue LHS = Op.getOperand(0);
10933 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10934 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10936 // Extract the RHS vectors
10937 SDValue RHS = Op.getOperand(1);
10938 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10939 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10941 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10942 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10944 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10945 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10946 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10949 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10950 assert(Op.getValueType().is256BitVector() &&
10951 Op.getValueType().isInteger() &&
10952 "Only handle AVX 256-bit vector integer operation");
10953 return Lower256IntArith(Op, DAG);
10956 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10957 assert(Op.getValueType().is256BitVector() &&
10958 Op.getValueType().isInteger() &&
10959 "Only handle AVX 256-bit vector integer operation");
10960 return Lower256IntArith(Op, DAG);
10963 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10964 SelectionDAG &DAG) {
10965 EVT VT = Op.getValueType();
10967 // Decompose 256-bit ops into smaller 128-bit ops.
10968 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10969 return Lower256IntArith(Op, DAG);
10971 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10972 "Only know how to lower V2I64/V4I64 multiply");
10974 DebugLoc dl = Op.getDebugLoc();
10976 // Ahi = psrlqi(a, 32);
10977 // Bhi = psrlqi(b, 32);
10979 // AloBlo = pmuludq(a, b);
10980 // AloBhi = pmuludq(a, Bhi);
10981 // AhiBlo = pmuludq(Ahi, b);
10983 // AloBhi = psllqi(AloBhi, 32);
10984 // AhiBlo = psllqi(AhiBlo, 32);
10985 // return AloBlo + AloBhi + AhiBlo;
10987 SDValue A = Op.getOperand(0);
10988 SDValue B = Op.getOperand(1);
10990 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10992 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10993 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10995 // Bit cast to 32-bit vectors for MULUDQ
10996 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10997 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10998 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10999 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11000 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11002 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11003 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11004 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11006 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11007 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11009 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11010 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11013 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11015 EVT VT = Op.getValueType();
11016 DebugLoc dl = Op.getDebugLoc();
11017 SDValue R = Op.getOperand(0);
11018 SDValue Amt = Op.getOperand(1);
11019 LLVMContext *Context = DAG.getContext();
11021 if (!Subtarget->hasSSE2())
11024 // Optimize shl/srl/sra with constant shift amount.
11025 if (isSplatVector(Amt.getNode())) {
11026 SDValue SclrAmt = Amt->getOperand(0);
11027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11028 uint64_t ShiftAmt = C->getZExtValue();
11030 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11031 (Subtarget->hasAVX2() &&
11032 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11033 if (Op.getOpcode() == ISD::SHL)
11034 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11035 DAG.getConstant(ShiftAmt, MVT::i32));
11036 if (Op.getOpcode() == ISD::SRL)
11037 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11038 DAG.getConstant(ShiftAmt, MVT::i32));
11039 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11040 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11041 DAG.getConstant(ShiftAmt, MVT::i32));
11044 if (VT == MVT::v16i8) {
11045 if (Op.getOpcode() == ISD::SHL) {
11046 // Make a large shift.
11047 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11048 DAG.getConstant(ShiftAmt, MVT::i32));
11049 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11050 // Zero out the rightmost bits.
11051 SmallVector<SDValue, 16> V(16,
11052 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11054 return DAG.getNode(ISD::AND, dl, VT, SHL,
11055 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11057 if (Op.getOpcode() == ISD::SRL) {
11058 // Make a large shift.
11059 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11060 DAG.getConstant(ShiftAmt, MVT::i32));
11061 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11062 // Zero out the leftmost bits.
11063 SmallVector<SDValue, 16> V(16,
11064 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11066 return DAG.getNode(ISD::AND, dl, VT, SRL,
11067 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11069 if (Op.getOpcode() == ISD::SRA) {
11070 if (ShiftAmt == 7) {
11071 // R s>> 7 === R s< 0
11072 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11073 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11076 // R s>> a === ((R u>> a) ^ m) - m
11077 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11078 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11080 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11081 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11082 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11085 llvm_unreachable("Unknown shift opcode.");
11088 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11089 if (Op.getOpcode() == ISD::SHL) {
11090 // Make a large shift.
11091 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11092 DAG.getConstant(ShiftAmt, MVT::i32));
11093 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11094 // Zero out the rightmost bits.
11095 SmallVector<SDValue, 32> V(32,
11096 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11098 return DAG.getNode(ISD::AND, dl, VT, SHL,
11099 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11101 if (Op.getOpcode() == ISD::SRL) {
11102 // Make a large shift.
11103 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11104 DAG.getConstant(ShiftAmt, MVT::i32));
11105 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11106 // Zero out the leftmost bits.
11107 SmallVector<SDValue, 32> V(32,
11108 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11110 return DAG.getNode(ISD::AND, dl, VT, SRL,
11111 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11113 if (Op.getOpcode() == ISD::SRA) {
11114 if (ShiftAmt == 7) {
11115 // R s>> 7 === R s< 0
11116 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11117 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11120 // R s>> a === ((R u>> a) ^ m) - m
11121 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11122 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11124 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11125 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11126 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11129 llvm_unreachable("Unknown shift opcode.");
11134 // Lower SHL with variable shift amount.
11135 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11136 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11137 DAG.getConstant(23, MVT::i32));
11139 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11140 Constant *C = ConstantDataVector::get(*Context, CV);
11141 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11142 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11143 MachinePointerInfo::getConstantPool(),
11144 false, false, false, 16);
11146 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11147 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11148 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11149 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11151 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11152 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11155 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11156 DAG.getConstant(5, MVT::i32));
11157 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11159 // Turn 'a' into a mask suitable for VSELECT
11160 SDValue VSelM = DAG.getConstant(0x80, VT);
11161 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11162 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11164 SDValue CM1 = DAG.getConstant(0x0f, VT);
11165 SDValue CM2 = DAG.getConstant(0x3f, VT);
11167 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11168 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11169 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11170 DAG.getConstant(4, MVT::i32), DAG);
11171 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11172 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11175 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11176 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11177 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11179 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11180 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11181 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11182 DAG.getConstant(2, MVT::i32), DAG);
11183 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11184 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11187 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11188 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11189 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11191 // return VSELECT(r, r+r, a);
11192 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11193 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11197 // Decompose 256-bit shifts into smaller 128-bit shifts.
11198 if (VT.is256BitVector()) {
11199 unsigned NumElems = VT.getVectorNumElements();
11200 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11201 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11203 // Extract the two vectors
11204 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11205 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11207 // Recreate the shift amount vectors
11208 SDValue Amt1, Amt2;
11209 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11210 // Constant shift amount
11211 SmallVector<SDValue, 4> Amt1Csts;
11212 SmallVector<SDValue, 4> Amt2Csts;
11213 for (unsigned i = 0; i != NumElems/2; ++i)
11214 Amt1Csts.push_back(Amt->getOperand(i));
11215 for (unsigned i = NumElems/2; i != NumElems; ++i)
11216 Amt2Csts.push_back(Amt->getOperand(i));
11218 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11219 &Amt1Csts[0], NumElems/2);
11220 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11221 &Amt2Csts[0], NumElems/2);
11223 // Variable shift amount
11224 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11225 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11228 // Issue new vector shifts for the smaller types
11229 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11230 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11232 // Concatenate the result back
11233 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11239 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11240 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11241 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11242 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11243 // has only one use.
11244 SDNode *N = Op.getNode();
11245 SDValue LHS = N->getOperand(0);
11246 SDValue RHS = N->getOperand(1);
11247 unsigned BaseOp = 0;
11249 DebugLoc DL = Op.getDebugLoc();
11250 switch (Op.getOpcode()) {
11251 default: llvm_unreachable("Unknown ovf instruction!");
11253 // A subtract of one will be selected as a INC. Note that INC doesn't
11254 // set CF, so we can't do this for UADDO.
11255 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11257 BaseOp = X86ISD::INC;
11258 Cond = X86::COND_O;
11261 BaseOp = X86ISD::ADD;
11262 Cond = X86::COND_O;
11265 BaseOp = X86ISD::ADD;
11266 Cond = X86::COND_B;
11269 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11270 // set CF, so we can't do this for USUBO.
11271 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11273 BaseOp = X86ISD::DEC;
11274 Cond = X86::COND_O;
11277 BaseOp = X86ISD::SUB;
11278 Cond = X86::COND_O;
11281 BaseOp = X86ISD::SUB;
11282 Cond = X86::COND_B;
11285 BaseOp = X86ISD::SMUL;
11286 Cond = X86::COND_O;
11288 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11289 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11291 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11294 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11295 DAG.getConstant(X86::COND_O, MVT::i32),
11296 SDValue(Sum.getNode(), 2));
11298 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11302 // Also sets EFLAGS.
11303 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11304 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11307 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11308 DAG.getConstant(Cond, MVT::i32),
11309 SDValue(Sum.getNode(), 1));
11311 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11314 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11315 SelectionDAG &DAG) const {
11316 DebugLoc dl = Op.getDebugLoc();
11317 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11318 EVT VT = Op.getValueType();
11320 if (!Subtarget->hasSSE2() || !VT.isVector())
11323 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11324 ExtraVT.getScalarType().getSizeInBits();
11325 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11327 switch (VT.getSimpleVT().SimpleTy) {
11328 default: return SDValue();
11331 if (!Subtarget->hasAVX())
11333 if (!Subtarget->hasAVX2()) {
11334 // needs to be split
11335 unsigned NumElems = VT.getVectorNumElements();
11337 // Extract the LHS vectors
11338 SDValue LHS = Op.getOperand(0);
11339 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11340 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11342 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11343 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11345 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11346 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11347 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11349 SDValue Extra = DAG.getValueType(ExtraVT);
11351 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11352 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11354 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11359 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11360 Op.getOperand(0), ShAmt, DAG);
11361 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11367 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11368 SelectionDAG &DAG) {
11369 DebugLoc dl = Op.getDebugLoc();
11371 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11372 // There isn't any reason to disable it if the target processor supports it.
11373 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11374 SDValue Chain = Op.getOperand(0);
11375 SDValue Zero = DAG.getConstant(0, MVT::i32);
11377 DAG.getRegister(X86::ESP, MVT::i32), // Base
11378 DAG.getTargetConstant(1, MVT::i8), // Scale
11379 DAG.getRegister(0, MVT::i32), // Index
11380 DAG.getTargetConstant(0, MVT::i32), // Disp
11381 DAG.getRegister(0, MVT::i32), // Segment.
11386 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11387 array_lengthof(Ops));
11388 return SDValue(Res, 0);
11391 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11393 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11395 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11396 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11397 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11398 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11400 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11401 if (!Op1 && !Op2 && !Op3 && Op4)
11402 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11404 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11405 if (Op1 && !Op2 && !Op3 && !Op4)
11406 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11408 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11410 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11413 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11414 SelectionDAG &DAG) {
11415 DebugLoc dl = Op.getDebugLoc();
11416 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11417 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11418 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11419 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11421 // The only fence that needs an instruction is a sequentially-consistent
11422 // cross-thread fence.
11423 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11424 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11425 // no-sse2). There isn't any reason to disable it if the target processor
11427 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11428 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11430 SDValue Chain = Op.getOperand(0);
11431 SDValue Zero = DAG.getConstant(0, MVT::i32);
11433 DAG.getRegister(X86::ESP, MVT::i32), // Base
11434 DAG.getTargetConstant(1, MVT::i8), // Scale
11435 DAG.getRegister(0, MVT::i32), // Index
11436 DAG.getTargetConstant(0, MVT::i32), // Disp
11437 DAG.getRegister(0, MVT::i32), // Segment.
11442 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11443 array_lengthof(Ops));
11444 return SDValue(Res, 0);
11447 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11448 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11452 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11453 SelectionDAG &DAG) {
11454 EVT T = Op.getValueType();
11455 DebugLoc DL = Op.getDebugLoc();
11458 switch(T.getSimpleVT().SimpleTy) {
11459 default: llvm_unreachable("Invalid value type!");
11460 case MVT::i8: Reg = X86::AL; size = 1; break;
11461 case MVT::i16: Reg = X86::AX; size = 2; break;
11462 case MVT::i32: Reg = X86::EAX; size = 4; break;
11464 assert(Subtarget->is64Bit() && "Node not type legal!");
11465 Reg = X86::RAX; size = 8;
11468 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11469 Op.getOperand(2), SDValue());
11470 SDValue Ops[] = { cpIn.getValue(0),
11473 DAG.getTargetConstant(size, MVT::i8),
11474 cpIn.getValue(1) };
11475 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11476 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11477 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11480 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11484 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11485 SelectionDAG &DAG) {
11486 assert(Subtarget->is64Bit() && "Result not type legalized?");
11487 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11488 SDValue TheChain = Op.getOperand(0);
11489 DebugLoc dl = Op.getDebugLoc();
11490 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11491 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11492 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11494 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11495 DAG.getConstant(32, MVT::i8));
11497 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11500 return DAG.getMergeValues(Ops, 2, dl);
11503 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11504 EVT SrcVT = Op.getOperand(0).getValueType();
11505 EVT DstVT = Op.getValueType();
11506 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11507 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11508 assert((DstVT == MVT::i64 ||
11509 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11510 "Unexpected custom BITCAST");
11511 // i64 <=> MMX conversions are Legal.
11512 if (SrcVT==MVT::i64 && DstVT.isVector())
11514 if (DstVT==MVT::i64 && SrcVT.isVector())
11516 // MMX <=> MMX conversions are Legal.
11517 if (SrcVT.isVector() && DstVT.isVector())
11519 // All other conversions need to be expanded.
11523 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11524 SDNode *Node = Op.getNode();
11525 DebugLoc dl = Node->getDebugLoc();
11526 EVT T = Node->getValueType(0);
11527 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11528 DAG.getConstant(0, T), Node->getOperand(2));
11529 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11530 cast<AtomicSDNode>(Node)->getMemoryVT(),
11531 Node->getOperand(0),
11532 Node->getOperand(1), negOp,
11533 cast<AtomicSDNode>(Node)->getSrcValue(),
11534 cast<AtomicSDNode>(Node)->getAlignment(),
11535 cast<AtomicSDNode>(Node)->getOrdering(),
11536 cast<AtomicSDNode>(Node)->getSynchScope());
11539 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11540 SDNode *Node = Op.getNode();
11541 DebugLoc dl = Node->getDebugLoc();
11542 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11544 // Convert seq_cst store -> xchg
11545 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11546 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11547 // (The only way to get a 16-byte store is cmpxchg16b)
11548 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11549 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11550 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11551 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11552 cast<AtomicSDNode>(Node)->getMemoryVT(),
11553 Node->getOperand(0),
11554 Node->getOperand(1), Node->getOperand(2),
11555 cast<AtomicSDNode>(Node)->getMemOperand(),
11556 cast<AtomicSDNode>(Node)->getOrdering(),
11557 cast<AtomicSDNode>(Node)->getSynchScope());
11558 return Swap.getValue(1);
11560 // Other atomic stores have a simple pattern.
11564 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11565 EVT VT = Op.getNode()->getValueType(0);
11567 // Let legalize expand this if it isn't a legal type yet.
11568 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11571 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11574 bool ExtraOp = false;
11575 switch (Op.getOpcode()) {
11576 default: llvm_unreachable("Invalid code");
11577 case ISD::ADDC: Opc = X86ISD::ADD; break;
11578 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11579 case ISD::SUBC: Opc = X86ISD::SUB; break;
11580 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11584 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11586 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11587 Op.getOperand(1), Op.getOperand(2));
11590 /// LowerOperation - Provide custom lowering hooks for some operations.
11592 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11593 switch (Op.getOpcode()) {
11594 default: llvm_unreachable("Should not custom lower this!");
11595 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11596 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11597 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11598 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11599 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11600 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11601 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11602 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11603 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11604 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11605 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11606 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11607 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11608 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11609 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11610 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11611 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11612 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11613 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11614 case ISD::SHL_PARTS:
11615 case ISD::SRA_PARTS:
11616 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11617 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11618 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11619 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11620 case ISD::ZERO_EXTEND: return lowerZERO_EXTEND(Op, DAG);
11621 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11622 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11623 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11624 case ISD::FABS: return LowerFABS(Op, DAG);
11625 case ISD::FNEG: return LowerFNEG(Op, DAG);
11626 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11627 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11628 case ISD::SETCC: return LowerSETCC(Op, DAG);
11629 case ISD::SELECT: return LowerSELECT(Op, DAG);
11630 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11631 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11632 case ISD::VASTART: return LowerVASTART(Op, DAG);
11633 case ISD::VAARG: return LowerVAARG(Op, DAG);
11634 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11635 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11636 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11637 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11638 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11639 case ISD::FRAME_TO_ARGS_OFFSET:
11640 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11641 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11642 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11643 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11644 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11645 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11646 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11647 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11648 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11649 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11650 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11651 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11654 case ISD::SHL: return LowerShift(Op, DAG);
11660 case ISD::UMULO: return LowerXALUO(Op, DAG);
11661 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11662 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11666 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11667 case ISD::ADD: return LowerADD(Op, DAG);
11668 case ISD::SUB: return LowerSUB(Op, DAG);
11672 static void ReplaceATOMIC_LOAD(SDNode *Node,
11673 SmallVectorImpl<SDValue> &Results,
11674 SelectionDAG &DAG) {
11675 DebugLoc dl = Node->getDebugLoc();
11676 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11678 // Convert wide load -> cmpxchg8b/cmpxchg16b
11679 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11680 // (The only way to get a 16-byte load is cmpxchg16b)
11681 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11682 SDValue Zero = DAG.getConstant(0, VT);
11683 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11684 Node->getOperand(0),
11685 Node->getOperand(1), Zero, Zero,
11686 cast<AtomicSDNode>(Node)->getMemOperand(),
11687 cast<AtomicSDNode>(Node)->getOrdering(),
11688 cast<AtomicSDNode>(Node)->getSynchScope());
11689 Results.push_back(Swap.getValue(0));
11690 Results.push_back(Swap.getValue(1));
11694 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11695 SelectionDAG &DAG, unsigned NewOp) {
11696 DebugLoc dl = Node->getDebugLoc();
11697 assert (Node->getValueType(0) == MVT::i64 &&
11698 "Only know how to expand i64 atomics");
11700 SDValue Chain = Node->getOperand(0);
11701 SDValue In1 = Node->getOperand(1);
11702 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11703 Node->getOperand(2), DAG.getIntPtrConstant(0));
11704 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11705 Node->getOperand(2), DAG.getIntPtrConstant(1));
11706 SDValue Ops[] = { Chain, In1, In2L, In2H };
11707 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11709 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11710 cast<MemSDNode>(Node)->getMemOperand());
11711 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11712 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11713 Results.push_back(Result.getValue(2));
11716 /// ReplaceNodeResults - Replace a node with an illegal result type
11717 /// with a new node built out of custom code.
11718 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11719 SmallVectorImpl<SDValue>&Results,
11720 SelectionDAG &DAG) const {
11721 DebugLoc dl = N->getDebugLoc();
11722 switch (N->getOpcode()) {
11724 llvm_unreachable("Do not know how to custom type legalize this operation!");
11725 case ISD::SIGN_EXTEND_INREG:
11730 // We don't want to expand or promote these.
11732 case ISD::FP_TO_SINT:
11733 case ISD::FP_TO_UINT: {
11734 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11736 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11739 std::pair<SDValue,SDValue> Vals =
11740 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11741 SDValue FIST = Vals.first, StackSlot = Vals.second;
11742 if (FIST.getNode() != 0) {
11743 EVT VT = N->getValueType(0);
11744 // Return a load from the stack slot.
11745 if (StackSlot.getNode() != 0)
11746 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11747 MachinePointerInfo(),
11748 false, false, false, 0));
11750 Results.push_back(FIST);
11754 case ISD::FP_ROUND: {
11755 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11756 Results.push_back(V);
11759 case ISD::READCYCLECOUNTER: {
11760 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11761 SDValue TheChain = N->getOperand(0);
11762 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11763 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11765 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11767 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11768 SDValue Ops[] = { eax, edx };
11769 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11770 Results.push_back(edx.getValue(1));
11773 case ISD::ATOMIC_CMP_SWAP: {
11774 EVT T = N->getValueType(0);
11775 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11776 bool Regs64bit = T == MVT::i128;
11777 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11778 SDValue cpInL, cpInH;
11779 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11780 DAG.getConstant(0, HalfT));
11781 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11782 DAG.getConstant(1, HalfT));
11783 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11784 Regs64bit ? X86::RAX : X86::EAX,
11786 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11787 Regs64bit ? X86::RDX : X86::EDX,
11788 cpInH, cpInL.getValue(1));
11789 SDValue swapInL, swapInH;
11790 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11791 DAG.getConstant(0, HalfT));
11792 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11793 DAG.getConstant(1, HalfT));
11794 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11795 Regs64bit ? X86::RBX : X86::EBX,
11796 swapInL, cpInH.getValue(1));
11797 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11798 Regs64bit ? X86::RCX : X86::ECX,
11799 swapInH, swapInL.getValue(1));
11800 SDValue Ops[] = { swapInH.getValue(0),
11802 swapInH.getValue(1) };
11803 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11804 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11805 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11806 X86ISD::LCMPXCHG8_DAG;
11807 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11809 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11810 Regs64bit ? X86::RAX : X86::EAX,
11811 HalfT, Result.getValue(1));
11812 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11813 Regs64bit ? X86::RDX : X86::EDX,
11814 HalfT, cpOutL.getValue(2));
11815 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11816 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11817 Results.push_back(cpOutH.getValue(1));
11820 case ISD::ATOMIC_LOAD_ADD:
11821 case ISD::ATOMIC_LOAD_AND:
11822 case ISD::ATOMIC_LOAD_NAND:
11823 case ISD::ATOMIC_LOAD_OR:
11824 case ISD::ATOMIC_LOAD_SUB:
11825 case ISD::ATOMIC_LOAD_XOR:
11826 case ISD::ATOMIC_LOAD_MAX:
11827 case ISD::ATOMIC_LOAD_MIN:
11828 case ISD::ATOMIC_LOAD_UMAX:
11829 case ISD::ATOMIC_LOAD_UMIN:
11830 case ISD::ATOMIC_SWAP: {
11832 switch (N->getOpcode()) {
11833 default: llvm_unreachable("Unexpected opcode");
11834 case ISD::ATOMIC_LOAD_ADD:
11835 Opc = X86ISD::ATOMADD64_DAG;
11837 case ISD::ATOMIC_LOAD_AND:
11838 Opc = X86ISD::ATOMAND64_DAG;
11840 case ISD::ATOMIC_LOAD_NAND:
11841 Opc = X86ISD::ATOMNAND64_DAG;
11843 case ISD::ATOMIC_LOAD_OR:
11844 Opc = X86ISD::ATOMOR64_DAG;
11846 case ISD::ATOMIC_LOAD_SUB:
11847 Opc = X86ISD::ATOMSUB64_DAG;
11849 case ISD::ATOMIC_LOAD_XOR:
11850 Opc = X86ISD::ATOMXOR64_DAG;
11852 case ISD::ATOMIC_LOAD_MAX:
11853 Opc = X86ISD::ATOMMAX64_DAG;
11855 case ISD::ATOMIC_LOAD_MIN:
11856 Opc = X86ISD::ATOMMIN64_DAG;
11858 case ISD::ATOMIC_LOAD_UMAX:
11859 Opc = X86ISD::ATOMUMAX64_DAG;
11861 case ISD::ATOMIC_LOAD_UMIN:
11862 Opc = X86ISD::ATOMUMIN64_DAG;
11864 case ISD::ATOMIC_SWAP:
11865 Opc = X86ISD::ATOMSWAP64_DAG;
11868 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11871 case ISD::ATOMIC_LOAD:
11872 ReplaceATOMIC_LOAD(N, Results, DAG);
11876 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11878 default: return NULL;
11879 case X86ISD::BSF: return "X86ISD::BSF";
11880 case X86ISD::BSR: return "X86ISD::BSR";
11881 case X86ISD::SHLD: return "X86ISD::SHLD";
11882 case X86ISD::SHRD: return "X86ISD::SHRD";
11883 case X86ISD::FAND: return "X86ISD::FAND";
11884 case X86ISD::FOR: return "X86ISD::FOR";
11885 case X86ISD::FXOR: return "X86ISD::FXOR";
11886 case X86ISD::FSRL: return "X86ISD::FSRL";
11887 case X86ISD::FILD: return "X86ISD::FILD";
11888 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11889 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11890 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11891 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11892 case X86ISD::FLD: return "X86ISD::FLD";
11893 case X86ISD::FST: return "X86ISD::FST";
11894 case X86ISD::CALL: return "X86ISD::CALL";
11895 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11896 case X86ISD::BT: return "X86ISD::BT";
11897 case X86ISD::CMP: return "X86ISD::CMP";
11898 case X86ISD::COMI: return "X86ISD::COMI";
11899 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11900 case X86ISD::SETCC: return "X86ISD::SETCC";
11901 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11902 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11903 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11904 case X86ISD::CMOV: return "X86ISD::CMOV";
11905 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11906 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11907 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11908 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11909 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11910 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11911 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11912 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11913 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11914 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11915 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11916 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11917 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11918 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11919 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11920 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11921 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11922 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11923 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11924 case X86ISD::HADD: return "X86ISD::HADD";
11925 case X86ISD::HSUB: return "X86ISD::HSUB";
11926 case X86ISD::FHADD: return "X86ISD::FHADD";
11927 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11928 case X86ISD::FMAX: return "X86ISD::FMAX";
11929 case X86ISD::FMIN: return "X86ISD::FMIN";
11930 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11931 case X86ISD::FMINC: return "X86ISD::FMINC";
11932 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11933 case X86ISD::FRCP: return "X86ISD::FRCP";
11934 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11935 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11936 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11937 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11938 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11939 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11940 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11941 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11942 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11943 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11944 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11945 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11946 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11947 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11948 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11949 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11950 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11951 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11952 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11953 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11954 case X86ISD::VZEXT: return "X86ISD::VZEXT";
11955 case X86ISD::VSEXT: return "X86ISD::VSEXT";
11956 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11957 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11958 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11959 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11960 case X86ISD::VSHL: return "X86ISD::VSHL";
11961 case X86ISD::VSRL: return "X86ISD::VSRL";
11962 case X86ISD::VSRA: return "X86ISD::VSRA";
11963 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11964 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11965 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11966 case X86ISD::CMPP: return "X86ISD::CMPP";
11967 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11968 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11969 case X86ISD::ADD: return "X86ISD::ADD";
11970 case X86ISD::SUB: return "X86ISD::SUB";
11971 case X86ISD::ADC: return "X86ISD::ADC";
11972 case X86ISD::SBB: return "X86ISD::SBB";
11973 case X86ISD::SMUL: return "X86ISD::SMUL";
11974 case X86ISD::UMUL: return "X86ISD::UMUL";
11975 case X86ISD::INC: return "X86ISD::INC";
11976 case X86ISD::DEC: return "X86ISD::DEC";
11977 case X86ISD::OR: return "X86ISD::OR";
11978 case X86ISD::XOR: return "X86ISD::XOR";
11979 case X86ISD::AND: return "X86ISD::AND";
11980 case X86ISD::ANDN: return "X86ISD::ANDN";
11981 case X86ISD::BLSI: return "X86ISD::BLSI";
11982 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11983 case X86ISD::BLSR: return "X86ISD::BLSR";
11984 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11985 case X86ISD::PTEST: return "X86ISD::PTEST";
11986 case X86ISD::TESTP: return "X86ISD::TESTP";
11987 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11988 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11989 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11990 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11991 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11992 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11993 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11994 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11995 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11996 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11997 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11998 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11999 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12000 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12001 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12002 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12003 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12004 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12005 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12006 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12007 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12008 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12009 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12010 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12011 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12012 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12013 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12014 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12015 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12016 case X86ISD::SAHF: return "X86ISD::SAHF";
12017 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12018 case X86ISD::FMADD: return "X86ISD::FMADD";
12019 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12020 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12021 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12022 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12023 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12027 // isLegalAddressingMode - Return true if the addressing mode represented
12028 // by AM is legal for this target, for a load/store of the specified type.
12029 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12031 // X86 supports extremely general addressing modes.
12032 CodeModel::Model M = getTargetMachine().getCodeModel();
12033 Reloc::Model R = getTargetMachine().getRelocationModel();
12035 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12036 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12041 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12043 // If a reference to this global requires an extra load, we can't fold it.
12044 if (isGlobalStubReference(GVFlags))
12047 // If BaseGV requires a register for the PIC base, we cannot also have a
12048 // BaseReg specified.
12049 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12052 // If lower 4G is not available, then we must use rip-relative addressing.
12053 if ((M != CodeModel::Small || R != Reloc::Static) &&
12054 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12058 switch (AM.Scale) {
12064 // These scales always work.
12069 // These scales are formed with basereg+scalereg. Only accept if there is
12074 default: // Other stuff never works.
12082 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12083 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12085 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12086 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12087 if (NumBits1 <= NumBits2)
12092 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12093 return Imm == (int32_t)Imm;
12096 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12097 // Can also use sub to handle negated immediates.
12098 return Imm == (int32_t)Imm;
12101 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12102 if (!VT1.isInteger() || !VT2.isInteger())
12104 unsigned NumBits1 = VT1.getSizeInBits();
12105 unsigned NumBits2 = VT2.getSizeInBits();
12106 if (NumBits1 <= NumBits2)
12111 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12112 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12113 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12116 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12117 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12118 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12121 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12122 // i16 instructions are longer (0x66 prefix) and potentially slower.
12123 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12126 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12127 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12128 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12129 /// are assumed to be legal.
12131 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12133 // Very little shuffling can be done for 64-bit vectors right now.
12134 if (VT.getSizeInBits() == 64)
12137 // FIXME: pshufb, blends, shifts.
12138 return (VT.getVectorNumElements() == 2 ||
12139 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12140 isMOVLMask(M, VT) ||
12141 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12142 isPSHUFDMask(M, VT) ||
12143 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12144 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12145 isPALIGNRMask(M, VT, Subtarget) ||
12146 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12147 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12148 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12149 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12153 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12155 unsigned NumElts = VT.getVectorNumElements();
12156 // FIXME: This collection of masks seems suspect.
12159 if (NumElts == 4 && VT.is128BitVector()) {
12160 return (isMOVLMask(Mask, VT) ||
12161 isCommutedMOVLMask(Mask, VT, true) ||
12162 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12163 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12168 //===----------------------------------------------------------------------===//
12169 // X86 Scheduler Hooks
12170 //===----------------------------------------------------------------------===//
12172 // private utility function
12174 // Get CMPXCHG opcode for the specified data type.
12175 static unsigned getCmpXChgOpcode(EVT VT) {
12176 switch (VT.getSimpleVT().SimpleTy) {
12177 case MVT::i8: return X86::LCMPXCHG8;
12178 case MVT::i16: return X86::LCMPXCHG16;
12179 case MVT::i32: return X86::LCMPXCHG32;
12180 case MVT::i64: return X86::LCMPXCHG64;
12184 llvm_unreachable("Invalid operand size!");
12187 // Get LOAD opcode for the specified data type.
12188 static unsigned getLoadOpcode(EVT VT) {
12189 switch (VT.getSimpleVT().SimpleTy) {
12190 case MVT::i8: return X86::MOV8rm;
12191 case MVT::i16: return X86::MOV16rm;
12192 case MVT::i32: return X86::MOV32rm;
12193 case MVT::i64: return X86::MOV64rm;
12197 llvm_unreachable("Invalid operand size!");
12200 // Get opcode of the non-atomic one from the specified atomic instruction.
12201 static unsigned getNonAtomicOpcode(unsigned Opc) {
12203 case X86::ATOMAND8: return X86::AND8rr;
12204 case X86::ATOMAND16: return X86::AND16rr;
12205 case X86::ATOMAND32: return X86::AND32rr;
12206 case X86::ATOMAND64: return X86::AND64rr;
12207 case X86::ATOMOR8: return X86::OR8rr;
12208 case X86::ATOMOR16: return X86::OR16rr;
12209 case X86::ATOMOR32: return X86::OR32rr;
12210 case X86::ATOMOR64: return X86::OR64rr;
12211 case X86::ATOMXOR8: return X86::XOR8rr;
12212 case X86::ATOMXOR16: return X86::XOR16rr;
12213 case X86::ATOMXOR32: return X86::XOR32rr;
12214 case X86::ATOMXOR64: return X86::XOR64rr;
12216 llvm_unreachable("Unhandled atomic-load-op opcode!");
12219 // Get opcode of the non-atomic one from the specified atomic instruction with
12221 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12222 unsigned &ExtraOpc) {
12224 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12225 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12226 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12227 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12228 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12229 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12230 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12231 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12232 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12233 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12234 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12235 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12236 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12237 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12238 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12239 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12240 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12241 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12242 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12243 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12245 llvm_unreachable("Unhandled atomic-load-op opcode!");
12248 // Get opcode of the non-atomic one from the specified atomic instruction for
12249 // 64-bit data type on 32-bit target.
12250 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12252 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12253 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12254 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12255 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12256 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12257 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12258 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12259 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12260 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12261 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12263 llvm_unreachable("Unhandled atomic-load-op opcode!");
12266 // Get opcode of the non-atomic one from the specified atomic instruction for
12267 // 64-bit data type on 32-bit target with extra opcode.
12268 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12270 unsigned &ExtraOpc) {
12272 case X86::ATOMNAND6432:
12273 ExtraOpc = X86::NOT32r;
12274 HiOpc = X86::AND32rr;
12275 return X86::AND32rr;
12277 llvm_unreachable("Unhandled atomic-load-op opcode!");
12280 // Get pseudo CMOV opcode from the specified data type.
12281 static unsigned getPseudoCMOVOpc(EVT VT) {
12282 switch (VT.getSimpleVT().SimpleTy) {
12283 case MVT::i8: return X86::CMOV_GR8;
12284 case MVT::i16: return X86::CMOV_GR16;
12285 case MVT::i32: return X86::CMOV_GR32;
12289 llvm_unreachable("Unknown CMOV opcode!");
12292 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12293 // They will be translated into a spin-loop or compare-exchange loop from
12296 // dst = atomic-fetch-op MI.addr, MI.val
12302 // EAX = LOAD MI.addr
12304 // t1 = OP MI.val, EAX
12305 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12310 MachineBasicBlock *
12311 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12312 MachineBasicBlock *MBB) const {
12313 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12314 DebugLoc DL = MI->getDebugLoc();
12316 MachineFunction *MF = MBB->getParent();
12317 MachineRegisterInfo &MRI = MF->getRegInfo();
12319 const BasicBlock *BB = MBB->getBasicBlock();
12320 MachineFunction::iterator I = MBB;
12323 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12324 "Unexpected number of operands");
12326 assert(MI->hasOneMemOperand() &&
12327 "Expected atomic-load-op to have one memoperand");
12329 // Memory Reference
12330 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12331 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12333 unsigned DstReg, SrcReg;
12334 unsigned MemOpndSlot;
12336 unsigned CurOp = 0;
12338 DstReg = MI->getOperand(CurOp++).getReg();
12339 MemOpndSlot = CurOp;
12340 CurOp += X86::AddrNumOperands;
12341 SrcReg = MI->getOperand(CurOp++).getReg();
12343 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12344 MVT::SimpleValueType VT = *RC->vt_begin();
12345 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12347 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12348 unsigned LOADOpc = getLoadOpcode(VT);
12350 // For the atomic load-arith operator, we generate
12353 // EAX = LOAD [MI.addr]
12355 // t1 = OP MI.val, EAX
12356 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12360 MachineBasicBlock *thisMBB = MBB;
12361 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12362 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12363 MF->insert(I, mainMBB);
12364 MF->insert(I, sinkMBB);
12366 MachineInstrBuilder MIB;
12368 // Transfer the remainder of BB and its successor edges to sinkMBB.
12369 sinkMBB->splice(sinkMBB->begin(), MBB,
12370 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12371 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12374 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12375 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12376 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12377 MIB.setMemRefs(MMOBegin, MMOEnd);
12379 thisMBB->addSuccessor(mainMBB);
12382 MachineBasicBlock *origMainMBB = mainMBB;
12383 mainMBB->addLiveIn(AccPhyReg);
12385 // Copy AccPhyReg as it is used more than once.
12386 unsigned AccReg = MRI.createVirtualRegister(RC);
12387 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12388 .addReg(AccPhyReg);
12390 unsigned t1 = MRI.createVirtualRegister(RC);
12391 unsigned Opc = MI->getOpcode();
12394 llvm_unreachable("Unhandled atomic-load-op opcode!");
12395 case X86::ATOMAND8:
12396 case X86::ATOMAND16:
12397 case X86::ATOMAND32:
12398 case X86::ATOMAND64:
12400 case X86::ATOMOR16:
12401 case X86::ATOMOR32:
12402 case X86::ATOMOR64:
12403 case X86::ATOMXOR8:
12404 case X86::ATOMXOR16:
12405 case X86::ATOMXOR32:
12406 case X86::ATOMXOR64: {
12407 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12408 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12412 case X86::ATOMNAND8:
12413 case X86::ATOMNAND16:
12414 case X86::ATOMNAND32:
12415 case X86::ATOMNAND64: {
12416 unsigned t2 = MRI.createVirtualRegister(RC);
12418 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12419 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12421 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12424 case X86::ATOMMAX8:
12425 case X86::ATOMMAX16:
12426 case X86::ATOMMAX32:
12427 case X86::ATOMMAX64:
12428 case X86::ATOMMIN8:
12429 case X86::ATOMMIN16:
12430 case X86::ATOMMIN32:
12431 case X86::ATOMMIN64:
12432 case X86::ATOMUMAX8:
12433 case X86::ATOMUMAX16:
12434 case X86::ATOMUMAX32:
12435 case X86::ATOMUMAX64:
12436 case X86::ATOMUMIN8:
12437 case X86::ATOMUMIN16:
12438 case X86::ATOMUMIN32:
12439 case X86::ATOMUMIN64: {
12441 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12443 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12447 if (Subtarget->hasCMov()) {
12448 if (VT != MVT::i8) {
12450 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12454 // Promote i8 to i32 to use CMOV32
12455 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12456 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12457 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12458 unsigned t2 = MRI.createVirtualRegister(RC32);
12460 unsigned Undef = MRI.createVirtualRegister(RC32);
12461 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12463 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12466 .addImm(X86::sub_8bit);
12467 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12470 .addImm(X86::sub_8bit);
12472 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12476 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12477 .addReg(t2, 0, X86::sub_8bit);
12480 // Use pseudo select and lower them.
12481 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12482 "Invalid atomic-load-op transformation!");
12483 unsigned SelOpc = getPseudoCMOVOpc(VT);
12484 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12485 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12486 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12487 .addReg(SrcReg).addReg(AccReg)
12489 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12495 // Copy AccPhyReg back from virtual register.
12496 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12499 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12500 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12501 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12503 MIB.setMemRefs(MMOBegin, MMOEnd);
12505 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12507 mainMBB->addSuccessor(origMainMBB);
12508 mainMBB->addSuccessor(sinkMBB);
12511 sinkMBB->addLiveIn(AccPhyReg);
12513 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12514 TII->get(TargetOpcode::COPY), DstReg)
12515 .addReg(AccPhyReg);
12517 MI->eraseFromParent();
12521 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12522 // instructions. They will be translated into a spin-loop or compare-exchange
12526 // dst = atomic-fetch-op MI.addr, MI.val
12532 // EAX = LOAD [MI.addr + 0]
12533 // EDX = LOAD [MI.addr + 4]
12535 // EBX = OP MI.val.lo, EAX
12536 // ECX = OP MI.val.hi, EDX
12537 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12542 MachineBasicBlock *
12543 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12544 MachineBasicBlock *MBB) const {
12545 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12546 DebugLoc DL = MI->getDebugLoc();
12548 MachineFunction *MF = MBB->getParent();
12549 MachineRegisterInfo &MRI = MF->getRegInfo();
12551 const BasicBlock *BB = MBB->getBasicBlock();
12552 MachineFunction::iterator I = MBB;
12555 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12556 "Unexpected number of operands");
12558 assert(MI->hasOneMemOperand() &&
12559 "Expected atomic-load-op32 to have one memoperand");
12561 // Memory Reference
12562 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12563 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12565 unsigned DstLoReg, DstHiReg;
12566 unsigned SrcLoReg, SrcHiReg;
12567 unsigned MemOpndSlot;
12569 unsigned CurOp = 0;
12571 DstLoReg = MI->getOperand(CurOp++).getReg();
12572 DstHiReg = MI->getOperand(CurOp++).getReg();
12573 MemOpndSlot = CurOp;
12574 CurOp += X86::AddrNumOperands;
12575 SrcLoReg = MI->getOperand(CurOp++).getReg();
12576 SrcHiReg = MI->getOperand(CurOp++).getReg();
12578 const TargetRegisterClass *RC = &X86::GR32RegClass;
12579 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12581 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12582 unsigned LOADOpc = X86::MOV32rm;
12584 // For the atomic load-arith operator, we generate
12587 // EAX = LOAD [MI.addr + 0]
12588 // EDX = LOAD [MI.addr + 4]
12590 // EBX = OP MI.vallo, EAX
12591 // ECX = OP MI.valhi, EDX
12592 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12596 MachineBasicBlock *thisMBB = MBB;
12597 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12598 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12599 MF->insert(I, mainMBB);
12600 MF->insert(I, sinkMBB);
12602 MachineInstrBuilder MIB;
12604 // Transfer the remainder of BB and its successor edges to sinkMBB.
12605 sinkMBB->splice(sinkMBB->begin(), MBB,
12606 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12607 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12611 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12612 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12613 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12614 MIB.setMemRefs(MMOBegin, MMOEnd);
12616 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12617 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12618 if (i == X86::AddrDisp)
12619 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12621 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12623 MIB.setMemRefs(MMOBegin, MMOEnd);
12625 thisMBB->addSuccessor(mainMBB);
12628 MachineBasicBlock *origMainMBB = mainMBB;
12629 mainMBB->addLiveIn(X86::EAX);
12630 mainMBB->addLiveIn(X86::EDX);
12632 // Copy EDX:EAX as they are used more than once.
12633 unsigned LoReg = MRI.createVirtualRegister(RC);
12634 unsigned HiReg = MRI.createVirtualRegister(RC);
12635 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12636 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12638 unsigned t1L = MRI.createVirtualRegister(RC);
12639 unsigned t1H = MRI.createVirtualRegister(RC);
12641 unsigned Opc = MI->getOpcode();
12644 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12645 case X86::ATOMAND6432:
12646 case X86::ATOMOR6432:
12647 case X86::ATOMXOR6432:
12648 case X86::ATOMADD6432:
12649 case X86::ATOMSUB6432: {
12651 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12652 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12653 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12656 case X86::ATOMNAND6432: {
12657 unsigned HiOpc, NOTOpc;
12658 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12659 unsigned t2L = MRI.createVirtualRegister(RC);
12660 unsigned t2H = MRI.createVirtualRegister(RC);
12661 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12662 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12663 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12664 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12667 case X86::ATOMMAX6432:
12668 case X86::ATOMMIN6432:
12669 case X86::ATOMUMAX6432:
12670 case X86::ATOMUMIN6432: {
12672 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12673 unsigned cL = MRI.createVirtualRegister(RC8);
12674 unsigned cH = MRI.createVirtualRegister(RC8);
12675 unsigned cL32 = MRI.createVirtualRegister(RC);
12676 unsigned cH32 = MRI.createVirtualRegister(RC);
12677 unsigned cc = MRI.createVirtualRegister(RC);
12678 // cl := cmp src_lo, lo
12679 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12680 .addReg(SrcLoReg).addReg(LoReg);
12681 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12682 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12683 // ch := cmp src_hi, hi
12684 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12685 .addReg(SrcHiReg).addReg(HiReg);
12686 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12687 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12688 // cc := if (src_hi == hi) ? cl : ch;
12689 if (Subtarget->hasCMov()) {
12690 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12691 .addReg(cH32).addReg(cL32);
12693 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12694 .addReg(cH32).addReg(cL32)
12695 .addImm(X86::COND_E);
12696 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12698 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12699 if (Subtarget->hasCMov()) {
12700 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12701 .addReg(SrcLoReg).addReg(LoReg);
12702 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12703 .addReg(SrcHiReg).addReg(HiReg);
12705 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12706 .addReg(SrcLoReg).addReg(LoReg)
12707 .addImm(X86::COND_NE);
12708 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12709 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12710 .addReg(SrcHiReg).addReg(HiReg)
12711 .addImm(X86::COND_NE);
12712 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12716 case X86::ATOMSWAP6432: {
12718 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12719 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12720 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12725 // Copy EDX:EAX back from HiReg:LoReg
12726 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12727 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12728 // Copy ECX:EBX from t1H:t1L
12729 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12730 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12732 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12733 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12734 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12735 MIB.setMemRefs(MMOBegin, MMOEnd);
12737 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12739 mainMBB->addSuccessor(origMainMBB);
12740 mainMBB->addSuccessor(sinkMBB);
12743 sinkMBB->addLiveIn(X86::EAX);
12744 sinkMBB->addLiveIn(X86::EDX);
12746 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12747 TII->get(TargetOpcode::COPY), DstLoReg)
12749 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12750 TII->get(TargetOpcode::COPY), DstHiReg)
12753 MI->eraseFromParent();
12757 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12758 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12759 // in the .td file.
12760 MachineBasicBlock *
12761 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12762 unsigned numArgs, bool memArg) const {
12763 assert(Subtarget->hasSSE42() &&
12764 "Target must have SSE4.2 or AVX features enabled");
12766 DebugLoc dl = MI->getDebugLoc();
12767 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12769 if (!Subtarget->hasAVX()) {
12771 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12773 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12776 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12778 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12781 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12782 for (unsigned i = 0; i < numArgs; ++i) {
12783 MachineOperand &Op = MI->getOperand(i+1);
12784 if (!(Op.isReg() && Op.isImplicit()))
12785 MIB.addOperand(Op);
12787 BuildMI(*BB, MI, dl,
12788 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12789 .addReg(X86::XMM0);
12791 MI->eraseFromParent();
12795 MachineBasicBlock *
12796 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12797 DebugLoc dl = MI->getDebugLoc();
12798 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12800 // Address into RAX/EAX, other two args into ECX, EDX.
12801 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12802 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12803 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12804 for (int i = 0; i < X86::AddrNumOperands; ++i)
12805 MIB.addOperand(MI->getOperand(i));
12807 unsigned ValOps = X86::AddrNumOperands;
12808 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12809 .addReg(MI->getOperand(ValOps).getReg());
12810 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12811 .addReg(MI->getOperand(ValOps+1).getReg());
12813 // The instruction doesn't actually take any operands though.
12814 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12816 MI->eraseFromParent(); // The pseudo is gone now.
12820 MachineBasicBlock *
12821 X86TargetLowering::EmitVAARG64WithCustomInserter(
12823 MachineBasicBlock *MBB) const {
12824 // Emit va_arg instruction on X86-64.
12826 // Operands to this pseudo-instruction:
12827 // 0 ) Output : destination address (reg)
12828 // 1-5) Input : va_list address (addr, i64mem)
12829 // 6 ) ArgSize : Size (in bytes) of vararg type
12830 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12831 // 8 ) Align : Alignment of type
12832 // 9 ) EFLAGS (implicit-def)
12834 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12835 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12837 unsigned DestReg = MI->getOperand(0).getReg();
12838 MachineOperand &Base = MI->getOperand(1);
12839 MachineOperand &Scale = MI->getOperand(2);
12840 MachineOperand &Index = MI->getOperand(3);
12841 MachineOperand &Disp = MI->getOperand(4);
12842 MachineOperand &Segment = MI->getOperand(5);
12843 unsigned ArgSize = MI->getOperand(6).getImm();
12844 unsigned ArgMode = MI->getOperand(7).getImm();
12845 unsigned Align = MI->getOperand(8).getImm();
12847 // Memory Reference
12848 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12849 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12850 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12852 // Machine Information
12853 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12854 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12855 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12856 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12857 DebugLoc DL = MI->getDebugLoc();
12859 // struct va_list {
12862 // i64 overflow_area (address)
12863 // i64 reg_save_area (address)
12865 // sizeof(va_list) = 24
12866 // alignment(va_list) = 8
12868 unsigned TotalNumIntRegs = 6;
12869 unsigned TotalNumXMMRegs = 8;
12870 bool UseGPOffset = (ArgMode == 1);
12871 bool UseFPOffset = (ArgMode == 2);
12872 unsigned MaxOffset = TotalNumIntRegs * 8 +
12873 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12875 /* Align ArgSize to a multiple of 8 */
12876 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12877 bool NeedsAlign = (Align > 8);
12879 MachineBasicBlock *thisMBB = MBB;
12880 MachineBasicBlock *overflowMBB;
12881 MachineBasicBlock *offsetMBB;
12882 MachineBasicBlock *endMBB;
12884 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12885 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12886 unsigned OffsetReg = 0;
12888 if (!UseGPOffset && !UseFPOffset) {
12889 // If we only pull from the overflow region, we don't create a branch.
12890 // We don't need to alter control flow.
12891 OffsetDestReg = 0; // unused
12892 OverflowDestReg = DestReg;
12895 overflowMBB = thisMBB;
12898 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12899 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12900 // If not, pull from overflow_area. (branch to overflowMBB)
12905 // offsetMBB overflowMBB
12910 // Registers for the PHI in endMBB
12911 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12912 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12914 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12915 MachineFunction *MF = MBB->getParent();
12916 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12917 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12918 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12920 MachineFunction::iterator MBBIter = MBB;
12923 // Insert the new basic blocks
12924 MF->insert(MBBIter, offsetMBB);
12925 MF->insert(MBBIter, overflowMBB);
12926 MF->insert(MBBIter, endMBB);
12928 // Transfer the remainder of MBB and its successor edges to endMBB.
12929 endMBB->splice(endMBB->begin(), thisMBB,
12930 llvm::next(MachineBasicBlock::iterator(MI)),
12932 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12934 // Make offsetMBB and overflowMBB successors of thisMBB
12935 thisMBB->addSuccessor(offsetMBB);
12936 thisMBB->addSuccessor(overflowMBB);
12938 // endMBB is a successor of both offsetMBB and overflowMBB
12939 offsetMBB->addSuccessor(endMBB);
12940 overflowMBB->addSuccessor(endMBB);
12942 // Load the offset value into a register
12943 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12944 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12948 .addDisp(Disp, UseFPOffset ? 4 : 0)
12949 .addOperand(Segment)
12950 .setMemRefs(MMOBegin, MMOEnd);
12952 // Check if there is enough room left to pull this argument.
12953 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12955 .addImm(MaxOffset + 8 - ArgSizeA8);
12957 // Branch to "overflowMBB" if offset >= max
12958 // Fall through to "offsetMBB" otherwise
12959 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12960 .addMBB(overflowMBB);
12963 // In offsetMBB, emit code to use the reg_save_area.
12965 assert(OffsetReg != 0);
12967 // Read the reg_save_area address.
12968 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12969 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12974 .addOperand(Segment)
12975 .setMemRefs(MMOBegin, MMOEnd);
12977 // Zero-extend the offset
12978 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12979 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12982 .addImm(X86::sub_32bit);
12984 // Add the offset to the reg_save_area to get the final address.
12985 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12986 .addReg(OffsetReg64)
12987 .addReg(RegSaveReg);
12989 // Compute the offset for the next argument
12990 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12991 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12993 .addImm(UseFPOffset ? 16 : 8);
12995 // Store it back into the va_list.
12996 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13000 .addDisp(Disp, UseFPOffset ? 4 : 0)
13001 .addOperand(Segment)
13002 .addReg(NextOffsetReg)
13003 .setMemRefs(MMOBegin, MMOEnd);
13006 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13011 // Emit code to use overflow area
13014 // Load the overflow_area address into a register.
13015 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13016 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13021 .addOperand(Segment)
13022 .setMemRefs(MMOBegin, MMOEnd);
13024 // If we need to align it, do so. Otherwise, just copy the address
13025 // to OverflowDestReg.
13027 // Align the overflow address
13028 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13029 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13031 // aligned_addr = (addr + (align-1)) & ~(align-1)
13032 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13033 .addReg(OverflowAddrReg)
13036 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13038 .addImm(~(uint64_t)(Align-1));
13040 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13041 .addReg(OverflowAddrReg);
13044 // Compute the next overflow address after this argument.
13045 // (the overflow address should be kept 8-byte aligned)
13046 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13047 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13048 .addReg(OverflowDestReg)
13049 .addImm(ArgSizeA8);
13051 // Store the new overflow address.
13052 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13057 .addOperand(Segment)
13058 .addReg(NextAddrReg)
13059 .setMemRefs(MMOBegin, MMOEnd);
13061 // If we branched, emit the PHI to the front of endMBB.
13063 BuildMI(*endMBB, endMBB->begin(), DL,
13064 TII->get(X86::PHI), DestReg)
13065 .addReg(OffsetDestReg).addMBB(offsetMBB)
13066 .addReg(OverflowDestReg).addMBB(overflowMBB);
13069 // Erase the pseudo instruction
13070 MI->eraseFromParent();
13075 MachineBasicBlock *
13076 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13078 MachineBasicBlock *MBB) const {
13079 // Emit code to save XMM registers to the stack. The ABI says that the
13080 // number of registers to save is given in %al, so it's theoretically
13081 // possible to do an indirect jump trick to avoid saving all of them,
13082 // however this code takes a simpler approach and just executes all
13083 // of the stores if %al is non-zero. It's less code, and it's probably
13084 // easier on the hardware branch predictor, and stores aren't all that
13085 // expensive anyway.
13087 // Create the new basic blocks. One block contains all the XMM stores,
13088 // and one block is the final destination regardless of whether any
13089 // stores were performed.
13090 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13091 MachineFunction *F = MBB->getParent();
13092 MachineFunction::iterator MBBIter = MBB;
13094 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13095 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13096 F->insert(MBBIter, XMMSaveMBB);
13097 F->insert(MBBIter, EndMBB);
13099 // Transfer the remainder of MBB and its successor edges to EndMBB.
13100 EndMBB->splice(EndMBB->begin(), MBB,
13101 llvm::next(MachineBasicBlock::iterator(MI)),
13103 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13105 // The original block will now fall through to the XMM save block.
13106 MBB->addSuccessor(XMMSaveMBB);
13107 // The XMMSaveMBB will fall through to the end block.
13108 XMMSaveMBB->addSuccessor(EndMBB);
13110 // Now add the instructions.
13111 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13112 DebugLoc DL = MI->getDebugLoc();
13114 unsigned CountReg = MI->getOperand(0).getReg();
13115 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13116 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13118 if (!Subtarget->isTargetWin64()) {
13119 // If %al is 0, branch around the XMM save block.
13120 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13121 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13122 MBB->addSuccessor(EndMBB);
13125 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13126 // In the XMM save block, save all the XMM argument registers.
13127 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13128 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13129 MachineMemOperand *MMO =
13130 F->getMachineMemOperand(
13131 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13132 MachineMemOperand::MOStore,
13133 /*Size=*/16, /*Align=*/16);
13134 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13135 .addFrameIndex(RegSaveFrameIndex)
13136 .addImm(/*Scale=*/1)
13137 .addReg(/*IndexReg=*/0)
13138 .addImm(/*Disp=*/Offset)
13139 .addReg(/*Segment=*/0)
13140 .addReg(MI->getOperand(i).getReg())
13141 .addMemOperand(MMO);
13144 MI->eraseFromParent(); // The pseudo instruction is gone now.
13149 // The EFLAGS operand of SelectItr might be missing a kill marker
13150 // because there were multiple uses of EFLAGS, and ISel didn't know
13151 // which to mark. Figure out whether SelectItr should have had a
13152 // kill marker, and set it if it should. Returns the correct kill
13154 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13155 MachineBasicBlock* BB,
13156 const TargetRegisterInfo* TRI) {
13157 // Scan forward through BB for a use/def of EFLAGS.
13158 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13159 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13160 const MachineInstr& mi = *miI;
13161 if (mi.readsRegister(X86::EFLAGS))
13163 if (mi.definesRegister(X86::EFLAGS))
13164 break; // Should have kill-flag - update below.
13167 // If we hit the end of the block, check whether EFLAGS is live into a
13169 if (miI == BB->end()) {
13170 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13171 sEnd = BB->succ_end();
13172 sItr != sEnd; ++sItr) {
13173 MachineBasicBlock* succ = *sItr;
13174 if (succ->isLiveIn(X86::EFLAGS))
13179 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13180 // out. SelectMI should have a kill flag on EFLAGS.
13181 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13185 MachineBasicBlock *
13186 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13187 MachineBasicBlock *BB) const {
13188 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13189 DebugLoc DL = MI->getDebugLoc();
13191 // To "insert" a SELECT_CC instruction, we actually have to insert the
13192 // diamond control-flow pattern. The incoming instruction knows the
13193 // destination vreg to set, the condition code register to branch on, the
13194 // true/false values to select between, and a branch opcode to use.
13195 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13196 MachineFunction::iterator It = BB;
13202 // cmpTY ccX, r1, r2
13204 // fallthrough --> copy0MBB
13205 MachineBasicBlock *thisMBB = BB;
13206 MachineFunction *F = BB->getParent();
13207 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13208 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13209 F->insert(It, copy0MBB);
13210 F->insert(It, sinkMBB);
13212 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13213 // live into the sink and copy blocks.
13214 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13215 if (!MI->killsRegister(X86::EFLAGS) &&
13216 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13217 copy0MBB->addLiveIn(X86::EFLAGS);
13218 sinkMBB->addLiveIn(X86::EFLAGS);
13221 // Transfer the remainder of BB and its successor edges to sinkMBB.
13222 sinkMBB->splice(sinkMBB->begin(), BB,
13223 llvm::next(MachineBasicBlock::iterator(MI)),
13225 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13227 // Add the true and fallthrough blocks as its successors.
13228 BB->addSuccessor(copy0MBB);
13229 BB->addSuccessor(sinkMBB);
13231 // Create the conditional branch instruction.
13233 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13234 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13237 // %FalseValue = ...
13238 // # fallthrough to sinkMBB
13239 copy0MBB->addSuccessor(sinkMBB);
13242 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13244 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13245 TII->get(X86::PHI), MI->getOperand(0).getReg())
13246 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13247 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13249 MI->eraseFromParent(); // The pseudo instruction is gone now.
13253 MachineBasicBlock *
13254 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13255 bool Is64Bit) const {
13256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13257 DebugLoc DL = MI->getDebugLoc();
13258 MachineFunction *MF = BB->getParent();
13259 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13261 assert(getTargetMachine().Options.EnableSegmentedStacks);
13263 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13264 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13267 // ... [Till the alloca]
13268 // If stacklet is not large enough, jump to mallocMBB
13271 // Allocate by subtracting from RSP
13272 // Jump to continueMBB
13275 // Allocate by call to runtime
13279 // [rest of original BB]
13282 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13283 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13284 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13286 MachineRegisterInfo &MRI = MF->getRegInfo();
13287 const TargetRegisterClass *AddrRegClass =
13288 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13290 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13291 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13292 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13293 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13294 sizeVReg = MI->getOperand(1).getReg(),
13295 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13297 MachineFunction::iterator MBBIter = BB;
13300 MF->insert(MBBIter, bumpMBB);
13301 MF->insert(MBBIter, mallocMBB);
13302 MF->insert(MBBIter, continueMBB);
13304 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13305 (MachineBasicBlock::iterator(MI)), BB->end());
13306 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13308 // Add code to the main basic block to check if the stack limit has been hit,
13309 // and if so, jump to mallocMBB otherwise to bumpMBB.
13310 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13311 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13312 .addReg(tmpSPVReg).addReg(sizeVReg);
13313 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13314 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13315 .addReg(SPLimitVReg);
13316 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13318 // bumpMBB simply decreases the stack pointer, since we know the current
13319 // stacklet has enough space.
13320 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13321 .addReg(SPLimitVReg);
13322 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13323 .addReg(SPLimitVReg);
13324 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13326 // Calls into a routine in libgcc to allocate more space from the heap.
13327 const uint32_t *RegMask =
13328 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13330 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13332 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13333 .addExternalSymbol("__morestack_allocate_stack_space")
13334 .addRegMask(RegMask)
13335 .addReg(X86::RDI, RegState::Implicit)
13336 .addReg(X86::RAX, RegState::ImplicitDefine);
13338 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13340 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13341 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13342 .addExternalSymbol("__morestack_allocate_stack_space")
13343 .addRegMask(RegMask)
13344 .addReg(X86::EAX, RegState::ImplicitDefine);
13348 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13351 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13352 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13353 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13355 // Set up the CFG correctly.
13356 BB->addSuccessor(bumpMBB);
13357 BB->addSuccessor(mallocMBB);
13358 mallocMBB->addSuccessor(continueMBB);
13359 bumpMBB->addSuccessor(continueMBB);
13361 // Take care of the PHI nodes.
13362 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13363 MI->getOperand(0).getReg())
13364 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13365 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13367 // Delete the original pseudo instruction.
13368 MI->eraseFromParent();
13371 return continueMBB;
13374 MachineBasicBlock *
13375 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13376 MachineBasicBlock *BB) const {
13377 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13378 DebugLoc DL = MI->getDebugLoc();
13380 assert(!Subtarget->isTargetEnvMacho());
13382 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13383 // non-trivial part is impdef of ESP.
13385 if (Subtarget->isTargetWin64()) {
13386 if (Subtarget->isTargetCygMing()) {
13387 // ___chkstk(Mingw64):
13388 // Clobbers R10, R11, RAX and EFLAGS.
13390 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13391 .addExternalSymbol("___chkstk")
13392 .addReg(X86::RAX, RegState::Implicit)
13393 .addReg(X86::RSP, RegState::Implicit)
13394 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13395 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13396 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13398 // __chkstk(MSVCRT): does not update stack pointer.
13399 // Clobbers R10, R11 and EFLAGS.
13400 // FIXME: RAX(allocated size) might be reused and not killed.
13401 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13402 .addExternalSymbol("__chkstk")
13403 .addReg(X86::RAX, RegState::Implicit)
13404 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13405 // RAX has the offset to subtracted from RSP.
13406 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13411 const char *StackProbeSymbol =
13412 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13414 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13415 .addExternalSymbol(StackProbeSymbol)
13416 .addReg(X86::EAX, RegState::Implicit)
13417 .addReg(X86::ESP, RegState::Implicit)
13418 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13419 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13420 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13423 MI->eraseFromParent(); // The pseudo instruction is gone now.
13427 MachineBasicBlock *
13428 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13429 MachineBasicBlock *BB) const {
13430 // This is pretty easy. We're taking the value that we received from
13431 // our load from the relocation, sticking it in either RDI (x86-64)
13432 // or EAX and doing an indirect call. The return value will then
13433 // be in the normal return register.
13434 const X86InstrInfo *TII
13435 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13436 DebugLoc DL = MI->getDebugLoc();
13437 MachineFunction *F = BB->getParent();
13439 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13440 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13442 // Get a register mask for the lowered call.
13443 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13444 // proper register mask.
13445 const uint32_t *RegMask =
13446 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13447 if (Subtarget->is64Bit()) {
13448 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13449 TII->get(X86::MOV64rm), X86::RDI)
13451 .addImm(0).addReg(0)
13452 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13453 MI->getOperand(3).getTargetFlags())
13455 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13456 addDirectMem(MIB, X86::RDI);
13457 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13458 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13459 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13460 TII->get(X86::MOV32rm), X86::EAX)
13462 .addImm(0).addReg(0)
13463 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13464 MI->getOperand(3).getTargetFlags())
13466 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13467 addDirectMem(MIB, X86::EAX);
13468 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13470 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13471 TII->get(X86::MOV32rm), X86::EAX)
13472 .addReg(TII->getGlobalBaseReg(F))
13473 .addImm(0).addReg(0)
13474 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13475 MI->getOperand(3).getTargetFlags())
13477 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13478 addDirectMem(MIB, X86::EAX);
13479 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13482 MI->eraseFromParent(); // The pseudo instruction is gone now.
13486 MachineBasicBlock *
13487 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13488 MachineBasicBlock *MBB) const {
13489 DebugLoc DL = MI->getDebugLoc();
13490 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13492 MachineFunction *MF = MBB->getParent();
13493 MachineRegisterInfo &MRI = MF->getRegInfo();
13495 const BasicBlock *BB = MBB->getBasicBlock();
13496 MachineFunction::iterator I = MBB;
13499 // Memory Reference
13500 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13501 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13504 unsigned MemOpndSlot = 0;
13506 unsigned CurOp = 0;
13508 DstReg = MI->getOperand(CurOp++).getReg();
13509 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13510 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13511 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13512 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13514 MemOpndSlot = CurOp;
13516 MVT PVT = getPointerTy();
13517 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13518 "Invalid Pointer Size!");
13520 // For v = setjmp(buf), we generate
13523 // buf[LabelOffset] = restoreMBB
13524 // SjLjSetup restoreMBB
13530 // v = phi(main, restore)
13535 MachineBasicBlock *thisMBB = MBB;
13536 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13537 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13538 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13539 MF->insert(I, mainMBB);
13540 MF->insert(I, sinkMBB);
13541 MF->push_back(restoreMBB);
13543 MachineInstrBuilder MIB;
13545 // Transfer the remainder of BB and its successor edges to sinkMBB.
13546 sinkMBB->splice(sinkMBB->begin(), MBB,
13547 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13548 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13551 unsigned PtrStoreOpc = 0;
13552 unsigned LabelReg = 0;
13553 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13554 Reloc::Model RM = getTargetMachine().getRelocationModel();
13555 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13556 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13558 // Prepare IP either in reg or imm.
13559 if (!UseImmLabel) {
13560 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13561 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13562 LabelReg = MRI.createVirtualRegister(PtrRC);
13563 if (Subtarget->is64Bit()) {
13564 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13568 .addMBB(restoreMBB)
13571 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13572 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13573 .addReg(XII->getGlobalBaseReg(MF))
13576 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13580 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13582 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13583 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13584 if (i == X86::AddrDisp)
13585 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13587 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13590 MIB.addReg(LabelReg);
13592 MIB.addMBB(restoreMBB);
13593 MIB.setMemRefs(MMOBegin, MMOEnd);
13595 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13596 .addMBB(restoreMBB);
13597 MIB.addRegMask(RegInfo->getNoPreservedMask());
13598 thisMBB->addSuccessor(mainMBB);
13599 thisMBB->addSuccessor(restoreMBB);
13603 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13604 mainMBB->addSuccessor(sinkMBB);
13607 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13608 TII->get(X86::PHI), DstReg)
13609 .addReg(mainDstReg).addMBB(mainMBB)
13610 .addReg(restoreDstReg).addMBB(restoreMBB);
13613 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13614 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13615 restoreMBB->addSuccessor(sinkMBB);
13617 MI->eraseFromParent();
13621 MachineBasicBlock *
13622 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13623 MachineBasicBlock *MBB) const {
13624 DebugLoc DL = MI->getDebugLoc();
13625 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13627 MachineFunction *MF = MBB->getParent();
13628 MachineRegisterInfo &MRI = MF->getRegInfo();
13630 // Memory Reference
13631 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13632 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13634 MVT PVT = getPointerTy();
13635 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13636 "Invalid Pointer Size!");
13638 const TargetRegisterClass *RC =
13639 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13640 unsigned Tmp = MRI.createVirtualRegister(RC);
13641 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13642 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13643 unsigned SP = RegInfo->getStackRegister();
13645 MachineInstrBuilder MIB;
13647 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13648 const int64_t SPOffset = 2 * PVT.getStoreSize();
13650 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13651 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13654 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13655 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13656 MIB.addOperand(MI->getOperand(i));
13657 MIB.setMemRefs(MMOBegin, MMOEnd);
13659 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13660 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13661 if (i == X86::AddrDisp)
13662 MIB.addDisp(MI->getOperand(i), LabelOffset);
13664 MIB.addOperand(MI->getOperand(i));
13666 MIB.setMemRefs(MMOBegin, MMOEnd);
13668 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13669 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13670 if (i == X86::AddrDisp)
13671 MIB.addDisp(MI->getOperand(i), SPOffset);
13673 MIB.addOperand(MI->getOperand(i));
13675 MIB.setMemRefs(MMOBegin, MMOEnd);
13677 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13679 MI->eraseFromParent();
13683 MachineBasicBlock *
13684 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13685 MachineBasicBlock *BB) const {
13686 switch (MI->getOpcode()) {
13687 default: llvm_unreachable("Unexpected instr type to insert");
13688 case X86::TAILJMPd64:
13689 case X86::TAILJMPr64:
13690 case X86::TAILJMPm64:
13691 llvm_unreachable("TAILJMP64 would not be touched here.");
13692 case X86::TCRETURNdi64:
13693 case X86::TCRETURNri64:
13694 case X86::TCRETURNmi64:
13696 case X86::WIN_ALLOCA:
13697 return EmitLoweredWinAlloca(MI, BB);
13698 case X86::SEG_ALLOCA_32:
13699 return EmitLoweredSegAlloca(MI, BB, false);
13700 case X86::SEG_ALLOCA_64:
13701 return EmitLoweredSegAlloca(MI, BB, true);
13702 case X86::TLSCall_32:
13703 case X86::TLSCall_64:
13704 return EmitLoweredTLSCall(MI, BB);
13705 case X86::CMOV_GR8:
13706 case X86::CMOV_FR32:
13707 case X86::CMOV_FR64:
13708 case X86::CMOV_V4F32:
13709 case X86::CMOV_V2F64:
13710 case X86::CMOV_V2I64:
13711 case X86::CMOV_V8F32:
13712 case X86::CMOV_V4F64:
13713 case X86::CMOV_V4I64:
13714 case X86::CMOV_GR16:
13715 case X86::CMOV_GR32:
13716 case X86::CMOV_RFP32:
13717 case X86::CMOV_RFP64:
13718 case X86::CMOV_RFP80:
13719 return EmitLoweredSelect(MI, BB);
13721 case X86::FP32_TO_INT16_IN_MEM:
13722 case X86::FP32_TO_INT32_IN_MEM:
13723 case X86::FP32_TO_INT64_IN_MEM:
13724 case X86::FP64_TO_INT16_IN_MEM:
13725 case X86::FP64_TO_INT32_IN_MEM:
13726 case X86::FP64_TO_INT64_IN_MEM:
13727 case X86::FP80_TO_INT16_IN_MEM:
13728 case X86::FP80_TO_INT32_IN_MEM:
13729 case X86::FP80_TO_INT64_IN_MEM: {
13730 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13731 DebugLoc DL = MI->getDebugLoc();
13733 // Change the floating point control register to use "round towards zero"
13734 // mode when truncating to an integer value.
13735 MachineFunction *F = BB->getParent();
13736 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13737 addFrameReference(BuildMI(*BB, MI, DL,
13738 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13740 // Load the old value of the high byte of the control word...
13742 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13743 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13746 // Set the high part to be round to zero...
13747 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13750 // Reload the modified control word now...
13751 addFrameReference(BuildMI(*BB, MI, DL,
13752 TII->get(X86::FLDCW16m)), CWFrameIdx);
13754 // Restore the memory image of control word to original value
13755 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13758 // Get the X86 opcode to use.
13760 switch (MI->getOpcode()) {
13761 default: llvm_unreachable("illegal opcode!");
13762 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13763 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13764 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13765 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13766 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13767 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13768 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13769 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13770 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13774 MachineOperand &Op = MI->getOperand(0);
13776 AM.BaseType = X86AddressMode::RegBase;
13777 AM.Base.Reg = Op.getReg();
13779 AM.BaseType = X86AddressMode::FrameIndexBase;
13780 AM.Base.FrameIndex = Op.getIndex();
13782 Op = MI->getOperand(1);
13784 AM.Scale = Op.getImm();
13785 Op = MI->getOperand(2);
13787 AM.IndexReg = Op.getImm();
13788 Op = MI->getOperand(3);
13789 if (Op.isGlobal()) {
13790 AM.GV = Op.getGlobal();
13792 AM.Disp = Op.getImm();
13794 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13795 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13797 // Reload the original control word now.
13798 addFrameReference(BuildMI(*BB, MI, DL,
13799 TII->get(X86::FLDCW16m)), CWFrameIdx);
13801 MI->eraseFromParent(); // The pseudo instruction is gone now.
13804 // String/text processing lowering.
13805 case X86::PCMPISTRM128REG:
13806 case X86::VPCMPISTRM128REG:
13807 case X86::PCMPISTRM128MEM:
13808 case X86::VPCMPISTRM128MEM:
13809 case X86::PCMPESTRM128REG:
13810 case X86::VPCMPESTRM128REG:
13811 case X86::PCMPESTRM128MEM:
13812 case X86::VPCMPESTRM128MEM: {
13815 switch (MI->getOpcode()) {
13816 default: llvm_unreachable("illegal opcode!");
13817 case X86::PCMPISTRM128REG:
13818 case X86::VPCMPISTRM128REG:
13819 NumArgs = 3; MemArg = false; break;
13820 case X86::PCMPISTRM128MEM:
13821 case X86::VPCMPISTRM128MEM:
13822 NumArgs = 3; MemArg = true; break;
13823 case X86::PCMPESTRM128REG:
13824 case X86::VPCMPESTRM128REG:
13825 NumArgs = 5; MemArg = false; break;
13826 case X86::PCMPESTRM128MEM:
13827 case X86::VPCMPESTRM128MEM:
13828 NumArgs = 5; MemArg = true; break;
13830 return EmitPCMP(MI, BB, NumArgs, MemArg);
13833 // Thread synchronization.
13835 return EmitMonitor(MI, BB);
13837 // Atomic Lowering.
13838 case X86::ATOMAND8:
13839 case X86::ATOMAND16:
13840 case X86::ATOMAND32:
13841 case X86::ATOMAND64:
13844 case X86::ATOMOR16:
13845 case X86::ATOMOR32:
13846 case X86::ATOMOR64:
13848 case X86::ATOMXOR16:
13849 case X86::ATOMXOR8:
13850 case X86::ATOMXOR32:
13851 case X86::ATOMXOR64:
13853 case X86::ATOMNAND8:
13854 case X86::ATOMNAND16:
13855 case X86::ATOMNAND32:
13856 case X86::ATOMNAND64:
13858 case X86::ATOMMAX8:
13859 case X86::ATOMMAX16:
13860 case X86::ATOMMAX32:
13861 case X86::ATOMMAX64:
13863 case X86::ATOMMIN8:
13864 case X86::ATOMMIN16:
13865 case X86::ATOMMIN32:
13866 case X86::ATOMMIN64:
13868 case X86::ATOMUMAX8:
13869 case X86::ATOMUMAX16:
13870 case X86::ATOMUMAX32:
13871 case X86::ATOMUMAX64:
13873 case X86::ATOMUMIN8:
13874 case X86::ATOMUMIN16:
13875 case X86::ATOMUMIN32:
13876 case X86::ATOMUMIN64:
13877 return EmitAtomicLoadArith(MI, BB);
13879 // This group does 64-bit operations on a 32-bit host.
13880 case X86::ATOMAND6432:
13881 case X86::ATOMOR6432:
13882 case X86::ATOMXOR6432:
13883 case X86::ATOMNAND6432:
13884 case X86::ATOMADD6432:
13885 case X86::ATOMSUB6432:
13886 case X86::ATOMMAX6432:
13887 case X86::ATOMMIN6432:
13888 case X86::ATOMUMAX6432:
13889 case X86::ATOMUMIN6432:
13890 case X86::ATOMSWAP6432:
13891 return EmitAtomicLoadArith6432(MI, BB);
13893 case X86::VASTART_SAVE_XMM_REGS:
13894 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13896 case X86::VAARG_64:
13897 return EmitVAARG64WithCustomInserter(MI, BB);
13899 case X86::EH_SjLj_SetJmp32:
13900 case X86::EH_SjLj_SetJmp64:
13901 return emitEHSjLjSetJmp(MI, BB);
13903 case X86::EH_SjLj_LongJmp32:
13904 case X86::EH_SjLj_LongJmp64:
13905 return emitEHSjLjLongJmp(MI, BB);
13909 //===----------------------------------------------------------------------===//
13910 // X86 Optimization Hooks
13911 //===----------------------------------------------------------------------===//
13913 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13916 const SelectionDAG &DAG,
13917 unsigned Depth) const {
13918 unsigned BitWidth = KnownZero.getBitWidth();
13919 unsigned Opc = Op.getOpcode();
13920 assert((Opc >= ISD::BUILTIN_OP_END ||
13921 Opc == ISD::INTRINSIC_WO_CHAIN ||
13922 Opc == ISD::INTRINSIC_W_CHAIN ||
13923 Opc == ISD::INTRINSIC_VOID) &&
13924 "Should use MaskedValueIsZero if you don't know whether Op"
13925 " is a target node!");
13927 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13941 // These nodes' second result is a boolean.
13942 if (Op.getResNo() == 0)
13945 case X86ISD::SETCC:
13946 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13948 case ISD::INTRINSIC_WO_CHAIN: {
13949 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13950 unsigned NumLoBits = 0;
13953 case Intrinsic::x86_sse_movmsk_ps:
13954 case Intrinsic::x86_avx_movmsk_ps_256:
13955 case Intrinsic::x86_sse2_movmsk_pd:
13956 case Intrinsic::x86_avx_movmsk_pd_256:
13957 case Intrinsic::x86_mmx_pmovmskb:
13958 case Intrinsic::x86_sse2_pmovmskb_128:
13959 case Intrinsic::x86_avx2_pmovmskb: {
13960 // High bits of movmskp{s|d}, pmovmskb are known zero.
13962 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13963 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13964 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13965 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13966 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13967 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13968 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13969 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13971 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13980 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13981 unsigned Depth) const {
13982 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13983 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13984 return Op.getValueType().getScalarType().getSizeInBits();
13990 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13991 /// node is a GlobalAddress + offset.
13992 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13993 const GlobalValue* &GA,
13994 int64_t &Offset) const {
13995 if (N->getOpcode() == X86ISD::Wrapper) {
13996 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13997 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13998 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14002 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14005 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14006 /// same as extracting the high 128-bit part of 256-bit vector and then
14007 /// inserting the result into the low part of a new 256-bit vector
14008 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14009 EVT VT = SVOp->getValueType(0);
14010 unsigned NumElems = VT.getVectorNumElements();
14012 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14013 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14014 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14015 SVOp->getMaskElt(j) >= 0)
14021 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14022 /// same as extracting the low 128-bit part of 256-bit vector and then
14023 /// inserting the result into the high part of a new 256-bit vector
14024 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14025 EVT VT = SVOp->getValueType(0);
14026 unsigned NumElems = VT.getVectorNumElements();
14028 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14029 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14030 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14031 SVOp->getMaskElt(j) >= 0)
14037 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14038 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14039 TargetLowering::DAGCombinerInfo &DCI,
14040 const X86Subtarget* Subtarget) {
14041 DebugLoc dl = N->getDebugLoc();
14042 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14043 SDValue V1 = SVOp->getOperand(0);
14044 SDValue V2 = SVOp->getOperand(1);
14045 EVT VT = SVOp->getValueType(0);
14046 unsigned NumElems = VT.getVectorNumElements();
14048 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14049 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14053 // V UNDEF BUILD_VECTOR UNDEF
14055 // CONCAT_VECTOR CONCAT_VECTOR
14058 // RESULT: V + zero extended
14060 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14061 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14062 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14065 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14068 // To match the shuffle mask, the first half of the mask should
14069 // be exactly the first vector, and all the rest a splat with the
14070 // first element of the second one.
14071 for (unsigned i = 0; i != NumElems/2; ++i)
14072 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14073 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14076 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14077 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14078 if (Ld->hasNUsesOfValue(1, 0)) {
14079 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14080 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14082 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14084 Ld->getPointerInfo(),
14085 Ld->getAlignment(),
14086 false/*isVolatile*/, true/*ReadMem*/,
14087 false/*WriteMem*/);
14088 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14092 // Emit a zeroed vector and insert the desired subvector on its
14094 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14095 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14096 return DCI.CombineTo(N, InsV);
14099 //===--------------------------------------------------------------------===//
14100 // Combine some shuffles into subvector extracts and inserts:
14103 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14104 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14105 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14106 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14107 return DCI.CombineTo(N, InsV);
14110 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14111 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14112 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14113 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14114 return DCI.CombineTo(N, InsV);
14120 /// PerformShuffleCombine - Performs several different shuffle combines.
14121 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14122 TargetLowering::DAGCombinerInfo &DCI,
14123 const X86Subtarget *Subtarget) {
14124 DebugLoc dl = N->getDebugLoc();
14125 EVT VT = N->getValueType(0);
14127 // Don't create instructions with illegal types after legalize types has run.
14128 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14129 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14132 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14133 if (Subtarget->hasAVX() && VT.is256BitVector() &&
14134 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14135 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14137 // Only handle 128 wide vector from here on.
14138 if (!VT.is128BitVector())
14141 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14142 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14143 // consecutive, non-overlapping, and in the right order.
14144 SmallVector<SDValue, 16> Elts;
14145 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14146 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14148 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14152 /// PerformTruncateCombine - Converts truncate operation to
14153 /// a sequence of vector shuffle operations.
14154 /// It is possible when we truncate 256-bit vector to 128-bit vector
14155 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14156 TargetLowering::DAGCombinerInfo &DCI,
14157 const X86Subtarget *Subtarget) {
14158 if (!DCI.isBeforeLegalizeOps())
14161 if (!Subtarget->hasAVX())
14164 EVT VT = N->getValueType(0);
14165 SDValue Op = N->getOperand(0);
14166 EVT OpVT = Op.getValueType();
14167 DebugLoc dl = N->getDebugLoc();
14169 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14171 if (Subtarget->hasAVX2()) {
14172 // AVX2: v4i64 -> v4i32
14175 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14177 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14178 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14181 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14182 DAG.getIntPtrConstant(0));
14185 // AVX: v4i64 -> v4i32
14186 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14187 DAG.getIntPtrConstant(0));
14189 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14190 DAG.getIntPtrConstant(2));
14192 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14193 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14196 static const int ShufMask1[] = {0, 2, 0, 0};
14198 SDValue Undef = DAG.getUNDEF(VT);
14199 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14200 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14203 static const int ShufMask2[] = {0, 1, 4, 5};
14205 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14208 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14210 if (Subtarget->hasAVX2()) {
14211 // AVX2: v8i32 -> v8i16
14213 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14216 SmallVector<SDValue,32> pshufbMask;
14217 for (unsigned i = 0; i < 2; ++i) {
14218 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14219 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14220 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14221 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14222 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14223 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14224 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14225 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14226 for (unsigned j = 0; j < 8; ++j)
14227 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14229 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14230 &pshufbMask[0], 32);
14231 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14233 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14235 static const int ShufMask[] = {0, 2, -1, -1};
14236 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14239 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14240 DAG.getIntPtrConstant(0));
14242 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14245 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14246 DAG.getIntPtrConstant(0));
14248 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14249 DAG.getIntPtrConstant(4));
14251 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14252 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14255 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14256 -1, -1, -1, -1, -1, -1, -1, -1};
14258 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14259 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14260 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14262 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14263 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14266 static const int ShufMask2[] = {0, 1, 4, 5};
14268 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14269 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14275 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14276 /// specific shuffle of a load can be folded into a single element load.
14277 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14278 /// shuffles have been customed lowered so we need to handle those here.
14279 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14280 TargetLowering::DAGCombinerInfo &DCI) {
14281 if (DCI.isBeforeLegalizeOps())
14284 SDValue InVec = N->getOperand(0);
14285 SDValue EltNo = N->getOperand(1);
14287 if (!isa<ConstantSDNode>(EltNo))
14290 EVT VT = InVec.getValueType();
14292 bool HasShuffleIntoBitcast = false;
14293 if (InVec.getOpcode() == ISD::BITCAST) {
14294 // Don't duplicate a load with other uses.
14295 if (!InVec.hasOneUse())
14297 EVT BCVT = InVec.getOperand(0).getValueType();
14298 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14300 InVec = InVec.getOperand(0);
14301 HasShuffleIntoBitcast = true;
14304 if (!isTargetShuffle(InVec.getOpcode()))
14307 // Don't duplicate a load with other uses.
14308 if (!InVec.hasOneUse())
14311 SmallVector<int, 16> ShuffleMask;
14313 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14317 // Select the input vector, guarding against out of range extract vector.
14318 unsigned NumElems = VT.getVectorNumElements();
14319 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14320 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14321 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14322 : InVec.getOperand(1);
14324 // If inputs to shuffle are the same for both ops, then allow 2 uses
14325 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14327 if (LdNode.getOpcode() == ISD::BITCAST) {
14328 // Don't duplicate a load with other uses.
14329 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14332 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14333 LdNode = LdNode.getOperand(0);
14336 if (!ISD::isNormalLoad(LdNode.getNode()))
14339 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14341 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14344 if (HasShuffleIntoBitcast) {
14345 // If there's a bitcast before the shuffle, check if the load type and
14346 // alignment is valid.
14347 unsigned Align = LN0->getAlignment();
14348 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14349 unsigned NewAlign = TLI.getDataLayout()->
14350 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14352 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14356 // All checks match so transform back to vector_shuffle so that DAG combiner
14357 // can finish the job
14358 DebugLoc dl = N->getDebugLoc();
14360 // Create shuffle node taking into account the case that its a unary shuffle
14361 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14362 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14363 InVec.getOperand(0), Shuffle,
14365 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14366 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14370 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14371 /// generation and convert it from being a bunch of shuffles and extracts
14372 /// to a simple store and scalar loads to extract the elements.
14373 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14374 TargetLowering::DAGCombinerInfo &DCI) {
14375 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14376 if (NewOp.getNode())
14379 SDValue InputVector = N->getOperand(0);
14381 // Only operate on vectors of 4 elements, where the alternative shuffling
14382 // gets to be more expensive.
14383 if (InputVector.getValueType() != MVT::v4i32)
14386 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14387 // single use which is a sign-extend or zero-extend, and all elements are
14389 SmallVector<SDNode *, 4> Uses;
14390 unsigned ExtractedElements = 0;
14391 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14392 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14393 if (UI.getUse().getResNo() != InputVector.getResNo())
14396 SDNode *Extract = *UI;
14397 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14400 if (Extract->getValueType(0) != MVT::i32)
14402 if (!Extract->hasOneUse())
14404 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14405 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14407 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14410 // Record which element was extracted.
14411 ExtractedElements |=
14412 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14414 Uses.push_back(Extract);
14417 // If not all the elements were used, this may not be worthwhile.
14418 if (ExtractedElements != 15)
14421 // Ok, we've now decided to do the transformation.
14422 DebugLoc dl = InputVector.getDebugLoc();
14424 // Store the value to a temporary stack slot.
14425 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14426 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14427 MachinePointerInfo(), false, false, 0);
14429 // Replace each use (extract) with a load of the appropriate element.
14430 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14431 UE = Uses.end(); UI != UE; ++UI) {
14432 SDNode *Extract = *UI;
14434 // cOMpute the element's address.
14435 SDValue Idx = Extract->getOperand(1);
14437 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14438 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14440 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14442 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14443 StackPtr, OffsetVal);
14445 // Load the scalar.
14446 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14447 ScalarAddr, MachinePointerInfo(),
14448 false, false, false, 0);
14450 // Replace the exact with the load.
14451 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14454 // The replacement was made in place; don't return anything.
14458 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14460 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14461 TargetLowering::DAGCombinerInfo &DCI,
14462 const X86Subtarget *Subtarget) {
14463 DebugLoc DL = N->getDebugLoc();
14464 SDValue Cond = N->getOperand(0);
14465 // Get the LHS/RHS of the select.
14466 SDValue LHS = N->getOperand(1);
14467 SDValue RHS = N->getOperand(2);
14468 EVT VT = LHS.getValueType();
14470 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14471 // instructions match the semantics of the common C idiom x<y?x:y but not
14472 // x<=y?x:y, because of how they handle negative zero (which can be
14473 // ignored in unsafe-math mode).
14474 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14475 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14476 (Subtarget->hasSSE2() ||
14477 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14478 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14480 unsigned Opcode = 0;
14481 // Check for x CC y ? x : y.
14482 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14483 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14487 // Converting this to a min would handle NaNs incorrectly, and swapping
14488 // the operands would cause it to handle comparisons between positive
14489 // and negative zero incorrectly.
14490 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14491 if (!DAG.getTarget().Options.UnsafeFPMath &&
14492 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14494 std::swap(LHS, RHS);
14496 Opcode = X86ISD::FMIN;
14499 // Converting this to a min would handle comparisons between positive
14500 // and negative zero incorrectly.
14501 if (!DAG.getTarget().Options.UnsafeFPMath &&
14502 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14504 Opcode = X86ISD::FMIN;
14507 // Converting this to a min would handle both negative zeros and NaNs
14508 // incorrectly, but we can swap the operands to fix both.
14509 std::swap(LHS, RHS);
14513 Opcode = X86ISD::FMIN;
14517 // Converting this to a max would handle comparisons between positive
14518 // and negative zero incorrectly.
14519 if (!DAG.getTarget().Options.UnsafeFPMath &&
14520 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14522 Opcode = X86ISD::FMAX;
14525 // Converting this to a max would handle NaNs incorrectly, and swapping
14526 // the operands would cause it to handle comparisons between positive
14527 // and negative zero incorrectly.
14528 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14529 if (!DAG.getTarget().Options.UnsafeFPMath &&
14530 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14532 std::swap(LHS, RHS);
14534 Opcode = X86ISD::FMAX;
14537 // Converting this to a max would handle both negative zeros and NaNs
14538 // incorrectly, but we can swap the operands to fix both.
14539 std::swap(LHS, RHS);
14543 Opcode = X86ISD::FMAX;
14546 // Check for x CC y ? y : x -- a min/max with reversed arms.
14547 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14548 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14552 // Converting this to a min would handle comparisons between positive
14553 // and negative zero incorrectly, and swapping the operands would
14554 // cause it to handle NaNs incorrectly.
14555 if (!DAG.getTarget().Options.UnsafeFPMath &&
14556 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14557 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14559 std::swap(LHS, RHS);
14561 Opcode = X86ISD::FMIN;
14564 // Converting this to a min would handle NaNs incorrectly.
14565 if (!DAG.getTarget().Options.UnsafeFPMath &&
14566 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14568 Opcode = X86ISD::FMIN;
14571 // Converting this to a min would handle both negative zeros and NaNs
14572 // incorrectly, but we can swap the operands to fix both.
14573 std::swap(LHS, RHS);
14577 Opcode = X86ISD::FMIN;
14581 // Converting this to a max would handle NaNs incorrectly.
14582 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14584 Opcode = X86ISD::FMAX;
14587 // Converting this to a max would handle comparisons between positive
14588 // and negative zero incorrectly, and swapping the operands would
14589 // cause it to handle NaNs incorrectly.
14590 if (!DAG.getTarget().Options.UnsafeFPMath &&
14591 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14592 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14594 std::swap(LHS, RHS);
14596 Opcode = X86ISD::FMAX;
14599 // Converting this to a max would handle both negative zeros and NaNs
14600 // incorrectly, but we can swap the operands to fix both.
14601 std::swap(LHS, RHS);
14605 Opcode = X86ISD::FMAX;
14611 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14614 // If this is a select between two integer constants, try to do some
14616 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14617 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14618 // Don't do this for crazy integer types.
14619 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14620 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14621 // so that TrueC (the true value) is larger than FalseC.
14622 bool NeedsCondInvert = false;
14624 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14625 // Efficiently invertible.
14626 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14627 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14628 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14629 NeedsCondInvert = true;
14630 std::swap(TrueC, FalseC);
14633 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14634 if (FalseC->getAPIntValue() == 0 &&
14635 TrueC->getAPIntValue().isPowerOf2()) {
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, LHS.getValueType(), Cond);
14643 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14644 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14645 DAG.getConstant(ShAmt, MVT::i8));
14648 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14649 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14650 if (NeedsCondInvert) // Invert the condition if needed.
14651 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14652 DAG.getConstant(1, Cond.getValueType()));
14654 // Zero extend the condition if needed.
14655 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14656 FalseC->getValueType(0), Cond);
14657 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14658 SDValue(FalseC, 0));
14661 // Optimize cases that will turn into an LEA instruction. This requires
14662 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14663 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14664 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14665 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14667 bool isFastMultiplier = false;
14669 switch ((unsigned char)Diff) {
14671 case 1: // result = add base, cond
14672 case 2: // result = lea base( , cond*2)
14673 case 3: // result = lea base(cond, cond*2)
14674 case 4: // result = lea base( , cond*4)
14675 case 5: // result = lea base(cond, cond*4)
14676 case 8: // result = lea base( , cond*8)
14677 case 9: // result = lea base(cond, cond*8)
14678 isFastMultiplier = true;
14683 if (isFastMultiplier) {
14684 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14685 if (NeedsCondInvert) // Invert the condition if needed.
14686 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14687 DAG.getConstant(1, Cond.getValueType()));
14689 // Zero extend the condition if needed.
14690 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14692 // Scale the condition by the difference.
14694 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14695 DAG.getConstant(Diff, Cond.getValueType()));
14697 // Add the base if non-zero.
14698 if (FalseC->getAPIntValue() != 0)
14699 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14700 SDValue(FalseC, 0));
14707 // Canonicalize max and min:
14708 // (x > y) ? x : y -> (x >= y) ? x : y
14709 // (x < y) ? x : y -> (x <= y) ? x : y
14710 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14711 // the need for an extra compare
14712 // against zero. e.g.
14713 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14715 // testl %edi, %edi
14717 // cmovgl %edi, %eax
14721 // cmovsl %eax, %edi
14722 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14723 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14724 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14725 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14730 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14731 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14732 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14733 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14738 // If we know that this node is legal then we know that it is going to be
14739 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14740 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14741 // to simplify previous instructions.
14742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14743 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14744 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14745 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14747 // Don't optimize vector selects that map to mask-registers.
14751 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14752 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14754 APInt KnownZero, KnownOne;
14755 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14756 DCI.isBeforeLegalizeOps());
14757 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14758 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14759 DCI.CommitTargetLoweringOpt(TLO);
14765 // Check whether a boolean test is testing a boolean value generated by
14766 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14769 // Simplify the following patterns:
14770 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14771 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14772 // to (Op EFLAGS Cond)
14774 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14775 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14776 // to (Op EFLAGS !Cond)
14778 // where Op could be BRCOND or CMOV.
14780 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14781 // Quit if not CMP and SUB with its value result used.
14782 if (Cmp.getOpcode() != X86ISD::CMP &&
14783 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14786 // Quit if not used as a boolean value.
14787 if (CC != X86::COND_E && CC != X86::COND_NE)
14790 // Check CMP operands. One of them should be 0 or 1 and the other should be
14791 // an SetCC or extended from it.
14792 SDValue Op1 = Cmp.getOperand(0);
14793 SDValue Op2 = Cmp.getOperand(1);
14796 const ConstantSDNode* C = 0;
14797 bool needOppositeCond = (CC == X86::COND_E);
14799 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14801 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14803 else // Quit if all operands are not constants.
14806 if (C->getZExtValue() == 1)
14807 needOppositeCond = !needOppositeCond;
14808 else if (C->getZExtValue() != 0)
14809 // Quit if the constant is neither 0 or 1.
14812 // Skip 'zext' node.
14813 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14814 SetCC = SetCC.getOperand(0);
14816 switch (SetCC.getOpcode()) {
14817 case X86ISD::SETCC:
14818 // Set the condition code or opposite one if necessary.
14819 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14820 if (needOppositeCond)
14821 CC = X86::GetOppositeBranchCondition(CC);
14822 return SetCC.getOperand(1);
14823 case X86ISD::CMOV: {
14824 // Check whether false/true value has canonical one, i.e. 0 or 1.
14825 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14826 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14827 // Quit if true value is not a constant.
14830 // Quit if false value is not a constant.
14832 // A special case for rdrand, where 0 is set if false cond is found.
14833 SDValue Op = SetCC.getOperand(0);
14834 if (Op.getOpcode() != X86ISD::RDRAND)
14837 // Quit if false value is not the constant 0 or 1.
14838 bool FValIsFalse = true;
14839 if (FVal && FVal->getZExtValue() != 0) {
14840 if (FVal->getZExtValue() != 1)
14842 // If FVal is 1, opposite cond is needed.
14843 needOppositeCond = !needOppositeCond;
14844 FValIsFalse = false;
14846 // Quit if TVal is not the constant opposite of FVal.
14847 if (FValIsFalse && TVal->getZExtValue() != 1)
14849 if (!FValIsFalse && TVal->getZExtValue() != 0)
14851 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14852 if (needOppositeCond)
14853 CC = X86::GetOppositeBranchCondition(CC);
14854 return SetCC.getOperand(3);
14861 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14862 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14863 TargetLowering::DAGCombinerInfo &DCI,
14864 const X86Subtarget *Subtarget) {
14865 DebugLoc DL = N->getDebugLoc();
14867 // If the flag operand isn't dead, don't touch this CMOV.
14868 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14871 SDValue FalseOp = N->getOperand(0);
14872 SDValue TrueOp = N->getOperand(1);
14873 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14874 SDValue Cond = N->getOperand(3);
14876 if (CC == X86::COND_E || CC == X86::COND_NE) {
14877 switch (Cond.getOpcode()) {
14881 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14882 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14883 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14889 Flags = checkBoolTestSetCCCombine(Cond, CC);
14890 if (Flags.getNode() &&
14891 // Extra check as FCMOV only supports a subset of X86 cond.
14892 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14893 SDValue Ops[] = { FalseOp, TrueOp,
14894 DAG.getConstant(CC, MVT::i8), Flags };
14895 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14896 Ops, array_lengthof(Ops));
14899 // If this is a select between two integer constants, try to do some
14900 // optimizations. Note that the operands are ordered the opposite of SELECT
14902 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14903 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14904 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14905 // larger than FalseC (the false value).
14906 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14907 CC = X86::GetOppositeBranchCondition(CC);
14908 std::swap(TrueC, FalseC);
14909 std::swap(TrueOp, FalseOp);
14912 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14913 // This is efficient for any integer data type (including i8/i16) and
14915 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14916 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14917 DAG.getConstant(CC, MVT::i8), Cond);
14919 // Zero extend the condition if needed.
14920 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14922 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14923 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14924 DAG.getConstant(ShAmt, MVT::i8));
14925 if (N->getNumValues() == 2) // Dead flag value?
14926 return DCI.CombineTo(N, Cond, SDValue());
14930 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14931 // for any integer data type, including i8/i16.
14932 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14933 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14934 DAG.getConstant(CC, MVT::i8), Cond);
14936 // Zero extend the condition if needed.
14937 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14938 FalseC->getValueType(0), Cond);
14939 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14940 SDValue(FalseC, 0));
14942 if (N->getNumValues() == 2) // Dead flag value?
14943 return DCI.CombineTo(N, Cond, SDValue());
14947 // Optimize cases that will turn into an LEA instruction. This requires
14948 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14949 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14950 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14951 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14953 bool isFastMultiplier = false;
14955 switch ((unsigned char)Diff) {
14957 case 1: // result = add base, cond
14958 case 2: // result = lea base( , cond*2)
14959 case 3: // result = lea base(cond, cond*2)
14960 case 4: // result = lea base( , cond*4)
14961 case 5: // result = lea base(cond, cond*4)
14962 case 8: // result = lea base( , cond*8)
14963 case 9: // result = lea base(cond, cond*8)
14964 isFastMultiplier = true;
14969 if (isFastMultiplier) {
14970 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14971 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14972 DAG.getConstant(CC, MVT::i8), Cond);
14973 // Zero extend the condition if needed.
14974 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14976 // Scale the condition by the difference.
14978 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14979 DAG.getConstant(Diff, Cond.getValueType()));
14981 // Add the base if non-zero.
14982 if (FalseC->getAPIntValue() != 0)
14983 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14984 SDValue(FalseC, 0));
14985 if (N->getNumValues() == 2) // Dead flag value?
14986 return DCI.CombineTo(N, Cond, SDValue());
14993 // Handle these cases:
14994 // (select (x != c), e, c) -> select (x != c), e, x),
14995 // (select (x == c), c, e) -> select (x == c), x, e)
14996 // where the c is an integer constant, and the "select" is the combination
14997 // of CMOV and CMP.
14999 // The rationale for this change is that the conditional-move from a constant
15000 // needs two instructions, however, conditional-move from a register needs
15001 // only one instruction.
15003 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15004 // some instruction-combining opportunities. This opt needs to be
15005 // postponed as late as possible.
15007 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15008 // the DCI.xxxx conditions are provided to postpone the optimization as
15009 // late as possible.
15011 ConstantSDNode *CmpAgainst = 0;
15012 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15013 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15014 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15016 if (CC == X86::COND_NE &&
15017 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15018 CC = X86::GetOppositeBranchCondition(CC);
15019 std::swap(TrueOp, FalseOp);
15022 if (CC == X86::COND_E &&
15023 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15024 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15025 DAG.getConstant(CC, MVT::i8), Cond };
15026 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15027 array_lengthof(Ops));
15036 /// PerformMulCombine - Optimize a single multiply with constant into two
15037 /// in order to implement it with two cheaper instructions, e.g.
15038 /// LEA + SHL, LEA + LEA.
15039 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15040 TargetLowering::DAGCombinerInfo &DCI) {
15041 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15044 EVT VT = N->getValueType(0);
15045 if (VT != MVT::i64)
15048 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15051 uint64_t MulAmt = C->getZExtValue();
15052 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15055 uint64_t MulAmt1 = 0;
15056 uint64_t MulAmt2 = 0;
15057 if ((MulAmt % 9) == 0) {
15059 MulAmt2 = MulAmt / 9;
15060 } else if ((MulAmt % 5) == 0) {
15062 MulAmt2 = MulAmt / 5;
15063 } else if ((MulAmt % 3) == 0) {
15065 MulAmt2 = MulAmt / 3;
15068 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15069 DebugLoc DL = N->getDebugLoc();
15071 if (isPowerOf2_64(MulAmt2) &&
15072 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15073 // If second multiplifer is pow2, issue it first. We want the multiply by
15074 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15076 std::swap(MulAmt1, MulAmt2);
15079 if (isPowerOf2_64(MulAmt1))
15080 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15081 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15083 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15084 DAG.getConstant(MulAmt1, VT));
15086 if (isPowerOf2_64(MulAmt2))
15087 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15088 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15090 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15091 DAG.getConstant(MulAmt2, VT));
15093 // Do not add new nodes to DAG combiner worklist.
15094 DCI.CombineTo(N, NewMul, false);
15099 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15100 SDValue N0 = N->getOperand(0);
15101 SDValue N1 = N->getOperand(1);
15102 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15103 EVT VT = N0.getValueType();
15105 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15106 // since the result of setcc_c is all zero's or all ones.
15107 if (VT.isInteger() && !VT.isVector() &&
15108 N1C && N0.getOpcode() == ISD::AND &&
15109 N0.getOperand(1).getOpcode() == ISD::Constant) {
15110 SDValue N00 = N0.getOperand(0);
15111 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15112 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15113 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15114 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15115 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15116 APInt ShAmt = N1C->getAPIntValue();
15117 Mask = Mask.shl(ShAmt);
15119 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15120 N00, DAG.getConstant(Mask, VT));
15125 // Hardware support for vector shifts is sparse which makes us scalarize the
15126 // vector operations in many cases. Also, on sandybridge ADD is faster than
15128 // (shl V, 1) -> add V,V
15129 if (isSplatVector(N1.getNode())) {
15130 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15131 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15132 // We shift all of the values by one. In many cases we do not have
15133 // hardware support for this operation. This is better expressed as an ADD
15135 if (N1C && (1 == N1C->getZExtValue())) {
15136 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15143 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15145 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15146 TargetLowering::DAGCombinerInfo &DCI,
15147 const X86Subtarget *Subtarget) {
15148 EVT VT = N->getValueType(0);
15149 if (N->getOpcode() == ISD::SHL) {
15150 SDValue V = PerformSHLCombine(N, DAG);
15151 if (V.getNode()) return V;
15154 // On X86 with SSE2 support, we can transform this to a vector shift if
15155 // all elements are shifted by the same amount. We can't do this in legalize
15156 // because the a constant vector is typically transformed to a constant pool
15157 // so we have no knowledge of the shift amount.
15158 if (!Subtarget->hasSSE2())
15161 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15162 (!Subtarget->hasAVX2() ||
15163 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15166 SDValue ShAmtOp = N->getOperand(1);
15167 EVT EltVT = VT.getVectorElementType();
15168 DebugLoc DL = N->getDebugLoc();
15169 SDValue BaseShAmt = SDValue();
15170 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15171 unsigned NumElts = VT.getVectorNumElements();
15173 for (; i != NumElts; ++i) {
15174 SDValue Arg = ShAmtOp.getOperand(i);
15175 if (Arg.getOpcode() == ISD::UNDEF) continue;
15179 // Handle the case where the build_vector is all undef
15180 // FIXME: Should DAG allow this?
15184 for (; i != NumElts; ++i) {
15185 SDValue Arg = ShAmtOp.getOperand(i);
15186 if (Arg.getOpcode() == ISD::UNDEF) continue;
15187 if (Arg != BaseShAmt) {
15191 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15192 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15193 SDValue InVec = ShAmtOp.getOperand(0);
15194 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15195 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15197 for (; i != NumElts; ++i) {
15198 SDValue Arg = InVec.getOperand(i);
15199 if (Arg.getOpcode() == ISD::UNDEF) continue;
15203 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15204 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15205 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15206 if (C->getZExtValue() == SplatIdx)
15207 BaseShAmt = InVec.getOperand(1);
15210 if (BaseShAmt.getNode() == 0) {
15211 // Don't create instructions with illegal types after legalize
15213 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15214 !DCI.isBeforeLegalize())
15217 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15218 DAG.getIntPtrConstant(0));
15223 // The shift amount is an i32.
15224 if (EltVT.bitsGT(MVT::i32))
15225 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15226 else if (EltVT.bitsLT(MVT::i32))
15227 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15229 // The shift amount is identical so we can do a vector shift.
15230 SDValue ValOp = N->getOperand(0);
15231 switch (N->getOpcode()) {
15233 llvm_unreachable("Unknown shift opcode!");
15235 switch (VT.getSimpleVT().SimpleTy) {
15236 default: return SDValue();
15243 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15246 switch (VT.getSimpleVT().SimpleTy) {
15247 default: return SDValue();
15252 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15255 switch (VT.getSimpleVT().SimpleTy) {
15256 default: return SDValue();
15263 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15269 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15270 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15271 // and friends. Likewise for OR -> CMPNEQSS.
15272 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15273 TargetLowering::DAGCombinerInfo &DCI,
15274 const X86Subtarget *Subtarget) {
15277 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15278 // we're requiring SSE2 for both.
15279 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15280 SDValue N0 = N->getOperand(0);
15281 SDValue N1 = N->getOperand(1);
15282 SDValue CMP0 = N0->getOperand(1);
15283 SDValue CMP1 = N1->getOperand(1);
15284 DebugLoc DL = N->getDebugLoc();
15286 // The SETCCs should both refer to the same CMP.
15287 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15290 SDValue CMP00 = CMP0->getOperand(0);
15291 SDValue CMP01 = CMP0->getOperand(1);
15292 EVT VT = CMP00.getValueType();
15294 if (VT == MVT::f32 || VT == MVT::f64) {
15295 bool ExpectingFlags = false;
15296 // Check for any users that want flags:
15297 for (SDNode::use_iterator UI = N->use_begin(),
15299 !ExpectingFlags && UI != UE; ++UI)
15300 switch (UI->getOpcode()) {
15305 ExpectingFlags = true;
15307 case ISD::CopyToReg:
15308 case ISD::SIGN_EXTEND:
15309 case ISD::ZERO_EXTEND:
15310 case ISD::ANY_EXTEND:
15314 if (!ExpectingFlags) {
15315 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15316 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15318 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15319 X86::CondCode tmp = cc0;
15324 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15325 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15326 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15327 X86ISD::NodeType NTOperator = is64BitFP ?
15328 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15329 // FIXME: need symbolic constants for these magic numbers.
15330 // See X86ATTInstPrinter.cpp:printSSECC().
15331 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15332 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15333 DAG.getConstant(x86cc, MVT::i8));
15334 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15336 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15337 DAG.getConstant(1, MVT::i32));
15338 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15339 return OneBitOfTruth;
15347 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15348 /// so it can be folded inside ANDNP.
15349 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15350 EVT VT = N->getValueType(0);
15352 // Match direct AllOnes for 128 and 256-bit vectors
15353 if (ISD::isBuildVectorAllOnes(N))
15356 // Look through a bit convert.
15357 if (N->getOpcode() == ISD::BITCAST)
15358 N = N->getOperand(0).getNode();
15360 // Sometimes the operand may come from a insert_subvector building a 256-bit
15362 if (VT.is256BitVector() &&
15363 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15364 SDValue V1 = N->getOperand(0);
15365 SDValue V2 = N->getOperand(1);
15367 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15368 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15369 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15370 ISD::isBuildVectorAllOnes(V2.getNode()))
15377 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15378 TargetLowering::DAGCombinerInfo &DCI,
15379 const X86Subtarget *Subtarget) {
15380 if (DCI.isBeforeLegalizeOps())
15383 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15387 EVT VT = N->getValueType(0);
15389 // Create ANDN, BLSI, and BLSR instructions
15390 // BLSI is X & (-X)
15391 // BLSR is X & (X-1)
15392 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15393 SDValue N0 = N->getOperand(0);
15394 SDValue N1 = N->getOperand(1);
15395 DebugLoc DL = N->getDebugLoc();
15397 // Check LHS for not
15398 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15399 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15400 // Check RHS for not
15401 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15402 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15404 // Check LHS for neg
15405 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15406 isZero(N0.getOperand(0)))
15407 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15409 // Check RHS for neg
15410 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15411 isZero(N1.getOperand(0)))
15412 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15414 // Check LHS for X-1
15415 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15416 isAllOnes(N0.getOperand(1)))
15417 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15419 // Check RHS for X-1
15420 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15421 isAllOnes(N1.getOperand(1)))
15422 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15427 // Want to form ANDNP nodes:
15428 // 1) In the hopes of then easily combining them with OR and AND nodes
15429 // to form PBLEND/PSIGN.
15430 // 2) To match ANDN packed intrinsics
15431 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15434 SDValue N0 = N->getOperand(0);
15435 SDValue N1 = N->getOperand(1);
15436 DebugLoc DL = N->getDebugLoc();
15438 // Check LHS for vnot
15439 if (N0.getOpcode() == ISD::XOR &&
15440 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15441 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15442 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15444 // Check RHS for vnot
15445 if (N1.getOpcode() == ISD::XOR &&
15446 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15447 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15448 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15453 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15454 TargetLowering::DAGCombinerInfo &DCI,
15455 const X86Subtarget *Subtarget) {
15456 if (DCI.isBeforeLegalizeOps())
15459 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15463 EVT VT = N->getValueType(0);
15465 SDValue N0 = N->getOperand(0);
15466 SDValue N1 = N->getOperand(1);
15468 // look for psign/blend
15469 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15470 if (!Subtarget->hasSSSE3() ||
15471 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15474 // Canonicalize pandn to RHS
15475 if (N0.getOpcode() == X86ISD::ANDNP)
15477 // or (and (m, y), (pandn m, x))
15478 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15479 SDValue Mask = N1.getOperand(0);
15480 SDValue X = N1.getOperand(1);
15482 if (N0.getOperand(0) == Mask)
15483 Y = N0.getOperand(1);
15484 if (N0.getOperand(1) == Mask)
15485 Y = N0.getOperand(0);
15487 // Check to see if the mask appeared in both the AND and ANDNP and
15491 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15492 // Look through mask bitcast.
15493 if (Mask.getOpcode() == ISD::BITCAST)
15494 Mask = Mask.getOperand(0);
15495 if (X.getOpcode() == ISD::BITCAST)
15496 X = X.getOperand(0);
15497 if (Y.getOpcode() == ISD::BITCAST)
15498 Y = Y.getOperand(0);
15500 EVT MaskVT = Mask.getValueType();
15502 // Validate that the Mask operand is a vector sra node.
15503 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15504 // there is no psrai.b
15505 if (Mask.getOpcode() != X86ISD::VSRAI)
15508 // Check that the SRA is all signbits.
15509 SDValue SraC = Mask.getOperand(1);
15510 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15511 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15512 if ((SraAmt + 1) != EltBits)
15515 DebugLoc DL = N->getDebugLoc();
15517 // Now we know we at least have a plendvb with the mask val. See if
15518 // we can form a psignb/w/d.
15519 // psign = x.type == y.type == mask.type && y = sub(0, x);
15520 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15521 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15522 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15523 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15524 "Unsupported VT for PSIGN");
15525 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15526 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15528 // PBLENDVB only available on SSE 4.1
15529 if (!Subtarget->hasSSE41())
15532 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15534 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15535 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15536 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15537 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15538 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15542 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15545 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15546 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15548 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15550 if (!N0.hasOneUse() || !N1.hasOneUse())
15553 SDValue ShAmt0 = N0.getOperand(1);
15554 if (ShAmt0.getValueType() != MVT::i8)
15556 SDValue ShAmt1 = N1.getOperand(1);
15557 if (ShAmt1.getValueType() != MVT::i8)
15559 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15560 ShAmt0 = ShAmt0.getOperand(0);
15561 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15562 ShAmt1 = ShAmt1.getOperand(0);
15564 DebugLoc DL = N->getDebugLoc();
15565 unsigned Opc = X86ISD::SHLD;
15566 SDValue Op0 = N0.getOperand(0);
15567 SDValue Op1 = N1.getOperand(0);
15568 if (ShAmt0.getOpcode() == ISD::SUB) {
15569 Opc = X86ISD::SHRD;
15570 std::swap(Op0, Op1);
15571 std::swap(ShAmt0, ShAmt1);
15574 unsigned Bits = VT.getSizeInBits();
15575 if (ShAmt1.getOpcode() == ISD::SUB) {
15576 SDValue Sum = ShAmt1.getOperand(0);
15577 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15578 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15579 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15580 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15581 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15582 return DAG.getNode(Opc, DL, VT,
15584 DAG.getNode(ISD::TRUNCATE, DL,
15587 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15588 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15590 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15591 return DAG.getNode(Opc, DL, VT,
15592 N0.getOperand(0), N1.getOperand(0),
15593 DAG.getNode(ISD::TRUNCATE, DL,
15600 // Generate NEG and CMOV for integer abs.
15601 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15602 EVT VT = N->getValueType(0);
15604 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15605 // 8-bit integer abs to NEG and CMOV.
15606 if (VT.isInteger() && VT.getSizeInBits() == 8)
15609 SDValue N0 = N->getOperand(0);
15610 SDValue N1 = N->getOperand(1);
15611 DebugLoc DL = N->getDebugLoc();
15613 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15614 // and change it to SUB and CMOV.
15615 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15616 N0.getOpcode() == ISD::ADD &&
15617 N0.getOperand(1) == N1 &&
15618 N1.getOpcode() == ISD::SRA &&
15619 N1.getOperand(0) == N0.getOperand(0))
15620 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15621 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15622 // Generate SUB & CMOV.
15623 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15624 DAG.getConstant(0, VT), N0.getOperand(0));
15626 SDValue Ops[] = { N0.getOperand(0), Neg,
15627 DAG.getConstant(X86::COND_GE, MVT::i8),
15628 SDValue(Neg.getNode(), 1) };
15629 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15630 Ops, array_lengthof(Ops));
15635 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15636 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15637 TargetLowering::DAGCombinerInfo &DCI,
15638 const X86Subtarget *Subtarget) {
15639 if (DCI.isBeforeLegalizeOps())
15642 if (Subtarget->hasCMov()) {
15643 SDValue RV = performIntegerAbsCombine(N, DAG);
15648 // Try forming BMI if it is available.
15649 if (!Subtarget->hasBMI())
15652 EVT VT = N->getValueType(0);
15654 if (VT != MVT::i32 && VT != MVT::i64)
15657 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15659 // Create BLSMSK instructions by finding X ^ (X-1)
15660 SDValue N0 = N->getOperand(0);
15661 SDValue N1 = N->getOperand(1);
15662 DebugLoc DL = N->getDebugLoc();
15664 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15665 isAllOnes(N0.getOperand(1)))
15666 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15668 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15669 isAllOnes(N1.getOperand(1)))
15670 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15675 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15676 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15677 TargetLowering::DAGCombinerInfo &DCI,
15678 const X86Subtarget *Subtarget) {
15679 LoadSDNode *Ld = cast<LoadSDNode>(N);
15680 EVT RegVT = Ld->getValueType(0);
15681 EVT MemVT = Ld->getMemoryVT();
15682 DebugLoc dl = Ld->getDebugLoc();
15683 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15685 ISD::LoadExtType Ext = Ld->getExtensionType();
15687 // If this is a vector EXT Load then attempt to optimize it using a
15688 // shuffle. We need SSSE3 shuffles.
15689 // TODO: It is possible to support ZExt by zeroing the undef values
15690 // during the shuffle phase or after the shuffle.
15691 if (RegVT.isVector() && RegVT.isInteger() &&
15692 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15693 assert(MemVT != RegVT && "Cannot extend to the same type");
15694 assert(MemVT.isVector() && "Must load a vector from memory");
15696 unsigned NumElems = RegVT.getVectorNumElements();
15697 unsigned RegSz = RegVT.getSizeInBits();
15698 unsigned MemSz = MemVT.getSizeInBits();
15699 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15701 // All sizes must be a power of two.
15702 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15705 // Attempt to load the original value using scalar loads.
15706 // Find the largest scalar type that divides the total loaded size.
15707 MVT SclrLoadTy = MVT::i8;
15708 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15709 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15710 MVT Tp = (MVT::SimpleValueType)tp;
15711 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15716 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15717 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15719 SclrLoadTy = MVT::f64;
15721 // Calculate the number of scalar loads that we need to perform
15722 // in order to load our vector from memory.
15723 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15725 // Represent our vector as a sequence of elements which are the
15726 // largest scalar that we can load.
15727 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15728 RegSz/SclrLoadTy.getSizeInBits());
15730 // Represent the data using the same element type that is stored in
15731 // memory. In practice, we ''widen'' MemVT.
15732 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15733 RegSz/MemVT.getScalarType().getSizeInBits());
15735 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15736 "Invalid vector type");
15738 // We can't shuffle using an illegal type.
15739 if (!TLI.isTypeLegal(WideVecVT))
15742 SmallVector<SDValue, 8> Chains;
15743 SDValue Ptr = Ld->getBasePtr();
15744 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15745 TLI.getPointerTy());
15746 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15748 for (unsigned i = 0; i < NumLoads; ++i) {
15749 // Perform a single load.
15750 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15751 Ptr, Ld->getPointerInfo(),
15752 Ld->isVolatile(), Ld->isNonTemporal(),
15753 Ld->isInvariant(), Ld->getAlignment());
15754 Chains.push_back(ScalarLoad.getValue(1));
15755 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15756 // another round of DAGCombining.
15758 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15760 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15761 ScalarLoad, DAG.getIntPtrConstant(i));
15763 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15766 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15769 // Bitcast the loaded value to a vector of the original element type, in
15770 // the size of the target vector type.
15771 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15772 unsigned SizeRatio = RegSz/MemSz;
15774 // Redistribute the loaded elements into the different locations.
15775 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15776 for (unsigned i = 0; i != NumElems; ++i)
15777 ShuffleVec[i*SizeRatio] = i;
15779 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15780 DAG.getUNDEF(WideVecVT),
15783 // Bitcast to the requested type.
15784 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15785 // Replace the original load with the new sequence
15786 // and return the new chain.
15787 return DCI.CombineTo(N, Shuff, TF, true);
15793 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15794 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15795 const X86Subtarget *Subtarget) {
15796 StoreSDNode *St = cast<StoreSDNode>(N);
15797 EVT VT = St->getValue().getValueType();
15798 EVT StVT = St->getMemoryVT();
15799 DebugLoc dl = St->getDebugLoc();
15800 SDValue StoredVal = St->getOperand(1);
15801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15803 // If we are saving a concatenation of two XMM registers, perform two stores.
15804 // On Sandy Bridge, 256-bit memory operations are executed by two
15805 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15806 // memory operation.
15807 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15808 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15809 StoredVal.getNumOperands() == 2) {
15810 SDValue Value0 = StoredVal.getOperand(0);
15811 SDValue Value1 = StoredVal.getOperand(1);
15813 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15814 SDValue Ptr0 = St->getBasePtr();
15815 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15817 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15818 St->getPointerInfo(), St->isVolatile(),
15819 St->isNonTemporal(), St->getAlignment());
15820 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15821 St->getPointerInfo(), St->isVolatile(),
15822 St->isNonTemporal(), St->getAlignment());
15823 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15826 // Optimize trunc store (of multiple scalars) to shuffle and store.
15827 // First, pack all of the elements in one place. Next, store to memory
15828 // in fewer chunks.
15829 if (St->isTruncatingStore() && VT.isVector()) {
15830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15831 unsigned NumElems = VT.getVectorNumElements();
15832 assert(StVT != VT && "Cannot truncate to the same type");
15833 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15834 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15836 // From, To sizes and ElemCount must be pow of two
15837 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15838 // We are going to use the original vector elt for storing.
15839 // Accumulated smaller vector elements must be a multiple of the store size.
15840 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15842 unsigned SizeRatio = FromSz / ToSz;
15844 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15846 // Create a type on which we perform the shuffle
15847 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15848 StVT.getScalarType(), NumElems*SizeRatio);
15850 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15852 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15853 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15854 for (unsigned i = 0; i != NumElems; ++i)
15855 ShuffleVec[i] = i * SizeRatio;
15857 // Can't shuffle using an illegal type.
15858 if (!TLI.isTypeLegal(WideVecVT))
15861 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15862 DAG.getUNDEF(WideVecVT),
15864 // At this point all of the data is stored at the bottom of the
15865 // register. We now need to save it to mem.
15867 // Find the largest store unit
15868 MVT StoreType = MVT::i8;
15869 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15870 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15871 MVT Tp = (MVT::SimpleValueType)tp;
15872 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15876 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15877 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15878 (64 <= NumElems * ToSz))
15879 StoreType = MVT::f64;
15881 // Bitcast the original vector into a vector of store-size units
15882 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15883 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15884 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15885 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15886 SmallVector<SDValue, 8> Chains;
15887 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15888 TLI.getPointerTy());
15889 SDValue Ptr = St->getBasePtr();
15891 // Perform one or more big stores into memory.
15892 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15893 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15894 StoreType, ShuffWide,
15895 DAG.getIntPtrConstant(i));
15896 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15897 St->getPointerInfo(), St->isVolatile(),
15898 St->isNonTemporal(), St->getAlignment());
15899 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15900 Chains.push_back(Ch);
15903 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15908 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15909 // the FP state in cases where an emms may be missing.
15910 // A preferable solution to the general problem is to figure out the right
15911 // places to insert EMMS. This qualifies as a quick hack.
15913 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15914 if (VT.getSizeInBits() != 64)
15917 const Function *F = DAG.getMachineFunction().getFunction();
15918 bool NoImplicitFloatOps = F->getFnAttributes().
15919 hasAttribute(Attributes::NoImplicitFloat);
15920 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15921 && Subtarget->hasSSE2();
15922 if ((VT.isVector() ||
15923 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15924 isa<LoadSDNode>(St->getValue()) &&
15925 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15926 St->getChain().hasOneUse() && !St->isVolatile()) {
15927 SDNode* LdVal = St->getValue().getNode();
15928 LoadSDNode *Ld = 0;
15929 int TokenFactorIndex = -1;
15930 SmallVector<SDValue, 8> Ops;
15931 SDNode* ChainVal = St->getChain().getNode();
15932 // Must be a store of a load. We currently handle two cases: the load
15933 // is a direct child, and it's under an intervening TokenFactor. It is
15934 // possible to dig deeper under nested TokenFactors.
15935 if (ChainVal == LdVal)
15936 Ld = cast<LoadSDNode>(St->getChain());
15937 else if (St->getValue().hasOneUse() &&
15938 ChainVal->getOpcode() == ISD::TokenFactor) {
15939 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15940 if (ChainVal->getOperand(i).getNode() == LdVal) {
15941 TokenFactorIndex = i;
15942 Ld = cast<LoadSDNode>(St->getValue());
15944 Ops.push_back(ChainVal->getOperand(i));
15948 if (!Ld || !ISD::isNormalLoad(Ld))
15951 // If this is not the MMX case, i.e. we are just turning i64 load/store
15952 // into f64 load/store, avoid the transformation if there are multiple
15953 // uses of the loaded value.
15954 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15957 DebugLoc LdDL = Ld->getDebugLoc();
15958 DebugLoc StDL = N->getDebugLoc();
15959 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15960 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15962 if (Subtarget->is64Bit() || F64IsLegal) {
15963 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15964 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15965 Ld->getPointerInfo(), Ld->isVolatile(),
15966 Ld->isNonTemporal(), Ld->isInvariant(),
15967 Ld->getAlignment());
15968 SDValue NewChain = NewLd.getValue(1);
15969 if (TokenFactorIndex != -1) {
15970 Ops.push_back(NewChain);
15971 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15974 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15975 St->getPointerInfo(),
15976 St->isVolatile(), St->isNonTemporal(),
15977 St->getAlignment());
15980 // Otherwise, lower to two pairs of 32-bit loads / stores.
15981 SDValue LoAddr = Ld->getBasePtr();
15982 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15983 DAG.getConstant(4, MVT::i32));
15985 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15986 Ld->getPointerInfo(),
15987 Ld->isVolatile(), Ld->isNonTemporal(),
15988 Ld->isInvariant(), Ld->getAlignment());
15989 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15990 Ld->getPointerInfo().getWithOffset(4),
15991 Ld->isVolatile(), Ld->isNonTemporal(),
15993 MinAlign(Ld->getAlignment(), 4));
15995 SDValue NewChain = LoLd.getValue(1);
15996 if (TokenFactorIndex != -1) {
15997 Ops.push_back(LoLd);
15998 Ops.push_back(HiLd);
15999 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16003 LoAddr = St->getBasePtr();
16004 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16005 DAG.getConstant(4, MVT::i32));
16007 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16008 St->getPointerInfo(),
16009 St->isVolatile(), St->isNonTemporal(),
16010 St->getAlignment());
16011 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16012 St->getPointerInfo().getWithOffset(4),
16014 St->isNonTemporal(),
16015 MinAlign(St->getAlignment(), 4));
16016 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16021 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16022 /// and return the operands for the horizontal operation in LHS and RHS. A
16023 /// horizontal operation performs the binary operation on successive elements
16024 /// of its first operand, then on successive elements of its second operand,
16025 /// returning the resulting values in a vector. For example, if
16026 /// A = < float a0, float a1, float a2, float a3 >
16028 /// B = < float b0, float b1, float b2, float b3 >
16029 /// then the result of doing a horizontal operation on A and B is
16030 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16031 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16032 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16033 /// set to A, RHS to B, and the routine returns 'true'.
16034 /// Note that the binary operation should have the property that if one of the
16035 /// operands is UNDEF then the result is UNDEF.
16036 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16037 // Look for the following pattern: if
16038 // A = < float a0, float a1, float a2, float a3 >
16039 // B = < float b0, float b1, float b2, float b3 >
16041 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16042 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16043 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16044 // which is A horizontal-op B.
16046 // At least one of the operands should be a vector shuffle.
16047 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16048 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16051 EVT VT = LHS.getValueType();
16053 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16054 "Unsupported vector type for horizontal add/sub");
16056 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16057 // operate independently on 128-bit lanes.
16058 unsigned NumElts = VT.getVectorNumElements();
16059 unsigned NumLanes = VT.getSizeInBits()/128;
16060 unsigned NumLaneElts = NumElts / NumLanes;
16061 assert((NumLaneElts % 2 == 0) &&
16062 "Vector type should have an even number of elements in each lane");
16063 unsigned HalfLaneElts = NumLaneElts/2;
16065 // View LHS in the form
16066 // LHS = VECTOR_SHUFFLE A, B, LMask
16067 // If LHS is not a shuffle then pretend it is the shuffle
16068 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16069 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16072 SmallVector<int, 16> LMask(NumElts);
16073 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16074 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16075 A = LHS.getOperand(0);
16076 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16077 B = LHS.getOperand(1);
16078 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16079 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16081 if (LHS.getOpcode() != ISD::UNDEF)
16083 for (unsigned i = 0; i != NumElts; ++i)
16087 // Likewise, view RHS in the form
16088 // RHS = VECTOR_SHUFFLE C, D, RMask
16090 SmallVector<int, 16> RMask(NumElts);
16091 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16092 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16093 C = RHS.getOperand(0);
16094 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16095 D = RHS.getOperand(1);
16096 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16097 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16099 if (RHS.getOpcode() != ISD::UNDEF)
16101 for (unsigned i = 0; i != NumElts; ++i)
16105 // Check that the shuffles are both shuffling the same vectors.
16106 if (!(A == C && B == D) && !(A == D && B == C))
16109 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16110 if (!A.getNode() && !B.getNode())
16113 // If A and B occur in reverse order in RHS, then "swap" them (which means
16114 // rewriting the mask).
16116 CommuteVectorShuffleMask(RMask, NumElts);
16118 // At this point LHS and RHS are equivalent to
16119 // LHS = VECTOR_SHUFFLE A, B, LMask
16120 // RHS = VECTOR_SHUFFLE A, B, RMask
16121 // Check that the masks correspond to performing a horizontal operation.
16122 for (unsigned i = 0; i != NumElts; ++i) {
16123 int LIdx = LMask[i], RIdx = RMask[i];
16125 // Ignore any UNDEF components.
16126 if (LIdx < 0 || RIdx < 0 ||
16127 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16128 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16131 // Check that successive elements are being operated on. If not, this is
16132 // not a horizontal operation.
16133 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16134 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16135 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16136 if (!(LIdx == Index && RIdx == Index + 1) &&
16137 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16141 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16142 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16146 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16147 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16148 const X86Subtarget *Subtarget) {
16149 EVT VT = N->getValueType(0);
16150 SDValue LHS = N->getOperand(0);
16151 SDValue RHS = N->getOperand(1);
16153 // Try to synthesize horizontal adds from adds of shuffles.
16154 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16155 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16156 isHorizontalBinOp(LHS, RHS, true))
16157 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16161 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16162 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16163 const X86Subtarget *Subtarget) {
16164 EVT VT = N->getValueType(0);
16165 SDValue LHS = N->getOperand(0);
16166 SDValue RHS = N->getOperand(1);
16168 // Try to synthesize horizontal subs from subs of shuffles.
16169 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16170 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16171 isHorizontalBinOp(LHS, RHS, false))
16172 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16176 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16177 /// X86ISD::FXOR nodes.
16178 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16179 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16180 // F[X]OR(0.0, x) -> x
16181 // F[X]OR(x, 0.0) -> x
16182 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16183 if (C->getValueAPF().isPosZero())
16184 return N->getOperand(1);
16185 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16186 if (C->getValueAPF().isPosZero())
16187 return N->getOperand(0);
16191 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16192 /// X86ISD::FMAX nodes.
16193 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16194 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16196 // Only perform optimizations if UnsafeMath is used.
16197 if (!DAG.getTarget().Options.UnsafeFPMath)
16200 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16201 // into FMINC and FMAXC, which are Commutative operations.
16202 unsigned NewOp = 0;
16203 switch (N->getOpcode()) {
16204 default: llvm_unreachable("unknown opcode");
16205 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16206 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16209 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16210 N->getOperand(0), N->getOperand(1));
16214 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16215 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16216 // FAND(0.0, x) -> 0.0
16217 // FAND(x, 0.0) -> 0.0
16218 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16219 if (C->getValueAPF().isPosZero())
16220 return N->getOperand(0);
16221 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16222 if (C->getValueAPF().isPosZero())
16223 return N->getOperand(1);
16227 static SDValue PerformBTCombine(SDNode *N,
16229 TargetLowering::DAGCombinerInfo &DCI) {
16230 // BT ignores high bits in the bit index operand.
16231 SDValue Op1 = N->getOperand(1);
16232 if (Op1.hasOneUse()) {
16233 unsigned BitWidth = Op1.getValueSizeInBits();
16234 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16235 APInt KnownZero, KnownOne;
16236 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16237 !DCI.isBeforeLegalizeOps());
16238 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16239 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16240 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16241 DCI.CommitTargetLoweringOpt(TLO);
16246 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16247 SDValue Op = N->getOperand(0);
16248 if (Op.getOpcode() == ISD::BITCAST)
16249 Op = Op.getOperand(0);
16250 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16251 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16252 VT.getVectorElementType().getSizeInBits() ==
16253 OpVT.getVectorElementType().getSizeInBits()) {
16254 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16259 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16260 TargetLowering::DAGCombinerInfo &DCI,
16261 const X86Subtarget *Subtarget) {
16262 if (!DCI.isBeforeLegalizeOps())
16265 if (!Subtarget->hasAVX())
16268 EVT VT = N->getValueType(0);
16269 SDValue Op = N->getOperand(0);
16270 EVT OpVT = Op.getValueType();
16271 DebugLoc dl = N->getDebugLoc();
16273 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16274 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16276 if (Subtarget->hasAVX2())
16277 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16279 // Optimize vectors in AVX mode
16280 // Sign extend v8i16 to v8i32 and
16283 // Divide input vector into two parts
16284 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16285 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16286 // concat the vectors to original VT
16288 unsigned NumElems = OpVT.getVectorNumElements();
16289 SDValue Undef = DAG.getUNDEF(OpVT);
16291 SmallVector<int,8> ShufMask1(NumElems, -1);
16292 for (unsigned i = 0; i != NumElems/2; ++i)
16295 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16297 SmallVector<int,8> ShufMask2(NumElems, -1);
16298 for (unsigned i = 0; i != NumElems/2; ++i)
16299 ShufMask2[i] = i + NumElems/2;
16301 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16303 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16304 VT.getVectorNumElements()/2);
16306 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16307 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16309 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16314 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16315 const X86Subtarget* Subtarget) {
16316 DebugLoc dl = N->getDebugLoc();
16317 EVT VT = N->getValueType(0);
16319 // Let legalize expand this if it isn't a legal type yet.
16320 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16323 EVT ScalarVT = VT.getScalarType();
16324 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16325 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16328 SDValue A = N->getOperand(0);
16329 SDValue B = N->getOperand(1);
16330 SDValue C = N->getOperand(2);
16332 bool NegA = (A.getOpcode() == ISD::FNEG);
16333 bool NegB = (B.getOpcode() == ISD::FNEG);
16334 bool NegC = (C.getOpcode() == ISD::FNEG);
16336 // Negative multiplication when NegA xor NegB
16337 bool NegMul = (NegA != NegB);
16339 A = A.getOperand(0);
16341 B = B.getOperand(0);
16343 C = C.getOperand(0);
16347 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16349 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16351 return DAG.getNode(Opcode, dl, VT, A, B, C);
16354 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16355 TargetLowering::DAGCombinerInfo &DCI,
16356 const X86Subtarget *Subtarget) {
16357 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16358 // (and (i32 x86isd::setcc_carry), 1)
16359 // This eliminates the zext. This transformation is necessary because
16360 // ISD::SETCC is always legalized to i8.
16361 DebugLoc dl = N->getDebugLoc();
16362 SDValue N0 = N->getOperand(0);
16363 EVT VT = N->getValueType(0);
16364 EVT OpVT = N0.getValueType();
16366 if (N0.getOpcode() == ISD::AND &&
16368 N0.getOperand(0).hasOneUse()) {
16369 SDValue N00 = N0.getOperand(0);
16370 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16373 if (!C || C->getZExtValue() != 1)
16375 return DAG.getNode(ISD::AND, dl, VT,
16376 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16377 N00.getOperand(0), N00.getOperand(1)),
16378 DAG.getConstant(1, VT));
16381 // Optimize vectors in AVX mode:
16384 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16385 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16386 // Concat upper and lower parts.
16389 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16390 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16391 // Concat upper and lower parts.
16393 if (!DCI.isBeforeLegalizeOps())
16396 if (!Subtarget->hasAVX())
16399 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16400 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16402 if (Subtarget->hasAVX2())
16403 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16405 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16406 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16407 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16409 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16410 VT.getVectorNumElements()/2);
16412 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16413 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16415 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16421 // Optimize x == -y --> x+y == 0
16422 // x != -y --> x+y != 0
16423 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16424 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16425 SDValue LHS = N->getOperand(0);
16426 SDValue RHS = N->getOperand(1);
16428 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16429 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16430 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16431 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16432 LHS.getValueType(), RHS, LHS.getOperand(1));
16433 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16434 addV, DAG.getConstant(0, addV.getValueType()), CC);
16436 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16437 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16438 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16439 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16440 RHS.getValueType(), LHS, RHS.getOperand(1));
16441 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16442 addV, DAG.getConstant(0, addV.getValueType()), CC);
16447 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16448 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16449 TargetLowering::DAGCombinerInfo &DCI,
16450 const X86Subtarget *Subtarget) {
16451 DebugLoc DL = N->getDebugLoc();
16452 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16453 SDValue EFLAGS = N->getOperand(1);
16455 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16456 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16458 if (CC == X86::COND_B)
16459 return DAG.getNode(ISD::AND, DL, MVT::i8,
16460 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16461 DAG.getConstant(CC, MVT::i8), EFLAGS),
16462 DAG.getConstant(1, MVT::i8));
16466 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16467 if (Flags.getNode()) {
16468 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16469 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16475 // Optimize branch condition evaluation.
16477 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16478 TargetLowering::DAGCombinerInfo &DCI,
16479 const X86Subtarget *Subtarget) {
16480 DebugLoc DL = N->getDebugLoc();
16481 SDValue Chain = N->getOperand(0);
16482 SDValue Dest = N->getOperand(1);
16483 SDValue EFLAGS = N->getOperand(3);
16484 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16488 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16489 if (Flags.getNode()) {
16490 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16491 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16498 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16499 const X86TargetLowering *XTLI) {
16500 SDValue Op0 = N->getOperand(0);
16501 EVT InVT = Op0->getValueType(0);
16503 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16504 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16505 DebugLoc dl = N->getDebugLoc();
16506 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16507 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16508 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16511 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16512 // a 32-bit target where SSE doesn't support i64->FP operations.
16513 if (Op0.getOpcode() == ISD::LOAD) {
16514 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16515 EVT VT = Ld->getValueType(0);
16516 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16517 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16518 !XTLI->getSubtarget()->is64Bit() &&
16519 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16520 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16521 Ld->getChain(), Op0, DAG);
16522 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16529 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16530 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16531 X86TargetLowering::DAGCombinerInfo &DCI) {
16532 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16533 // the result is either zero or one (depending on the input carry bit).
16534 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16535 if (X86::isZeroNode(N->getOperand(0)) &&
16536 X86::isZeroNode(N->getOperand(1)) &&
16537 // We don't have a good way to replace an EFLAGS use, so only do this when
16539 SDValue(N, 1).use_empty()) {
16540 DebugLoc DL = N->getDebugLoc();
16541 EVT VT = N->getValueType(0);
16542 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16543 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16544 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16545 DAG.getConstant(X86::COND_B,MVT::i8),
16547 DAG.getConstant(1, VT));
16548 return DCI.CombineTo(N, Res1, CarryOut);
16554 // fold (add Y, (sete X, 0)) -> adc 0, Y
16555 // (add Y, (setne X, 0)) -> sbb -1, Y
16556 // (sub (sete X, 0), Y) -> sbb 0, Y
16557 // (sub (setne X, 0), Y) -> adc -1, Y
16558 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16559 DebugLoc DL = N->getDebugLoc();
16561 // Look through ZExts.
16562 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16563 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16566 SDValue SetCC = Ext.getOperand(0);
16567 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16570 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16571 if (CC != X86::COND_E && CC != X86::COND_NE)
16574 SDValue Cmp = SetCC.getOperand(1);
16575 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16576 !X86::isZeroNode(Cmp.getOperand(1)) ||
16577 !Cmp.getOperand(0).getValueType().isInteger())
16580 SDValue CmpOp0 = Cmp.getOperand(0);
16581 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16582 DAG.getConstant(1, CmpOp0.getValueType()));
16584 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16585 if (CC == X86::COND_NE)
16586 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16587 DL, OtherVal.getValueType(), OtherVal,
16588 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16589 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16590 DL, OtherVal.getValueType(), OtherVal,
16591 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16594 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16595 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16596 const X86Subtarget *Subtarget) {
16597 EVT VT = N->getValueType(0);
16598 SDValue Op0 = N->getOperand(0);
16599 SDValue Op1 = N->getOperand(1);
16601 // Try to synthesize horizontal adds from adds of shuffles.
16602 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16603 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16604 isHorizontalBinOp(Op0, Op1, true))
16605 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16607 return OptimizeConditionalInDecrement(N, DAG);
16610 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16611 const X86Subtarget *Subtarget) {
16612 SDValue Op0 = N->getOperand(0);
16613 SDValue Op1 = N->getOperand(1);
16615 // X86 can't encode an immediate LHS of a sub. See if we can push the
16616 // negation into a preceding instruction.
16617 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16618 // If the RHS of the sub is a XOR with one use and a constant, invert the
16619 // immediate. Then add one to the LHS of the sub so we can turn
16620 // X-Y -> X+~Y+1, saving one register.
16621 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16622 isa<ConstantSDNode>(Op1.getOperand(1))) {
16623 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16624 EVT VT = Op0.getValueType();
16625 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16627 DAG.getConstant(~XorC, VT));
16628 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16629 DAG.getConstant(C->getAPIntValue()+1, VT));
16633 // Try to synthesize horizontal adds from adds of shuffles.
16634 EVT VT = N->getValueType(0);
16635 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16636 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16637 isHorizontalBinOp(Op0, Op1, true))
16638 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16640 return OptimizeConditionalInDecrement(N, DAG);
16643 /// performVZEXTCombine - Performs build vector combines
16644 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16645 TargetLowering::DAGCombinerInfo &DCI,
16646 const X86Subtarget *Subtarget) {
16647 // (vzext (bitcast (vzext (x)) -> (vzext x)
16648 SDValue In = N->getOperand(0);
16649 while (In.getOpcode() == ISD::BITCAST)
16650 In = In.getOperand(0);
16652 if (In.getOpcode() != X86ISD::VZEXT)
16655 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16658 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16659 DAGCombinerInfo &DCI) const {
16660 SelectionDAG &DAG = DCI.DAG;
16661 switch (N->getOpcode()) {
16663 case ISD::EXTRACT_VECTOR_ELT:
16664 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16666 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16667 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16668 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16669 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16670 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16671 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16674 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16675 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16676 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16677 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16678 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16679 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16680 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16681 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16682 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16684 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16686 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16687 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16688 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16689 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16690 case ISD::ANY_EXTEND:
16691 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16692 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16693 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16694 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16695 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16696 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16697 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
16698 case X86ISD::SHUFP: // Handle all target specific shuffles
16699 case X86ISD::PALIGN:
16700 case X86ISD::UNPCKH:
16701 case X86ISD::UNPCKL:
16702 case X86ISD::MOVHLPS:
16703 case X86ISD::MOVLHPS:
16704 case X86ISD::PSHUFD:
16705 case X86ISD::PSHUFHW:
16706 case X86ISD::PSHUFLW:
16707 case X86ISD::MOVSS:
16708 case X86ISD::MOVSD:
16709 case X86ISD::VPERMILP:
16710 case X86ISD::VPERM2X128:
16711 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16712 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16718 /// isTypeDesirableForOp - Return true if the target has native support for
16719 /// the specified value type and it is 'desirable' to use the type for the
16720 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16721 /// instruction encodings are longer and some i16 instructions are slow.
16722 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16723 if (!isTypeLegal(VT))
16725 if (VT != MVT::i16)
16732 case ISD::SIGN_EXTEND:
16733 case ISD::ZERO_EXTEND:
16734 case ISD::ANY_EXTEND:
16747 /// IsDesirableToPromoteOp - This method query the target whether it is
16748 /// beneficial for dag combiner to promote the specified node. If true, it
16749 /// should return the desired promotion type by reference.
16750 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16751 EVT VT = Op.getValueType();
16752 if (VT != MVT::i16)
16755 bool Promote = false;
16756 bool Commute = false;
16757 switch (Op.getOpcode()) {
16760 LoadSDNode *LD = cast<LoadSDNode>(Op);
16761 // If the non-extending load has a single use and it's not live out, then it
16762 // might be folded.
16763 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16764 Op.hasOneUse()*/) {
16765 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16766 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16767 // The only case where we'd want to promote LOAD (rather then it being
16768 // promoted as an operand is when it's only use is liveout.
16769 if (UI->getOpcode() != ISD::CopyToReg)
16776 case ISD::SIGN_EXTEND:
16777 case ISD::ZERO_EXTEND:
16778 case ISD::ANY_EXTEND:
16783 SDValue N0 = Op.getOperand(0);
16784 // Look out for (store (shl (load), x)).
16785 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16798 SDValue N0 = Op.getOperand(0);
16799 SDValue N1 = Op.getOperand(1);
16800 if (!Commute && MayFoldLoad(N1))
16802 // Avoid disabling potential load folding opportunities.
16803 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16805 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16815 //===----------------------------------------------------------------------===//
16816 // X86 Inline Assembly Support
16817 //===----------------------------------------------------------------------===//
16820 // Helper to match a string separated by whitespace.
16821 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16822 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16824 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16825 StringRef piece(*args[i]);
16826 if (!s.startswith(piece)) // Check if the piece matches.
16829 s = s.substr(piece.size());
16830 StringRef::size_type pos = s.find_first_not_of(" \t");
16831 if (pos == 0) // We matched a prefix.
16839 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16842 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16843 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16845 std::string AsmStr = IA->getAsmString();
16847 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16848 if (!Ty || Ty->getBitWidth() % 16 != 0)
16851 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16852 SmallVector<StringRef, 4> AsmPieces;
16853 SplitString(AsmStr, AsmPieces, ";\n");
16855 switch (AsmPieces.size()) {
16856 default: return false;
16858 // FIXME: this should verify that we are targeting a 486 or better. If not,
16859 // we will turn this bswap into something that will be lowered to logical
16860 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16861 // lower so don't worry about this.
16863 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16864 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16865 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16866 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16867 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16868 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16869 // No need to check constraints, nothing other than the equivalent of
16870 // "=r,0" would be valid here.
16871 return IntrinsicLowering::LowerToByteSwap(CI);
16874 // rorw $$8, ${0:w} --> llvm.bswap.i16
16875 if (CI->getType()->isIntegerTy(16) &&
16876 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16877 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16878 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16880 const std::string &ConstraintsStr = IA->getConstraintString();
16881 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16882 std::sort(AsmPieces.begin(), AsmPieces.end());
16883 if (AsmPieces.size() == 4 &&
16884 AsmPieces[0] == "~{cc}" &&
16885 AsmPieces[1] == "~{dirflag}" &&
16886 AsmPieces[2] == "~{flags}" &&
16887 AsmPieces[3] == "~{fpsr}")
16888 return IntrinsicLowering::LowerToByteSwap(CI);
16892 if (CI->getType()->isIntegerTy(32) &&
16893 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16894 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16895 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16896 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16898 const std::string &ConstraintsStr = IA->getConstraintString();
16899 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16900 std::sort(AsmPieces.begin(), AsmPieces.end());
16901 if (AsmPieces.size() == 4 &&
16902 AsmPieces[0] == "~{cc}" &&
16903 AsmPieces[1] == "~{dirflag}" &&
16904 AsmPieces[2] == "~{flags}" &&
16905 AsmPieces[3] == "~{fpsr}")
16906 return IntrinsicLowering::LowerToByteSwap(CI);
16909 if (CI->getType()->isIntegerTy(64)) {
16910 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16911 if (Constraints.size() >= 2 &&
16912 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16913 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16914 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16915 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16916 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16917 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16918 return IntrinsicLowering::LowerToByteSwap(CI);
16928 /// getConstraintType - Given a constraint letter, return the type of
16929 /// constraint it is for this target.
16930 X86TargetLowering::ConstraintType
16931 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16932 if (Constraint.size() == 1) {
16933 switch (Constraint[0]) {
16944 return C_RegisterClass;
16968 return TargetLowering::getConstraintType(Constraint);
16971 /// Examine constraint type and operand type and determine a weight value.
16972 /// This object must already have been set up with the operand type
16973 /// and the current alternative constraint selected.
16974 TargetLowering::ConstraintWeight
16975 X86TargetLowering::getSingleConstraintMatchWeight(
16976 AsmOperandInfo &info, const char *constraint) const {
16977 ConstraintWeight weight = CW_Invalid;
16978 Value *CallOperandVal = info.CallOperandVal;
16979 // If we don't have a value, we can't do a match,
16980 // but allow it at the lowest weight.
16981 if (CallOperandVal == NULL)
16983 Type *type = CallOperandVal->getType();
16984 // Look at the constraint type.
16985 switch (*constraint) {
16987 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16998 if (CallOperandVal->getType()->isIntegerTy())
16999 weight = CW_SpecificReg;
17004 if (type->isFloatingPointTy())
17005 weight = CW_SpecificReg;
17008 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17009 weight = CW_SpecificReg;
17013 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17014 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17015 weight = CW_Register;
17018 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17019 if (C->getZExtValue() <= 31)
17020 weight = CW_Constant;
17024 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17025 if (C->getZExtValue() <= 63)
17026 weight = CW_Constant;
17030 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17031 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17032 weight = CW_Constant;
17036 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17037 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17038 weight = CW_Constant;
17042 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17043 if (C->getZExtValue() <= 3)
17044 weight = CW_Constant;
17048 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17049 if (C->getZExtValue() <= 0xff)
17050 weight = CW_Constant;
17055 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17056 weight = CW_Constant;
17060 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17061 if ((C->getSExtValue() >= -0x80000000LL) &&
17062 (C->getSExtValue() <= 0x7fffffffLL))
17063 weight = CW_Constant;
17067 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17068 if (C->getZExtValue() <= 0xffffffff)
17069 weight = CW_Constant;
17076 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17077 /// with another that has more specific requirements based on the type of the
17078 /// corresponding operand.
17079 const char *X86TargetLowering::
17080 LowerXConstraint(EVT ConstraintVT) const {
17081 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17082 // 'f' like normal targets.
17083 if (ConstraintVT.isFloatingPoint()) {
17084 if (Subtarget->hasSSE2())
17086 if (Subtarget->hasSSE1())
17090 return TargetLowering::LowerXConstraint(ConstraintVT);
17093 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17094 /// vector. If it is invalid, don't add anything to Ops.
17095 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17096 std::string &Constraint,
17097 std::vector<SDValue>&Ops,
17098 SelectionDAG &DAG) const {
17099 SDValue Result(0, 0);
17101 // Only support length 1 constraints for now.
17102 if (Constraint.length() > 1) return;
17104 char ConstraintLetter = Constraint[0];
17105 switch (ConstraintLetter) {
17108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17109 if (C->getZExtValue() <= 31) {
17110 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17117 if (C->getZExtValue() <= 63) {
17118 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17125 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17126 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17133 if (C->getZExtValue() <= 255) {
17134 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17140 // 32-bit signed value
17141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17142 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17143 C->getSExtValue())) {
17144 // Widen to 64 bits here to get it sign extended.
17145 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17148 // FIXME gcc accepts some relocatable values here too, but only in certain
17149 // memory models; it's complicated.
17154 // 32-bit unsigned value
17155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17156 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17157 C->getZExtValue())) {
17158 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17162 // FIXME gcc accepts some relocatable values here too, but only in certain
17163 // memory models; it's complicated.
17167 // Literal immediates are always ok.
17168 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17169 // Widen to 64 bits here to get it sign extended.
17170 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17174 // In any sort of PIC mode addresses need to be computed at runtime by
17175 // adding in a register or some sort of table lookup. These can't
17176 // be used as immediates.
17177 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17180 // If we are in non-pic codegen mode, we allow the address of a global (with
17181 // an optional displacement) to be used with 'i'.
17182 GlobalAddressSDNode *GA = 0;
17183 int64_t Offset = 0;
17185 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17187 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17188 Offset += GA->getOffset();
17190 } else if (Op.getOpcode() == ISD::ADD) {
17191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17192 Offset += C->getZExtValue();
17193 Op = Op.getOperand(0);
17196 } else if (Op.getOpcode() == ISD::SUB) {
17197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17198 Offset += -C->getZExtValue();
17199 Op = Op.getOperand(0);
17204 // Otherwise, this isn't something we can handle, reject it.
17208 const GlobalValue *GV = GA->getGlobal();
17209 // If we require an extra load to get this address, as in PIC mode, we
17210 // can't accept it.
17211 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17212 getTargetMachine())))
17215 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17216 GA->getValueType(0), Offset);
17221 if (Result.getNode()) {
17222 Ops.push_back(Result);
17225 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17228 std::pair<unsigned, const TargetRegisterClass*>
17229 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17231 // First, see if this is a constraint that directly corresponds to an LLVM
17233 if (Constraint.size() == 1) {
17234 // GCC Constraint Letters
17235 switch (Constraint[0]) {
17237 // TODO: Slight differences here in allocation order and leaving
17238 // RIP in the class. Do they matter any more here than they do
17239 // in the normal allocation?
17240 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17241 if (Subtarget->is64Bit()) {
17242 if (VT == MVT::i32 || VT == MVT::f32)
17243 return std::make_pair(0U, &X86::GR32RegClass);
17244 if (VT == MVT::i16)
17245 return std::make_pair(0U, &X86::GR16RegClass);
17246 if (VT == MVT::i8 || VT == MVT::i1)
17247 return std::make_pair(0U, &X86::GR8RegClass);
17248 if (VT == MVT::i64 || VT == MVT::f64)
17249 return std::make_pair(0U, &X86::GR64RegClass);
17252 // 32-bit fallthrough
17253 case 'Q': // Q_REGS
17254 if (VT == MVT::i32 || VT == MVT::f32)
17255 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17256 if (VT == MVT::i16)
17257 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17258 if (VT == MVT::i8 || VT == MVT::i1)
17259 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17260 if (VT == MVT::i64)
17261 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17263 case 'r': // GENERAL_REGS
17264 case 'l': // INDEX_REGS
17265 if (VT == MVT::i8 || VT == MVT::i1)
17266 return std::make_pair(0U, &X86::GR8RegClass);
17267 if (VT == MVT::i16)
17268 return std::make_pair(0U, &X86::GR16RegClass);
17269 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17270 return std::make_pair(0U, &X86::GR32RegClass);
17271 return std::make_pair(0U, &X86::GR64RegClass);
17272 case 'R': // LEGACY_REGS
17273 if (VT == MVT::i8 || VT == MVT::i1)
17274 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17275 if (VT == MVT::i16)
17276 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17277 if (VT == MVT::i32 || !Subtarget->is64Bit())
17278 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17279 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17280 case 'f': // FP Stack registers.
17281 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17282 // value to the correct fpstack register class.
17283 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17284 return std::make_pair(0U, &X86::RFP32RegClass);
17285 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17286 return std::make_pair(0U, &X86::RFP64RegClass);
17287 return std::make_pair(0U, &X86::RFP80RegClass);
17288 case 'y': // MMX_REGS if MMX allowed.
17289 if (!Subtarget->hasMMX()) break;
17290 return std::make_pair(0U, &X86::VR64RegClass);
17291 case 'Y': // SSE_REGS if SSE2 allowed
17292 if (!Subtarget->hasSSE2()) break;
17294 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17295 if (!Subtarget->hasSSE1()) break;
17297 switch (VT.getSimpleVT().SimpleTy) {
17299 // Scalar SSE types.
17302 return std::make_pair(0U, &X86::FR32RegClass);
17305 return std::make_pair(0U, &X86::FR64RegClass);
17313 return std::make_pair(0U, &X86::VR128RegClass);
17321 return std::make_pair(0U, &X86::VR256RegClass);
17327 // Use the default implementation in TargetLowering to convert the register
17328 // constraint into a member of a register class.
17329 std::pair<unsigned, const TargetRegisterClass*> Res;
17330 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17332 // Not found as a standard register?
17333 if (Res.second == 0) {
17334 // Map st(0) -> st(7) -> ST0
17335 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17336 tolower(Constraint[1]) == 's' &&
17337 tolower(Constraint[2]) == 't' &&
17338 Constraint[3] == '(' &&
17339 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17340 Constraint[5] == ')' &&
17341 Constraint[6] == '}') {
17343 Res.first = X86::ST0+Constraint[4]-'0';
17344 Res.second = &X86::RFP80RegClass;
17348 // GCC allows "st(0)" to be called just plain "st".
17349 if (StringRef("{st}").equals_lower(Constraint)) {
17350 Res.first = X86::ST0;
17351 Res.second = &X86::RFP80RegClass;
17356 if (StringRef("{flags}").equals_lower(Constraint)) {
17357 Res.first = X86::EFLAGS;
17358 Res.second = &X86::CCRRegClass;
17362 // 'A' means EAX + EDX.
17363 if (Constraint == "A") {
17364 Res.first = X86::EAX;
17365 Res.second = &X86::GR32_ADRegClass;
17371 // Otherwise, check to see if this is a register class of the wrong value
17372 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17373 // turn into {ax},{dx}.
17374 if (Res.second->hasType(VT))
17375 return Res; // Correct type already, nothing to do.
17377 // All of the single-register GCC register classes map their values onto
17378 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17379 // really want an 8-bit or 32-bit register, map to the appropriate register
17380 // class and return the appropriate register.
17381 if (Res.second == &X86::GR16RegClass) {
17382 if (VT == MVT::i8) {
17383 unsigned DestReg = 0;
17384 switch (Res.first) {
17386 case X86::AX: DestReg = X86::AL; break;
17387 case X86::DX: DestReg = X86::DL; break;
17388 case X86::CX: DestReg = X86::CL; break;
17389 case X86::BX: DestReg = X86::BL; break;
17392 Res.first = DestReg;
17393 Res.second = &X86::GR8RegClass;
17395 } else if (VT == MVT::i32) {
17396 unsigned DestReg = 0;
17397 switch (Res.first) {
17399 case X86::AX: DestReg = X86::EAX; break;
17400 case X86::DX: DestReg = X86::EDX; break;
17401 case X86::CX: DestReg = X86::ECX; break;
17402 case X86::BX: DestReg = X86::EBX; break;
17403 case X86::SI: DestReg = X86::ESI; break;
17404 case X86::DI: DestReg = X86::EDI; break;
17405 case X86::BP: DestReg = X86::EBP; break;
17406 case X86::SP: DestReg = X86::ESP; break;
17409 Res.first = DestReg;
17410 Res.second = &X86::GR32RegClass;
17412 } else if (VT == MVT::i64) {
17413 unsigned DestReg = 0;
17414 switch (Res.first) {
17416 case X86::AX: DestReg = X86::RAX; break;
17417 case X86::DX: DestReg = X86::RDX; break;
17418 case X86::CX: DestReg = X86::RCX; break;
17419 case X86::BX: DestReg = X86::RBX; break;
17420 case X86::SI: DestReg = X86::RSI; break;
17421 case X86::DI: DestReg = X86::RDI; break;
17422 case X86::BP: DestReg = X86::RBP; break;
17423 case X86::SP: DestReg = X86::RSP; break;
17426 Res.first = DestReg;
17427 Res.second = &X86::GR64RegClass;
17430 } else if (Res.second == &X86::FR32RegClass ||
17431 Res.second == &X86::FR64RegClass ||
17432 Res.second == &X86::VR128RegClass) {
17433 // Handle references to XMM physical registers that got mapped into the
17434 // wrong class. This can happen with constraints like {xmm0} where the
17435 // target independent register mapper will just pick the first match it can
17436 // find, ignoring the required type.
17438 if (VT == MVT::f32 || VT == MVT::i32)
17439 Res.second = &X86::FR32RegClass;
17440 else if (VT == MVT::f64 || VT == MVT::i64)
17441 Res.second = &X86::FR64RegClass;
17442 else if (X86::VR128RegClass.hasType(VT))
17443 Res.second = &X86::VR128RegClass;
17444 else if (X86::VR256RegClass.hasType(VT))
17445 Res.second = &X86::VR256RegClass;