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, not
463 // other SjLj exception interfaces are implemented and please don't build
464 // your own exception handling based on them.
465 // LLVM/Clang supports zero-cost DWARF exception handling.
466 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
470 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
471 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
473 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
474 if (Subtarget->is64Bit())
475 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
477 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
480 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
481 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
482 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
483 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
485 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
488 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
492 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
495 if (Subtarget->hasSSE1())
496 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
498 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
499 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
501 // On X86 and X86-64, atomic operations are lowered to locked instructions.
502 // Locked instructions, in turn, have implicit fence semantics (all memory
503 // operations are flushed before issuing the locked instruction, and they
504 // are not buffered), so we can fold away the common pattern of
505 // fence-atomic-fence.
506 setShouldFoldAtomicFences(true);
508 // Expand certain atomics
509 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
511 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
516 if (!Subtarget->is64Bit()) {
517 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
531 if (Subtarget->hasCmpxchg16b()) {
532 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
535 // FIXME - use subtarget debug flags
536 if (!Subtarget->isTargetDarwin() &&
537 !Subtarget->isTargetELF() &&
538 !Subtarget->isTargetCygMing()) {
539 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
542 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
544 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
546 if (Subtarget->is64Bit()) {
547 setExceptionPointerRegister(X86::RAX);
548 setExceptionSelectorRegister(X86::RDX);
550 setExceptionPointerRegister(X86::EAX);
551 setExceptionSelectorRegister(X86::EDX);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
556 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
559 setOperationAction(ISD::TRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
729 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
730 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
745 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
747 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
781 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
782 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
784 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
785 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
786 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
787 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
788 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
789 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
790 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
791 setTruncStoreAction((MVT::SimpleValueType)VT,
792 (MVT::SimpleValueType)InnerVT, Expand);
793 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
794 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
798 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
799 // with -msoft-float, disable use of MMX as well.
800 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
801 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
802 // No operations on x86mmx supported, everything uses intrinsics.
805 // MMX-sized vectors (other than x86mmx) are expected to be expanded
806 // into smaller operations.
807 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
808 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
809 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
810 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
811 setOperationAction(ISD::AND, MVT::v8i8, Expand);
812 setOperationAction(ISD::AND, MVT::v4i16, Expand);
813 setOperationAction(ISD::AND, MVT::v2i32, Expand);
814 setOperationAction(ISD::AND, MVT::v1i64, Expand);
815 setOperationAction(ISD::OR, MVT::v8i8, Expand);
816 setOperationAction(ISD::OR, MVT::v4i16, Expand);
817 setOperationAction(ISD::OR, MVT::v2i32, Expand);
818 setOperationAction(ISD::OR, MVT::v1i64, Expand);
819 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
820 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
821 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
822 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
823 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
825 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
826 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
827 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
828 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
829 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
830 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
831 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
832 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
833 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
834 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
835 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
837 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
838 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
840 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
841 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
842 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
843 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
844 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
845 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
846 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
847 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
848 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
849 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
851 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
854 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
855 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
857 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
858 // registers cannot be used even for integer operations.
859 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
860 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
861 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
862 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
864 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
865 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
866 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
867 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
868 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
869 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
870 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
871 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
872 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
874 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
875 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
876 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
877 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
878 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
879 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
880 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
882 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
883 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
884 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
885 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
887 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
893 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
894 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
895 MVT VT = (MVT::SimpleValueType)i;
896 // Do not attempt to custom lower non-power-of-2 vectors
897 if (!isPowerOf2_32(VT.getVectorNumElements()))
899 // Do not attempt to custom lower non-128-bit vectors
900 if (!VT.is128BitVector())
902 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
903 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
904 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
907 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
911 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
914 if (Subtarget->is64Bit()) {
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
919 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
920 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
921 MVT VT = (MVT::SimpleValueType)i;
923 // Do not attempt to promote non-128-bit vectors
924 if (!VT.is128BitVector())
927 setOperationAction(ISD::AND, VT, Promote);
928 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
929 setOperationAction(ISD::OR, VT, Promote);
930 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
931 setOperationAction(ISD::XOR, VT, Promote);
932 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
933 setOperationAction(ISD::LOAD, VT, Promote);
934 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
935 setOperationAction(ISD::SELECT, VT, Promote);
936 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
939 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
941 // Custom lower v2i64 and v2f64 selects.
942 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
943 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
944 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
945 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
947 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
948 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
950 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
951 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
953 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
956 if (Subtarget->hasSSE41()) {
957 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
958 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
959 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
960 setOperationAction(ISD::FRINT, MVT::f32, Legal);
961 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
962 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
963 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
964 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
965 setOperationAction(ISD::FRINT, MVT::f64, Legal);
966 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
968 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
969 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
971 // FIXME: Do we need to handle scalar-to-vector here?
972 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
974 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
975 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
976 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
977 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
978 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
980 // i8 and i16 vectors are custom , because the source register and source
981 // source memory operand types are not the same width. f32 vectors are
982 // custom since the immediate controlling the insert encodes additional
984 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
985 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
986 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
987 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
990 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
991 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
992 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
994 // FIXME: these should be Legal but thats only for the case where
995 // the index is constant. For now custom expand to deal with that.
996 if (Subtarget->is64Bit()) {
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002 if (Subtarget->hasSSE2()) {
1003 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1004 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1006 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1007 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1009 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1010 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1012 if (Subtarget->hasAVX2()) {
1013 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1014 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1016 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1017 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1019 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1021 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1022 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1024 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1025 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1027 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1031 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1032 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1033 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1034 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1035 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1036 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1037 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1039 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1040 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1041 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1043 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1044 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1045 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1046 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1047 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1048 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1049 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1050 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1052 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1053 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1054 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1055 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1056 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1057 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1058 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1059 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1061 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1062 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1063 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1065 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1067 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1068 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1070 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1071 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1073 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1074 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1076 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1077 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1078 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1079 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1081 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1082 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1083 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1085 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1086 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1087 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1088 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1090 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1091 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1092 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1093 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1094 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1095 setOperationAction(ISD::FMA, MVT::f32, Custom);
1096 setOperationAction(ISD::FMA, MVT::f64, Custom);
1099 if (Subtarget->hasAVX2()) {
1100 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1101 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1102 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1103 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1105 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1106 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1107 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1108 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1110 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1111 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1112 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1113 // Don't lower v32i8 because there is no 128-bit byte mul
1115 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1117 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1118 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1120 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1121 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1123 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1125 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1126 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1127 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1128 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1130 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1131 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1132 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1133 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1135 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1136 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1137 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1138 // Don't lower v32i8 because there is no 128-bit byte mul
1140 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1141 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1143 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1144 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1146 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1149 // Custom lower several nodes for 256-bit types.
1150 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1151 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1152 MVT VT = (MVT::SimpleValueType)i;
1154 // Extract subvector is special because the value type
1155 // (result) is 128-bit but the source is 256-bit wide.
1156 if (VT.is128BitVector())
1157 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1159 // Do not attempt to custom lower other non-256-bit vectors
1160 if (!VT.is256BitVector())
1163 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1164 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1165 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1166 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1167 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1168 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1169 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1172 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1173 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1174 MVT VT = (MVT::SimpleValueType)i;
1176 // Do not attempt to promote non-256-bit vectors
1177 if (!VT.is256BitVector())
1180 setOperationAction(ISD::AND, VT, Promote);
1181 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1182 setOperationAction(ISD::OR, VT, Promote);
1183 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1184 setOperationAction(ISD::XOR, VT, Promote);
1185 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1186 setOperationAction(ISD::LOAD, VT, Promote);
1187 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1188 setOperationAction(ISD::SELECT, VT, Promote);
1189 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1193 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1194 // of this type with custom code.
1195 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1196 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1197 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1201 // We want to custom lower some of our intrinsics.
1202 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1203 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1206 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1207 // handle type legalization for these operations here.
1209 // FIXME: We really should do custom legalization for addition and
1210 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1211 // than generic legalization for 64-bit multiplication-with-overflow, though.
1212 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1213 // Add/Sub/Mul with overflow operations are custom lowered.
1215 setOperationAction(ISD::SADDO, VT, Custom);
1216 setOperationAction(ISD::UADDO, VT, Custom);
1217 setOperationAction(ISD::SSUBO, VT, Custom);
1218 setOperationAction(ISD::USUBO, VT, Custom);
1219 setOperationAction(ISD::SMULO, VT, Custom);
1220 setOperationAction(ISD::UMULO, VT, Custom);
1223 // There are no 8-bit 3-address imul/mul instructions
1224 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1225 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1227 if (!Subtarget->is64Bit()) {
1228 // These libcalls are not available in 32-bit.
1229 setLibcallName(RTLIB::SHL_I128, 0);
1230 setLibcallName(RTLIB::SRL_I128, 0);
1231 setLibcallName(RTLIB::SRA_I128, 0);
1234 // We have target-specific dag combine patterns for the following nodes:
1235 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1236 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1237 setTargetDAGCombine(ISD::VSELECT);
1238 setTargetDAGCombine(ISD::SELECT);
1239 setTargetDAGCombine(ISD::SHL);
1240 setTargetDAGCombine(ISD::SRA);
1241 setTargetDAGCombine(ISD::SRL);
1242 setTargetDAGCombine(ISD::OR);
1243 setTargetDAGCombine(ISD::AND);
1244 setTargetDAGCombine(ISD::ADD);
1245 setTargetDAGCombine(ISD::FADD);
1246 setTargetDAGCombine(ISD::FSUB);
1247 setTargetDAGCombine(ISD::FMA);
1248 setTargetDAGCombine(ISD::SUB);
1249 setTargetDAGCombine(ISD::LOAD);
1250 setTargetDAGCombine(ISD::STORE);
1251 setTargetDAGCombine(ISD::ZERO_EXTEND);
1252 setTargetDAGCombine(ISD::ANY_EXTEND);
1253 setTargetDAGCombine(ISD::SIGN_EXTEND);
1254 setTargetDAGCombine(ISD::TRUNCATE);
1255 setTargetDAGCombine(ISD::UINT_TO_FP);
1256 setTargetDAGCombine(ISD::SINT_TO_FP);
1257 setTargetDAGCombine(ISD::SETCC);
1258 setTargetDAGCombine(ISD::FP_TO_SINT);
1259 if (Subtarget->is64Bit())
1260 setTargetDAGCombine(ISD::MUL);
1261 setTargetDAGCombine(ISD::XOR);
1263 computeRegisterProperties();
1265 // On Darwin, -Os means optimize for size without hurting performance,
1266 // do not reduce the limit.
1267 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1268 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1269 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1270 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1271 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1272 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1273 setPrefLoopAlignment(4); // 2^4 bytes.
1274 benefitFromCodePlacementOpt = true;
1276 // Predictable cmov don't hurt on atom because it's in-order.
1277 predictableSelectIsExpensive = !Subtarget->isAtom();
1279 setPrefFunctionAlignment(4); // 2^4 bytes.
1283 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1284 if (!VT.isVector()) return MVT::i8;
1285 return VT.changeVectorElementTypeToInteger();
1289 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1290 /// the desired ByVal argument alignment.
1291 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1294 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1295 if (VTy->getBitWidth() == 128)
1297 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1298 unsigned EltAlign = 0;
1299 getMaxByValAlign(ATy->getElementType(), EltAlign);
1300 if (EltAlign > MaxAlign)
1301 MaxAlign = EltAlign;
1302 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1303 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1304 unsigned EltAlign = 0;
1305 getMaxByValAlign(STy->getElementType(i), EltAlign);
1306 if (EltAlign > MaxAlign)
1307 MaxAlign = EltAlign;
1314 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1315 /// function arguments in the caller parameter area. For X86, aggregates
1316 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1317 /// are at 4-byte boundaries.
1318 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1319 if (Subtarget->is64Bit()) {
1320 // Max of 8 and alignment of type.
1321 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1328 if (Subtarget->hasSSE1())
1329 getMaxByValAlign(Ty, Align);
1333 /// getOptimalMemOpType - Returns the target specific optimal type for load
1334 /// and store operations as a result of memset, memcpy, and memmove
1335 /// lowering. If DstAlign is zero that means it's safe to destination
1336 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1337 /// means there isn't a need to check it against alignment requirement,
1338 /// probably because the source does not need to be loaded. If
1339 /// 'IsZeroVal' is true, that means it's safe to return a
1340 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1341 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1342 /// constant so it does not need to be loaded.
1343 /// It returns EVT::Other if the type should be determined using generic
1344 /// target-independent logic.
1346 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1347 unsigned DstAlign, unsigned SrcAlign,
1350 MachineFunction &MF) const {
1351 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1352 // linux. This is because the stack realignment code can't handle certain
1353 // cases like PR2962. This should be removed when PR2962 is fixed.
1354 const Function *F = MF.getFunction();
1356 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1358 (Subtarget->isUnalignedMemAccessFast() ||
1359 ((DstAlign == 0 || DstAlign >= 16) &&
1360 (SrcAlign == 0 || SrcAlign >= 16))) &&
1361 Subtarget->getStackAlignment() >= 16) {
1362 if (Subtarget->getStackAlignment() >= 32) {
1363 if (Subtarget->hasAVX2())
1365 if (Subtarget->hasAVX())
1368 if (Subtarget->hasSSE2())
1370 if (Subtarget->hasSSE1())
1372 } else if (!MemcpyStrSrc && Size >= 8 &&
1373 !Subtarget->is64Bit() &&
1374 Subtarget->getStackAlignment() >= 8 &&
1375 Subtarget->hasSSE2()) {
1376 // Do not use f64 to lower memcpy if source is string constant. It's
1377 // better to use i32 to avoid the loads.
1381 if (Subtarget->is64Bit() && Size >= 8)
1386 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1387 /// current function. The returned value is a member of the
1388 /// MachineJumpTableInfo::JTEntryKind enum.
1389 unsigned X86TargetLowering::getJumpTableEncoding() const {
1390 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1392 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1393 Subtarget->isPICStyleGOT())
1394 return MachineJumpTableInfo::EK_Custom32;
1396 // Otherwise, use the normal jump table encoding heuristics.
1397 return TargetLowering::getJumpTableEncoding();
1401 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1402 const MachineBasicBlock *MBB,
1403 unsigned uid,MCContext &Ctx) const{
1404 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1405 Subtarget->isPICStyleGOT());
1406 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1408 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1409 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1412 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1414 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1415 SelectionDAG &DAG) const {
1416 if (!Subtarget->is64Bit())
1417 // This doesn't have DebugLoc associated with it, but is not really the
1418 // same as a Register.
1419 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1423 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1424 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1426 const MCExpr *X86TargetLowering::
1427 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1428 MCContext &Ctx) const {
1429 // X86-64 uses RIP relative addressing based on the jump table label.
1430 if (Subtarget->isPICStyleRIPRel())
1431 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1433 // Otherwise, the reference is relative to the PIC base.
1434 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1437 // FIXME: Why this routine is here? Move to RegInfo!
1438 std::pair<const TargetRegisterClass*, uint8_t>
1439 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1440 const TargetRegisterClass *RRC = 0;
1442 switch (VT.getSimpleVT().SimpleTy) {
1444 return TargetLowering::findRepresentativeClass(VT);
1445 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1446 RRC = Subtarget->is64Bit() ?
1447 (const TargetRegisterClass*)&X86::GR64RegClass :
1448 (const TargetRegisterClass*)&X86::GR32RegClass;
1451 RRC = &X86::VR64RegClass;
1453 case MVT::f32: case MVT::f64:
1454 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1455 case MVT::v4f32: case MVT::v2f64:
1456 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1458 RRC = &X86::VR128RegClass;
1461 return std::make_pair(RRC, Cost);
1464 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1465 unsigned &Offset) const {
1466 if (!Subtarget->isTargetLinux())
1469 if (Subtarget->is64Bit()) {
1470 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1472 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1485 //===----------------------------------------------------------------------===//
1486 // Return Value Calling Convention Implementation
1487 //===----------------------------------------------------------------------===//
1489 #include "X86GenCallingConv.inc"
1492 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1493 MachineFunction &MF, bool isVarArg,
1494 const SmallVectorImpl<ISD::OutputArg> &Outs,
1495 LLVMContext &Context) const {
1496 SmallVector<CCValAssign, 16> RVLocs;
1497 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1499 return CCInfo.CheckReturn(Outs, RetCC_X86);
1503 X86TargetLowering::LowerReturn(SDValue Chain,
1504 CallingConv::ID CallConv, bool isVarArg,
1505 const SmallVectorImpl<ISD::OutputArg> &Outs,
1506 const SmallVectorImpl<SDValue> &OutVals,
1507 DebugLoc dl, SelectionDAG &DAG) const {
1508 MachineFunction &MF = DAG.getMachineFunction();
1509 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1511 SmallVector<CCValAssign, 16> RVLocs;
1512 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1513 RVLocs, *DAG.getContext());
1514 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1516 // Add the regs to the liveout set for the function.
1517 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1518 for (unsigned i = 0; i != RVLocs.size(); ++i)
1519 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1520 MRI.addLiveOut(RVLocs[i].getLocReg());
1524 SmallVector<SDValue, 6> RetOps;
1525 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1526 // Operand #1 = Bytes To Pop
1527 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1530 // Copy the result values into the output registers.
1531 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1532 CCValAssign &VA = RVLocs[i];
1533 assert(VA.isRegLoc() && "Can only return in registers!");
1534 SDValue ValToCopy = OutVals[i];
1535 EVT ValVT = ValToCopy.getValueType();
1537 // Promote values to the appropriate types
1538 if (VA.getLocInfo() == CCValAssign::SExt)
1539 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1540 else if (VA.getLocInfo() == CCValAssign::ZExt)
1541 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1542 else if (VA.getLocInfo() == CCValAssign::AExt)
1543 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1544 else if (VA.getLocInfo() == CCValAssign::BCvt)
1545 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1547 // If this is x86-64, and we disabled SSE, we can't return FP values,
1548 // or SSE or MMX vectors.
1549 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1550 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1551 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1552 report_fatal_error("SSE register return with SSE disabled");
1554 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1555 // llvm-gcc has never done it right and no one has noticed, so this
1556 // should be OK for now.
1557 if (ValVT == MVT::f64 &&
1558 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1559 report_fatal_error("SSE2 register return with SSE2 disabled");
1561 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1562 // the RET instruction and handled by the FP Stackifier.
1563 if (VA.getLocReg() == X86::ST0 ||
1564 VA.getLocReg() == X86::ST1) {
1565 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1566 // change the value to the FP stack register class.
1567 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1568 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1569 RetOps.push_back(ValToCopy);
1570 // Don't emit a copytoreg.
1574 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1575 // which is returned in RAX / RDX.
1576 if (Subtarget->is64Bit()) {
1577 if (ValVT == MVT::x86mmx) {
1578 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1579 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1580 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1582 // If we don't have SSE2 available, convert to v4f32 so the generated
1583 // register is legal.
1584 if (!Subtarget->hasSSE2())
1585 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1590 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1591 Flag = Chain.getValue(1);
1594 // The x86-64 ABI for returning structs by value requires that we copy
1595 // the sret argument into %rax for the return. We saved the argument into
1596 // a virtual register in the entry block, so now we copy the value out
1598 if (Subtarget->is64Bit() &&
1599 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1600 MachineFunction &MF = DAG.getMachineFunction();
1601 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1602 unsigned Reg = FuncInfo->getSRetReturnReg();
1604 "SRetReturnReg should have been set in LowerFormalArguments().");
1605 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1607 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1608 Flag = Chain.getValue(1);
1610 // RAX now acts like a return value.
1611 MRI.addLiveOut(X86::RAX);
1614 RetOps[0] = Chain; // Update chain.
1616 // Add the flag if we have it.
1618 RetOps.push_back(Flag);
1620 return DAG.getNode(X86ISD::RET_FLAG, dl,
1621 MVT::Other, &RetOps[0], RetOps.size());
1624 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1625 if (N->getNumValues() != 1)
1627 if (!N->hasNUsesOfValue(1, 0))
1630 SDValue TCChain = Chain;
1631 SDNode *Copy = *N->use_begin();
1632 if (Copy->getOpcode() == ISD::CopyToReg) {
1633 // If the copy has a glue operand, we conservatively assume it isn't safe to
1634 // perform a tail call.
1635 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1637 TCChain = Copy->getOperand(0);
1638 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1641 bool HasRet = false;
1642 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1644 if (UI->getOpcode() != X86ISD::RET_FLAG)
1657 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1658 ISD::NodeType ExtendKind) const {
1660 // TODO: Is this also valid on 32-bit?
1661 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1662 ReturnMVT = MVT::i8;
1664 ReturnMVT = MVT::i32;
1666 EVT MinVT = getRegisterType(Context, ReturnMVT);
1667 return VT.bitsLT(MinVT) ? MinVT : VT;
1670 /// LowerCallResult - Lower the result values of a call into the
1671 /// appropriate copies out of appropriate physical registers.
1674 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1675 CallingConv::ID CallConv, bool isVarArg,
1676 const SmallVectorImpl<ISD::InputArg> &Ins,
1677 DebugLoc dl, SelectionDAG &DAG,
1678 SmallVectorImpl<SDValue> &InVals) const {
1680 // Assign locations to each value returned by this call.
1681 SmallVector<CCValAssign, 16> RVLocs;
1682 bool Is64Bit = Subtarget->is64Bit();
1683 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1684 getTargetMachine(), RVLocs, *DAG.getContext());
1685 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1687 // Copy all of the result registers out of their specified physreg.
1688 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1689 CCValAssign &VA = RVLocs[i];
1690 EVT CopyVT = VA.getValVT();
1692 // If this is x86-64, and we disabled SSE, we can't return FP values
1693 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1694 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1695 report_fatal_error("SSE register return with SSE disabled");
1700 // If this is a call to a function that returns an fp value on the floating
1701 // point stack, we must guarantee the value is popped from the stack, so
1702 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1703 // if the return value is not used. We use the FpPOP_RETVAL instruction
1705 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1706 // If we prefer to use the value in xmm registers, copy it out as f80 and
1707 // use a truncate to move it from fp stack reg to xmm reg.
1708 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1709 SDValue Ops[] = { Chain, InFlag };
1710 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1711 MVT::Other, MVT::Glue, Ops, 2), 1);
1712 Val = Chain.getValue(0);
1714 // Round the f80 to the right size, which also moves it to the appropriate
1716 if (CopyVT != VA.getValVT())
1717 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1718 // This truncation won't change the value.
1719 DAG.getIntPtrConstant(1));
1721 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1722 CopyVT, InFlag).getValue(1);
1723 Val = Chain.getValue(0);
1725 InFlag = Chain.getValue(2);
1726 InVals.push_back(Val);
1733 //===----------------------------------------------------------------------===//
1734 // C & StdCall & Fast Calling Convention implementation
1735 //===----------------------------------------------------------------------===//
1736 // StdCall calling convention seems to be standard for many Windows' API
1737 // routines and around. It differs from C calling convention just a little:
1738 // callee should clean up the stack, not caller. Symbols should be also
1739 // decorated in some fancy way :) It doesn't support any vector arguments.
1740 // For info on fast calling convention see Fast Calling Convention (tail call)
1741 // implementation LowerX86_32FastCCCallTo.
1743 /// CallIsStructReturn - Determines whether a call uses struct return
1745 enum StructReturnType {
1750 static StructReturnType
1751 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1753 return NotStructReturn;
1755 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1756 if (!Flags.isSRet())
1757 return NotStructReturn;
1758 if (Flags.isInReg())
1759 return RegStructReturn;
1760 return StackStructReturn;
1763 /// ArgsAreStructReturn - Determines whether a function uses struct
1764 /// return semantics.
1765 static StructReturnType
1766 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1768 return NotStructReturn;
1770 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1771 if (!Flags.isSRet())
1772 return NotStructReturn;
1773 if (Flags.isInReg())
1774 return RegStructReturn;
1775 return StackStructReturn;
1778 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1779 /// by "Src" to address "Dst" with size and alignment information specified by
1780 /// the specific parameter attribute. The copy will be passed as a byval
1781 /// function parameter.
1783 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1784 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1786 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1788 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1789 /*isVolatile*/false, /*AlwaysInline=*/true,
1790 MachinePointerInfo(), MachinePointerInfo());
1793 /// IsTailCallConvention - Return true if the calling convention is one that
1794 /// supports tail call optimization.
1795 static bool IsTailCallConvention(CallingConv::ID CC) {
1796 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1799 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1800 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1804 CallingConv::ID CalleeCC = CS.getCallingConv();
1805 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1811 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1812 /// a tailcall target by changing its ABI.
1813 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1814 bool GuaranteedTailCallOpt) {
1815 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1819 X86TargetLowering::LowerMemArgument(SDValue Chain,
1820 CallingConv::ID CallConv,
1821 const SmallVectorImpl<ISD::InputArg> &Ins,
1822 DebugLoc dl, SelectionDAG &DAG,
1823 const CCValAssign &VA,
1824 MachineFrameInfo *MFI,
1826 // Create the nodes corresponding to a load from this parameter slot.
1827 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1828 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1829 getTargetMachine().Options.GuaranteedTailCallOpt);
1830 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1833 // If value is passed by pointer we have address passed instead of the value
1835 if (VA.getLocInfo() == CCValAssign::Indirect)
1836 ValVT = VA.getLocVT();
1838 ValVT = VA.getValVT();
1840 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1841 // changed with more analysis.
1842 // In case of tail call optimization mark all arguments mutable. Since they
1843 // could be overwritten by lowering of arguments in case of a tail call.
1844 if (Flags.isByVal()) {
1845 unsigned Bytes = Flags.getByValSize();
1846 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1847 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1848 return DAG.getFrameIndex(FI, getPointerTy());
1850 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1851 VA.getLocMemOffset(), isImmutable);
1852 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1853 return DAG.getLoad(ValVT, dl, Chain, FIN,
1854 MachinePointerInfo::getFixedStack(FI),
1855 false, false, false, 0);
1860 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1861 CallingConv::ID CallConv,
1863 const SmallVectorImpl<ISD::InputArg> &Ins,
1866 SmallVectorImpl<SDValue> &InVals)
1868 MachineFunction &MF = DAG.getMachineFunction();
1869 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1871 const Function* Fn = MF.getFunction();
1872 if (Fn->hasExternalLinkage() &&
1873 Subtarget->isTargetCygMing() &&
1874 Fn->getName() == "main")
1875 FuncInfo->setForceFramePointer(true);
1877 MachineFrameInfo *MFI = MF.getFrameInfo();
1878 bool Is64Bit = Subtarget->is64Bit();
1879 bool IsWindows = Subtarget->isTargetWindows();
1880 bool IsWin64 = Subtarget->isTargetWin64();
1882 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1883 "Var args not supported with calling convention fastcc or ghc");
1885 // Assign locations to all of the incoming arguments.
1886 SmallVector<CCValAssign, 16> ArgLocs;
1887 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1888 ArgLocs, *DAG.getContext());
1890 // Allocate shadow area for Win64
1892 CCInfo.AllocateStack(32, 8);
1895 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1897 unsigned LastVal = ~0U;
1899 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1900 CCValAssign &VA = ArgLocs[i];
1901 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1903 assert(VA.getValNo() != LastVal &&
1904 "Don't support value assigned to multiple locs yet");
1906 LastVal = VA.getValNo();
1908 if (VA.isRegLoc()) {
1909 EVT RegVT = VA.getLocVT();
1910 const TargetRegisterClass *RC;
1911 if (RegVT == MVT::i32)
1912 RC = &X86::GR32RegClass;
1913 else if (Is64Bit && RegVT == MVT::i64)
1914 RC = &X86::GR64RegClass;
1915 else if (RegVT == MVT::f32)
1916 RC = &X86::FR32RegClass;
1917 else if (RegVT == MVT::f64)
1918 RC = &X86::FR64RegClass;
1919 else if (RegVT.is256BitVector())
1920 RC = &X86::VR256RegClass;
1921 else if (RegVT.is128BitVector())
1922 RC = &X86::VR128RegClass;
1923 else if (RegVT == MVT::x86mmx)
1924 RC = &X86::VR64RegClass;
1926 llvm_unreachable("Unknown argument type!");
1928 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1929 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1931 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1932 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1934 if (VA.getLocInfo() == CCValAssign::SExt)
1935 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1936 DAG.getValueType(VA.getValVT()));
1937 else if (VA.getLocInfo() == CCValAssign::ZExt)
1938 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1939 DAG.getValueType(VA.getValVT()));
1940 else if (VA.getLocInfo() == CCValAssign::BCvt)
1941 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1943 if (VA.isExtInLoc()) {
1944 // Handle MMX values passed in XMM regs.
1945 if (RegVT.isVector()) {
1946 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1949 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1952 assert(VA.isMemLoc());
1953 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1956 // If value is passed via pointer - do a load.
1957 if (VA.getLocInfo() == CCValAssign::Indirect)
1958 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1959 MachinePointerInfo(), false, false, false, 0);
1961 InVals.push_back(ArgValue);
1964 // The x86-64 ABI for returning structs by value requires that we copy
1965 // the sret argument into %rax for the return. Save the argument into
1966 // a virtual register so that we can access it from the return points.
1967 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1968 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1969 unsigned Reg = FuncInfo->getSRetReturnReg();
1971 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1972 FuncInfo->setSRetReturnReg(Reg);
1974 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1975 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1978 unsigned StackSize = CCInfo.getNextStackOffset();
1979 // Align stack specially for tail calls.
1980 if (FuncIsMadeTailCallSafe(CallConv,
1981 MF.getTarget().Options.GuaranteedTailCallOpt))
1982 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1984 // If the function takes variable number of arguments, make a frame index for
1985 // the start of the first vararg value... for expansion of llvm.va_start.
1987 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1988 CallConv != CallingConv::X86_ThisCall)) {
1989 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1992 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1994 // FIXME: We should really autogenerate these arrays
1995 static const uint16_t GPR64ArgRegsWin64[] = {
1996 X86::RCX, X86::RDX, X86::R8, X86::R9
1998 static const uint16_t GPR64ArgRegs64Bit[] = {
1999 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2001 static const uint16_t XMMArgRegs64Bit[] = {
2002 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2003 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2005 const uint16_t *GPR64ArgRegs;
2006 unsigned NumXMMRegs = 0;
2009 // The XMM registers which might contain var arg parameters are shadowed
2010 // in their paired GPR. So we only need to save the GPR to their home
2012 TotalNumIntRegs = 4;
2013 GPR64ArgRegs = GPR64ArgRegsWin64;
2015 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2016 GPR64ArgRegs = GPR64ArgRegs64Bit;
2018 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2021 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2024 bool NoImplicitFloatOps = Fn->getFnAttributes().
2025 hasAttribute(Attributes::NoImplicitFloat);
2026 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2027 "SSE register cannot be used when SSE is disabled!");
2028 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2029 NoImplicitFloatOps) &&
2030 "SSE register cannot be used when SSE is disabled!");
2031 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2032 !Subtarget->hasSSE1())
2033 // Kernel mode asks for SSE to be disabled, so don't push them
2035 TotalNumXMMRegs = 0;
2038 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2039 // Get to the caller-allocated home save location. Add 8 to account
2040 // for the return address.
2041 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2042 FuncInfo->setRegSaveFrameIndex(
2043 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2044 // Fixup to set vararg frame on shadow area (4 x i64).
2046 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2048 // For X86-64, if there are vararg parameters that are passed via
2049 // registers, then we must store them to their spots on the stack so
2050 // they may be loaded by deferencing the result of va_next.
2051 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2052 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2053 FuncInfo->setRegSaveFrameIndex(
2054 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2058 // Store the integer parameter registers.
2059 SmallVector<SDValue, 8> MemOps;
2060 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2062 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2063 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2064 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2065 DAG.getIntPtrConstant(Offset));
2066 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2067 &X86::GR64RegClass);
2068 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2070 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2071 MachinePointerInfo::getFixedStack(
2072 FuncInfo->getRegSaveFrameIndex(), Offset),
2074 MemOps.push_back(Store);
2078 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2079 // Now store the XMM (fp + vector) parameter registers.
2080 SmallVector<SDValue, 11> SaveXMMOps;
2081 SaveXMMOps.push_back(Chain);
2083 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2084 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2085 SaveXMMOps.push_back(ALVal);
2087 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2088 FuncInfo->getRegSaveFrameIndex()));
2089 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2090 FuncInfo->getVarArgsFPOffset()));
2092 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2093 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2094 &X86::VR128RegClass);
2095 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2096 SaveXMMOps.push_back(Val);
2098 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2100 &SaveXMMOps[0], SaveXMMOps.size()));
2103 if (!MemOps.empty())
2104 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2105 &MemOps[0], MemOps.size());
2109 // Some CCs need callee pop.
2110 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2111 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2112 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2114 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2115 // If this is an sret function, the return should pop the hidden pointer.
2116 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2117 argsAreStructReturn(Ins) == StackStructReturn)
2118 FuncInfo->setBytesToPopOnReturn(4);
2122 // RegSaveFrameIndex is X86-64 only.
2123 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2124 if (CallConv == CallingConv::X86_FastCall ||
2125 CallConv == CallingConv::X86_ThisCall)
2126 // fastcc functions can't have varargs.
2127 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2130 FuncInfo->setArgumentStackSize(StackSize);
2136 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2137 SDValue StackPtr, SDValue Arg,
2138 DebugLoc dl, SelectionDAG &DAG,
2139 const CCValAssign &VA,
2140 ISD::ArgFlagsTy Flags) const {
2141 unsigned LocMemOffset = VA.getLocMemOffset();
2142 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2143 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2144 if (Flags.isByVal())
2145 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2147 return DAG.getStore(Chain, dl, Arg, PtrOff,
2148 MachinePointerInfo::getStack(LocMemOffset),
2152 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2153 /// optimization is performed and it is required.
2155 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2156 SDValue &OutRetAddr, SDValue Chain,
2157 bool IsTailCall, bool Is64Bit,
2158 int FPDiff, DebugLoc dl) const {
2159 // Adjust the Return address stack slot.
2160 EVT VT = getPointerTy();
2161 OutRetAddr = getReturnAddressFrameIndex(DAG);
2163 // Load the "old" Return address.
2164 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2165 false, false, false, 0);
2166 return SDValue(OutRetAddr.getNode(), 1);
2169 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2170 /// optimization is performed and it is required (FPDiff!=0).
2172 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2173 SDValue Chain, SDValue RetAddrFrIdx,
2174 bool Is64Bit, int FPDiff, DebugLoc dl) {
2175 // Store the return address to the appropriate stack slot.
2176 if (!FPDiff) return Chain;
2177 // Calculate the new stack slot for the return address.
2178 int SlotSize = Is64Bit ? 8 : 4;
2179 int NewReturnAddrFI =
2180 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2181 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2182 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2183 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2184 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2190 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2191 SmallVectorImpl<SDValue> &InVals) const {
2192 SelectionDAG &DAG = CLI.DAG;
2193 DebugLoc &dl = CLI.DL;
2194 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2195 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2196 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2197 SDValue Chain = CLI.Chain;
2198 SDValue Callee = CLI.Callee;
2199 CallingConv::ID CallConv = CLI.CallConv;
2200 bool &isTailCall = CLI.IsTailCall;
2201 bool isVarArg = CLI.IsVarArg;
2203 MachineFunction &MF = DAG.getMachineFunction();
2204 bool Is64Bit = Subtarget->is64Bit();
2205 bool IsWin64 = Subtarget->isTargetWin64();
2206 bool IsWindows = Subtarget->isTargetWindows();
2207 StructReturnType SR = callIsStructReturn(Outs);
2208 bool IsSibcall = false;
2210 if (MF.getTarget().Options.DisableTailCalls)
2214 // Check if it's really possible to do a tail call.
2215 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2216 isVarArg, SR != NotStructReturn,
2217 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2218 Outs, OutVals, Ins, DAG);
2220 // Sibcalls are automatically detected tailcalls which do not require
2222 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2229 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2230 "Var args not supported with calling convention fastcc or ghc");
2232 // Analyze operands of the call, assigning locations to each operand.
2233 SmallVector<CCValAssign, 16> ArgLocs;
2234 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2235 ArgLocs, *DAG.getContext());
2237 // Allocate shadow area for Win64
2239 CCInfo.AllocateStack(32, 8);
2242 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2244 // Get a count of how many bytes are to be pushed on the stack.
2245 unsigned NumBytes = CCInfo.getNextStackOffset();
2247 // This is a sibcall. The memory operands are available in caller's
2248 // own caller's stack.
2250 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2251 IsTailCallConvention(CallConv))
2252 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2255 if (isTailCall && !IsSibcall) {
2256 // Lower arguments at fp - stackoffset + fpdiff.
2257 unsigned NumBytesCallerPushed =
2258 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2259 FPDiff = NumBytesCallerPushed - NumBytes;
2261 // Set the delta of movement of the returnaddr stackslot.
2262 // But only set if delta is greater than previous delta.
2263 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2264 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2268 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2270 SDValue RetAddrFrIdx;
2271 // Load return address for tail calls.
2272 if (isTailCall && FPDiff)
2273 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2274 Is64Bit, FPDiff, dl);
2276 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2277 SmallVector<SDValue, 8> MemOpChains;
2280 // Walk the register/memloc assignments, inserting copies/loads. In the case
2281 // of tail call optimization arguments are handle later.
2282 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2283 CCValAssign &VA = ArgLocs[i];
2284 EVT RegVT = VA.getLocVT();
2285 SDValue Arg = OutVals[i];
2286 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2287 bool isByVal = Flags.isByVal();
2289 // Promote the value if needed.
2290 switch (VA.getLocInfo()) {
2291 default: llvm_unreachable("Unknown loc info!");
2292 case CCValAssign::Full: break;
2293 case CCValAssign::SExt:
2294 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2296 case CCValAssign::ZExt:
2297 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2299 case CCValAssign::AExt:
2300 if (RegVT.is128BitVector()) {
2301 // Special case: passing MMX values in XMM registers.
2302 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2303 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2304 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2306 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2308 case CCValAssign::BCvt:
2309 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2311 case CCValAssign::Indirect: {
2312 // Store the argument.
2313 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2314 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2315 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2316 MachinePointerInfo::getFixedStack(FI),
2323 if (VA.isRegLoc()) {
2324 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2325 if (isVarArg && IsWin64) {
2326 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2327 // shadow reg if callee is a varargs function.
2328 unsigned ShadowReg = 0;
2329 switch (VA.getLocReg()) {
2330 case X86::XMM0: ShadowReg = X86::RCX; break;
2331 case X86::XMM1: ShadowReg = X86::RDX; break;
2332 case X86::XMM2: ShadowReg = X86::R8; break;
2333 case X86::XMM3: ShadowReg = X86::R9; break;
2336 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2338 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2339 assert(VA.isMemLoc());
2340 if (StackPtr.getNode() == 0)
2341 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2342 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2343 dl, DAG, VA, Flags));
2347 if (!MemOpChains.empty())
2348 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2349 &MemOpChains[0], MemOpChains.size());
2351 if (Subtarget->isPICStyleGOT()) {
2352 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2355 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2356 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2358 // If we are tail calling and generating PIC/GOT style code load the
2359 // address of the callee into ECX. The value in ecx is used as target of
2360 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2361 // for tail calls on PIC/GOT architectures. Normally we would just put the
2362 // address of GOT into ebx and then call target@PLT. But for tail calls
2363 // ebx would be restored (since ebx is callee saved) before jumping to the
2366 // Note: The actual moving to ECX is done further down.
2367 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2368 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2369 !G->getGlobal()->hasProtectedVisibility())
2370 Callee = LowerGlobalAddress(Callee, DAG);
2371 else if (isa<ExternalSymbolSDNode>(Callee))
2372 Callee = LowerExternalSymbol(Callee, DAG);
2376 if (Is64Bit && isVarArg && !IsWin64) {
2377 // From AMD64 ABI document:
2378 // For calls that may call functions that use varargs or stdargs
2379 // (prototype-less calls or calls to functions containing ellipsis (...) in
2380 // the declaration) %al is used as hidden argument to specify the number
2381 // of SSE registers used. The contents of %al do not need to match exactly
2382 // the number of registers, but must be an ubound on the number of SSE
2383 // registers used and is in the range 0 - 8 inclusive.
2385 // Count the number of XMM registers allocated.
2386 static const uint16_t XMMArgRegs[] = {
2387 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2388 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2390 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2391 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2392 && "SSE registers cannot be used when SSE is disabled");
2394 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2395 DAG.getConstant(NumXMMRegs, MVT::i8)));
2398 // For tail calls lower the arguments to the 'real' stack slot.
2400 // Force all the incoming stack arguments to be loaded from the stack
2401 // before any new outgoing arguments are stored to the stack, because the
2402 // outgoing stack slots may alias the incoming argument stack slots, and
2403 // the alias isn't otherwise explicit. This is slightly more conservative
2404 // than necessary, because it means that each store effectively depends
2405 // on every argument instead of just those arguments it would clobber.
2406 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2408 SmallVector<SDValue, 8> MemOpChains2;
2411 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2412 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2413 CCValAssign &VA = ArgLocs[i];
2416 assert(VA.isMemLoc());
2417 SDValue Arg = OutVals[i];
2418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419 // Create frame index.
2420 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2421 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2422 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2423 FIN = DAG.getFrameIndex(FI, getPointerTy());
2425 if (Flags.isByVal()) {
2426 // Copy relative to framepointer.
2427 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2428 if (StackPtr.getNode() == 0)
2429 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2431 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2433 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2437 // Store relative to framepointer.
2438 MemOpChains2.push_back(
2439 DAG.getStore(ArgChain, dl, Arg, FIN,
2440 MachinePointerInfo::getFixedStack(FI),
2446 if (!MemOpChains2.empty())
2447 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2448 &MemOpChains2[0], MemOpChains2.size());
2450 // Store the return address to the appropriate stack slot.
2451 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2455 // Build a sequence of copy-to-reg nodes chained together with token chain
2456 // and flag operands which copy the outgoing args into registers.
2458 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2459 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2460 RegsToPass[i].second, InFlag);
2461 InFlag = Chain.getValue(1);
2464 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2465 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2466 // In the 64-bit large code model, we have to make all calls
2467 // through a register, since the call instruction's 32-bit
2468 // pc-relative offset may not be large enough to hold the whole
2470 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2471 // If the callee is a GlobalAddress node (quite common, every direct call
2472 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2475 // We should use extra load for direct calls to dllimported functions in
2477 const GlobalValue *GV = G->getGlobal();
2478 if (!GV->hasDLLImportLinkage()) {
2479 unsigned char OpFlags = 0;
2480 bool ExtraLoad = false;
2481 unsigned WrapperKind = ISD::DELETED_NODE;
2483 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2484 // external symbols most go through the PLT in PIC mode. If the symbol
2485 // has hidden or protected visibility, or if it is static or local, then
2486 // we don't need to use the PLT - we can directly call it.
2487 if (Subtarget->isTargetELF() &&
2488 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2489 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2490 OpFlags = X86II::MO_PLT;
2491 } else if (Subtarget->isPICStyleStubAny() &&
2492 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2493 (!Subtarget->getTargetTriple().isMacOSX() ||
2494 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2495 // PC-relative references to external symbols should go through $stub,
2496 // unless we're building with the leopard linker or later, which
2497 // automatically synthesizes these stubs.
2498 OpFlags = X86II::MO_DARWIN_STUB;
2499 } else if (Subtarget->isPICStyleRIPRel() &&
2500 isa<Function>(GV) &&
2501 cast<Function>(GV)->getFnAttributes().
2502 hasAttribute(Attributes::NonLazyBind)) {
2503 // If the function is marked as non-lazy, generate an indirect call
2504 // which loads from the GOT directly. This avoids runtime overhead
2505 // at the cost of eager binding (and one extra byte of encoding).
2506 OpFlags = X86II::MO_GOTPCREL;
2507 WrapperKind = X86ISD::WrapperRIP;
2511 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2512 G->getOffset(), OpFlags);
2514 // Add a wrapper if needed.
2515 if (WrapperKind != ISD::DELETED_NODE)
2516 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2517 // Add extra indirection if needed.
2519 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2520 MachinePointerInfo::getGOT(),
2521 false, false, false, 0);
2523 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2524 unsigned char OpFlags = 0;
2526 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2527 // external symbols should go through the PLT.
2528 if (Subtarget->isTargetELF() &&
2529 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2530 OpFlags = X86II::MO_PLT;
2531 } else if (Subtarget->isPICStyleStubAny() &&
2532 (!Subtarget->getTargetTriple().isMacOSX() ||
2533 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2534 // PC-relative references to external symbols should go through $stub,
2535 // unless we're building with the leopard linker or later, which
2536 // automatically synthesizes these stubs.
2537 OpFlags = X86II::MO_DARWIN_STUB;
2540 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2544 // Returns a chain & a flag for retval copy to use.
2545 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2546 SmallVector<SDValue, 8> Ops;
2548 if (!IsSibcall && isTailCall) {
2549 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2550 DAG.getIntPtrConstant(0, true), InFlag);
2551 InFlag = Chain.getValue(1);
2554 Ops.push_back(Chain);
2555 Ops.push_back(Callee);
2558 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2560 // Add argument registers to the end of the list so that they are known live
2562 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2563 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2564 RegsToPass[i].second.getValueType()));
2566 // Add a register mask operand representing the call-preserved registers.
2567 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2568 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2569 assert(Mask && "Missing call preserved mask for calling convention");
2570 Ops.push_back(DAG.getRegisterMask(Mask));
2572 if (InFlag.getNode())
2573 Ops.push_back(InFlag);
2577 //// If this is the first return lowered for this function, add the regs
2578 //// to the liveout set for the function.
2579 // This isn't right, although it's probably harmless on x86; liveouts
2580 // should be computed from returns not tail calls. Consider a void
2581 // function making a tail call to a function returning int.
2582 return DAG.getNode(X86ISD::TC_RETURN, dl,
2583 NodeTys, &Ops[0], Ops.size());
2586 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2587 InFlag = Chain.getValue(1);
2589 // Create the CALLSEQ_END node.
2590 unsigned NumBytesForCalleeToPush;
2591 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2592 getTargetMachine().Options.GuaranteedTailCallOpt))
2593 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2594 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2595 SR == StackStructReturn)
2596 // If this is a call to a struct-return function, the callee
2597 // pops the hidden struct pointer, so we have to push it back.
2598 // This is common for Darwin/X86, Linux & Mingw32 targets.
2599 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2600 NumBytesForCalleeToPush = 4;
2602 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2604 // Returns a flag for retval copy to use.
2606 Chain = DAG.getCALLSEQ_END(Chain,
2607 DAG.getIntPtrConstant(NumBytes, true),
2608 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2611 InFlag = Chain.getValue(1);
2614 // Handle result values, copying them out of physregs into vregs that we
2616 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2617 Ins, dl, DAG, InVals);
2621 //===----------------------------------------------------------------------===//
2622 // Fast Calling Convention (tail call) implementation
2623 //===----------------------------------------------------------------------===//
2625 // Like std call, callee cleans arguments, convention except that ECX is
2626 // reserved for storing the tail called function address. Only 2 registers are
2627 // free for argument passing (inreg). Tail call optimization is performed
2629 // * tailcallopt is enabled
2630 // * caller/callee are fastcc
2631 // On X86_64 architecture with GOT-style position independent code only local
2632 // (within module) calls are supported at the moment.
2633 // To keep the stack aligned according to platform abi the function
2634 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2635 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2636 // If a tail called function callee has more arguments than the caller the
2637 // caller needs to make sure that there is room to move the RETADDR to. This is
2638 // achieved by reserving an area the size of the argument delta right after the
2639 // original REtADDR, but before the saved framepointer or the spilled registers
2640 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2652 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2653 /// for a 16 byte align requirement.
2655 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2656 SelectionDAG& DAG) const {
2657 MachineFunction &MF = DAG.getMachineFunction();
2658 const TargetMachine &TM = MF.getTarget();
2659 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2660 unsigned StackAlignment = TFI.getStackAlignment();
2661 uint64_t AlignMask = StackAlignment - 1;
2662 int64_t Offset = StackSize;
2663 uint64_t SlotSize = TD->getPointerSize(0);
2664 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2665 // Number smaller than 12 so just add the difference.
2666 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2668 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2669 Offset = ((~AlignMask) & Offset) + StackAlignment +
2670 (StackAlignment-SlotSize);
2675 /// MatchingStackOffset - Return true if the given stack call argument is
2676 /// already available in the same position (relatively) of the caller's
2677 /// incoming argument stack.
2679 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2680 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2681 const X86InstrInfo *TII) {
2682 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2684 if (Arg.getOpcode() == ISD::CopyFromReg) {
2685 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2686 if (!TargetRegisterInfo::isVirtualRegister(VR))
2688 MachineInstr *Def = MRI->getVRegDef(VR);
2691 if (!Flags.isByVal()) {
2692 if (!TII->isLoadFromStackSlot(Def, FI))
2695 unsigned Opcode = Def->getOpcode();
2696 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2697 Def->getOperand(1).isFI()) {
2698 FI = Def->getOperand(1).getIndex();
2699 Bytes = Flags.getByValSize();
2703 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2704 if (Flags.isByVal())
2705 // ByVal argument is passed in as a pointer but it's now being
2706 // dereferenced. e.g.
2707 // define @foo(%struct.X* %A) {
2708 // tail call @bar(%struct.X* byval %A)
2711 SDValue Ptr = Ld->getBasePtr();
2712 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2715 FI = FINode->getIndex();
2716 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2717 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2718 FI = FINode->getIndex();
2719 Bytes = Flags.getByValSize();
2723 assert(FI != INT_MAX);
2724 if (!MFI->isFixedObjectIndex(FI))
2726 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2729 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2730 /// for tail call optimization. Targets which want to do tail call
2731 /// optimization should implement this function.
2733 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2734 CallingConv::ID CalleeCC,
2736 bool isCalleeStructRet,
2737 bool isCallerStructRet,
2739 const SmallVectorImpl<ISD::OutputArg> &Outs,
2740 const SmallVectorImpl<SDValue> &OutVals,
2741 const SmallVectorImpl<ISD::InputArg> &Ins,
2742 SelectionDAG& DAG) const {
2743 if (!IsTailCallConvention(CalleeCC) &&
2744 CalleeCC != CallingConv::C)
2747 // If -tailcallopt is specified, make fastcc functions tail-callable.
2748 const MachineFunction &MF = DAG.getMachineFunction();
2749 const Function *CallerF = DAG.getMachineFunction().getFunction();
2751 // If the function return type is x86_fp80 and the callee return type is not,
2752 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2753 // perform a tailcall optimization here.
2754 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2757 CallingConv::ID CallerCC = CallerF->getCallingConv();
2758 bool CCMatch = CallerCC == CalleeCC;
2760 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2761 if (IsTailCallConvention(CalleeCC) && CCMatch)
2766 // Look for obvious safe cases to perform tail call optimization that do not
2767 // require ABI changes. This is what gcc calls sibcall.
2769 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2770 // emit a special epilogue.
2771 if (RegInfo->needsStackRealignment(MF))
2774 // Also avoid sibcall optimization if either caller or callee uses struct
2775 // return semantics.
2776 if (isCalleeStructRet || isCallerStructRet)
2779 // An stdcall caller is expected to clean up its arguments; the callee
2780 // isn't going to do that.
2781 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2784 // Do not sibcall optimize vararg calls unless all arguments are passed via
2786 if (isVarArg && !Outs.empty()) {
2788 // Optimizing for varargs on Win64 is unlikely to be safe without
2789 // additional testing.
2790 if (Subtarget->isTargetWin64())
2793 SmallVector<CCValAssign, 16> ArgLocs;
2794 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2795 getTargetMachine(), ArgLocs, *DAG.getContext());
2797 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2798 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2799 if (!ArgLocs[i].isRegLoc())
2803 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2804 // stack. Therefore, if it's not used by the call it is not safe to optimize
2805 // this into a sibcall.
2806 bool Unused = false;
2807 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2814 SmallVector<CCValAssign, 16> RVLocs;
2815 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2816 getTargetMachine(), RVLocs, *DAG.getContext());
2817 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2818 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2819 CCValAssign &VA = RVLocs[i];
2820 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2825 // If the calling conventions do not match, then we'd better make sure the
2826 // results are returned in the same way as what the caller expects.
2828 SmallVector<CCValAssign, 16> RVLocs1;
2829 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2830 getTargetMachine(), RVLocs1, *DAG.getContext());
2831 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2833 SmallVector<CCValAssign, 16> RVLocs2;
2834 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2835 getTargetMachine(), RVLocs2, *DAG.getContext());
2836 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2838 if (RVLocs1.size() != RVLocs2.size())
2840 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2841 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2843 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2845 if (RVLocs1[i].isRegLoc()) {
2846 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2849 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2855 // If the callee takes no arguments then go on to check the results of the
2857 if (!Outs.empty()) {
2858 // Check if stack adjustment is needed. For now, do not do this if any
2859 // argument is passed on the stack.
2860 SmallVector<CCValAssign, 16> ArgLocs;
2861 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2862 getTargetMachine(), ArgLocs, *DAG.getContext());
2864 // Allocate shadow area for Win64
2865 if (Subtarget->isTargetWin64()) {
2866 CCInfo.AllocateStack(32, 8);
2869 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2870 if (CCInfo.getNextStackOffset()) {
2871 MachineFunction &MF = DAG.getMachineFunction();
2872 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2875 // Check if the arguments are already laid out in the right way as
2876 // the caller's fixed stack objects.
2877 MachineFrameInfo *MFI = MF.getFrameInfo();
2878 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2879 const X86InstrInfo *TII =
2880 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2881 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2882 CCValAssign &VA = ArgLocs[i];
2883 SDValue Arg = OutVals[i];
2884 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2885 if (VA.getLocInfo() == CCValAssign::Indirect)
2887 if (!VA.isRegLoc()) {
2888 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2895 // If the tailcall address may be in a register, then make sure it's
2896 // possible to register allocate for it. In 32-bit, the call address can
2897 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2898 // callee-saved registers are restored. These happen to be the same
2899 // registers used to pass 'inreg' arguments so watch out for those.
2900 if (!Subtarget->is64Bit() &&
2901 !isa<GlobalAddressSDNode>(Callee) &&
2902 !isa<ExternalSymbolSDNode>(Callee)) {
2903 unsigned NumInRegs = 0;
2904 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2905 CCValAssign &VA = ArgLocs[i];
2908 unsigned Reg = VA.getLocReg();
2911 case X86::EAX: case X86::EDX: case X86::ECX:
2912 if (++NumInRegs == 3)
2924 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2925 const TargetLibraryInfo *libInfo) const {
2926 return X86::createFastISel(funcInfo, libInfo);
2930 //===----------------------------------------------------------------------===//
2931 // Other Lowering Hooks
2932 //===----------------------------------------------------------------------===//
2934 static bool MayFoldLoad(SDValue Op) {
2935 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2938 static bool MayFoldIntoStore(SDValue Op) {
2939 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2942 static bool isTargetShuffle(unsigned Opcode) {
2944 default: return false;
2945 case X86ISD::PSHUFD:
2946 case X86ISD::PSHUFHW:
2947 case X86ISD::PSHUFLW:
2949 case X86ISD::PALIGN:
2950 case X86ISD::MOVLHPS:
2951 case X86ISD::MOVLHPD:
2952 case X86ISD::MOVHLPS:
2953 case X86ISD::MOVLPS:
2954 case X86ISD::MOVLPD:
2955 case X86ISD::MOVSHDUP:
2956 case X86ISD::MOVSLDUP:
2957 case X86ISD::MOVDDUP:
2960 case X86ISD::UNPCKL:
2961 case X86ISD::UNPCKH:
2962 case X86ISD::VPERMILP:
2963 case X86ISD::VPERM2X128:
2964 case X86ISD::VPERMI:
2969 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2970 SDValue V1, SelectionDAG &DAG) {
2972 default: llvm_unreachable("Unknown x86 shuffle node");
2973 case X86ISD::MOVSHDUP:
2974 case X86ISD::MOVSLDUP:
2975 case X86ISD::MOVDDUP:
2976 return DAG.getNode(Opc, dl, VT, V1);
2980 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2981 SDValue V1, unsigned TargetMask,
2982 SelectionDAG &DAG) {
2984 default: llvm_unreachable("Unknown x86 shuffle node");
2985 case X86ISD::PSHUFD:
2986 case X86ISD::PSHUFHW:
2987 case X86ISD::PSHUFLW:
2988 case X86ISD::VPERMILP:
2989 case X86ISD::VPERMI:
2990 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2994 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2995 SDValue V1, SDValue V2, unsigned TargetMask,
2996 SelectionDAG &DAG) {
2998 default: llvm_unreachable("Unknown x86 shuffle node");
2999 case X86ISD::PALIGN:
3001 case X86ISD::VPERM2X128:
3002 return DAG.getNode(Opc, dl, VT, V1, V2,
3003 DAG.getConstant(TargetMask, MVT::i8));
3007 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3008 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3010 default: llvm_unreachable("Unknown x86 shuffle node");
3011 case X86ISD::MOVLHPS:
3012 case X86ISD::MOVLHPD:
3013 case X86ISD::MOVHLPS:
3014 case X86ISD::MOVLPS:
3015 case X86ISD::MOVLPD:
3018 case X86ISD::UNPCKL:
3019 case X86ISD::UNPCKH:
3020 return DAG.getNode(Opc, dl, VT, V1, V2);
3024 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3025 MachineFunction &MF = DAG.getMachineFunction();
3026 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3027 int ReturnAddrIndex = FuncInfo->getRAIndex();
3029 if (ReturnAddrIndex == 0) {
3030 // Set up a frame object for the return address.
3031 uint64_t SlotSize = TD->getPointerSize(0);
3032 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3034 FuncInfo->setRAIndex(ReturnAddrIndex);
3037 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3041 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3042 bool hasSymbolicDisplacement) {
3043 // Offset should fit into 32 bit immediate field.
3044 if (!isInt<32>(Offset))
3047 // If we don't have a symbolic displacement - we don't have any extra
3049 if (!hasSymbolicDisplacement)
3052 // FIXME: Some tweaks might be needed for medium code model.
3053 if (M != CodeModel::Small && M != CodeModel::Kernel)
3056 // For small code model we assume that latest object is 16MB before end of 31
3057 // bits boundary. We may also accept pretty large negative constants knowing
3058 // that all objects are in the positive half of address space.
3059 if (M == CodeModel::Small && Offset < 16*1024*1024)
3062 // For kernel code model we know that all object resist in the negative half
3063 // of 32bits address space. We may not accept negative offsets, since they may
3064 // be just off and we may accept pretty large positive ones.
3065 if (M == CodeModel::Kernel && Offset > 0)
3071 /// isCalleePop - Determines whether the callee is required to pop its
3072 /// own arguments. Callee pop is necessary to support tail calls.
3073 bool X86::isCalleePop(CallingConv::ID CallingConv,
3074 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3078 switch (CallingConv) {
3081 case CallingConv::X86_StdCall:
3083 case CallingConv::X86_FastCall:
3085 case CallingConv::X86_ThisCall:
3087 case CallingConv::Fast:
3089 case CallingConv::GHC:
3094 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3095 /// specific condition code, returning the condition code and the LHS/RHS of the
3096 /// comparison to make.
3097 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3098 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3100 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3101 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3102 // X > -1 -> X == 0, jump !sign.
3103 RHS = DAG.getConstant(0, RHS.getValueType());
3104 return X86::COND_NS;
3106 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3107 // X < 0 -> X == 0, jump on sign.
3110 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3112 RHS = DAG.getConstant(0, RHS.getValueType());
3113 return X86::COND_LE;
3117 switch (SetCCOpcode) {
3118 default: llvm_unreachable("Invalid integer condition!");
3119 case ISD::SETEQ: return X86::COND_E;
3120 case ISD::SETGT: return X86::COND_G;
3121 case ISD::SETGE: return X86::COND_GE;
3122 case ISD::SETLT: return X86::COND_L;
3123 case ISD::SETLE: return X86::COND_LE;
3124 case ISD::SETNE: return X86::COND_NE;
3125 case ISD::SETULT: return X86::COND_B;
3126 case ISD::SETUGT: return X86::COND_A;
3127 case ISD::SETULE: return X86::COND_BE;
3128 case ISD::SETUGE: return X86::COND_AE;
3132 // First determine if it is required or is profitable to flip the operands.
3134 // If LHS is a foldable load, but RHS is not, flip the condition.
3135 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3136 !ISD::isNON_EXTLoad(RHS.getNode())) {
3137 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3138 std::swap(LHS, RHS);
3141 switch (SetCCOpcode) {
3147 std::swap(LHS, RHS);
3151 // On a floating point condition, the flags are set as follows:
3153 // 0 | 0 | 0 | X > Y
3154 // 0 | 0 | 1 | X < Y
3155 // 1 | 0 | 0 | X == Y
3156 // 1 | 1 | 1 | unordered
3157 switch (SetCCOpcode) {
3158 default: llvm_unreachable("Condcode should be pre-legalized away");
3160 case ISD::SETEQ: return X86::COND_E;
3161 case ISD::SETOLT: // flipped
3163 case ISD::SETGT: return X86::COND_A;
3164 case ISD::SETOLE: // flipped
3166 case ISD::SETGE: return X86::COND_AE;
3167 case ISD::SETUGT: // flipped
3169 case ISD::SETLT: return X86::COND_B;
3170 case ISD::SETUGE: // flipped
3172 case ISD::SETLE: return X86::COND_BE;
3174 case ISD::SETNE: return X86::COND_NE;
3175 case ISD::SETUO: return X86::COND_P;
3176 case ISD::SETO: return X86::COND_NP;
3178 case ISD::SETUNE: return X86::COND_INVALID;
3182 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3183 /// code. Current x86 isa includes the following FP cmov instructions:
3184 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3185 static bool hasFPCMov(unsigned X86CC) {
3201 /// isFPImmLegal - Returns true if the target can instruction select the
3202 /// specified FP immediate natively. If false, the legalizer will
3203 /// materialize the FP immediate as a load from a constant pool.
3204 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3205 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3206 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3212 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3213 /// the specified range (L, H].
3214 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3215 return (Val < 0) || (Val >= Low && Val < Hi);
3218 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3219 /// specified value.
3220 static bool isUndefOrEqual(int Val, int CmpVal) {
3221 if (Val < 0 || Val == CmpVal)
3226 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3227 /// from position Pos and ending in Pos+Size, falls within the specified
3228 /// sequential range (L, L+Pos]. or is undef.
3229 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3230 unsigned Pos, unsigned Size, int Low) {
3231 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3232 if (!isUndefOrEqual(Mask[i], Low))
3237 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3238 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3239 /// the second operand.
3240 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3241 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3242 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3243 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3244 return (Mask[0] < 2 && Mask[1] < 2);
3248 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3249 /// is suitable for input to PSHUFHW.
3250 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3251 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3254 // Lower quadword copied in order or undef.
3255 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3258 // Upper quadword shuffled.
3259 for (unsigned i = 4; i != 8; ++i)
3260 if (!isUndefOrInRange(Mask[i], 4, 8))
3263 if (VT == MVT::v16i16) {
3264 // Lower quadword copied in order or undef.
3265 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3268 // Upper quadword shuffled.
3269 for (unsigned i = 12; i != 16; ++i)
3270 if (!isUndefOrInRange(Mask[i], 12, 16))
3277 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3278 /// is suitable for input to PSHUFLW.
3279 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3280 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3283 // Upper quadword copied in order.
3284 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3287 // Lower quadword shuffled.
3288 for (unsigned i = 0; i != 4; ++i)
3289 if (!isUndefOrInRange(Mask[i], 0, 4))
3292 if (VT == MVT::v16i16) {
3293 // Upper quadword copied in order.
3294 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3297 // Lower quadword shuffled.
3298 for (unsigned i = 8; i != 12; ++i)
3299 if (!isUndefOrInRange(Mask[i], 8, 12))
3306 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3307 /// is suitable for input to PALIGNR.
3308 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3309 const X86Subtarget *Subtarget) {
3310 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3311 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3314 unsigned NumElts = VT.getVectorNumElements();
3315 unsigned NumLanes = VT.getSizeInBits()/128;
3316 unsigned NumLaneElts = NumElts/NumLanes;
3318 // Do not handle 64-bit element shuffles with palignr.
3319 if (NumLaneElts == 2)
3322 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3324 for (i = 0; i != NumLaneElts; ++i) {
3329 // Lane is all undef, go to next lane
3330 if (i == NumLaneElts)
3333 int Start = Mask[i+l];
3335 // Make sure its in this lane in one of the sources
3336 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3337 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3340 // If not lane 0, then we must match lane 0
3341 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3344 // Correct second source to be contiguous with first source
3345 if (Start >= (int)NumElts)
3346 Start -= NumElts - NumLaneElts;
3348 // Make sure we're shifting in the right direction.
3349 if (Start <= (int)(i+l))
3354 // Check the rest of the elements to see if they are consecutive.
3355 for (++i; i != NumLaneElts; ++i) {
3356 int Idx = Mask[i+l];
3358 // Make sure its in this lane
3359 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3360 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3363 // If not lane 0, then we must match lane 0
3364 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3367 if (Idx >= (int)NumElts)
3368 Idx -= NumElts - NumLaneElts;
3370 if (!isUndefOrEqual(Idx, Start+i))
3379 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3380 /// the two vector operands have swapped position.
3381 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3382 unsigned NumElems) {
3383 for (unsigned i = 0; i != NumElems; ++i) {
3387 else if (idx < (int)NumElems)
3388 Mask[i] = idx + NumElems;
3390 Mask[i] = idx - NumElems;
3394 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3395 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3396 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3397 /// reverse of what x86 shuffles want.
3398 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3399 bool Commuted = false) {
3400 if (!HasAVX && VT.getSizeInBits() == 256)
3403 unsigned NumElems = VT.getVectorNumElements();
3404 unsigned NumLanes = VT.getSizeInBits()/128;
3405 unsigned NumLaneElems = NumElems/NumLanes;
3407 if (NumLaneElems != 2 && NumLaneElems != 4)
3410 // VSHUFPSY divides the resulting vector into 4 chunks.
3411 // The sources are also splitted into 4 chunks, and each destination
3412 // chunk must come from a different source chunk.
3414 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3415 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3417 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3418 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3420 // VSHUFPDY 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 => X3 X2 X1 X0
3425 // SRC2 => Y3 Y2 Y1 Y0
3427 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3429 unsigned HalfLaneElems = NumLaneElems/2;
3430 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3431 for (unsigned i = 0; i != NumLaneElems; ++i) {
3432 int Idx = Mask[i+l];
3433 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3434 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3436 // For VSHUFPSY, the mask of the second half must be the same as the
3437 // first but with the appropriate offsets. This works in the same way as
3438 // VPERMILPS works with masks.
3439 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3441 if (!isUndefOrEqual(Idx, Mask[i]+l))
3449 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3450 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3451 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3452 if (!VT.is128BitVector())
3455 unsigned NumElems = VT.getVectorNumElements();
3460 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3461 return isUndefOrEqual(Mask[0], 6) &&
3462 isUndefOrEqual(Mask[1], 7) &&
3463 isUndefOrEqual(Mask[2], 2) &&
3464 isUndefOrEqual(Mask[3], 3);
3467 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3468 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3470 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3471 if (!VT.is128BitVector())
3474 unsigned NumElems = VT.getVectorNumElements();
3479 return isUndefOrEqual(Mask[0], 2) &&
3480 isUndefOrEqual(Mask[1], 3) &&
3481 isUndefOrEqual(Mask[2], 2) &&
3482 isUndefOrEqual(Mask[3], 3);
3485 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3486 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3487 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3488 if (!VT.is128BitVector())
3491 unsigned NumElems = VT.getVectorNumElements();
3493 if (NumElems != 2 && NumElems != 4)
3496 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3497 if (!isUndefOrEqual(Mask[i], i + NumElems))
3500 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3501 if (!isUndefOrEqual(Mask[i], i))
3507 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3508 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3509 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3510 if (!VT.is128BitVector())
3513 unsigned NumElems = VT.getVectorNumElements();
3515 if (NumElems != 2 && NumElems != 4)
3518 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3519 if (!isUndefOrEqual(Mask[i], i))
3522 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3523 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3530 // Some special combinations that can be optimized.
3533 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3534 SelectionDAG &DAG) {
3535 EVT VT = SVOp->getValueType(0);
3536 DebugLoc dl = SVOp->getDebugLoc();
3538 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3541 ArrayRef<int> Mask = SVOp->getMask();
3543 // These are the special masks that may be optimized.
3544 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3545 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3546 bool MatchEvenMask = true;
3547 bool MatchOddMask = true;
3548 for (int i=0; i<8; ++i) {
3549 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3550 MatchEvenMask = false;
3551 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3552 MatchOddMask = false;
3555 if (!MatchEvenMask && !MatchOddMask)
3558 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3560 SDValue Op0 = SVOp->getOperand(0);
3561 SDValue Op1 = SVOp->getOperand(1);
3563 if (MatchEvenMask) {
3564 // Shift the second operand right to 32 bits.
3565 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3566 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3568 // Shift the first operand left to 32 bits.
3569 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3570 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3572 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3573 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3576 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3577 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3578 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3579 bool HasAVX2, bool V2IsSplat = false) {
3580 unsigned NumElts = VT.getVectorNumElements();
3582 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3583 "Unsupported vector type for unpckh");
3585 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3586 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3589 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3590 // independently on 128-bit lanes.
3591 unsigned NumLanes = VT.getSizeInBits()/128;
3592 unsigned NumLaneElts = NumElts/NumLanes;
3594 for (unsigned l = 0; l != NumLanes; ++l) {
3595 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3596 i != (l+1)*NumLaneElts;
3599 int BitI1 = Mask[i+1];
3600 if (!isUndefOrEqual(BitI, j))
3603 if (!isUndefOrEqual(BitI1, NumElts))
3606 if (!isUndefOrEqual(BitI1, j + NumElts))
3615 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3616 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3617 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3618 bool HasAVX2, bool V2IsSplat = false) {
3619 unsigned NumElts = VT.getVectorNumElements();
3621 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3622 "Unsupported vector type for unpckh");
3624 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3625 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3628 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3629 // independently on 128-bit lanes.
3630 unsigned NumLanes = VT.getSizeInBits()/128;
3631 unsigned NumLaneElts = NumElts/NumLanes;
3633 for (unsigned l = 0; l != NumLanes; ++l) {
3634 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3635 i != (l+1)*NumLaneElts; i += 2, ++j) {
3637 int BitI1 = Mask[i+1];
3638 if (!isUndefOrEqual(BitI, j))
3641 if (isUndefOrEqual(BitI1, NumElts))
3644 if (!isUndefOrEqual(BitI1, j+NumElts))
3652 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3653 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3655 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3657 unsigned NumElts = VT.getVectorNumElements();
3659 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3660 "Unsupported vector type for unpckh");
3662 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3663 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3666 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3667 // FIXME: Need a better way to get rid of this, there's no latency difference
3668 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3669 // the former later. We should also remove the "_undef" special mask.
3670 if (NumElts == 4 && VT.getSizeInBits() == 256)
3673 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3674 // independently on 128-bit lanes.
3675 unsigned NumLanes = VT.getSizeInBits()/128;
3676 unsigned NumLaneElts = NumElts/NumLanes;
3678 for (unsigned l = 0; l != NumLanes; ++l) {
3679 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3680 i != (l+1)*NumLaneElts;
3683 int BitI1 = Mask[i+1];
3685 if (!isUndefOrEqual(BitI, j))
3687 if (!isUndefOrEqual(BitI1, j))
3695 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3696 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3698 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3699 unsigned NumElts = VT.getVectorNumElements();
3701 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3702 "Unsupported vector type for unpckh");
3704 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3705 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3708 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3709 // independently on 128-bit lanes.
3710 unsigned NumLanes = VT.getSizeInBits()/128;
3711 unsigned NumLaneElts = NumElts/NumLanes;
3713 for (unsigned l = 0; l != NumLanes; ++l) {
3714 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3715 i != (l+1)*NumLaneElts; i += 2, ++j) {
3717 int BitI1 = Mask[i+1];
3718 if (!isUndefOrEqual(BitI, j))
3720 if (!isUndefOrEqual(BitI1, j))
3727 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3728 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3729 /// MOVSD, and MOVD, i.e. setting the lowest element.
3730 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3731 if (VT.getVectorElementType().getSizeInBits() < 32)
3733 if (!VT.is128BitVector())
3736 unsigned NumElts = VT.getVectorNumElements();
3738 if (!isUndefOrEqual(Mask[0], NumElts))
3741 for (unsigned i = 1; i != NumElts; ++i)
3742 if (!isUndefOrEqual(Mask[i], i))
3748 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3749 /// as permutations between 128-bit chunks or halves. As an example: this
3751 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3752 /// The first half comes from the second half of V1 and the second half from the
3753 /// the second half of V2.
3754 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3755 if (!HasAVX || !VT.is256BitVector())
3758 // The shuffle result is divided into half A and half B. In total the two
3759 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3760 // B must come from C, D, E or F.
3761 unsigned HalfSize = VT.getVectorNumElements()/2;
3762 bool MatchA = false, MatchB = false;
3764 // Check if A comes from one of C, D, E, F.
3765 for (unsigned Half = 0; Half != 4; ++Half) {
3766 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3772 // Check if B comes from one of C, D, E, F.
3773 for (unsigned Half = 0; Half != 4; ++Half) {
3774 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3780 return MatchA && MatchB;
3783 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3784 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3785 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3786 EVT VT = SVOp->getValueType(0);
3788 unsigned HalfSize = VT.getVectorNumElements()/2;
3790 unsigned FstHalf = 0, SndHalf = 0;
3791 for (unsigned i = 0; i < HalfSize; ++i) {
3792 if (SVOp->getMaskElt(i) > 0) {
3793 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3797 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3798 if (SVOp->getMaskElt(i) > 0) {
3799 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3804 return (FstHalf | (SndHalf << 4));
3807 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3809 /// Note that VPERMIL mask matching is different depending whether theunderlying
3810 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3811 /// to the same elements of the low, but to the higher half of the source.
3812 /// In VPERMILPD the two lanes could be shuffled independently of each other
3813 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3814 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3818 unsigned NumElts = VT.getVectorNumElements();
3819 // Only match 256-bit with 32/64-bit types
3820 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3823 unsigned NumLanes = VT.getSizeInBits()/128;
3824 unsigned LaneSize = NumElts/NumLanes;
3825 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3826 for (unsigned i = 0; i != LaneSize; ++i) {
3827 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3829 if (NumElts != 8 || l == 0)
3831 // VPERMILPS handling
3834 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3842 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3843 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3844 /// element of vector 2 and the other elements to come from vector 1 in order.
3845 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3846 bool V2IsSplat = false, bool V2IsUndef = false) {
3847 if (!VT.is128BitVector())
3850 unsigned NumOps = VT.getVectorNumElements();
3851 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3854 if (!isUndefOrEqual(Mask[0], 0))
3857 for (unsigned i = 1; i != NumOps; ++i)
3858 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3859 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3860 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3866 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3867 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3868 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3869 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3870 const X86Subtarget *Subtarget) {
3871 if (!Subtarget->hasSSE3())
3874 unsigned NumElems = VT.getVectorNumElements();
3876 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3877 (VT.getSizeInBits() == 256 && NumElems != 8))
3880 // "i+1" is the value the indexed mask element must have
3881 for (unsigned i = 0; i != NumElems; i += 2)
3882 if (!isUndefOrEqual(Mask[i], i+1) ||
3883 !isUndefOrEqual(Mask[i+1], i+1))
3889 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3890 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3891 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3892 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3893 const X86Subtarget *Subtarget) {
3894 if (!Subtarget->hasSSE3())
3897 unsigned NumElems = VT.getVectorNumElements();
3899 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3900 (VT.getSizeInBits() == 256 && NumElems != 8))
3903 // "i" is the value the indexed mask element must have
3904 for (unsigned i = 0; i != NumElems; i += 2)
3905 if (!isUndefOrEqual(Mask[i], i) ||
3906 !isUndefOrEqual(Mask[i+1], i))
3912 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3913 /// specifies a shuffle of elements that is suitable for input to 256-bit
3914 /// version of MOVDDUP.
3915 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3916 if (!HasAVX || !VT.is256BitVector())
3919 unsigned NumElts = VT.getVectorNumElements();
3923 for (unsigned i = 0; i != NumElts/2; ++i)
3924 if (!isUndefOrEqual(Mask[i], 0))
3926 for (unsigned i = NumElts/2; i != NumElts; ++i)
3927 if (!isUndefOrEqual(Mask[i], NumElts/2))
3932 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3933 /// specifies a shuffle of elements that is suitable for input to 128-bit
3934 /// version of MOVDDUP.
3935 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3936 if (!VT.is128BitVector())
3939 unsigned e = VT.getVectorNumElements() / 2;
3940 for (unsigned i = 0; i != e; ++i)
3941 if (!isUndefOrEqual(Mask[i], i))
3943 for (unsigned i = 0; i != e; ++i)
3944 if (!isUndefOrEqual(Mask[e+i], i))
3949 /// isVEXTRACTF128Index - Return true if the specified
3950 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3951 /// suitable for input to VEXTRACTF128.
3952 bool X86::isVEXTRACTF128Index(SDNode *N) {
3953 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3956 // The index should be aligned on a 128-bit boundary.
3958 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3960 unsigned VL = N->getValueType(0).getVectorNumElements();
3961 unsigned VBits = N->getValueType(0).getSizeInBits();
3962 unsigned ElSize = VBits / VL;
3963 bool Result = (Index * ElSize) % 128 == 0;
3968 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3969 /// operand specifies a subvector insert that is suitable for input to
3971 bool X86::isVINSERTF128Index(SDNode *N) {
3972 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3975 // The index should be aligned on a 128-bit boundary.
3977 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3979 unsigned VL = N->getValueType(0).getVectorNumElements();
3980 unsigned VBits = N->getValueType(0).getSizeInBits();
3981 unsigned ElSize = VBits / VL;
3982 bool Result = (Index * ElSize) % 128 == 0;
3987 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3988 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3989 /// Handles 128-bit and 256-bit.
3990 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3991 EVT VT = N->getValueType(0);
3993 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3994 "Unsupported vector type for PSHUF/SHUFP");
3996 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3997 // independently on 128-bit lanes.
3998 unsigned NumElts = VT.getVectorNumElements();
3999 unsigned NumLanes = VT.getSizeInBits()/128;
4000 unsigned NumLaneElts = NumElts/NumLanes;
4002 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4003 "Only supports 2 or 4 elements per lane");
4005 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4007 for (unsigned i = 0; i != NumElts; ++i) {
4008 int Elt = N->getMaskElt(i);
4009 if (Elt < 0) continue;
4010 Elt &= NumLaneElts - 1;
4011 unsigned ShAmt = (i << Shift) % 8;
4012 Mask |= Elt << ShAmt;
4018 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4019 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4020 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4021 EVT VT = N->getValueType(0);
4023 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4024 "Unsupported vector type for PSHUFHW");
4026 unsigned NumElts = VT.getVectorNumElements();
4029 for (unsigned l = 0; l != NumElts; l += 8) {
4030 // 8 nodes per lane, but we only care about the last 4.
4031 for (unsigned i = 0; i < 4; ++i) {
4032 int Elt = N->getMaskElt(l+i+4);
4033 if (Elt < 0) continue;
4034 Elt &= 0x3; // only 2-bits.
4035 Mask |= Elt << (i * 2);
4042 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4044 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4045 EVT VT = N->getValueType(0);
4047 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4048 "Unsupported vector type for PSHUFHW");
4050 unsigned NumElts = VT.getVectorNumElements();
4053 for (unsigned l = 0; l != NumElts; l += 8) {
4054 // 8 nodes per lane, but we only care about the first 4.
4055 for (unsigned i = 0; i < 4; ++i) {
4056 int Elt = N->getMaskElt(l+i);
4057 if (Elt < 0) continue;
4058 Elt &= 0x3; // only 2-bits
4059 Mask |= Elt << (i * 2);
4066 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4067 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4068 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4069 EVT VT = SVOp->getValueType(0);
4070 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4072 unsigned NumElts = VT.getVectorNumElements();
4073 unsigned NumLanes = VT.getSizeInBits()/128;
4074 unsigned NumLaneElts = NumElts/NumLanes;
4078 for (i = 0; i != NumElts; ++i) {
4079 Val = SVOp->getMaskElt(i);
4083 if (Val >= (int)NumElts)
4084 Val -= NumElts - NumLaneElts;
4086 assert(Val - i > 0 && "PALIGNR imm should be positive");
4087 return (Val - i) * EltSize;
4090 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4091 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4093 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4094 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4095 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4098 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4100 EVT VecVT = N->getOperand(0).getValueType();
4101 EVT ElVT = VecVT.getVectorElementType();
4103 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4104 return Index / NumElemsPerChunk;
4107 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4108 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4110 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4111 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4112 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4115 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4117 EVT VecVT = N->getValueType(0);
4118 EVT ElVT = VecVT.getVectorElementType();
4120 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4121 return Index / NumElemsPerChunk;
4124 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4125 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4126 /// Handles 256-bit.
4127 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4128 EVT VT = N->getValueType(0);
4130 unsigned NumElts = VT.getVectorNumElements();
4132 assert((VT.is256BitVector() && NumElts == 4) &&
4133 "Unsupported vector type for VPERMQ/VPERMPD");
4136 for (unsigned i = 0; i != NumElts; ++i) {
4137 int Elt = N->getMaskElt(i);
4140 Mask |= Elt << (i*2);
4145 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4147 bool X86::isZeroNode(SDValue Elt) {
4148 return ((isa<ConstantSDNode>(Elt) &&
4149 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4150 (isa<ConstantFPSDNode>(Elt) &&
4151 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4154 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4155 /// their permute mask.
4156 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4157 SelectionDAG &DAG) {
4158 EVT VT = SVOp->getValueType(0);
4159 unsigned NumElems = VT.getVectorNumElements();
4160 SmallVector<int, 8> MaskVec;
4162 for (unsigned i = 0; i != NumElems; ++i) {
4163 int Idx = SVOp->getMaskElt(i);
4165 if (Idx < (int)NumElems)
4170 MaskVec.push_back(Idx);
4172 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4173 SVOp->getOperand(0), &MaskVec[0]);
4176 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4177 /// match movhlps. The lower half elements should come from upper half of
4178 /// V1 (and in order), and the upper half elements should come from the upper
4179 /// half of V2 (and in order).
4180 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4181 if (!VT.is128BitVector())
4183 if (VT.getVectorNumElements() != 4)
4185 for (unsigned i = 0, e = 2; i != e; ++i)
4186 if (!isUndefOrEqual(Mask[i], i+2))
4188 for (unsigned i = 2; i != 4; ++i)
4189 if (!isUndefOrEqual(Mask[i], i+4))
4194 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4195 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4197 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4198 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4200 N = N->getOperand(0).getNode();
4201 if (!ISD::isNON_EXTLoad(N))
4204 *LD = cast<LoadSDNode>(N);
4208 // Test whether the given value is a vector value which will be legalized
4210 static bool WillBeConstantPoolLoad(SDNode *N) {
4211 if (N->getOpcode() != ISD::BUILD_VECTOR)
4214 // Check for any non-constant elements.
4215 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4216 switch (N->getOperand(i).getNode()->getOpcode()) {
4218 case ISD::ConstantFP:
4225 // Vectors of all-zeros and all-ones are materialized with special
4226 // instructions rather than being loaded.
4227 return !ISD::isBuildVectorAllZeros(N) &&
4228 !ISD::isBuildVectorAllOnes(N);
4231 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4232 /// match movlp{s|d}. The lower half elements should come from lower half of
4233 /// V1 (and in order), and the upper half elements should come from the upper
4234 /// half of V2 (and in order). And since V1 will become the source of the
4235 /// MOVLP, it must be either a vector load or a scalar load to vector.
4236 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4237 ArrayRef<int> Mask, EVT VT) {
4238 if (!VT.is128BitVector())
4241 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4243 // Is V2 is a vector load, don't do this transformation. We will try to use
4244 // load folding shufps op.
4245 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4248 unsigned NumElems = VT.getVectorNumElements();
4250 if (NumElems != 2 && NumElems != 4)
4252 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4253 if (!isUndefOrEqual(Mask[i], i))
4255 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4256 if (!isUndefOrEqual(Mask[i], i+NumElems))
4261 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4263 static bool isSplatVector(SDNode *N) {
4264 if (N->getOpcode() != ISD::BUILD_VECTOR)
4267 SDValue SplatValue = N->getOperand(0);
4268 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4269 if (N->getOperand(i) != SplatValue)
4274 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4275 /// to an zero vector.
4276 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4277 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4278 SDValue V1 = N->getOperand(0);
4279 SDValue V2 = N->getOperand(1);
4280 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4281 for (unsigned i = 0; i != NumElems; ++i) {
4282 int Idx = N->getMaskElt(i);
4283 if (Idx >= (int)NumElems) {
4284 unsigned Opc = V2.getOpcode();
4285 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4287 if (Opc != ISD::BUILD_VECTOR ||
4288 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4290 } else if (Idx >= 0) {
4291 unsigned Opc = V1.getOpcode();
4292 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4294 if (Opc != ISD::BUILD_VECTOR ||
4295 !X86::isZeroNode(V1.getOperand(Idx)))
4302 /// getZeroVector - Returns a vector of specified type with all zero elements.
4304 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4305 SelectionDAG &DAG, DebugLoc dl) {
4306 assert(VT.isVector() && "Expected a vector type");
4307 unsigned Size = VT.getSizeInBits();
4309 // Always build SSE zero vectors as <4 x i32> bitcasted
4310 // to their dest type. This ensures they get CSE'd.
4312 if (Size == 128) { // SSE
4313 if (Subtarget->hasSSE2()) { // SSE2
4314 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4315 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4317 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4318 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4320 } else if (Size == 256) { // AVX
4321 if (Subtarget->hasAVX2()) { // AVX2
4322 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4323 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4324 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4326 // 256-bit logic and arithmetic instructions in AVX are all
4327 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4328 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4329 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4330 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4333 llvm_unreachable("Unexpected vector type");
4335 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4338 /// getOnesVector - Returns a vector of specified type with all bits set.
4339 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4340 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4341 /// Then bitcast to their original type, ensuring they get CSE'd.
4342 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4344 assert(VT.isVector() && "Expected a vector type");
4345 unsigned Size = VT.getSizeInBits();
4347 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4350 if (HasAVX2) { // AVX2
4351 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4352 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4354 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4355 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4357 } else if (Size == 128) {
4358 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4360 llvm_unreachable("Unexpected vector type");
4362 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4365 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4366 /// that point to V2 points to its first element.
4367 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4368 for (unsigned i = 0; i != NumElems; ++i) {
4369 if (Mask[i] > (int)NumElems) {
4375 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4376 /// operation of specified width.
4377 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4379 unsigned NumElems = VT.getVectorNumElements();
4380 SmallVector<int, 8> Mask;
4381 Mask.push_back(NumElems);
4382 for (unsigned i = 1; i != NumElems; ++i)
4384 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4387 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4388 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4390 unsigned NumElems = VT.getVectorNumElements();
4391 SmallVector<int, 8> Mask;
4392 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4394 Mask.push_back(i + NumElems);
4396 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4399 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4400 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4402 unsigned NumElems = VT.getVectorNumElements();
4403 SmallVector<int, 8> Mask;
4404 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4405 Mask.push_back(i + Half);
4406 Mask.push_back(i + NumElems + Half);
4408 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4411 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4412 // a generic shuffle instruction because the target has no such instructions.
4413 // Generate shuffles which repeat i16 and i8 several times until they can be
4414 // represented by v4f32 and then be manipulated by target suported shuffles.
4415 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4416 EVT VT = V.getValueType();
4417 int NumElems = VT.getVectorNumElements();
4418 DebugLoc dl = V.getDebugLoc();
4420 while (NumElems > 4) {
4421 if (EltNo < NumElems/2) {
4422 V = getUnpackl(DAG, dl, VT, V, V);
4424 V = getUnpackh(DAG, dl, VT, V, V);
4425 EltNo -= NumElems/2;
4432 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4433 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4434 EVT VT = V.getValueType();
4435 DebugLoc dl = V.getDebugLoc();
4436 unsigned Size = VT.getSizeInBits();
4439 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4440 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4441 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4443 } else if (Size == 256) {
4444 // To use VPERMILPS to splat scalars, the second half of indicies must
4445 // refer to the higher part, which is a duplication of the lower one,
4446 // because VPERMILPS can only handle in-lane permutations.
4447 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4448 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4450 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4451 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4454 llvm_unreachable("Vector size not supported");
4456 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4459 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4460 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4461 EVT SrcVT = SV->getValueType(0);
4462 SDValue V1 = SV->getOperand(0);
4463 DebugLoc dl = SV->getDebugLoc();
4465 int EltNo = SV->getSplatIndex();
4466 int NumElems = SrcVT.getVectorNumElements();
4467 unsigned Size = SrcVT.getSizeInBits();
4469 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4470 "Unknown how to promote splat for type");
4472 // Extract the 128-bit part containing the splat element and update
4473 // the splat element index when it refers to the higher register.
4475 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4476 if (EltNo >= NumElems/2)
4477 EltNo -= NumElems/2;
4480 // All i16 and i8 vector types can't be used directly by a generic shuffle
4481 // instruction because the target has no such instruction. Generate shuffles
4482 // which repeat i16 and i8 several times until they fit in i32, and then can
4483 // be manipulated by target suported shuffles.
4484 EVT EltVT = SrcVT.getVectorElementType();
4485 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4486 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4488 // Recreate the 256-bit vector and place the same 128-bit vector
4489 // into the low and high part. This is necessary because we want
4490 // to use VPERM* to shuffle the vectors
4492 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4495 return getLegalSplat(DAG, V1, EltNo);
4498 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4499 /// vector of zero or undef vector. This produces a shuffle where the low
4500 /// element of V2 is swizzled into the zero/undef vector, landing at element
4501 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4502 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4504 const X86Subtarget *Subtarget,
4505 SelectionDAG &DAG) {
4506 EVT VT = V2.getValueType();
4508 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4509 unsigned NumElems = VT.getVectorNumElements();
4510 SmallVector<int, 16> MaskVec;
4511 for (unsigned i = 0; i != NumElems; ++i)
4512 // If this is the insertion idx, put the low elt of V2 here.
4513 MaskVec.push_back(i == Idx ? NumElems : i);
4514 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4517 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4518 /// target specific opcode. Returns true if the Mask could be calculated.
4519 /// Sets IsUnary to true if only uses one source.
4520 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4521 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4522 unsigned NumElems = VT.getVectorNumElements();
4526 switch(N->getOpcode()) {
4528 ImmN = N->getOperand(N->getNumOperands()-1);
4529 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4531 case X86ISD::UNPCKH:
4532 DecodeUNPCKHMask(VT, Mask);
4534 case X86ISD::UNPCKL:
4535 DecodeUNPCKLMask(VT, Mask);
4537 case X86ISD::MOVHLPS:
4538 DecodeMOVHLPSMask(NumElems, Mask);
4540 case X86ISD::MOVLHPS:
4541 DecodeMOVLHPSMask(NumElems, Mask);
4543 case X86ISD::PSHUFD:
4544 case X86ISD::VPERMILP:
4545 ImmN = N->getOperand(N->getNumOperands()-1);
4546 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4549 case X86ISD::PSHUFHW:
4550 ImmN = N->getOperand(N->getNumOperands()-1);
4551 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4554 case X86ISD::PSHUFLW:
4555 ImmN = N->getOperand(N->getNumOperands()-1);
4556 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4559 case X86ISD::VPERMI:
4560 ImmN = N->getOperand(N->getNumOperands()-1);
4561 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4565 case X86ISD::MOVSD: {
4566 // The index 0 always comes from the first element of the second source,
4567 // this is why MOVSS and MOVSD are used in the first place. The other
4568 // elements come from the other positions of the first source vector
4569 Mask.push_back(NumElems);
4570 for (unsigned i = 1; i != NumElems; ++i) {
4575 case X86ISD::VPERM2X128:
4576 ImmN = N->getOperand(N->getNumOperands()-1);
4577 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4578 if (Mask.empty()) return false;
4580 case X86ISD::MOVDDUP:
4581 case X86ISD::MOVLHPD:
4582 case X86ISD::MOVLPD:
4583 case X86ISD::MOVLPS:
4584 case X86ISD::MOVSHDUP:
4585 case X86ISD::MOVSLDUP:
4586 case X86ISD::PALIGN:
4587 // Not yet implemented
4589 default: llvm_unreachable("unknown target shuffle node");
4595 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4596 /// element of the result of the vector shuffle.
4597 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4600 return SDValue(); // Limit search depth.
4602 SDValue V = SDValue(N, 0);
4603 EVT VT = V.getValueType();
4604 unsigned Opcode = V.getOpcode();
4606 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4607 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4608 int Elt = SV->getMaskElt(Index);
4611 return DAG.getUNDEF(VT.getVectorElementType());
4613 unsigned NumElems = VT.getVectorNumElements();
4614 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4615 : SV->getOperand(1);
4616 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4619 // Recurse into target specific vector shuffles to find scalars.
4620 if (isTargetShuffle(Opcode)) {
4621 MVT ShufVT = V.getValueType().getSimpleVT();
4622 unsigned NumElems = ShufVT.getVectorNumElements();
4623 SmallVector<int, 16> ShuffleMask;
4627 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4630 int Elt = ShuffleMask[Index];
4632 return DAG.getUNDEF(ShufVT.getVectorElementType());
4634 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4636 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4640 // Actual nodes that may contain scalar elements
4641 if (Opcode == ISD::BITCAST) {
4642 V = V.getOperand(0);
4643 EVT SrcVT = V.getValueType();
4644 unsigned NumElems = VT.getVectorNumElements();
4646 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4650 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4651 return (Index == 0) ? V.getOperand(0)
4652 : DAG.getUNDEF(VT.getVectorElementType());
4654 if (V.getOpcode() == ISD::BUILD_VECTOR)
4655 return V.getOperand(Index);
4660 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4661 /// shuffle operation which come from a consecutively from a zero. The
4662 /// search can start in two different directions, from left or right.
4664 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4665 bool ZerosFromLeft, SelectionDAG &DAG) {
4667 for (i = 0; i != NumElems; ++i) {
4668 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4669 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4670 if (!(Elt.getNode() &&
4671 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4678 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4679 /// correspond consecutively to elements from one of the vector operands,
4680 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4682 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4683 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4684 unsigned NumElems, unsigned &OpNum) {
4685 bool SeenV1 = false;
4686 bool SeenV2 = false;
4688 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4689 int Idx = SVOp->getMaskElt(i);
4690 // Ignore undef indicies
4694 if (Idx < (int)NumElems)
4699 // Only accept consecutive elements from the same vector
4700 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4704 OpNum = SeenV1 ? 0 : 1;
4708 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4709 /// logical left shift of a vector.
4710 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4711 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4712 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4713 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4714 false /* check zeros from right */, DAG);
4720 // Considering the elements in the mask that are not consecutive zeros,
4721 // check if they consecutively come from only one of the source vectors.
4723 // V1 = {X, A, B, C} 0
4725 // vector_shuffle V1, V2 <1, 2, 3, X>
4727 if (!isShuffleMaskConsecutive(SVOp,
4728 0, // Mask Start Index
4729 NumElems-NumZeros, // Mask End Index(exclusive)
4730 NumZeros, // Where to start looking in the src vector
4731 NumElems, // Number of elements in vector
4732 OpSrc)) // Which source operand ?
4737 ShVal = SVOp->getOperand(OpSrc);
4741 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4742 /// logical left shift of a vector.
4743 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4744 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4745 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4746 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4747 true /* check zeros from left */, DAG);
4753 // Considering the elements in the mask that are not consecutive zeros,
4754 // check if they consecutively come from only one of the source vectors.
4756 // 0 { A, B, X, X } = V2
4758 // vector_shuffle V1, V2 <X, X, 4, 5>
4760 if (!isShuffleMaskConsecutive(SVOp,
4761 NumZeros, // Mask Start Index
4762 NumElems, // Mask End Index(exclusive)
4763 0, // Where to start looking in the src vector
4764 NumElems, // Number of elements in vector
4765 OpSrc)) // Which source operand ?
4770 ShVal = SVOp->getOperand(OpSrc);
4774 /// isVectorShift - Returns true if the shuffle can be implemented as a
4775 /// logical left or right shift of a vector.
4776 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4777 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4778 // Although the logic below support any bitwidth size, there are no
4779 // shift instructions which handle more than 128-bit vectors.
4780 if (!SVOp->getValueType(0).is128BitVector())
4783 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4784 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4790 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4792 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4793 unsigned NumNonZero, unsigned NumZero,
4795 const X86Subtarget* Subtarget,
4796 const TargetLowering &TLI) {
4800 DebugLoc dl = Op.getDebugLoc();
4803 for (unsigned i = 0; i < 16; ++i) {
4804 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4805 if (ThisIsNonZero && First) {
4807 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4809 V = DAG.getUNDEF(MVT::v8i16);
4814 SDValue ThisElt(0, 0), LastElt(0, 0);
4815 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4816 if (LastIsNonZero) {
4817 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4818 MVT::i16, Op.getOperand(i-1));
4820 if (ThisIsNonZero) {
4821 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4822 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4823 ThisElt, DAG.getConstant(8, MVT::i8));
4825 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4829 if (ThisElt.getNode())
4830 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4831 DAG.getIntPtrConstant(i/2));
4835 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4838 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4840 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4841 unsigned NumNonZero, unsigned NumZero,
4843 const X86Subtarget* Subtarget,
4844 const TargetLowering &TLI) {
4848 DebugLoc dl = Op.getDebugLoc();
4851 for (unsigned i = 0; i < 8; ++i) {
4852 bool isNonZero = (NonZeros & (1 << i)) != 0;
4856 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4858 V = DAG.getUNDEF(MVT::v8i16);
4861 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4862 MVT::v8i16, V, Op.getOperand(i),
4863 DAG.getIntPtrConstant(i));
4870 /// getVShift - Return a vector logical shift node.
4872 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4873 unsigned NumBits, SelectionDAG &DAG,
4874 const TargetLowering &TLI, DebugLoc dl) {
4875 assert(VT.is128BitVector() && "Unknown type for VShift");
4876 EVT ShVT = MVT::v2i64;
4877 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4878 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4879 return DAG.getNode(ISD::BITCAST, dl, VT,
4880 DAG.getNode(Opc, dl, ShVT, SrcOp,
4881 DAG.getConstant(NumBits,
4882 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4886 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4887 SelectionDAG &DAG) const {
4889 // Check if the scalar load can be widened into a vector load. And if
4890 // the address is "base + cst" see if the cst can be "absorbed" into
4891 // the shuffle mask.
4892 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4893 SDValue Ptr = LD->getBasePtr();
4894 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4896 EVT PVT = LD->getValueType(0);
4897 if (PVT != MVT::i32 && PVT != MVT::f32)
4902 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4903 FI = FINode->getIndex();
4905 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4906 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4907 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4908 Offset = Ptr.getConstantOperandVal(1);
4909 Ptr = Ptr.getOperand(0);
4914 // FIXME: 256-bit vector instructions don't require a strict alignment,
4915 // improve this code to support it better.
4916 unsigned RequiredAlign = VT.getSizeInBits()/8;
4917 SDValue Chain = LD->getChain();
4918 // Make sure the stack object alignment is at least 16 or 32.
4919 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4920 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4921 if (MFI->isFixedObjectIndex(FI)) {
4922 // Can't change the alignment. FIXME: It's possible to compute
4923 // the exact stack offset and reference FI + adjust offset instead.
4924 // If someone *really* cares about this. That's the way to implement it.
4927 MFI->setObjectAlignment(FI, RequiredAlign);
4931 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4932 // Ptr + (Offset & ~15).
4935 if ((Offset % RequiredAlign) & 3)
4937 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4939 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4940 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4942 int EltNo = (Offset - StartOffset) >> 2;
4943 unsigned NumElems = VT.getVectorNumElements();
4945 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4946 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4947 LD->getPointerInfo().getWithOffset(StartOffset),
4948 false, false, false, 0);
4950 SmallVector<int, 8> Mask;
4951 for (unsigned i = 0; i != NumElems; ++i)
4952 Mask.push_back(EltNo);
4954 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4960 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4961 /// vector of type 'VT', see if the elements can be replaced by a single large
4962 /// load which has the same value as a build_vector whose operands are 'elts'.
4964 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4966 /// FIXME: we'd also like to handle the case where the last elements are zero
4967 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4968 /// There's even a handy isZeroNode for that purpose.
4969 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4970 DebugLoc &DL, SelectionDAG &DAG) {
4971 EVT EltVT = VT.getVectorElementType();
4972 unsigned NumElems = Elts.size();
4974 LoadSDNode *LDBase = NULL;
4975 unsigned LastLoadedElt = -1U;
4977 // For each element in the initializer, see if we've found a load or an undef.
4978 // If we don't find an initial load element, or later load elements are
4979 // non-consecutive, bail out.
4980 for (unsigned i = 0; i < NumElems; ++i) {
4981 SDValue Elt = Elts[i];
4983 if (!Elt.getNode() ||
4984 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4987 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4989 LDBase = cast<LoadSDNode>(Elt.getNode());
4993 if (Elt.getOpcode() == ISD::UNDEF)
4996 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4997 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5002 // If we have found an entire vector of loads and undefs, then return a large
5003 // load of the entire vector width starting at the base pointer. If we found
5004 // consecutive loads for the low half, generate a vzext_load node.
5005 if (LastLoadedElt == NumElems - 1) {
5006 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5007 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5008 LDBase->getPointerInfo(),
5009 LDBase->isVolatile(), LDBase->isNonTemporal(),
5010 LDBase->isInvariant(), 0);
5011 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5012 LDBase->getPointerInfo(),
5013 LDBase->isVolatile(), LDBase->isNonTemporal(),
5014 LDBase->isInvariant(), LDBase->getAlignment());
5016 if (NumElems == 4 && LastLoadedElt == 1 &&
5017 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5018 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5019 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5021 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5022 LDBase->getPointerInfo(),
5023 LDBase->getAlignment(),
5024 false/*isVolatile*/, true/*ReadMem*/,
5027 // Make sure the newly-created LOAD is in the same position as LDBase in
5028 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5029 // update uses of LDBase's output chain to use the TokenFactor.
5030 if (LDBase->hasAnyUseOfValue(1)) {
5031 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5032 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5033 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5034 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5035 SDValue(ResNode.getNode(), 1));
5038 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5043 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5044 /// to generate a splat value for the following cases:
5045 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5046 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5047 /// a scalar load, or a constant.
5048 /// The VBROADCAST node is returned when a pattern is found,
5049 /// or SDValue() otherwise.
5051 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5052 if (!Subtarget->hasAVX())
5055 EVT VT = Op.getValueType();
5056 DebugLoc dl = Op.getDebugLoc();
5058 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5059 "Unsupported vector type for broadcast.");
5064 switch (Op.getOpcode()) {
5066 // Unknown pattern found.
5069 case ISD::BUILD_VECTOR: {
5070 // The BUILD_VECTOR node must be a splat.
5071 if (!isSplatVector(Op.getNode()))
5074 Ld = Op.getOperand(0);
5075 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5076 Ld.getOpcode() == ISD::ConstantFP);
5078 // The suspected load node has several users. Make sure that all
5079 // of its users are from the BUILD_VECTOR node.
5080 // Constants may have multiple users.
5081 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5086 case ISD::VECTOR_SHUFFLE: {
5087 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5089 // Shuffles must have a splat mask where the first element is
5091 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5094 SDValue Sc = Op.getOperand(0);
5095 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5096 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5098 if (!Subtarget->hasAVX2())
5101 // Use the register form of the broadcast instruction available on AVX2.
5102 if (VT.is256BitVector())
5103 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5104 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5107 Ld = Sc.getOperand(0);
5108 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5109 Ld.getOpcode() == ISD::ConstantFP);
5111 // The scalar_to_vector node and the suspected
5112 // load node must have exactly one user.
5113 // Constants may have multiple users.
5114 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5120 bool Is256 = VT.is256BitVector();
5122 // Handle the broadcasting a single constant scalar from the constant pool
5123 // into a vector. On Sandybridge it is still better to load a constant vector
5124 // from the constant pool and not to broadcast it from a scalar.
5125 if (ConstSplatVal && Subtarget->hasAVX2()) {
5126 EVT CVT = Ld.getValueType();
5127 assert(!CVT.isVector() && "Must not broadcast a vector type");
5128 unsigned ScalarSize = CVT.getSizeInBits();
5130 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5131 const Constant *C = 0;
5132 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5133 C = CI->getConstantIntValue();
5134 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5135 C = CF->getConstantFPValue();
5137 assert(C && "Invalid constant type");
5139 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5140 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5141 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5142 MachinePointerInfo::getConstantPool(),
5143 false, false, false, Alignment);
5145 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5149 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5150 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5152 // Handle AVX2 in-register broadcasts.
5153 if (!IsLoad && Subtarget->hasAVX2() &&
5154 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5155 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5157 // The scalar source must be a normal load.
5161 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5162 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5164 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5165 // double since there is no vbroadcastsd xmm
5166 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5167 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5168 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5171 // Unsupported broadcast.
5176 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5177 DebugLoc dl = Op.getDebugLoc();
5179 EVT VT = Op.getValueType();
5180 EVT ExtVT = VT.getVectorElementType();
5181 unsigned NumElems = Op.getNumOperands();
5183 // Vectors containing all zeros can be matched by pxor and xorps later
5184 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5185 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5186 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5187 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5190 return getZeroVector(VT, Subtarget, DAG, dl);
5193 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5194 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5195 // vpcmpeqd on 256-bit vectors.
5196 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5197 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5200 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5203 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5204 if (Broadcast.getNode())
5207 unsigned EVTBits = ExtVT.getSizeInBits();
5209 unsigned NumZero = 0;
5210 unsigned NumNonZero = 0;
5211 unsigned NonZeros = 0;
5212 bool IsAllConstants = true;
5213 SmallSet<SDValue, 8> Values;
5214 for (unsigned i = 0; i < NumElems; ++i) {
5215 SDValue Elt = Op.getOperand(i);
5216 if (Elt.getOpcode() == ISD::UNDEF)
5219 if (Elt.getOpcode() != ISD::Constant &&
5220 Elt.getOpcode() != ISD::ConstantFP)
5221 IsAllConstants = false;
5222 if (X86::isZeroNode(Elt))
5225 NonZeros |= (1 << i);
5230 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5231 if (NumNonZero == 0)
5232 return DAG.getUNDEF(VT);
5234 // Special case for single non-zero, non-undef, element.
5235 if (NumNonZero == 1) {
5236 unsigned Idx = CountTrailingZeros_32(NonZeros);
5237 SDValue Item = Op.getOperand(Idx);
5239 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5240 // the value are obviously zero, truncate the value to i32 and do the
5241 // insertion that way. Only do this if the value is non-constant or if the
5242 // value is a constant being inserted into element 0. It is cheaper to do
5243 // a constant pool load than it is to do a movd + shuffle.
5244 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5245 (!IsAllConstants || Idx == 0)) {
5246 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5248 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5249 EVT VecVT = MVT::v4i32;
5250 unsigned VecElts = 4;
5252 // Truncate the value (which may itself be a constant) to i32, and
5253 // convert it to a vector with movd (S2V+shuffle to zero extend).
5254 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5255 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5256 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5258 // Now we have our 32-bit value zero extended in the low element of
5259 // a vector. If Idx != 0, swizzle it into place.
5261 SmallVector<int, 4> Mask;
5262 Mask.push_back(Idx);
5263 for (unsigned i = 1; i != VecElts; ++i)
5265 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5268 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5272 // If we have a constant or non-constant insertion into the low element of
5273 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5274 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5275 // depending on what the source datatype is.
5278 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5280 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5281 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5282 if (VT.is256BitVector()) {
5283 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5284 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5285 Item, DAG.getIntPtrConstant(0));
5287 assert(VT.is128BitVector() && "Expected an SSE value type!");
5288 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5289 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5290 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5293 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5294 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5295 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5296 if (VT.is256BitVector()) {
5297 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5298 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5300 assert(VT.is128BitVector() && "Expected an SSE value type!");
5301 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5303 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5307 // Is it a vector logical left shift?
5308 if (NumElems == 2 && Idx == 1 &&
5309 X86::isZeroNode(Op.getOperand(0)) &&
5310 !X86::isZeroNode(Op.getOperand(1))) {
5311 unsigned NumBits = VT.getSizeInBits();
5312 return getVShift(true, VT,
5313 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5314 VT, Op.getOperand(1)),
5315 NumBits/2, DAG, *this, dl);
5318 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5321 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5322 // is a non-constant being inserted into an element other than the low one,
5323 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5324 // movd/movss) to move this into the low element, then shuffle it into
5326 if (EVTBits == 32) {
5327 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5329 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5330 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5331 SmallVector<int, 8> MaskVec;
5332 for (unsigned i = 0; i != NumElems; ++i)
5333 MaskVec.push_back(i == Idx ? 0 : 1);
5334 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5338 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5339 if (Values.size() == 1) {
5340 if (EVTBits == 32) {
5341 // Instead of a shuffle like this:
5342 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5343 // Check if it's possible to issue this instead.
5344 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5345 unsigned Idx = CountTrailingZeros_32(NonZeros);
5346 SDValue Item = Op.getOperand(Idx);
5347 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5348 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5353 // A vector full of immediates; various special cases are already
5354 // handled, so this is best done with a single constant-pool load.
5358 // For AVX-length vectors, build the individual 128-bit pieces and use
5359 // shuffles to put them in place.
5360 if (VT.is256BitVector()) {
5361 SmallVector<SDValue, 32> V;
5362 for (unsigned i = 0; i != NumElems; ++i)
5363 V.push_back(Op.getOperand(i));
5365 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5367 // Build both the lower and upper subvector.
5368 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5369 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5372 // Recreate the wider vector with the lower and upper part.
5373 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5376 // Let legalizer expand 2-wide build_vectors.
5377 if (EVTBits == 64) {
5378 if (NumNonZero == 1) {
5379 // One half is zero or undef.
5380 unsigned Idx = CountTrailingZeros_32(NonZeros);
5381 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5382 Op.getOperand(Idx));
5383 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5388 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5389 if (EVTBits == 8 && NumElems == 16) {
5390 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5392 if (V.getNode()) return V;
5395 if (EVTBits == 16 && NumElems == 8) {
5396 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5398 if (V.getNode()) return V;
5401 // If element VT is == 32 bits, turn it into a number of shuffles.
5402 SmallVector<SDValue, 8> V(NumElems);
5403 if (NumElems == 4 && NumZero > 0) {
5404 for (unsigned i = 0; i < 4; ++i) {
5405 bool isZero = !(NonZeros & (1 << i));
5407 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5409 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5412 for (unsigned i = 0; i < 2; ++i) {
5413 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5416 V[i] = V[i*2]; // Must be a zero vector.
5419 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5422 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5425 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5430 bool Reverse1 = (NonZeros & 0x3) == 2;
5431 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5435 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5436 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5438 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5441 if (Values.size() > 1 && VT.is128BitVector()) {
5442 // Check for a build vector of consecutive loads.
5443 for (unsigned i = 0; i < NumElems; ++i)
5444 V[i] = Op.getOperand(i);
5446 // Check for elements which are consecutive loads.
5447 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5451 // For SSE 4.1, use insertps to put the high elements into the low element.
5452 if (getSubtarget()->hasSSE41()) {
5454 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5455 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5457 Result = DAG.getUNDEF(VT);
5459 for (unsigned i = 1; i < NumElems; ++i) {
5460 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5461 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5462 Op.getOperand(i), DAG.getIntPtrConstant(i));
5467 // Otherwise, expand into a number of unpckl*, start by extending each of
5468 // our (non-undef) elements to the full vector width with the element in the
5469 // bottom slot of the vector (which generates no code for SSE).
5470 for (unsigned i = 0; i < NumElems; ++i) {
5471 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5472 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5474 V[i] = DAG.getUNDEF(VT);
5477 // Next, we iteratively mix elements, e.g. for v4f32:
5478 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5479 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5480 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5481 unsigned EltStride = NumElems >> 1;
5482 while (EltStride != 0) {
5483 for (unsigned i = 0; i < EltStride; ++i) {
5484 // If V[i+EltStride] is undef and this is the first round of mixing,
5485 // then it is safe to just drop this shuffle: V[i] is already in the
5486 // right place, the one element (since it's the first round) being
5487 // inserted as undef can be dropped. This isn't safe for successive
5488 // rounds because they will permute elements within both vectors.
5489 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5490 EltStride == NumElems/2)
5493 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5502 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5503 // to create 256-bit vectors from two other 128-bit ones.
5504 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5505 DebugLoc dl = Op.getDebugLoc();
5506 EVT ResVT = Op.getValueType();
5508 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5510 SDValue V1 = Op.getOperand(0);
5511 SDValue V2 = Op.getOperand(1);
5512 unsigned NumElems = ResVT.getVectorNumElements();
5514 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5517 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5518 assert(Op.getNumOperands() == 2);
5520 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5521 // from two other 128-bit ones.
5522 return LowerAVXCONCAT_VECTORS(Op, DAG);
5525 // Try to lower a shuffle node into a simple blend instruction.
5527 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5528 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5529 SDValue V1 = SVOp->getOperand(0);
5530 SDValue V2 = SVOp->getOperand(1);
5531 DebugLoc dl = SVOp->getDebugLoc();
5532 MVT VT = SVOp->getValueType(0).getSimpleVT();
5533 unsigned NumElems = VT.getVectorNumElements();
5535 if (!Subtarget->hasSSE41())
5541 switch (VT.SimpleTy) {
5542 default: return SDValue();
5544 ISDNo = X86ISD::BLENDPW;
5549 ISDNo = X86ISD::BLENDPS;
5554 ISDNo = X86ISD::BLENDPD;
5559 if (!Subtarget->hasAVX())
5561 ISDNo = X86ISD::BLENDPS;
5566 if (!Subtarget->hasAVX())
5568 ISDNo = X86ISD::BLENDPD;
5572 assert(ISDNo && "Invalid Op Number");
5574 unsigned MaskVals = 0;
5576 for (unsigned i = 0; i != NumElems; ++i) {
5577 int EltIdx = SVOp->getMaskElt(i);
5578 if (EltIdx == (int)i || EltIdx < 0)
5580 else if (EltIdx == (int)(i + NumElems))
5581 continue; // Bit is set to zero;
5586 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5587 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5588 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5589 DAG.getConstant(MaskVals, MVT::i32));
5590 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5593 // v8i16 shuffles - Prefer shuffles in the following order:
5594 // 1. [all] pshuflw, pshufhw, optional move
5595 // 2. [ssse3] 1 x pshufb
5596 // 3. [ssse3] 2 x pshufb + 1 x por
5597 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5599 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5600 SelectionDAG &DAG) {
5601 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5602 SDValue V1 = SVOp->getOperand(0);
5603 SDValue V2 = SVOp->getOperand(1);
5604 DebugLoc dl = SVOp->getDebugLoc();
5605 SmallVector<int, 8> MaskVals;
5607 // Determine if more than 1 of the words in each of the low and high quadwords
5608 // of the result come from the same quadword of one of the two inputs. Undef
5609 // mask values count as coming from any quadword, for better codegen.
5610 unsigned LoQuad[] = { 0, 0, 0, 0 };
5611 unsigned HiQuad[] = { 0, 0, 0, 0 };
5612 std::bitset<4> InputQuads;
5613 for (unsigned i = 0; i < 8; ++i) {
5614 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5615 int EltIdx = SVOp->getMaskElt(i);
5616 MaskVals.push_back(EltIdx);
5625 InputQuads.set(EltIdx / 4);
5628 int BestLoQuad = -1;
5629 unsigned MaxQuad = 1;
5630 for (unsigned i = 0; i < 4; ++i) {
5631 if (LoQuad[i] > MaxQuad) {
5633 MaxQuad = LoQuad[i];
5637 int BestHiQuad = -1;
5639 for (unsigned i = 0; i < 4; ++i) {
5640 if (HiQuad[i] > MaxQuad) {
5642 MaxQuad = HiQuad[i];
5646 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5647 // of the two input vectors, shuffle them into one input vector so only a
5648 // single pshufb instruction is necessary. If There are more than 2 input
5649 // quads, disable the next transformation since it does not help SSSE3.
5650 bool V1Used = InputQuads[0] || InputQuads[1];
5651 bool V2Used = InputQuads[2] || InputQuads[3];
5652 if (Subtarget->hasSSSE3()) {
5653 if (InputQuads.count() == 2 && V1Used && V2Used) {
5654 BestLoQuad = InputQuads[0] ? 0 : 1;
5655 BestHiQuad = InputQuads[2] ? 2 : 3;
5657 if (InputQuads.count() > 2) {
5663 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5664 // the shuffle mask. If a quad is scored as -1, that means that it contains
5665 // words from all 4 input quadwords.
5667 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5669 BestLoQuad < 0 ? 0 : BestLoQuad,
5670 BestHiQuad < 0 ? 1 : BestHiQuad
5672 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5673 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5674 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5675 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5677 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5678 // source words for the shuffle, to aid later transformations.
5679 bool AllWordsInNewV = true;
5680 bool InOrder[2] = { true, true };
5681 for (unsigned i = 0; i != 8; ++i) {
5682 int idx = MaskVals[i];
5684 InOrder[i/4] = false;
5685 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5687 AllWordsInNewV = false;
5691 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5692 if (AllWordsInNewV) {
5693 for (int i = 0; i != 8; ++i) {
5694 int idx = MaskVals[i];
5697 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5698 if ((idx != i) && idx < 4)
5700 if ((idx != i) && idx > 3)
5709 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5710 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5711 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5712 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5713 unsigned TargetMask = 0;
5714 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5715 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5716 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5717 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5718 getShufflePSHUFLWImmediate(SVOp);
5719 V1 = NewV.getOperand(0);
5720 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5724 // If we have SSSE3, and all words of the result are from 1 input vector,
5725 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5726 // is present, fall back to case 4.
5727 if (Subtarget->hasSSSE3()) {
5728 SmallVector<SDValue,16> pshufbMask;
5730 // If we have elements from both input vectors, set the high bit of the
5731 // shuffle mask element to zero out elements that come from V2 in the V1
5732 // mask, and elements that come from V1 in the V2 mask, so that the two
5733 // results can be OR'd together.
5734 bool TwoInputs = V1Used && V2Used;
5735 for (unsigned i = 0; i != 8; ++i) {
5736 int EltIdx = MaskVals[i] * 2;
5737 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5738 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5739 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5740 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5742 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5743 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5744 DAG.getNode(ISD::BUILD_VECTOR, dl,
5745 MVT::v16i8, &pshufbMask[0], 16));
5747 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5749 // Calculate the shuffle mask for the second input, shuffle it, and
5750 // OR it with the first shuffled input.
5752 for (unsigned i = 0; i != 8; ++i) {
5753 int EltIdx = MaskVals[i] * 2;
5754 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5755 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5756 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5757 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5759 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5760 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5761 DAG.getNode(ISD::BUILD_VECTOR, dl,
5762 MVT::v16i8, &pshufbMask[0], 16));
5763 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5764 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5767 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5768 // and update MaskVals with new element order.
5769 std::bitset<8> InOrder;
5770 if (BestLoQuad >= 0) {
5771 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5772 for (int i = 0; i != 4; ++i) {
5773 int idx = MaskVals[i];
5776 } else if ((idx / 4) == BestLoQuad) {
5781 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5784 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5786 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5788 getShufflePSHUFLWImmediate(SVOp), DAG);
5792 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5793 // and update MaskVals with the new element order.
5794 if (BestHiQuad >= 0) {
5795 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5796 for (unsigned i = 4; i != 8; ++i) {
5797 int idx = MaskVals[i];
5800 } else if ((idx / 4) == BestHiQuad) {
5801 MaskV[i] = (idx & 3) + 4;
5805 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5808 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5809 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5810 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5812 getShufflePSHUFHWImmediate(SVOp), DAG);
5816 // In case BestHi & BestLo were both -1, which means each quadword has a word
5817 // from each of the four input quadwords, calculate the InOrder bitvector now
5818 // before falling through to the insert/extract cleanup.
5819 if (BestLoQuad == -1 && BestHiQuad == -1) {
5821 for (int i = 0; i != 8; ++i)
5822 if (MaskVals[i] < 0 || MaskVals[i] == i)
5826 // The other elements are put in the right place using pextrw and pinsrw.
5827 for (unsigned i = 0; i != 8; ++i) {
5830 int EltIdx = MaskVals[i];
5833 SDValue ExtOp = (EltIdx < 8) ?
5834 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5835 DAG.getIntPtrConstant(EltIdx)) :
5836 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5837 DAG.getIntPtrConstant(EltIdx - 8));
5838 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5839 DAG.getIntPtrConstant(i));
5844 // v16i8 shuffles - Prefer shuffles in the following order:
5845 // 1. [ssse3] 1 x pshufb
5846 // 2. [ssse3] 2 x pshufb + 1 x por
5847 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5849 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5851 const X86TargetLowering &TLI) {
5852 SDValue V1 = SVOp->getOperand(0);
5853 SDValue V2 = SVOp->getOperand(1);
5854 DebugLoc dl = SVOp->getDebugLoc();
5855 ArrayRef<int> MaskVals = SVOp->getMask();
5857 // If we have SSSE3, case 1 is generated when all result bytes come from
5858 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5859 // present, fall back to case 3.
5861 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5862 if (TLI.getSubtarget()->hasSSSE3()) {
5863 SmallVector<SDValue,16> pshufbMask;
5865 // If all result elements are from one input vector, then only translate
5866 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5868 // Otherwise, we have elements from both input vectors, and must zero out
5869 // elements that come from V2 in the first mask, and V1 in the second mask
5870 // so that we can OR them together.
5871 for (unsigned i = 0; i != 16; ++i) {
5872 int EltIdx = MaskVals[i];
5873 if (EltIdx < 0 || EltIdx >= 16)
5875 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5877 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5878 DAG.getNode(ISD::BUILD_VECTOR, dl,
5879 MVT::v16i8, &pshufbMask[0], 16));
5881 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5882 // the 2nd operand if it's undefined or zero.
5883 if (V2.getOpcode() == ISD::UNDEF ||
5884 ISD::isBuildVectorAllZeros(V2.getNode()))
5887 // Calculate the shuffle mask for the second input, shuffle it, and
5888 // OR it with the first shuffled input.
5890 for (unsigned i = 0; i != 16; ++i) {
5891 int EltIdx = MaskVals[i];
5892 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5893 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5895 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5896 DAG.getNode(ISD::BUILD_VECTOR, dl,
5897 MVT::v16i8, &pshufbMask[0], 16));
5898 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5901 // No SSSE3 - Calculate in place words and then fix all out of place words
5902 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5903 // the 16 different words that comprise the two doublequadword input vectors.
5904 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5905 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5907 for (int i = 0; i != 8; ++i) {
5908 int Elt0 = MaskVals[i*2];
5909 int Elt1 = MaskVals[i*2+1];
5911 // This word of the result is all undef, skip it.
5912 if (Elt0 < 0 && Elt1 < 0)
5915 // This word of the result is already in the correct place, skip it.
5916 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5919 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5920 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5923 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5924 // using a single extract together, load it and store it.
5925 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5926 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5927 DAG.getIntPtrConstant(Elt1 / 2));
5928 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5929 DAG.getIntPtrConstant(i));
5933 // If Elt1 is defined, extract it from the appropriate source. If the
5934 // source byte is not also odd, shift the extracted word left 8 bits
5935 // otherwise clear the bottom 8 bits if we need to do an or.
5937 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5938 DAG.getIntPtrConstant(Elt1 / 2));
5939 if ((Elt1 & 1) == 0)
5940 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5942 TLI.getShiftAmountTy(InsElt.getValueType())));
5944 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5945 DAG.getConstant(0xFF00, MVT::i16));
5947 // If Elt0 is defined, extract it from the appropriate source. If the
5948 // source byte is not also even, shift the extracted word right 8 bits. If
5949 // Elt1 was also defined, OR the extracted values together before
5950 // inserting them in the result.
5952 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5953 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5954 if ((Elt0 & 1) != 0)
5955 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5957 TLI.getShiftAmountTy(InsElt0.getValueType())));
5959 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5960 DAG.getConstant(0x00FF, MVT::i16));
5961 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5964 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5965 DAG.getIntPtrConstant(i));
5967 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5970 // v32i8 shuffles - Translate to VPSHUFB if possible.
5972 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
5973 const X86Subtarget *Subtarget,
5974 SelectionDAG &DAG) {
5975 EVT VT = SVOp->getValueType(0);
5976 SDValue V1 = SVOp->getOperand(0);
5977 SDValue V2 = SVOp->getOperand(1);
5978 DebugLoc dl = SVOp->getDebugLoc();
5979 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
5981 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5982 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
5983 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
5985 // VPSHUFB may be generated if
5986 // (1) one of input vector is undefined or zeroinitializer.
5987 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
5988 // And (2) the mask indexes don't cross the 128-bit lane.
5989 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
5990 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
5993 if (V1IsAllZero && !V2IsAllZero) {
5994 CommuteVectorShuffleMask(MaskVals, 32);
5997 SmallVector<SDValue, 32> pshufbMask;
5998 for (unsigned i = 0; i != 32; i++) {
5999 int EltIdx = MaskVals[i];
6000 if (EltIdx < 0 || EltIdx >= 32)
6003 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6004 // Cross lane is not allowed.
6008 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6010 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6011 DAG.getNode(ISD::BUILD_VECTOR, dl,
6012 MVT::v32i8, &pshufbMask[0], 32));
6015 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6016 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6017 /// done when every pair / quad of shuffle mask elements point to elements in
6018 /// the right sequence. e.g.
6019 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6021 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6022 SelectionDAG &DAG, DebugLoc dl) {
6023 MVT VT = SVOp->getValueType(0).getSimpleVT();
6024 unsigned NumElems = VT.getVectorNumElements();
6027 switch (VT.SimpleTy) {
6028 default: llvm_unreachable("Unexpected!");
6029 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6030 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6031 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6032 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6033 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6034 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6037 SmallVector<int, 8> MaskVec;
6038 for (unsigned i = 0; i != NumElems; i += Scale) {
6040 for (unsigned j = 0; j != Scale; ++j) {
6041 int EltIdx = SVOp->getMaskElt(i+j);
6045 StartIdx = (EltIdx / Scale);
6046 if (EltIdx != (int)(StartIdx*Scale + j))
6049 MaskVec.push_back(StartIdx);
6052 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6053 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6054 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6057 /// getVZextMovL - Return a zero-extending vector move low node.
6059 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6060 SDValue SrcOp, SelectionDAG &DAG,
6061 const X86Subtarget *Subtarget, DebugLoc dl) {
6062 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6063 LoadSDNode *LD = NULL;
6064 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6065 LD = dyn_cast<LoadSDNode>(SrcOp);
6067 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6069 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6070 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6071 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6072 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6073 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6075 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6076 return DAG.getNode(ISD::BITCAST, dl, VT,
6077 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6078 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6086 return DAG.getNode(ISD::BITCAST, dl, VT,
6087 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6088 DAG.getNode(ISD::BITCAST, dl,
6092 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6093 /// which could not be matched by any known target speficic shuffle
6095 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6097 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6098 if (NewOp.getNode())
6101 EVT VT = SVOp->getValueType(0);
6103 unsigned NumElems = VT.getVectorNumElements();
6104 unsigned NumLaneElems = NumElems / 2;
6106 DebugLoc dl = SVOp->getDebugLoc();
6107 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6108 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6111 SmallVector<int, 16> Mask;
6112 for (unsigned l = 0; l < 2; ++l) {
6113 // Build a shuffle mask for the output, discovering on the fly which
6114 // input vectors to use as shuffle operands (recorded in InputUsed).
6115 // If building a suitable shuffle vector proves too hard, then bail
6116 // out with UseBuildVector set.
6117 bool UseBuildVector = false;
6118 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6119 unsigned LaneStart = l * NumLaneElems;
6120 for (unsigned i = 0; i != NumLaneElems; ++i) {
6121 // The mask element. This indexes into the input.
6122 int Idx = SVOp->getMaskElt(i+LaneStart);
6124 // the mask element does not index into any input vector.
6129 // The input vector this mask element indexes into.
6130 int Input = Idx / NumLaneElems;
6132 // Turn the index into an offset from the start of the input vector.
6133 Idx -= Input * NumLaneElems;
6135 // Find or create a shuffle vector operand to hold this input.
6137 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6138 if (InputUsed[OpNo] == Input)
6139 // This input vector is already an operand.
6141 if (InputUsed[OpNo] < 0) {
6142 // Create a new operand for this input vector.
6143 InputUsed[OpNo] = Input;
6148 if (OpNo >= array_lengthof(InputUsed)) {
6149 // More than two input vectors used! Give up on trying to create a
6150 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6151 UseBuildVector = true;
6155 // Add the mask index for the new shuffle vector.
6156 Mask.push_back(Idx + OpNo * NumLaneElems);
6159 if (UseBuildVector) {
6160 SmallVector<SDValue, 16> SVOps;
6161 for (unsigned i = 0; i != NumLaneElems; ++i) {
6162 // The mask element. This indexes into the input.
6163 int Idx = SVOp->getMaskElt(i+LaneStart);
6165 SVOps.push_back(DAG.getUNDEF(EltVT));
6169 // The input vector this mask element indexes into.
6170 int Input = Idx / NumElems;
6172 // Turn the index into an offset from the start of the input vector.
6173 Idx -= Input * NumElems;
6175 // Extract the vector element by hand.
6176 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6177 SVOp->getOperand(Input),
6178 DAG.getIntPtrConstant(Idx)));
6181 // Construct the output using a BUILD_VECTOR.
6182 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6184 } else if (InputUsed[0] < 0) {
6185 // No input vectors were used! The result is undefined.
6186 Output[l] = DAG.getUNDEF(NVT);
6188 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6189 (InputUsed[0] % 2) * NumLaneElems,
6191 // If only one input was used, use an undefined vector for the other.
6192 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6193 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6194 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6195 // At least one input vector was used. Create a new shuffle vector.
6196 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6202 // Concatenate the result back
6203 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6206 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6207 /// 4 elements, and match them with several different shuffle types.
6209 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6210 SDValue V1 = SVOp->getOperand(0);
6211 SDValue V2 = SVOp->getOperand(1);
6212 DebugLoc dl = SVOp->getDebugLoc();
6213 EVT VT = SVOp->getValueType(0);
6215 assert(VT.is128BitVector() && "Unsupported vector size");
6217 std::pair<int, int> Locs[4];
6218 int Mask1[] = { -1, -1, -1, -1 };
6219 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6223 for (unsigned i = 0; i != 4; ++i) {
6224 int Idx = PermMask[i];
6226 Locs[i] = std::make_pair(-1, -1);
6228 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6230 Locs[i] = std::make_pair(0, NumLo);
6234 Locs[i] = std::make_pair(1, NumHi);
6236 Mask1[2+NumHi] = Idx;
6242 if (NumLo <= 2 && NumHi <= 2) {
6243 // If no more than two elements come from either vector. This can be
6244 // implemented with two shuffles. First shuffle gather the elements.
6245 // The second shuffle, which takes the first shuffle as both of its
6246 // vector operands, put the elements into the right order.
6247 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6249 int Mask2[] = { -1, -1, -1, -1 };
6251 for (unsigned i = 0; i != 4; ++i)
6252 if (Locs[i].first != -1) {
6253 unsigned Idx = (i < 2) ? 0 : 4;
6254 Idx += Locs[i].first * 2 + Locs[i].second;
6258 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6261 if (NumLo == 3 || NumHi == 3) {
6262 // Otherwise, we must have three elements from one vector, call it X, and
6263 // one element from the other, call it Y. First, use a shufps to build an
6264 // intermediate vector with the one element from Y and the element from X
6265 // that will be in the same half in the final destination (the indexes don't
6266 // matter). Then, use a shufps to build the final vector, taking the half
6267 // containing the element from Y from the intermediate, and the other half
6270 // Normalize it so the 3 elements come from V1.
6271 CommuteVectorShuffleMask(PermMask, 4);
6275 // Find the element from V2.
6277 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6278 int Val = PermMask[HiIndex];
6285 Mask1[0] = PermMask[HiIndex];
6287 Mask1[2] = PermMask[HiIndex^1];
6289 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6292 Mask1[0] = PermMask[0];
6293 Mask1[1] = PermMask[1];
6294 Mask1[2] = HiIndex & 1 ? 6 : 4;
6295 Mask1[3] = HiIndex & 1 ? 4 : 6;
6296 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6299 Mask1[0] = HiIndex & 1 ? 2 : 0;
6300 Mask1[1] = HiIndex & 1 ? 0 : 2;
6301 Mask1[2] = PermMask[2];
6302 Mask1[3] = PermMask[3];
6307 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6310 // Break it into (shuffle shuffle_hi, shuffle_lo).
6311 int LoMask[] = { -1, -1, -1, -1 };
6312 int HiMask[] = { -1, -1, -1, -1 };
6314 int *MaskPtr = LoMask;
6315 unsigned MaskIdx = 0;
6318 for (unsigned i = 0; i != 4; ++i) {
6325 int Idx = PermMask[i];
6327 Locs[i] = std::make_pair(-1, -1);
6328 } else if (Idx < 4) {
6329 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6330 MaskPtr[LoIdx] = Idx;
6333 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6334 MaskPtr[HiIdx] = Idx;
6339 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6340 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6341 int MaskOps[] = { -1, -1, -1, -1 };
6342 for (unsigned i = 0; i != 4; ++i)
6343 if (Locs[i].first != -1)
6344 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6345 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6348 static bool MayFoldVectorLoad(SDValue V) {
6349 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6350 V = V.getOperand(0);
6351 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6352 V = V.getOperand(0);
6353 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6354 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6355 // BUILD_VECTOR (load), undef
6356 V = V.getOperand(0);
6362 // FIXME: the version above should always be used. Since there's
6363 // a bug where several vector shuffles can't be folded because the
6364 // DAG is not updated during lowering and a node claims to have two
6365 // uses while it only has one, use this version, and let isel match
6366 // another instruction if the load really happens to have more than
6367 // one use. Remove this version after this bug get fixed.
6368 // rdar://8434668, PR8156
6369 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6370 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6371 V = V.getOperand(0);
6372 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6373 V = V.getOperand(0);
6374 if (ISD::isNormalLoad(V.getNode()))
6380 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6381 EVT VT = Op.getValueType();
6383 // Canonizalize to v2f64.
6384 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6385 return DAG.getNode(ISD::BITCAST, dl, VT,
6386 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6391 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6393 SDValue V1 = Op.getOperand(0);
6394 SDValue V2 = Op.getOperand(1);
6395 EVT VT = Op.getValueType();
6397 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6399 if (HasSSE2 && VT == MVT::v2f64)
6400 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6402 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6403 return DAG.getNode(ISD::BITCAST, dl, VT,
6404 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6405 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6406 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6410 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6411 SDValue V1 = Op.getOperand(0);
6412 SDValue V2 = Op.getOperand(1);
6413 EVT VT = Op.getValueType();
6415 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6416 "unsupported shuffle type");
6418 if (V2.getOpcode() == ISD::UNDEF)
6422 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6426 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6427 SDValue V1 = Op.getOperand(0);
6428 SDValue V2 = Op.getOperand(1);
6429 EVT VT = Op.getValueType();
6430 unsigned NumElems = VT.getVectorNumElements();
6432 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6433 // operand of these instructions is only memory, so check if there's a
6434 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6436 bool CanFoldLoad = false;
6438 // Trivial case, when V2 comes from a load.
6439 if (MayFoldVectorLoad(V2))
6442 // When V1 is a load, it can be folded later into a store in isel, example:
6443 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6445 // (MOVLPSmr addr:$src1, VR128:$src2)
6446 // So, recognize this potential and also use MOVLPS or MOVLPD
6447 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6450 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6452 if (HasSSE2 && NumElems == 2)
6453 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6456 // If we don't care about the second element, proceed to use movss.
6457 if (SVOp->getMaskElt(1) != -1)
6458 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6461 // movl and movlp will both match v2i64, but v2i64 is never matched by
6462 // movl earlier because we make it strict to avoid messing with the movlp load
6463 // folding logic (see the code above getMOVLP call). Match it here then,
6464 // this is horrible, but will stay like this until we move all shuffle
6465 // matching to x86 specific nodes. Note that for the 1st condition all
6466 // types are matched with movsd.
6468 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6469 // as to remove this logic from here, as much as possible
6470 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6471 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6472 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6475 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6477 // Invert the operand order and use SHUFPS to match it.
6478 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6479 getShuffleSHUFImmediate(SVOp), DAG);
6483 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6484 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6485 EVT VT = Op.getValueType();
6486 DebugLoc dl = Op.getDebugLoc();
6487 SDValue V1 = Op.getOperand(0);
6488 SDValue V2 = Op.getOperand(1);
6490 if (isZeroShuffle(SVOp))
6491 return getZeroVector(VT, Subtarget, DAG, dl);
6493 // Handle splat operations
6494 if (SVOp->isSplat()) {
6495 unsigned NumElem = VT.getVectorNumElements();
6496 int Size = VT.getSizeInBits();
6498 // Use vbroadcast whenever the splat comes from a foldable load
6499 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6500 if (Broadcast.getNode())
6503 // Handle splats by matching through known shuffle masks
6504 if ((Size == 128 && NumElem <= 4) ||
6505 (Size == 256 && NumElem < 8))
6508 // All remaning splats are promoted to target supported vector shuffles.
6509 return PromoteSplat(SVOp, DAG);
6512 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6514 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6515 VT == MVT::v16i16 || VT == MVT::v32i8) {
6516 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6517 if (NewOp.getNode())
6518 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6519 } else if ((VT == MVT::v4i32 ||
6520 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6521 // FIXME: Figure out a cleaner way to do this.
6522 // Try to make use of movq to zero out the top part.
6523 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6524 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6525 if (NewOp.getNode()) {
6526 EVT NewVT = NewOp.getValueType();
6527 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6528 NewVT, true, false))
6529 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6530 DAG, Subtarget, dl);
6532 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6533 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6534 if (NewOp.getNode()) {
6535 EVT NewVT = NewOp.getValueType();
6536 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6537 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6538 DAG, Subtarget, dl);
6546 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6547 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6548 SDValue V1 = Op.getOperand(0);
6549 SDValue V2 = Op.getOperand(1);
6550 EVT VT = Op.getValueType();
6551 DebugLoc dl = Op.getDebugLoc();
6552 unsigned NumElems = VT.getVectorNumElements();
6553 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6554 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6555 bool V1IsSplat = false;
6556 bool V2IsSplat = false;
6557 bool HasSSE2 = Subtarget->hasSSE2();
6558 bool HasAVX = Subtarget->hasAVX();
6559 bool HasAVX2 = Subtarget->hasAVX2();
6560 MachineFunction &MF = DAG.getMachineFunction();
6561 bool OptForSize = MF.getFunction()->getFnAttributes().
6562 hasAttribute(Attributes::OptimizeForSize);
6564 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6566 if (V1IsUndef && V2IsUndef)
6567 return DAG.getUNDEF(VT);
6569 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6571 // Vector shuffle lowering takes 3 steps:
6573 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6574 // narrowing and commutation of operands should be handled.
6575 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6577 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6578 // so the shuffle can be broken into other shuffles and the legalizer can
6579 // try the lowering again.
6581 // The general idea is that no vector_shuffle operation should be left to
6582 // be matched during isel, all of them must be converted to a target specific
6585 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6586 // narrowing and commutation of operands should be handled. The actual code
6587 // doesn't include all of those, work in progress...
6588 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6589 if (NewOp.getNode())
6592 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6594 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6595 // unpckh_undef). Only use pshufd if speed is more important than size.
6596 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6597 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6598 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6599 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6601 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6602 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6603 return getMOVDDup(Op, dl, V1, DAG);
6605 if (isMOVHLPS_v_undef_Mask(M, VT))
6606 return getMOVHighToLow(Op, dl, DAG);
6608 // Use to match splats
6609 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6610 (VT == MVT::v2f64 || VT == MVT::v2i64))
6611 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6613 if (isPSHUFDMask(M, VT)) {
6614 // The actual implementation will match the mask in the if above and then
6615 // during isel it can match several different instructions, not only pshufd
6616 // as its name says, sad but true, emulate the behavior for now...
6617 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6618 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6620 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6622 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6623 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6625 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6626 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6628 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6632 // Check if this can be converted into a logical shift.
6633 bool isLeft = false;
6636 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6637 if (isShift && ShVal.hasOneUse()) {
6638 // If the shifted value has multiple uses, it may be cheaper to use
6639 // v_set0 + movlhps or movhlps, etc.
6640 EVT EltVT = VT.getVectorElementType();
6641 ShAmt *= EltVT.getSizeInBits();
6642 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6645 if (isMOVLMask(M, VT)) {
6646 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6647 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6648 if (!isMOVLPMask(M, VT)) {
6649 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6650 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6652 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6653 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6657 // FIXME: fold these into legal mask.
6658 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6659 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6661 if (isMOVHLPSMask(M, VT))
6662 return getMOVHighToLow(Op, dl, DAG);
6664 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6665 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6667 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6668 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6670 if (isMOVLPMask(M, VT))
6671 return getMOVLP(Op, dl, DAG, HasSSE2);
6673 if (ShouldXformToMOVHLPS(M, VT) ||
6674 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6675 return CommuteVectorShuffle(SVOp, DAG);
6678 // No better options. Use a vshldq / vsrldq.
6679 EVT EltVT = VT.getVectorElementType();
6680 ShAmt *= EltVT.getSizeInBits();
6681 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6684 bool Commuted = false;
6685 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6686 // 1,1,1,1 -> v8i16 though.
6687 V1IsSplat = isSplatVector(V1.getNode());
6688 V2IsSplat = isSplatVector(V2.getNode());
6690 // Canonicalize the splat or undef, if present, to be on the RHS.
6691 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6692 CommuteVectorShuffleMask(M, NumElems);
6694 std::swap(V1IsSplat, V2IsSplat);
6698 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6699 // Shuffling low element of v1 into undef, just return v1.
6702 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6703 // the instruction selector will not match, so get a canonical MOVL with
6704 // swapped operands to undo the commute.
6705 return getMOVL(DAG, dl, VT, V2, V1);
6708 if (isUNPCKLMask(M, VT, HasAVX2))
6709 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6711 if (isUNPCKHMask(M, VT, HasAVX2))
6712 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6715 // Normalize mask so all entries that point to V2 points to its first
6716 // element then try to match unpck{h|l} again. If match, return a
6717 // new vector_shuffle with the corrected mask.p
6718 SmallVector<int, 8> NewMask(M.begin(), M.end());
6719 NormalizeMask(NewMask, NumElems);
6720 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6721 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6722 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6723 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6727 // Commute is back and try unpck* again.
6728 // FIXME: this seems wrong.
6729 CommuteVectorShuffleMask(M, NumElems);
6731 std::swap(V1IsSplat, V2IsSplat);
6734 if (isUNPCKLMask(M, VT, HasAVX2))
6735 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6737 if (isUNPCKHMask(M, VT, HasAVX2))
6738 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6741 // Normalize the node to match x86 shuffle ops if needed
6742 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6743 return CommuteVectorShuffle(SVOp, DAG);
6745 // The checks below are all present in isShuffleMaskLegal, but they are
6746 // inlined here right now to enable us to directly emit target specific
6747 // nodes, and remove one by one until they don't return Op anymore.
6749 if (isPALIGNRMask(M, VT, Subtarget))
6750 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6751 getShufflePALIGNRImmediate(SVOp),
6754 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6755 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6756 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6757 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6760 if (isPSHUFHWMask(M, VT, HasAVX2))
6761 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6762 getShufflePSHUFHWImmediate(SVOp),
6765 if (isPSHUFLWMask(M, VT, HasAVX2))
6766 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6767 getShufflePSHUFLWImmediate(SVOp),
6770 if (isSHUFPMask(M, VT, HasAVX))
6771 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6772 getShuffleSHUFImmediate(SVOp), DAG);
6774 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6775 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6776 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6777 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6779 //===--------------------------------------------------------------------===//
6780 // Generate target specific nodes for 128 or 256-bit shuffles only
6781 // supported in the AVX instruction set.
6784 // Handle VMOVDDUPY permutations
6785 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6786 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6788 // Handle VPERMILPS/D* permutations
6789 if (isVPERMILPMask(M, VT, HasAVX)) {
6790 if (HasAVX2 && VT == MVT::v8i32)
6791 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6792 getShuffleSHUFImmediate(SVOp), DAG);
6793 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6794 getShuffleSHUFImmediate(SVOp), DAG);
6797 // Handle VPERM2F128/VPERM2I128 permutations
6798 if (isVPERM2X128Mask(M, VT, HasAVX))
6799 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6800 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6802 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6803 if (BlendOp.getNode())
6806 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6807 SmallVector<SDValue, 8> permclMask;
6808 for (unsigned i = 0; i != 8; ++i) {
6809 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6811 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6813 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6814 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6815 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6818 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6819 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6820 getShuffleCLImmediate(SVOp), DAG);
6823 //===--------------------------------------------------------------------===//
6824 // Since no target specific shuffle was selected for this generic one,
6825 // lower it into other known shuffles. FIXME: this isn't true yet, but
6826 // this is the plan.
6829 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6830 if (VT == MVT::v8i16) {
6831 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6832 if (NewOp.getNode())
6836 if (VT == MVT::v16i8) {
6837 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6838 if (NewOp.getNode())
6842 if (VT == MVT::v32i8) {
6843 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
6844 if (NewOp.getNode())
6848 // Handle all 128-bit wide vectors with 4 elements, and match them with
6849 // several different shuffle types.
6850 if (NumElems == 4 && VT.is128BitVector())
6851 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6853 // Handle general 256-bit shuffles
6854 if (VT.is256BitVector())
6855 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6862 SelectionDAG &DAG) const {
6863 EVT VT = Op.getValueType();
6864 DebugLoc dl = Op.getDebugLoc();
6866 if (!Op.getOperand(0).getValueType().is128BitVector())
6869 if (VT.getSizeInBits() == 8) {
6870 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6871 Op.getOperand(0), Op.getOperand(1));
6872 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6873 DAG.getValueType(VT));
6874 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6877 if (VT.getSizeInBits() == 16) {
6878 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6879 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6881 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6882 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6883 DAG.getNode(ISD::BITCAST, dl,
6887 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6888 Op.getOperand(0), Op.getOperand(1));
6889 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6890 DAG.getValueType(VT));
6891 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6894 if (VT == MVT::f32) {
6895 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6896 // the result back to FR32 register. It's only worth matching if the
6897 // result has a single use which is a store or a bitcast to i32. And in
6898 // the case of a store, it's not worth it if the index is a constant 0,
6899 // because a MOVSSmr can be used instead, which is smaller and faster.
6900 if (!Op.hasOneUse())
6902 SDNode *User = *Op.getNode()->use_begin();
6903 if ((User->getOpcode() != ISD::STORE ||
6904 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6905 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6906 (User->getOpcode() != ISD::BITCAST ||
6907 User->getValueType(0) != MVT::i32))
6909 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6910 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6913 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6916 if (VT == MVT::i32 || VT == MVT::i64) {
6917 // ExtractPS/pextrq works with constant index.
6918 if (isa<ConstantSDNode>(Op.getOperand(1)))
6926 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6927 SelectionDAG &DAG) const {
6928 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6931 SDValue Vec = Op.getOperand(0);
6932 EVT VecVT = Vec.getValueType();
6934 // If this is a 256-bit vector result, first extract the 128-bit vector and
6935 // then extract the element from the 128-bit vector.
6936 if (VecVT.is256BitVector()) {
6937 DebugLoc dl = Op.getNode()->getDebugLoc();
6938 unsigned NumElems = VecVT.getVectorNumElements();
6939 SDValue Idx = Op.getOperand(1);
6940 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6942 // Get the 128-bit vector.
6943 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6945 if (IdxVal >= NumElems/2)
6946 IdxVal -= NumElems/2;
6947 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6948 DAG.getConstant(IdxVal, MVT::i32));
6951 assert(VecVT.is128BitVector() && "Unexpected vector length");
6953 if (Subtarget->hasSSE41()) {
6954 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6959 EVT VT = Op.getValueType();
6960 DebugLoc dl = Op.getDebugLoc();
6961 // TODO: handle v16i8.
6962 if (VT.getSizeInBits() == 16) {
6963 SDValue Vec = Op.getOperand(0);
6964 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6966 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6967 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6968 DAG.getNode(ISD::BITCAST, dl,
6971 // Transform it so it match pextrw which produces a 32-bit result.
6972 EVT EltVT = MVT::i32;
6973 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6974 Op.getOperand(0), Op.getOperand(1));
6975 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6976 DAG.getValueType(VT));
6977 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6980 if (VT.getSizeInBits() == 32) {
6981 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6985 // SHUFPS the element to the lowest double word, then movss.
6986 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6987 EVT VVT = Op.getOperand(0).getValueType();
6988 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6989 DAG.getUNDEF(VVT), Mask);
6990 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6991 DAG.getIntPtrConstant(0));
6994 if (VT.getSizeInBits() == 64) {
6995 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6996 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6997 // to match extract_elt for f64.
6998 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7002 // UNPCKHPD the element to the lowest double word, then movsd.
7003 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7004 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7005 int Mask[2] = { 1, -1 };
7006 EVT VVT = Op.getOperand(0).getValueType();
7007 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7008 DAG.getUNDEF(VVT), Mask);
7009 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7010 DAG.getIntPtrConstant(0));
7017 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7018 SelectionDAG &DAG) const {
7019 EVT VT = Op.getValueType();
7020 EVT EltVT = VT.getVectorElementType();
7021 DebugLoc dl = Op.getDebugLoc();
7023 SDValue N0 = Op.getOperand(0);
7024 SDValue N1 = Op.getOperand(1);
7025 SDValue N2 = Op.getOperand(2);
7027 if (!VT.is128BitVector())
7030 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7031 isa<ConstantSDNode>(N2)) {
7033 if (VT == MVT::v8i16)
7034 Opc = X86ISD::PINSRW;
7035 else if (VT == MVT::v16i8)
7036 Opc = X86ISD::PINSRB;
7038 Opc = X86ISD::PINSRB;
7040 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7042 if (N1.getValueType() != MVT::i32)
7043 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7044 if (N2.getValueType() != MVT::i32)
7045 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7046 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7049 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7050 // Bits [7:6] of the constant are the source select. This will always be
7051 // zero here. The DAG Combiner may combine an extract_elt index into these
7052 // bits. For example (insert (extract, 3), 2) could be matched by putting
7053 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7054 // Bits [5:4] of the constant are the destination select. This is the
7055 // value of the incoming immediate.
7056 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7057 // combine either bitwise AND or insert of float 0.0 to set these bits.
7058 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7059 // Create this as a scalar to vector..
7060 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7061 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7064 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7065 // PINSR* works with constant index.
7072 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7073 EVT VT = Op.getValueType();
7074 EVT EltVT = VT.getVectorElementType();
7076 DebugLoc dl = Op.getDebugLoc();
7077 SDValue N0 = Op.getOperand(0);
7078 SDValue N1 = Op.getOperand(1);
7079 SDValue N2 = Op.getOperand(2);
7081 // If this is a 256-bit vector result, first extract the 128-bit vector,
7082 // insert the element into the extracted half and then place it back.
7083 if (VT.is256BitVector()) {
7084 if (!isa<ConstantSDNode>(N2))
7087 // Get the desired 128-bit vector half.
7088 unsigned NumElems = VT.getVectorNumElements();
7089 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7090 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7092 // Insert the element into the desired half.
7093 bool Upper = IdxVal >= NumElems/2;
7094 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7095 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7097 // Insert the changed part back to the 256-bit vector
7098 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7101 if (Subtarget->hasSSE41())
7102 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7104 if (EltVT == MVT::i8)
7107 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7108 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7109 // as its second argument.
7110 if (N1.getValueType() != MVT::i32)
7111 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7112 if (N2.getValueType() != MVT::i32)
7113 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7114 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7119 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7120 LLVMContext *Context = DAG.getContext();
7121 DebugLoc dl = Op.getDebugLoc();
7122 EVT OpVT = Op.getValueType();
7124 // If this is a 256-bit vector result, first insert into a 128-bit
7125 // vector and then insert into the 256-bit vector.
7126 if (!OpVT.is128BitVector()) {
7127 // Insert into a 128-bit vector.
7128 EVT VT128 = EVT::getVectorVT(*Context,
7129 OpVT.getVectorElementType(),
7130 OpVT.getVectorNumElements() / 2);
7132 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7134 // Insert the 128-bit vector.
7135 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7138 if (OpVT == MVT::v1i64 &&
7139 Op.getOperand(0).getValueType() == MVT::i64)
7140 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7142 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7143 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7144 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7145 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7148 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7149 // a simple subregister reference or explicit instructions to grab
7150 // upper bits of a vector.
7151 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7152 SelectionDAG &DAG) {
7153 if (Subtarget->hasAVX()) {
7154 DebugLoc dl = Op.getNode()->getDebugLoc();
7155 SDValue Vec = Op.getNode()->getOperand(0);
7156 SDValue Idx = Op.getNode()->getOperand(1);
7158 if (Op.getNode()->getValueType(0).is128BitVector() &&
7159 Vec.getNode()->getValueType(0).is256BitVector() &&
7160 isa<ConstantSDNode>(Idx)) {
7161 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7162 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7168 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7169 // simple superregister reference or explicit instructions to insert
7170 // the upper bits of a vector.
7171 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7172 SelectionDAG &DAG) {
7173 if (Subtarget->hasAVX()) {
7174 DebugLoc dl = Op.getNode()->getDebugLoc();
7175 SDValue Vec = Op.getNode()->getOperand(0);
7176 SDValue SubVec = Op.getNode()->getOperand(1);
7177 SDValue Idx = Op.getNode()->getOperand(2);
7179 if (Op.getNode()->getValueType(0).is256BitVector() &&
7180 SubVec.getNode()->getValueType(0).is128BitVector() &&
7181 isa<ConstantSDNode>(Idx)) {
7182 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7183 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7189 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7190 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7191 // one of the above mentioned nodes. It has to be wrapped because otherwise
7192 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7193 // be used to form addressing mode. These wrapped nodes will be selected
7196 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7197 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7199 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7201 unsigned char OpFlag = 0;
7202 unsigned WrapperKind = X86ISD::Wrapper;
7203 CodeModel::Model M = getTargetMachine().getCodeModel();
7205 if (Subtarget->isPICStyleRIPRel() &&
7206 (M == CodeModel::Small || M == CodeModel::Kernel))
7207 WrapperKind = X86ISD::WrapperRIP;
7208 else if (Subtarget->isPICStyleGOT())
7209 OpFlag = X86II::MO_GOTOFF;
7210 else if (Subtarget->isPICStyleStubPIC())
7211 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7213 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7215 CP->getOffset(), OpFlag);
7216 DebugLoc DL = CP->getDebugLoc();
7217 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7218 // With PIC, the address is actually $g + Offset.
7220 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7221 DAG.getNode(X86ISD::GlobalBaseReg,
7222 DebugLoc(), getPointerTy()),
7229 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7230 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7232 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7234 unsigned char OpFlag = 0;
7235 unsigned WrapperKind = X86ISD::Wrapper;
7236 CodeModel::Model M = getTargetMachine().getCodeModel();
7238 if (Subtarget->isPICStyleRIPRel() &&
7239 (M == CodeModel::Small || M == CodeModel::Kernel))
7240 WrapperKind = X86ISD::WrapperRIP;
7241 else if (Subtarget->isPICStyleGOT())
7242 OpFlag = X86II::MO_GOTOFF;
7243 else if (Subtarget->isPICStyleStubPIC())
7244 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7246 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7248 DebugLoc DL = JT->getDebugLoc();
7249 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7251 // With PIC, the address is actually $g + Offset.
7253 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7254 DAG.getNode(X86ISD::GlobalBaseReg,
7255 DebugLoc(), getPointerTy()),
7262 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7263 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7265 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7267 unsigned char OpFlag = 0;
7268 unsigned WrapperKind = X86ISD::Wrapper;
7269 CodeModel::Model M = getTargetMachine().getCodeModel();
7271 if (Subtarget->isPICStyleRIPRel() &&
7272 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7273 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7274 OpFlag = X86II::MO_GOTPCREL;
7275 WrapperKind = X86ISD::WrapperRIP;
7276 } else if (Subtarget->isPICStyleGOT()) {
7277 OpFlag = X86II::MO_GOT;
7278 } else if (Subtarget->isPICStyleStubPIC()) {
7279 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7280 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7281 OpFlag = X86II::MO_DARWIN_NONLAZY;
7284 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7286 DebugLoc DL = Op.getDebugLoc();
7287 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7290 // With PIC, the address is actually $g + Offset.
7291 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7292 !Subtarget->is64Bit()) {
7293 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7294 DAG.getNode(X86ISD::GlobalBaseReg,
7295 DebugLoc(), getPointerTy()),
7299 // For symbols that require a load from a stub to get the address, emit the
7301 if (isGlobalStubReference(OpFlag))
7302 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7303 MachinePointerInfo::getGOT(), false, false, false, 0);
7309 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7310 // Create the TargetBlockAddressAddress node.
7311 unsigned char OpFlags =
7312 Subtarget->ClassifyBlockAddressReference();
7313 CodeModel::Model M = getTargetMachine().getCodeModel();
7314 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7315 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7316 DebugLoc dl = Op.getDebugLoc();
7317 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7320 if (Subtarget->isPICStyleRIPRel() &&
7321 (M == CodeModel::Small || M == CodeModel::Kernel))
7322 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7324 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7326 // With PIC, the address is actually $g + Offset.
7327 if (isGlobalRelativeToPICBase(OpFlags)) {
7328 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7329 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7337 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7339 SelectionDAG &DAG) const {
7340 // Create the TargetGlobalAddress node, folding in the constant
7341 // offset if it is legal.
7342 unsigned char OpFlags =
7343 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7344 CodeModel::Model M = getTargetMachine().getCodeModel();
7346 if (OpFlags == X86II::MO_NO_FLAG &&
7347 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7348 // A direct static reference to a global.
7349 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7352 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7355 if (Subtarget->isPICStyleRIPRel() &&
7356 (M == CodeModel::Small || M == CodeModel::Kernel))
7357 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7359 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7361 // With PIC, the address is actually $g + Offset.
7362 if (isGlobalRelativeToPICBase(OpFlags)) {
7363 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7364 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7368 // For globals that require a load from a stub to get the address, emit the
7370 if (isGlobalStubReference(OpFlags))
7371 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7372 MachinePointerInfo::getGOT(), false, false, false, 0);
7374 // If there was a non-zero offset that we didn't fold, create an explicit
7377 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7378 DAG.getConstant(Offset, getPointerTy()));
7384 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7385 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7386 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7387 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7391 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7392 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7393 unsigned char OperandFlags, bool LocalDynamic = false) {
7394 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7395 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7396 DebugLoc dl = GA->getDebugLoc();
7397 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7398 GA->getValueType(0),
7402 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7406 SDValue Ops[] = { Chain, TGA, *InFlag };
7407 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7409 SDValue Ops[] = { Chain, TGA };
7410 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7413 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7414 MFI->setAdjustsStack(true);
7416 SDValue Flag = Chain.getValue(1);
7417 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7420 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7422 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7425 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7426 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7427 DAG.getNode(X86ISD::GlobalBaseReg,
7428 DebugLoc(), PtrVT), InFlag);
7429 InFlag = Chain.getValue(1);
7431 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7434 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7436 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7438 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7439 X86::RAX, X86II::MO_TLSGD);
7442 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7446 DebugLoc dl = GA->getDebugLoc();
7448 // Get the start address of the TLS block for this module.
7449 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7450 .getInfo<X86MachineFunctionInfo>();
7451 MFI->incNumLocalDynamicTLSAccesses();
7455 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7456 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7459 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7460 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7461 InFlag = Chain.getValue(1);
7462 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7463 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7466 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7470 unsigned char OperandFlags = X86II::MO_DTPOFF;
7471 unsigned WrapperKind = X86ISD::Wrapper;
7472 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7473 GA->getValueType(0),
7474 GA->getOffset(), OperandFlags);
7475 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7477 // Add x@dtpoff with the base.
7478 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7481 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7482 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7483 const EVT PtrVT, TLSModel::Model model,
7484 bool is64Bit, bool isPIC) {
7485 DebugLoc dl = GA->getDebugLoc();
7487 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7488 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7489 is64Bit ? 257 : 256));
7491 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7492 DAG.getIntPtrConstant(0),
7493 MachinePointerInfo(Ptr),
7494 false, false, false, 0);
7496 unsigned char OperandFlags = 0;
7497 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7499 unsigned WrapperKind = X86ISD::Wrapper;
7500 if (model == TLSModel::LocalExec) {
7501 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7502 } else if (model == TLSModel::InitialExec) {
7504 OperandFlags = X86II::MO_GOTTPOFF;
7505 WrapperKind = X86ISD::WrapperRIP;
7507 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7510 llvm_unreachable("Unexpected model");
7513 // emit "addl x@ntpoff,%eax" (local exec)
7514 // or "addl x@indntpoff,%eax" (initial exec)
7515 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7516 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7517 GA->getValueType(0),
7518 GA->getOffset(), OperandFlags);
7519 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7521 if (model == TLSModel::InitialExec) {
7522 if (isPIC && !is64Bit) {
7523 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7524 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7528 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7529 MachinePointerInfo::getGOT(), false, false, false,
7533 // The address of the thread local variable is the add of the thread
7534 // pointer with the offset of the variable.
7535 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7539 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7541 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7542 const GlobalValue *GV = GA->getGlobal();
7544 if (Subtarget->isTargetELF()) {
7545 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7548 case TLSModel::GeneralDynamic:
7549 if (Subtarget->is64Bit())
7550 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7551 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7552 case TLSModel::LocalDynamic:
7553 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7554 Subtarget->is64Bit());
7555 case TLSModel::InitialExec:
7556 case TLSModel::LocalExec:
7557 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7558 Subtarget->is64Bit(),
7559 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7561 llvm_unreachable("Unknown TLS model.");
7564 if (Subtarget->isTargetDarwin()) {
7565 // Darwin only has one model of TLS. Lower to that.
7566 unsigned char OpFlag = 0;
7567 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7568 X86ISD::WrapperRIP : X86ISD::Wrapper;
7570 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7572 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7573 !Subtarget->is64Bit();
7575 OpFlag = X86II::MO_TLVP_PIC_BASE;
7577 OpFlag = X86II::MO_TLVP;
7578 DebugLoc DL = Op.getDebugLoc();
7579 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7580 GA->getValueType(0),
7581 GA->getOffset(), OpFlag);
7582 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7584 // With PIC32, the address is actually $g + Offset.
7586 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7587 DAG.getNode(X86ISD::GlobalBaseReg,
7588 DebugLoc(), getPointerTy()),
7591 // Lowering the machine isd will make sure everything is in the right
7593 SDValue Chain = DAG.getEntryNode();
7594 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7595 SDValue Args[] = { Chain, Offset };
7596 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7598 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7599 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7600 MFI->setAdjustsStack(true);
7602 // And our return value (tls address) is in the standard call return value
7604 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7605 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7609 if (Subtarget->isTargetWindows()) {
7610 // Just use the implicit TLS architecture
7611 // Need to generate someting similar to:
7612 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7614 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7615 // mov rcx, qword [rdx+rcx*8]
7616 // mov eax, .tls$:tlsvar
7617 // [rax+rcx] contains the address
7618 // Windows 64bit: gs:0x58
7619 // Windows 32bit: fs:__tls_array
7621 // If GV is an alias then use the aliasee for determining
7622 // thread-localness.
7623 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7624 GV = GA->resolveAliasedGlobal(false);
7625 DebugLoc dl = GA->getDebugLoc();
7626 SDValue Chain = DAG.getEntryNode();
7628 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7629 // %gs:0x58 (64-bit).
7630 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7631 ? Type::getInt8PtrTy(*DAG.getContext(),
7633 : Type::getInt32PtrTy(*DAG.getContext(),
7636 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7637 Subtarget->is64Bit()
7638 ? DAG.getIntPtrConstant(0x58)
7639 : DAG.getExternalSymbol("_tls_array",
7641 MachinePointerInfo(Ptr),
7642 false, false, false, 0);
7644 // Load the _tls_index variable
7645 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7646 if (Subtarget->is64Bit())
7647 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7648 IDX, MachinePointerInfo(), MVT::i32,
7651 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7652 false, false, false, 0);
7654 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7656 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7658 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7659 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7660 false, false, false, 0);
7662 // Get the offset of start of .tls section
7663 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7664 GA->getValueType(0),
7665 GA->getOffset(), X86II::MO_SECREL);
7666 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7668 // The address of the thread local variable is the add of the thread
7669 // pointer with the offset of the variable.
7670 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7673 llvm_unreachable("TLS not implemented for this target.");
7677 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7678 /// and take a 2 x i32 value to shift plus a shift amount.
7679 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7680 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7681 EVT VT = Op.getValueType();
7682 unsigned VTBits = VT.getSizeInBits();
7683 DebugLoc dl = Op.getDebugLoc();
7684 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7685 SDValue ShOpLo = Op.getOperand(0);
7686 SDValue ShOpHi = Op.getOperand(1);
7687 SDValue ShAmt = Op.getOperand(2);
7688 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7689 DAG.getConstant(VTBits - 1, MVT::i8))
7690 : DAG.getConstant(0, VT);
7693 if (Op.getOpcode() == ISD::SHL_PARTS) {
7694 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7695 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7697 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7698 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7701 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7702 DAG.getConstant(VTBits, MVT::i8));
7703 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7704 AndNode, DAG.getConstant(0, MVT::i8));
7707 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7708 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7709 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7711 if (Op.getOpcode() == ISD::SHL_PARTS) {
7712 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7713 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7715 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7716 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7719 SDValue Ops[2] = { Lo, Hi };
7720 return DAG.getMergeValues(Ops, 2, dl);
7723 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7724 SelectionDAG &DAG) const {
7725 EVT SrcVT = Op.getOperand(0).getValueType();
7727 if (SrcVT.isVector())
7730 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7731 "Unknown SINT_TO_FP to lower!");
7733 // These are really Legal; return the operand so the caller accepts it as
7735 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7737 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7738 Subtarget->is64Bit()) {
7742 DebugLoc dl = Op.getDebugLoc();
7743 unsigned Size = SrcVT.getSizeInBits()/8;
7744 MachineFunction &MF = DAG.getMachineFunction();
7745 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7746 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7747 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7749 MachinePointerInfo::getFixedStack(SSFI),
7751 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7754 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7756 SelectionDAG &DAG) const {
7758 DebugLoc DL = Op.getDebugLoc();
7760 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7762 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7764 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7766 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7768 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7769 MachineMemOperand *MMO;
7771 int SSFI = FI->getIndex();
7773 DAG.getMachineFunction()
7774 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7775 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7777 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7778 StackSlot = StackSlot.getOperand(1);
7780 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7781 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7783 Tys, Ops, array_lengthof(Ops),
7787 Chain = Result.getValue(1);
7788 SDValue InFlag = Result.getValue(2);
7790 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7791 // shouldn't be necessary except that RFP cannot be live across
7792 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7793 MachineFunction &MF = DAG.getMachineFunction();
7794 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7795 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7796 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7797 Tys = DAG.getVTList(MVT::Other);
7799 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7801 MachineMemOperand *MMO =
7802 DAG.getMachineFunction()
7803 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7804 MachineMemOperand::MOStore, SSFISize, SSFISize);
7806 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7807 Ops, array_lengthof(Ops),
7808 Op.getValueType(), MMO);
7809 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7810 MachinePointerInfo::getFixedStack(SSFI),
7811 false, false, false, 0);
7817 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7818 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7819 SelectionDAG &DAG) const {
7820 // This algorithm is not obvious. Here it is what we're trying to output:
7823 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7824 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7828 pshufd $0x4e, %xmm0, %xmm1
7833 DebugLoc dl = Op.getDebugLoc();
7834 LLVMContext *Context = DAG.getContext();
7836 // Build some magic constants.
7837 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7838 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7839 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7841 SmallVector<Constant*,2> CV1;
7843 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7845 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7846 Constant *C1 = ConstantVector::get(CV1);
7847 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7849 // Load the 64-bit value into an XMM register.
7850 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7852 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7853 MachinePointerInfo::getConstantPool(),
7854 false, false, false, 16);
7855 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7856 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7859 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7860 MachinePointerInfo::getConstantPool(),
7861 false, false, false, 16);
7862 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7863 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7866 if (Subtarget->hasSSE3()) {
7867 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7868 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7870 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7871 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7873 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7874 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7878 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7879 DAG.getIntPtrConstant(0));
7882 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7883 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7884 SelectionDAG &DAG) const {
7885 DebugLoc dl = Op.getDebugLoc();
7886 // FP constant to bias correct the final result.
7887 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7890 // Load the 32-bit value into an XMM register.
7891 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7894 // Zero out the upper parts of the register.
7895 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7897 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7898 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7899 DAG.getIntPtrConstant(0));
7901 // Or the load with the bias.
7902 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7903 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7904 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7906 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7907 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7908 MVT::v2f64, Bias)));
7909 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7910 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7911 DAG.getIntPtrConstant(0));
7913 // Subtract the bias.
7914 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7916 // Handle final rounding.
7917 EVT DestVT = Op.getValueType();
7919 if (DestVT.bitsLT(MVT::f64))
7920 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7921 DAG.getIntPtrConstant(0));
7922 if (DestVT.bitsGT(MVT::f64))
7923 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7925 // Handle final rounding.
7929 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7930 SelectionDAG &DAG) const {
7931 SDValue N0 = Op.getOperand(0);
7932 DebugLoc dl = Op.getDebugLoc();
7934 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7935 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7936 // the optimization here.
7937 if (DAG.SignBitIsZero(N0))
7938 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7940 EVT SrcVT = N0.getValueType();
7941 EVT DstVT = Op.getValueType();
7942 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7943 return LowerUINT_TO_FP_i64(Op, DAG);
7944 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7945 return LowerUINT_TO_FP_i32(Op, DAG);
7946 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7949 // Make a 64-bit buffer, and use it to build an FILD.
7950 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7951 if (SrcVT == MVT::i32) {
7952 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7953 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7954 getPointerTy(), StackSlot, WordOff);
7955 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7956 StackSlot, MachinePointerInfo(),
7958 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7959 OffsetSlot, MachinePointerInfo(),
7961 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7965 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7966 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7967 StackSlot, MachinePointerInfo(),
7969 // For i64 source, we need to add the appropriate power of 2 if the input
7970 // was negative. This is the same as the optimization in
7971 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7972 // we must be careful to do the computation in x87 extended precision, not
7973 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7974 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7975 MachineMemOperand *MMO =
7976 DAG.getMachineFunction()
7977 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7978 MachineMemOperand::MOLoad, 8, 8);
7980 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7981 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7982 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7985 APInt FF(32, 0x5F800000ULL);
7987 // Check whether the sign bit is set.
7988 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7989 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7992 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7993 SDValue FudgePtr = DAG.getConstantPool(
7994 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7997 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7998 SDValue Zero = DAG.getIntPtrConstant(0);
7999 SDValue Four = DAG.getIntPtrConstant(4);
8000 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8002 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8004 // Load the value out, extending it from f32 to f80.
8005 // FIXME: Avoid the extend by constructing the right constant pool?
8006 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8007 FudgePtr, MachinePointerInfo::getConstantPool(),
8008 MVT::f32, false, false, 4);
8009 // Extend everything to 80 bits to force it to be done on x87.
8010 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8011 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8014 std::pair<SDValue,SDValue> X86TargetLowering::
8015 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8016 DebugLoc DL = Op.getDebugLoc();
8018 EVT DstTy = Op.getValueType();
8020 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8021 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8025 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8026 DstTy.getSimpleVT() >= MVT::i16 &&
8027 "Unknown FP_TO_INT to lower!");
8029 // These are really Legal.
8030 if (DstTy == MVT::i32 &&
8031 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8032 return std::make_pair(SDValue(), SDValue());
8033 if (Subtarget->is64Bit() &&
8034 DstTy == MVT::i64 &&
8035 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8036 return std::make_pair(SDValue(), SDValue());
8038 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8039 // stack slot, or into the FTOL runtime function.
8040 MachineFunction &MF = DAG.getMachineFunction();
8041 unsigned MemSize = DstTy.getSizeInBits()/8;
8042 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8043 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8046 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8047 Opc = X86ISD::WIN_FTOL;
8049 switch (DstTy.getSimpleVT().SimpleTy) {
8050 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8051 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8052 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8053 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8056 SDValue Chain = DAG.getEntryNode();
8057 SDValue Value = Op.getOperand(0);
8058 EVT TheVT = Op.getOperand(0).getValueType();
8059 // FIXME This causes a redundant load/store if the SSE-class value is already
8060 // in memory, such as if it is on the callstack.
8061 if (isScalarFPTypeInSSEReg(TheVT)) {
8062 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8063 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8064 MachinePointerInfo::getFixedStack(SSFI),
8066 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8068 Chain, StackSlot, DAG.getValueType(TheVT)
8071 MachineMemOperand *MMO =
8072 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8073 MachineMemOperand::MOLoad, MemSize, MemSize);
8074 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8076 Chain = Value.getValue(1);
8077 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8078 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8081 MachineMemOperand *MMO =
8082 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8083 MachineMemOperand::MOStore, MemSize, MemSize);
8085 if (Opc != X86ISD::WIN_FTOL) {
8086 // Build the FP_TO_INT*_IN_MEM
8087 SDValue Ops[] = { Chain, Value, StackSlot };
8088 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8089 Ops, 3, DstTy, MMO);
8090 return std::make_pair(FIST, StackSlot);
8092 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8093 DAG.getVTList(MVT::Other, MVT::Glue),
8095 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8096 MVT::i32, ftol.getValue(1));
8097 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8098 MVT::i32, eax.getValue(2));
8099 SDValue Ops[] = { eax, edx };
8100 SDValue pair = IsReplace
8101 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8102 : DAG.getMergeValues(Ops, 2, DL);
8103 return std::make_pair(pair, SDValue());
8107 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8108 SelectionDAG &DAG) const {
8109 if (Op.getValueType().isVector())
8112 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8113 /*IsSigned=*/ true, /*IsReplace=*/ false);
8114 SDValue FIST = Vals.first, StackSlot = Vals.second;
8115 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8116 if (FIST.getNode() == 0) return Op;
8118 if (StackSlot.getNode())
8120 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8121 FIST, StackSlot, MachinePointerInfo(),
8122 false, false, false, 0);
8124 // The node is the result.
8128 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8129 SelectionDAG &DAG) const {
8130 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8131 /*IsSigned=*/ false, /*IsReplace=*/ false);
8132 SDValue FIST = Vals.first, StackSlot = Vals.second;
8133 assert(FIST.getNode() && "Unexpected failure");
8135 if (StackSlot.getNode())
8137 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8138 FIST, StackSlot, MachinePointerInfo(),
8139 false, false, false, 0);
8141 // The node is the result.
8145 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8146 SelectionDAG &DAG) const {
8147 DebugLoc DL = Op.getDebugLoc();
8148 EVT VT = Op.getValueType();
8149 SDValue In = Op.getOperand(0);
8150 EVT SVT = In.getValueType();
8152 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8154 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8155 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8156 In, DAG.getUNDEF(SVT)));
8159 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8160 LLVMContext *Context = DAG.getContext();
8161 DebugLoc dl = Op.getDebugLoc();
8162 EVT VT = Op.getValueType();
8164 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8165 if (VT.isVector()) {
8166 EltVT = VT.getVectorElementType();
8167 NumElts = VT.getVectorNumElements();
8170 if (EltVT == MVT::f64)
8171 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8173 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8174 C = ConstantVector::getSplat(NumElts, C);
8175 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8176 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8177 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8178 MachinePointerInfo::getConstantPool(),
8179 false, false, false, Alignment);
8180 if (VT.isVector()) {
8181 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8182 return DAG.getNode(ISD::BITCAST, dl, VT,
8183 DAG.getNode(ISD::AND, dl, ANDVT,
8184 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8186 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8188 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8191 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8192 LLVMContext *Context = DAG.getContext();
8193 DebugLoc dl = Op.getDebugLoc();
8194 EVT VT = Op.getValueType();
8196 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8197 if (VT.isVector()) {
8198 EltVT = VT.getVectorElementType();
8199 NumElts = VT.getVectorNumElements();
8202 if (EltVT == MVT::f64)
8203 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8205 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8206 C = ConstantVector::getSplat(NumElts, C);
8207 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8208 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8209 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8210 MachinePointerInfo::getConstantPool(),
8211 false, false, false, Alignment);
8212 if (VT.isVector()) {
8213 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8214 return DAG.getNode(ISD::BITCAST, dl, VT,
8215 DAG.getNode(ISD::XOR, dl, XORVT,
8216 DAG.getNode(ISD::BITCAST, dl, XORVT,
8218 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8221 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8224 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8225 LLVMContext *Context = DAG.getContext();
8226 SDValue Op0 = Op.getOperand(0);
8227 SDValue Op1 = Op.getOperand(1);
8228 DebugLoc dl = Op.getDebugLoc();
8229 EVT VT = Op.getValueType();
8230 EVT SrcVT = Op1.getValueType();
8232 // If second operand is smaller, extend it first.
8233 if (SrcVT.bitsLT(VT)) {
8234 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8237 // And if it is bigger, shrink it first.
8238 if (SrcVT.bitsGT(VT)) {
8239 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8243 // At this point the operands and the result should have the same
8244 // type, and that won't be f80 since that is not custom lowered.
8246 // First get the sign bit of second operand.
8247 SmallVector<Constant*,4> CV;
8248 if (SrcVT == MVT::f64) {
8249 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8250 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8252 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8253 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8254 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8255 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8257 Constant *C = ConstantVector::get(CV);
8258 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8259 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8260 MachinePointerInfo::getConstantPool(),
8261 false, false, false, 16);
8262 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8264 // Shift sign bit right or left if the two operands have different types.
8265 if (SrcVT.bitsGT(VT)) {
8266 // Op0 is MVT::f32, Op1 is MVT::f64.
8267 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8268 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8269 DAG.getConstant(32, MVT::i32));
8270 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8271 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8272 DAG.getIntPtrConstant(0));
8275 // Clear first operand sign bit.
8277 if (VT == MVT::f64) {
8278 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8279 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8281 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8282 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8283 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8284 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8286 C = ConstantVector::get(CV);
8287 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8288 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8289 MachinePointerInfo::getConstantPool(),
8290 false, false, false, 16);
8291 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8293 // Or the value with the sign bit.
8294 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8297 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8298 SDValue N0 = Op.getOperand(0);
8299 DebugLoc dl = Op.getDebugLoc();
8300 EVT VT = Op.getValueType();
8302 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8303 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8304 DAG.getConstant(1, VT));
8305 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8308 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8310 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8311 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8313 if (!Subtarget->hasSSE41())
8316 if (!Op->hasOneUse())
8319 SDNode *N = Op.getNode();
8320 DebugLoc DL = N->getDebugLoc();
8322 SmallVector<SDValue, 8> Opnds;
8323 DenseMap<SDValue, unsigned> VecInMap;
8324 EVT VT = MVT::Other;
8326 // Recognize a special case where a vector is casted into wide integer to
8328 Opnds.push_back(N->getOperand(0));
8329 Opnds.push_back(N->getOperand(1));
8331 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8332 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8333 // BFS traverse all OR'd operands.
8334 if (I->getOpcode() == ISD::OR) {
8335 Opnds.push_back(I->getOperand(0));
8336 Opnds.push_back(I->getOperand(1));
8337 // Re-evaluate the number of nodes to be traversed.
8338 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8342 // Quit if a non-EXTRACT_VECTOR_ELT
8343 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8346 // Quit if without a constant index.
8347 SDValue Idx = I->getOperand(1);
8348 if (!isa<ConstantSDNode>(Idx))
8351 SDValue ExtractedFromVec = I->getOperand(0);
8352 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8353 if (M == VecInMap.end()) {
8354 VT = ExtractedFromVec.getValueType();
8355 // Quit if not 128/256-bit vector.
8356 if (!VT.is128BitVector() && !VT.is256BitVector())
8358 // Quit if not the same type.
8359 if (VecInMap.begin() != VecInMap.end() &&
8360 VT != VecInMap.begin()->first.getValueType())
8362 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8364 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8367 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8368 "Not extracted from 128-/256-bit vector.");
8370 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8371 SmallVector<SDValue, 8> VecIns;
8373 for (DenseMap<SDValue, unsigned>::const_iterator
8374 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8375 // Quit if not all elements are used.
8376 if (I->second != FullMask)
8378 VecIns.push_back(I->first);
8381 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8383 // Cast all vectors into TestVT for PTEST.
8384 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8385 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8387 // If more than one full vectors are evaluated, OR them first before PTEST.
8388 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8389 // Each iteration will OR 2 nodes and append the result until there is only
8390 // 1 node left, i.e. the final OR'd value of all vectors.
8391 SDValue LHS = VecIns[Slot];
8392 SDValue RHS = VecIns[Slot + 1];
8393 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8396 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8397 VecIns.back(), VecIns.back());
8400 /// Emit nodes that will be selected as "test Op0,Op0", or something
8402 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8403 SelectionDAG &DAG) const {
8404 DebugLoc dl = Op.getDebugLoc();
8406 // CF and OF aren't always set the way we want. Determine which
8407 // of these we need.
8408 bool NeedCF = false;
8409 bool NeedOF = false;
8412 case X86::COND_A: case X86::COND_AE:
8413 case X86::COND_B: case X86::COND_BE:
8416 case X86::COND_G: case X86::COND_GE:
8417 case X86::COND_L: case X86::COND_LE:
8418 case X86::COND_O: case X86::COND_NO:
8423 // See if we can use the EFLAGS value from the operand instead of
8424 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8425 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8426 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8427 // Emit a CMP with 0, which is the TEST pattern.
8428 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8429 DAG.getConstant(0, Op.getValueType()));
8431 unsigned Opcode = 0;
8432 unsigned NumOperands = 0;
8434 // Truncate operations may prevent the merge of the SETCC instruction
8435 // and the arithmetic intruction before it. Attempt to truncate the operands
8436 // of the arithmetic instruction and use a reduced bit-width instruction.
8437 bool NeedTruncation = false;
8438 SDValue ArithOp = Op;
8439 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8440 SDValue Arith = Op->getOperand(0);
8441 // Both the trunc and the arithmetic op need to have one user each.
8442 if (Arith->hasOneUse())
8443 switch (Arith.getOpcode()) {
8450 NeedTruncation = true;
8456 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8457 // which may be the result of a CAST. We use the variable 'Op', which is the
8458 // non-casted variable when we check for possible users.
8459 switch (ArithOp.getOpcode()) {
8461 // Due to an isel shortcoming, be conservative if this add is likely to be
8462 // selected as part of a load-modify-store instruction. When the root node
8463 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8464 // uses of other nodes in the match, such as the ADD in this case. This
8465 // leads to the ADD being left around and reselected, with the result being
8466 // two adds in the output. Alas, even if none our users are stores, that
8467 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8468 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8469 // climbing the DAG back to the root, and it doesn't seem to be worth the
8471 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8472 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8473 if (UI->getOpcode() != ISD::CopyToReg &&
8474 UI->getOpcode() != ISD::SETCC &&
8475 UI->getOpcode() != ISD::STORE)
8478 if (ConstantSDNode *C =
8479 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8480 // An add of one will be selected as an INC.
8481 if (C->getAPIntValue() == 1) {
8482 Opcode = X86ISD::INC;
8487 // An add of negative one (subtract of one) will be selected as a DEC.
8488 if (C->getAPIntValue().isAllOnesValue()) {
8489 Opcode = X86ISD::DEC;
8495 // Otherwise use a regular EFLAGS-setting add.
8496 Opcode = X86ISD::ADD;
8500 // If the primary and result isn't used, don't bother using X86ISD::AND,
8501 // because a TEST instruction will be better.
8502 bool NonFlagUse = false;
8503 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8504 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8506 unsigned UOpNo = UI.getOperandNo();
8507 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8508 // Look pass truncate.
8509 UOpNo = User->use_begin().getOperandNo();
8510 User = *User->use_begin();
8513 if (User->getOpcode() != ISD::BRCOND &&
8514 User->getOpcode() != ISD::SETCC &&
8515 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8528 // Due to the ISEL shortcoming noted above, be conservative if this op is
8529 // likely to be selected as part of a load-modify-store instruction.
8530 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8531 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8532 if (UI->getOpcode() == ISD::STORE)
8535 // Otherwise use a regular EFLAGS-setting instruction.
8536 switch (ArithOp.getOpcode()) {
8537 default: llvm_unreachable("unexpected operator!");
8538 case ISD::SUB: Opcode = X86ISD::SUB; break;
8539 case ISD::XOR: Opcode = X86ISD::XOR; break;
8540 case ISD::AND: Opcode = X86ISD::AND; break;
8542 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8543 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8544 if (EFLAGS.getNode())
8547 Opcode = X86ISD::OR;
8561 return SDValue(Op.getNode(), 1);
8567 // If we found that truncation is beneficial, perform the truncation and
8569 if (NeedTruncation) {
8570 EVT VT = Op.getValueType();
8571 SDValue WideVal = Op->getOperand(0);
8572 EVT WideVT = WideVal.getValueType();
8573 unsigned ConvertedOp = 0;
8574 // Use a target machine opcode to prevent further DAGCombine
8575 // optimizations that may separate the arithmetic operations
8576 // from the setcc node.
8577 switch (WideVal.getOpcode()) {
8579 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8580 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8581 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8582 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8583 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8587 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8588 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8589 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8590 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8591 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8597 // Emit a CMP with 0, which is the TEST pattern.
8598 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8599 DAG.getConstant(0, Op.getValueType()));
8601 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8602 SmallVector<SDValue, 4> Ops;
8603 for (unsigned i = 0; i != NumOperands; ++i)
8604 Ops.push_back(Op.getOperand(i));
8606 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8607 DAG.ReplaceAllUsesWith(Op, New);
8608 return SDValue(New.getNode(), 1);
8611 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8613 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8614 SelectionDAG &DAG) const {
8615 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8616 if (C->getAPIntValue() == 0)
8617 return EmitTest(Op0, X86CC, DAG);
8619 DebugLoc dl = Op0.getDebugLoc();
8620 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8621 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8622 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8623 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8624 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8626 return SDValue(Sub.getNode(), 1);
8628 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8631 /// Convert a comparison if required by the subtarget.
8632 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8633 SelectionDAG &DAG) const {
8634 // If the subtarget does not support the FUCOMI instruction, floating-point
8635 // comparisons have to be converted.
8636 if (Subtarget->hasCMov() ||
8637 Cmp.getOpcode() != X86ISD::CMP ||
8638 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8639 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8642 // The instruction selector will select an FUCOM instruction instead of
8643 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8644 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8645 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8646 DebugLoc dl = Cmp.getDebugLoc();
8647 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8648 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8649 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8650 DAG.getConstant(8, MVT::i8));
8651 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8652 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8655 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8656 /// if it's possible.
8657 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8658 DebugLoc dl, SelectionDAG &DAG) const {
8659 SDValue Op0 = And.getOperand(0);
8660 SDValue Op1 = And.getOperand(1);
8661 if (Op0.getOpcode() == ISD::TRUNCATE)
8662 Op0 = Op0.getOperand(0);
8663 if (Op1.getOpcode() == ISD::TRUNCATE)
8664 Op1 = Op1.getOperand(0);
8667 if (Op1.getOpcode() == ISD::SHL)
8668 std::swap(Op0, Op1);
8669 if (Op0.getOpcode() == ISD::SHL) {
8670 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8671 if (And00C->getZExtValue() == 1) {
8672 // If we looked past a truncate, check that it's only truncating away
8674 unsigned BitWidth = Op0.getValueSizeInBits();
8675 unsigned AndBitWidth = And.getValueSizeInBits();
8676 if (BitWidth > AndBitWidth) {
8678 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8679 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8683 RHS = Op0.getOperand(1);
8685 } else if (Op1.getOpcode() == ISD::Constant) {
8686 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8687 uint64_t AndRHSVal = AndRHS->getZExtValue();
8688 SDValue AndLHS = Op0;
8690 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8691 LHS = AndLHS.getOperand(0);
8692 RHS = AndLHS.getOperand(1);
8695 // Use BT if the immediate can't be encoded in a TEST instruction.
8696 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8698 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8702 if (LHS.getNode()) {
8703 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8704 // instruction. Since the shift amount is in-range-or-undefined, we know
8705 // that doing a bittest on the i32 value is ok. We extend to i32 because
8706 // the encoding for the i16 version is larger than the i32 version.
8707 // Also promote i16 to i32 for performance / code size reason.
8708 if (LHS.getValueType() == MVT::i8 ||
8709 LHS.getValueType() == MVT::i16)
8710 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8712 // If the operand types disagree, extend the shift amount to match. Since
8713 // BT ignores high bits (like shifts) we can use anyextend.
8714 if (LHS.getValueType() != RHS.getValueType())
8715 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8717 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8718 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8719 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8720 DAG.getConstant(Cond, MVT::i8), BT);
8726 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8728 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8730 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8731 SDValue Op0 = Op.getOperand(0);
8732 SDValue Op1 = Op.getOperand(1);
8733 DebugLoc dl = Op.getDebugLoc();
8734 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8736 // Optimize to BT if possible.
8737 // Lower (X & (1 << N)) == 0 to BT(X, N).
8738 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8739 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8740 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8741 Op1.getOpcode() == ISD::Constant &&
8742 cast<ConstantSDNode>(Op1)->isNullValue() &&
8743 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8744 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8745 if (NewSetCC.getNode())
8749 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8751 if (Op1.getOpcode() == ISD::Constant &&
8752 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8753 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8754 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8756 // If the input is a setcc, then reuse the input setcc or use a new one with
8757 // the inverted condition.
8758 if (Op0.getOpcode() == X86ISD::SETCC) {
8759 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8760 bool Invert = (CC == ISD::SETNE) ^
8761 cast<ConstantSDNode>(Op1)->isNullValue();
8762 if (!Invert) return Op0;
8764 CCode = X86::GetOppositeBranchCondition(CCode);
8765 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8766 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8770 bool isFP = Op1.getValueType().isFloatingPoint();
8771 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8772 if (X86CC == X86::COND_INVALID)
8775 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8776 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8777 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8778 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8781 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8782 // ones, and then concatenate the result back.
8783 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8784 EVT VT = Op.getValueType();
8786 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
8787 "Unsupported value type for operation");
8789 unsigned NumElems = VT.getVectorNumElements();
8790 DebugLoc dl = Op.getDebugLoc();
8791 SDValue CC = Op.getOperand(2);
8793 // Extract the LHS vectors
8794 SDValue LHS = Op.getOperand(0);
8795 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8796 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8798 // Extract the RHS vectors
8799 SDValue RHS = Op.getOperand(1);
8800 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8801 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8803 // Issue the operation on the smaller types and concatenate the result back
8804 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8805 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8806 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8807 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8808 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8812 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8814 SDValue Op0 = Op.getOperand(0);
8815 SDValue Op1 = Op.getOperand(1);
8816 SDValue CC = Op.getOperand(2);
8817 EVT VT = Op.getValueType();
8818 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8819 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8820 DebugLoc dl = Op.getDebugLoc();
8824 EVT EltVT = Op0.getValueType().getVectorElementType();
8825 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8831 // SSE Condition code mapping:
8840 switch (SetCCOpcode) {
8841 default: llvm_unreachable("Unexpected SETCC condition");
8843 case ISD::SETEQ: SSECC = 0; break;
8845 case ISD::SETGT: Swap = true; // Fallthrough
8847 case ISD::SETOLT: SSECC = 1; break;
8849 case ISD::SETGE: Swap = true; // Fallthrough
8851 case ISD::SETOLE: SSECC = 2; break;
8852 case ISD::SETUO: SSECC = 3; break;
8854 case ISD::SETNE: SSECC = 4; break;
8855 case ISD::SETULE: Swap = true; // Fallthrough
8856 case ISD::SETUGE: SSECC = 5; break;
8857 case ISD::SETULT: Swap = true; // Fallthrough
8858 case ISD::SETUGT: SSECC = 6; break;
8859 case ISD::SETO: SSECC = 7; break;
8861 case ISD::SETONE: SSECC = 8; break;
8864 std::swap(Op0, Op1);
8866 // In the two special cases we can't handle, emit two comparisons.
8869 unsigned CombineOpc;
8870 if (SetCCOpcode == ISD::SETUEQ) {
8871 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
8873 assert(SetCCOpcode == ISD::SETONE);
8874 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
8877 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8878 DAG.getConstant(CC0, MVT::i8));
8879 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8880 DAG.getConstant(CC1, MVT::i8));
8881 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
8883 // Handle all other FP comparisons here.
8884 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8885 DAG.getConstant(SSECC, MVT::i8));
8888 // Break 256-bit integer vector compare into smaller ones.
8889 if (VT.is256BitVector() && !Subtarget->hasAVX2())
8890 return Lower256IntVSETCC(Op, DAG);
8892 // We are handling one of the integer comparisons here. Since SSE only has
8893 // GT and EQ comparisons for integer, swapping operands and multiple
8894 // operations may be required for some comparisons.
8896 bool Swap = false, Invert = false, FlipSigns = false;
8898 switch (SetCCOpcode) {
8899 default: llvm_unreachable("Unexpected SETCC condition");
8900 case ISD::SETNE: Invert = true;
8901 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8902 case ISD::SETLT: Swap = true;
8903 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8904 case ISD::SETGE: Swap = true;
8905 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8906 case ISD::SETULT: Swap = true;
8907 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8908 case ISD::SETUGE: Swap = true;
8909 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8912 std::swap(Op0, Op1);
8914 // Check that the operation in question is available (most are plain SSE2,
8915 // but PCMPGTQ and PCMPEQQ have different requirements).
8916 if (VT == MVT::v2i64) {
8917 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
8919 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
8923 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8924 // bits of the inputs before performing those operations.
8926 EVT EltVT = VT.getVectorElementType();
8927 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8929 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8930 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8932 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8933 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8936 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8938 // If the logical-not of the result is required, perform that now.
8940 Result = DAG.getNOT(dl, Result, VT);
8945 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8946 static bool isX86LogicalCmp(SDValue Op) {
8947 unsigned Opc = Op.getNode()->getOpcode();
8948 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8949 Opc == X86ISD::SAHF)
8951 if (Op.getResNo() == 1 &&
8952 (Opc == X86ISD::ADD ||
8953 Opc == X86ISD::SUB ||
8954 Opc == X86ISD::ADC ||
8955 Opc == X86ISD::SBB ||
8956 Opc == X86ISD::SMUL ||
8957 Opc == X86ISD::UMUL ||
8958 Opc == X86ISD::INC ||
8959 Opc == X86ISD::DEC ||
8960 Opc == X86ISD::OR ||
8961 Opc == X86ISD::XOR ||
8962 Opc == X86ISD::AND))
8965 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8971 static bool isZero(SDValue V) {
8972 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8973 return C && C->isNullValue();
8976 static bool isAllOnes(SDValue V) {
8977 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8978 return C && C->isAllOnesValue();
8981 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
8982 if (V.getOpcode() != ISD::TRUNCATE)
8985 SDValue VOp0 = V.getOperand(0);
8986 unsigned InBits = VOp0.getValueSizeInBits();
8987 unsigned Bits = V.getValueSizeInBits();
8988 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
8991 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8992 bool addTest = true;
8993 SDValue Cond = Op.getOperand(0);
8994 SDValue Op1 = Op.getOperand(1);
8995 SDValue Op2 = Op.getOperand(2);
8996 DebugLoc DL = Op.getDebugLoc();
8999 if (Cond.getOpcode() == ISD::SETCC) {
9000 SDValue NewCond = LowerSETCC(Cond, DAG);
9001 if (NewCond.getNode())
9005 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9006 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9007 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9008 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9009 if (Cond.getOpcode() == X86ISD::SETCC &&
9010 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9011 isZero(Cond.getOperand(1).getOperand(1))) {
9012 SDValue Cmp = Cond.getOperand(1);
9014 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9016 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9017 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9018 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9020 SDValue CmpOp0 = Cmp.getOperand(0);
9021 // Apply further optimizations for special cases
9022 // (select (x != 0), -1, 0) -> neg & sbb
9023 // (select (x == 0), 0, -1) -> neg & sbb
9024 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9025 if (YC->isNullValue() &&
9026 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9027 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9028 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9029 DAG.getConstant(0, CmpOp0.getValueType()),
9031 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9032 DAG.getConstant(X86::COND_B, MVT::i8),
9033 SDValue(Neg.getNode(), 1));
9037 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9038 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9039 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9041 SDValue Res = // Res = 0 or -1.
9042 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9043 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9045 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9046 Res = DAG.getNOT(DL, Res, Res.getValueType());
9048 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9049 if (N2C == 0 || !N2C->isNullValue())
9050 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9055 // Look past (and (setcc_carry (cmp ...)), 1).
9056 if (Cond.getOpcode() == ISD::AND &&
9057 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9058 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9059 if (C && C->getAPIntValue() == 1)
9060 Cond = Cond.getOperand(0);
9063 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9064 // setting operand in place of the X86ISD::SETCC.
9065 unsigned CondOpcode = Cond.getOpcode();
9066 if (CondOpcode == X86ISD::SETCC ||
9067 CondOpcode == X86ISD::SETCC_CARRY) {
9068 CC = Cond.getOperand(0);
9070 SDValue Cmp = Cond.getOperand(1);
9071 unsigned Opc = Cmp.getOpcode();
9072 EVT VT = Op.getValueType();
9074 bool IllegalFPCMov = false;
9075 if (VT.isFloatingPoint() && !VT.isVector() &&
9076 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9077 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9079 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9080 Opc == X86ISD::BT) { // FIXME
9084 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9085 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9086 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9087 Cond.getOperand(0).getValueType() != MVT::i8)) {
9088 SDValue LHS = Cond.getOperand(0);
9089 SDValue RHS = Cond.getOperand(1);
9093 switch (CondOpcode) {
9094 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9095 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9096 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9097 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9098 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9099 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9100 default: llvm_unreachable("unexpected overflowing operator");
9102 if (CondOpcode == ISD::UMULO)
9103 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9106 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9108 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9110 if (CondOpcode == ISD::UMULO)
9111 Cond = X86Op.getValue(2);
9113 Cond = X86Op.getValue(1);
9115 CC = DAG.getConstant(X86Cond, MVT::i8);
9120 // Look pass the truncate if the high bits are known zero.
9121 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9122 Cond = Cond.getOperand(0);
9124 // We know the result of AND is compared against zero. Try to match
9126 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9127 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9128 if (NewSetCC.getNode()) {
9129 CC = NewSetCC.getOperand(0);
9130 Cond = NewSetCC.getOperand(1);
9137 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9138 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9141 // a < b ? -1 : 0 -> RES = ~setcc_carry
9142 // a < b ? 0 : -1 -> RES = setcc_carry
9143 // a >= b ? -1 : 0 -> RES = setcc_carry
9144 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9145 if (Cond.getOpcode() == X86ISD::SUB) {
9146 Cond = ConvertCmpIfNecessary(Cond, DAG);
9147 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9149 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9150 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9151 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9152 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9153 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9154 return DAG.getNOT(DL, Res, Res.getValueType());
9159 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9160 // widen the cmov and push the truncate through. This avoids introducing a new
9161 // branch during isel and doesn't add any extensions.
9162 if (Op.getValueType() == MVT::i8 &&
9163 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9164 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9165 if (T1.getValueType() == T2.getValueType() &&
9166 // Blacklist CopyFromReg to avoid partial register stalls.
9167 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9168 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9169 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9170 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9174 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9175 // condition is true.
9176 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9177 SDValue Ops[] = { Op2, Op1, CC, Cond };
9178 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9181 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9182 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9183 // from the AND / OR.
9184 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9185 Opc = Op.getOpcode();
9186 if (Opc != ISD::OR && Opc != ISD::AND)
9188 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9189 Op.getOperand(0).hasOneUse() &&
9190 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9191 Op.getOperand(1).hasOneUse());
9194 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9195 // 1 and that the SETCC node has a single use.
9196 static bool isXor1OfSetCC(SDValue Op) {
9197 if (Op.getOpcode() != ISD::XOR)
9199 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9200 if (N1C && N1C->getAPIntValue() == 1) {
9201 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9202 Op.getOperand(0).hasOneUse();
9207 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9208 bool addTest = true;
9209 SDValue Chain = Op.getOperand(0);
9210 SDValue Cond = Op.getOperand(1);
9211 SDValue Dest = Op.getOperand(2);
9212 DebugLoc dl = Op.getDebugLoc();
9214 bool Inverted = false;
9216 if (Cond.getOpcode() == ISD::SETCC) {
9217 // Check for setcc([su]{add,sub,mul}o == 0).
9218 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9219 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9220 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9221 Cond.getOperand(0).getResNo() == 1 &&
9222 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9223 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9224 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9225 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9226 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9227 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9229 Cond = Cond.getOperand(0);
9231 SDValue NewCond = LowerSETCC(Cond, DAG);
9232 if (NewCond.getNode())
9237 // FIXME: LowerXALUO doesn't handle these!!
9238 else if (Cond.getOpcode() == X86ISD::ADD ||
9239 Cond.getOpcode() == X86ISD::SUB ||
9240 Cond.getOpcode() == X86ISD::SMUL ||
9241 Cond.getOpcode() == X86ISD::UMUL)
9242 Cond = LowerXALUO(Cond, DAG);
9245 // Look pass (and (setcc_carry (cmp ...)), 1).
9246 if (Cond.getOpcode() == ISD::AND &&
9247 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9248 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9249 if (C && C->getAPIntValue() == 1)
9250 Cond = Cond.getOperand(0);
9253 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9254 // setting operand in place of the X86ISD::SETCC.
9255 unsigned CondOpcode = Cond.getOpcode();
9256 if (CondOpcode == X86ISD::SETCC ||
9257 CondOpcode == X86ISD::SETCC_CARRY) {
9258 CC = Cond.getOperand(0);
9260 SDValue Cmp = Cond.getOperand(1);
9261 unsigned Opc = Cmp.getOpcode();
9262 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9263 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9267 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9271 // These can only come from an arithmetic instruction with overflow,
9272 // e.g. SADDO, UADDO.
9273 Cond = Cond.getNode()->getOperand(1);
9279 CondOpcode = Cond.getOpcode();
9280 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9281 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9282 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9283 Cond.getOperand(0).getValueType() != MVT::i8)) {
9284 SDValue LHS = Cond.getOperand(0);
9285 SDValue RHS = Cond.getOperand(1);
9289 switch (CondOpcode) {
9290 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9291 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9292 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9293 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9294 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9295 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9296 default: llvm_unreachable("unexpected overflowing operator");
9299 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9300 if (CondOpcode == ISD::UMULO)
9301 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9304 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9306 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9308 if (CondOpcode == ISD::UMULO)
9309 Cond = X86Op.getValue(2);
9311 Cond = X86Op.getValue(1);
9313 CC = DAG.getConstant(X86Cond, MVT::i8);
9317 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9318 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9319 if (CondOpc == ISD::OR) {
9320 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9321 // two branches instead of an explicit OR instruction with a
9323 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9324 isX86LogicalCmp(Cmp)) {
9325 CC = Cond.getOperand(0).getOperand(0);
9326 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9327 Chain, Dest, CC, Cmp);
9328 CC = Cond.getOperand(1).getOperand(0);
9332 } else { // ISD::AND
9333 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9334 // two branches instead of an explicit AND instruction with a
9335 // separate test. However, we only do this if this block doesn't
9336 // have a fall-through edge, because this requires an explicit
9337 // jmp when the condition is false.
9338 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9339 isX86LogicalCmp(Cmp) &&
9340 Op.getNode()->hasOneUse()) {
9341 X86::CondCode CCode =
9342 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9343 CCode = X86::GetOppositeBranchCondition(CCode);
9344 CC = DAG.getConstant(CCode, MVT::i8);
9345 SDNode *User = *Op.getNode()->use_begin();
9346 // Look for an unconditional branch following this conditional branch.
9347 // We need this because we need to reverse the successors in order
9348 // to implement FCMP_OEQ.
9349 if (User->getOpcode() == ISD::BR) {
9350 SDValue FalseBB = User->getOperand(1);
9352 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9353 assert(NewBR == User);
9357 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9358 Chain, Dest, CC, Cmp);
9359 X86::CondCode CCode =
9360 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9361 CCode = X86::GetOppositeBranchCondition(CCode);
9362 CC = DAG.getConstant(CCode, MVT::i8);
9368 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9369 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9370 // It should be transformed during dag combiner except when the condition
9371 // is set by a arithmetics with overflow node.
9372 X86::CondCode CCode =
9373 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9374 CCode = X86::GetOppositeBranchCondition(CCode);
9375 CC = DAG.getConstant(CCode, MVT::i8);
9376 Cond = Cond.getOperand(0).getOperand(1);
9378 } else if (Cond.getOpcode() == ISD::SETCC &&
9379 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9380 // For FCMP_OEQ, we can emit
9381 // two branches instead of an explicit AND instruction with a
9382 // separate test. However, we only do this if this block doesn't
9383 // have a fall-through edge, because this requires an explicit
9384 // jmp when the condition is false.
9385 if (Op.getNode()->hasOneUse()) {
9386 SDNode *User = *Op.getNode()->use_begin();
9387 // Look for an unconditional branch following this conditional branch.
9388 // We need this because we need to reverse the successors in order
9389 // to implement FCMP_OEQ.
9390 if (User->getOpcode() == ISD::BR) {
9391 SDValue FalseBB = User->getOperand(1);
9393 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9394 assert(NewBR == User);
9398 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9399 Cond.getOperand(0), Cond.getOperand(1));
9400 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9401 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9402 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9403 Chain, Dest, CC, Cmp);
9404 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9409 } else if (Cond.getOpcode() == ISD::SETCC &&
9410 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9411 // For FCMP_UNE, we can emit
9412 // two branches instead of an explicit AND instruction with a
9413 // separate test. However, we only do this if this block doesn't
9414 // have a fall-through edge, because this requires an explicit
9415 // jmp when the condition is false.
9416 if (Op.getNode()->hasOneUse()) {
9417 SDNode *User = *Op.getNode()->use_begin();
9418 // Look for an unconditional branch following this conditional branch.
9419 // We need this because we need to reverse the successors in order
9420 // to implement FCMP_UNE.
9421 if (User->getOpcode() == ISD::BR) {
9422 SDValue FalseBB = User->getOperand(1);
9424 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9425 assert(NewBR == User);
9428 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9429 Cond.getOperand(0), Cond.getOperand(1));
9430 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9431 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9432 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9433 Chain, Dest, CC, Cmp);
9434 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9444 // Look pass the truncate if the high bits are known zero.
9445 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9446 Cond = Cond.getOperand(0);
9448 // We know the result of AND is compared against zero. Try to match
9450 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9451 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9452 if (NewSetCC.getNode()) {
9453 CC = NewSetCC.getOperand(0);
9454 Cond = NewSetCC.getOperand(1);
9461 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9462 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9464 Cond = ConvertCmpIfNecessary(Cond, DAG);
9465 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9466 Chain, Dest, CC, Cond);
9470 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9471 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9472 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9473 // that the guard pages used by the OS virtual memory manager are allocated in
9474 // correct sequence.
9476 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9477 SelectionDAG &DAG) const {
9478 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9479 getTargetMachine().Options.EnableSegmentedStacks) &&
9480 "This should be used only on Windows targets or when segmented stacks "
9482 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9483 DebugLoc dl = Op.getDebugLoc();
9486 SDValue Chain = Op.getOperand(0);
9487 SDValue Size = Op.getOperand(1);
9488 // FIXME: Ensure alignment here
9490 bool Is64Bit = Subtarget->is64Bit();
9491 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9493 if (getTargetMachine().Options.EnableSegmentedStacks) {
9494 MachineFunction &MF = DAG.getMachineFunction();
9495 MachineRegisterInfo &MRI = MF.getRegInfo();
9498 // The 64 bit implementation of segmented stacks needs to clobber both r10
9499 // r11. This makes it impossible to use it along with nested parameters.
9500 const Function *F = MF.getFunction();
9502 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9504 if (I->hasNestAttr())
9505 report_fatal_error("Cannot use segmented stacks with functions that "
9506 "have nested arguments.");
9509 const TargetRegisterClass *AddrRegClass =
9510 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9511 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9512 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9513 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9514 DAG.getRegister(Vreg, SPTy));
9515 SDValue Ops1[2] = { Value, Chain };
9516 return DAG.getMergeValues(Ops1, 2, dl);
9519 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9521 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9522 Flag = Chain.getValue(1);
9523 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9525 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9526 Flag = Chain.getValue(1);
9528 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9530 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9531 return DAG.getMergeValues(Ops1, 2, dl);
9535 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9536 MachineFunction &MF = DAG.getMachineFunction();
9537 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9539 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9540 DebugLoc DL = Op.getDebugLoc();
9542 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9543 // vastart just stores the address of the VarArgsFrameIndex slot into the
9544 // memory location argument.
9545 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9547 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9548 MachinePointerInfo(SV), false, false, 0);
9552 // gp_offset (0 - 6 * 8)
9553 // fp_offset (48 - 48 + 8 * 16)
9554 // overflow_arg_area (point to parameters coming in memory).
9556 SmallVector<SDValue, 8> MemOps;
9557 SDValue FIN = Op.getOperand(1);
9559 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9560 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9562 FIN, MachinePointerInfo(SV), false, false, 0);
9563 MemOps.push_back(Store);
9566 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9567 FIN, DAG.getIntPtrConstant(4));
9568 Store = DAG.getStore(Op.getOperand(0), DL,
9569 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9571 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9572 MemOps.push_back(Store);
9574 // Store ptr to overflow_arg_area
9575 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9576 FIN, DAG.getIntPtrConstant(4));
9577 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9579 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9580 MachinePointerInfo(SV, 8),
9582 MemOps.push_back(Store);
9584 // Store ptr to reg_save_area.
9585 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9586 FIN, DAG.getIntPtrConstant(8));
9587 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9589 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9590 MachinePointerInfo(SV, 16), false, false, 0);
9591 MemOps.push_back(Store);
9592 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9593 &MemOps[0], MemOps.size());
9596 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9597 assert(Subtarget->is64Bit() &&
9598 "LowerVAARG only handles 64-bit va_arg!");
9599 assert((Subtarget->isTargetLinux() ||
9600 Subtarget->isTargetDarwin()) &&
9601 "Unhandled target in LowerVAARG");
9602 assert(Op.getNode()->getNumOperands() == 4);
9603 SDValue Chain = Op.getOperand(0);
9604 SDValue SrcPtr = Op.getOperand(1);
9605 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9606 unsigned Align = Op.getConstantOperandVal(3);
9607 DebugLoc dl = Op.getDebugLoc();
9609 EVT ArgVT = Op.getNode()->getValueType(0);
9610 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9611 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9614 // Decide which area this value should be read from.
9615 // TODO: Implement the AMD64 ABI in its entirety. This simple
9616 // selection mechanism works only for the basic types.
9617 if (ArgVT == MVT::f80) {
9618 llvm_unreachable("va_arg for f80 not yet implemented");
9619 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9620 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9621 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9622 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9624 llvm_unreachable("Unhandled argument type in LowerVAARG");
9628 // Sanity Check: Make sure using fp_offset makes sense.
9629 assert(!getTargetMachine().Options.UseSoftFloat &&
9630 !(DAG.getMachineFunction()
9631 .getFunction()->getFnAttributes()
9632 .hasAttribute(Attributes::NoImplicitFloat)) &&
9633 Subtarget->hasSSE1());
9636 // Insert VAARG_64 node into the DAG
9637 // VAARG_64 returns two values: Variable Argument Address, Chain
9638 SmallVector<SDValue, 11> InstOps;
9639 InstOps.push_back(Chain);
9640 InstOps.push_back(SrcPtr);
9641 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9642 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9643 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9644 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9645 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9646 VTs, &InstOps[0], InstOps.size(),
9648 MachinePointerInfo(SV),
9653 Chain = VAARG.getValue(1);
9655 // Load the next argument and return it
9656 return DAG.getLoad(ArgVT, dl,
9659 MachinePointerInfo(),
9660 false, false, false, 0);
9663 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9664 SelectionDAG &DAG) {
9665 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9666 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9667 SDValue Chain = Op.getOperand(0);
9668 SDValue DstPtr = Op.getOperand(1);
9669 SDValue SrcPtr = Op.getOperand(2);
9670 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9671 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9672 DebugLoc DL = Op.getDebugLoc();
9674 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9675 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9677 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9680 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9681 // may or may not be a constant. Takes immediate version of shift as input.
9682 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9683 SDValue SrcOp, SDValue ShAmt,
9684 SelectionDAG &DAG) {
9685 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9687 if (isa<ConstantSDNode>(ShAmt)) {
9688 // Constant may be a TargetConstant. Use a regular constant.
9689 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9691 default: llvm_unreachable("Unknown target vector shift node");
9695 return DAG.getNode(Opc, dl, VT, SrcOp,
9696 DAG.getConstant(ShiftAmt, MVT::i32));
9700 // Change opcode to non-immediate version
9702 default: llvm_unreachable("Unknown target vector shift node");
9703 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9704 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9705 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9708 // Need to build a vector containing shift amount
9709 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9712 ShOps[1] = DAG.getConstant(0, MVT::i32);
9713 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9714 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9716 // The return type has to be a 128-bit type with the same element
9717 // type as the input type.
9718 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9719 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9721 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9722 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9725 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9726 DebugLoc dl = Op.getDebugLoc();
9727 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9729 default: return SDValue(); // Don't custom lower most intrinsics.
9730 // Comparison intrinsics.
9731 case Intrinsic::x86_sse_comieq_ss:
9732 case Intrinsic::x86_sse_comilt_ss:
9733 case Intrinsic::x86_sse_comile_ss:
9734 case Intrinsic::x86_sse_comigt_ss:
9735 case Intrinsic::x86_sse_comige_ss:
9736 case Intrinsic::x86_sse_comineq_ss:
9737 case Intrinsic::x86_sse_ucomieq_ss:
9738 case Intrinsic::x86_sse_ucomilt_ss:
9739 case Intrinsic::x86_sse_ucomile_ss:
9740 case Intrinsic::x86_sse_ucomigt_ss:
9741 case Intrinsic::x86_sse_ucomige_ss:
9742 case Intrinsic::x86_sse_ucomineq_ss:
9743 case Intrinsic::x86_sse2_comieq_sd:
9744 case Intrinsic::x86_sse2_comilt_sd:
9745 case Intrinsic::x86_sse2_comile_sd:
9746 case Intrinsic::x86_sse2_comigt_sd:
9747 case Intrinsic::x86_sse2_comige_sd:
9748 case Intrinsic::x86_sse2_comineq_sd:
9749 case Intrinsic::x86_sse2_ucomieq_sd:
9750 case Intrinsic::x86_sse2_ucomilt_sd:
9751 case Intrinsic::x86_sse2_ucomile_sd:
9752 case Intrinsic::x86_sse2_ucomigt_sd:
9753 case Intrinsic::x86_sse2_ucomige_sd:
9754 case Intrinsic::x86_sse2_ucomineq_sd: {
9758 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9759 case Intrinsic::x86_sse_comieq_ss:
9760 case Intrinsic::x86_sse2_comieq_sd:
9764 case Intrinsic::x86_sse_comilt_ss:
9765 case Intrinsic::x86_sse2_comilt_sd:
9769 case Intrinsic::x86_sse_comile_ss:
9770 case Intrinsic::x86_sse2_comile_sd:
9774 case Intrinsic::x86_sse_comigt_ss:
9775 case Intrinsic::x86_sse2_comigt_sd:
9779 case Intrinsic::x86_sse_comige_ss:
9780 case Intrinsic::x86_sse2_comige_sd:
9784 case Intrinsic::x86_sse_comineq_ss:
9785 case Intrinsic::x86_sse2_comineq_sd:
9789 case Intrinsic::x86_sse_ucomieq_ss:
9790 case Intrinsic::x86_sse2_ucomieq_sd:
9791 Opc = X86ISD::UCOMI;
9794 case Intrinsic::x86_sse_ucomilt_ss:
9795 case Intrinsic::x86_sse2_ucomilt_sd:
9796 Opc = X86ISD::UCOMI;
9799 case Intrinsic::x86_sse_ucomile_ss:
9800 case Intrinsic::x86_sse2_ucomile_sd:
9801 Opc = X86ISD::UCOMI;
9804 case Intrinsic::x86_sse_ucomigt_ss:
9805 case Intrinsic::x86_sse2_ucomigt_sd:
9806 Opc = X86ISD::UCOMI;
9809 case Intrinsic::x86_sse_ucomige_ss:
9810 case Intrinsic::x86_sse2_ucomige_sd:
9811 Opc = X86ISD::UCOMI;
9814 case Intrinsic::x86_sse_ucomineq_ss:
9815 case Intrinsic::x86_sse2_ucomineq_sd:
9816 Opc = X86ISD::UCOMI;
9821 SDValue LHS = Op.getOperand(1);
9822 SDValue RHS = Op.getOperand(2);
9823 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9824 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9825 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9826 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9827 DAG.getConstant(X86CC, MVT::i8), Cond);
9828 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9831 // Arithmetic intrinsics.
9832 case Intrinsic::x86_sse2_pmulu_dq:
9833 case Intrinsic::x86_avx2_pmulu_dq:
9834 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9835 Op.getOperand(1), Op.getOperand(2));
9837 // SSE3/AVX horizontal add/sub intrinsics
9838 case Intrinsic::x86_sse3_hadd_ps:
9839 case Intrinsic::x86_sse3_hadd_pd:
9840 case Intrinsic::x86_avx_hadd_ps_256:
9841 case Intrinsic::x86_avx_hadd_pd_256:
9842 case Intrinsic::x86_sse3_hsub_ps:
9843 case Intrinsic::x86_sse3_hsub_pd:
9844 case Intrinsic::x86_avx_hsub_ps_256:
9845 case Intrinsic::x86_avx_hsub_pd_256:
9846 case Intrinsic::x86_ssse3_phadd_w_128:
9847 case Intrinsic::x86_ssse3_phadd_d_128:
9848 case Intrinsic::x86_avx2_phadd_w:
9849 case Intrinsic::x86_avx2_phadd_d:
9850 case Intrinsic::x86_ssse3_phsub_w_128:
9851 case Intrinsic::x86_ssse3_phsub_d_128:
9852 case Intrinsic::x86_avx2_phsub_w:
9853 case Intrinsic::x86_avx2_phsub_d: {
9856 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9857 case Intrinsic::x86_sse3_hadd_ps:
9858 case Intrinsic::x86_sse3_hadd_pd:
9859 case Intrinsic::x86_avx_hadd_ps_256:
9860 case Intrinsic::x86_avx_hadd_pd_256:
9861 Opcode = X86ISD::FHADD;
9863 case Intrinsic::x86_sse3_hsub_ps:
9864 case Intrinsic::x86_sse3_hsub_pd:
9865 case Intrinsic::x86_avx_hsub_ps_256:
9866 case Intrinsic::x86_avx_hsub_pd_256:
9867 Opcode = X86ISD::FHSUB;
9869 case Intrinsic::x86_ssse3_phadd_w_128:
9870 case Intrinsic::x86_ssse3_phadd_d_128:
9871 case Intrinsic::x86_avx2_phadd_w:
9872 case Intrinsic::x86_avx2_phadd_d:
9873 Opcode = X86ISD::HADD;
9875 case Intrinsic::x86_ssse3_phsub_w_128:
9876 case Intrinsic::x86_ssse3_phsub_d_128:
9877 case Intrinsic::x86_avx2_phsub_w:
9878 case Intrinsic::x86_avx2_phsub_d:
9879 Opcode = X86ISD::HSUB;
9882 return DAG.getNode(Opcode, dl, Op.getValueType(),
9883 Op.getOperand(1), Op.getOperand(2));
9886 // AVX2 variable shift intrinsics
9887 case Intrinsic::x86_avx2_psllv_d:
9888 case Intrinsic::x86_avx2_psllv_q:
9889 case Intrinsic::x86_avx2_psllv_d_256:
9890 case Intrinsic::x86_avx2_psllv_q_256:
9891 case Intrinsic::x86_avx2_psrlv_d:
9892 case Intrinsic::x86_avx2_psrlv_q:
9893 case Intrinsic::x86_avx2_psrlv_d_256:
9894 case Intrinsic::x86_avx2_psrlv_q_256:
9895 case Intrinsic::x86_avx2_psrav_d:
9896 case Intrinsic::x86_avx2_psrav_d_256: {
9899 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9900 case Intrinsic::x86_avx2_psllv_d:
9901 case Intrinsic::x86_avx2_psllv_q:
9902 case Intrinsic::x86_avx2_psllv_d_256:
9903 case Intrinsic::x86_avx2_psllv_q_256:
9906 case Intrinsic::x86_avx2_psrlv_d:
9907 case Intrinsic::x86_avx2_psrlv_q:
9908 case Intrinsic::x86_avx2_psrlv_d_256:
9909 case Intrinsic::x86_avx2_psrlv_q_256:
9912 case Intrinsic::x86_avx2_psrav_d:
9913 case Intrinsic::x86_avx2_psrav_d_256:
9917 return DAG.getNode(Opcode, dl, Op.getValueType(),
9918 Op.getOperand(1), Op.getOperand(2));
9921 case Intrinsic::x86_ssse3_pshuf_b_128:
9922 case Intrinsic::x86_avx2_pshuf_b:
9923 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9924 Op.getOperand(1), Op.getOperand(2));
9926 case Intrinsic::x86_ssse3_psign_b_128:
9927 case Intrinsic::x86_ssse3_psign_w_128:
9928 case Intrinsic::x86_ssse3_psign_d_128:
9929 case Intrinsic::x86_avx2_psign_b:
9930 case Intrinsic::x86_avx2_psign_w:
9931 case Intrinsic::x86_avx2_psign_d:
9932 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9933 Op.getOperand(1), Op.getOperand(2));
9935 case Intrinsic::x86_sse41_insertps:
9936 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9937 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9939 case Intrinsic::x86_avx_vperm2f128_ps_256:
9940 case Intrinsic::x86_avx_vperm2f128_pd_256:
9941 case Intrinsic::x86_avx_vperm2f128_si_256:
9942 case Intrinsic::x86_avx2_vperm2i128:
9943 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9944 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9946 case Intrinsic::x86_avx2_permd:
9947 case Intrinsic::x86_avx2_permps:
9948 // Operands intentionally swapped. Mask is last operand to intrinsic,
9949 // but second operand for node/intruction.
9950 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9951 Op.getOperand(2), Op.getOperand(1));
9953 // ptest and testp intrinsics. The intrinsic these come from are designed to
9954 // return an integer value, not just an instruction so lower it to the ptest
9955 // or testp pattern and a setcc for the result.
9956 case Intrinsic::x86_sse41_ptestz:
9957 case Intrinsic::x86_sse41_ptestc:
9958 case Intrinsic::x86_sse41_ptestnzc:
9959 case Intrinsic::x86_avx_ptestz_256:
9960 case Intrinsic::x86_avx_ptestc_256:
9961 case Intrinsic::x86_avx_ptestnzc_256:
9962 case Intrinsic::x86_avx_vtestz_ps:
9963 case Intrinsic::x86_avx_vtestc_ps:
9964 case Intrinsic::x86_avx_vtestnzc_ps:
9965 case Intrinsic::x86_avx_vtestz_pd:
9966 case Intrinsic::x86_avx_vtestc_pd:
9967 case Intrinsic::x86_avx_vtestnzc_pd:
9968 case Intrinsic::x86_avx_vtestz_ps_256:
9969 case Intrinsic::x86_avx_vtestc_ps_256:
9970 case Intrinsic::x86_avx_vtestnzc_ps_256:
9971 case Intrinsic::x86_avx_vtestz_pd_256:
9972 case Intrinsic::x86_avx_vtestc_pd_256:
9973 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9974 bool IsTestPacked = false;
9977 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9978 case Intrinsic::x86_avx_vtestz_ps:
9979 case Intrinsic::x86_avx_vtestz_pd:
9980 case Intrinsic::x86_avx_vtestz_ps_256:
9981 case Intrinsic::x86_avx_vtestz_pd_256:
9982 IsTestPacked = true; // Fallthrough
9983 case Intrinsic::x86_sse41_ptestz:
9984 case Intrinsic::x86_avx_ptestz_256:
9986 X86CC = X86::COND_E;
9988 case Intrinsic::x86_avx_vtestc_ps:
9989 case Intrinsic::x86_avx_vtestc_pd:
9990 case Intrinsic::x86_avx_vtestc_ps_256:
9991 case Intrinsic::x86_avx_vtestc_pd_256:
9992 IsTestPacked = true; // Fallthrough
9993 case Intrinsic::x86_sse41_ptestc:
9994 case Intrinsic::x86_avx_ptestc_256:
9996 X86CC = X86::COND_B;
9998 case Intrinsic::x86_avx_vtestnzc_ps:
9999 case Intrinsic::x86_avx_vtestnzc_pd:
10000 case Intrinsic::x86_avx_vtestnzc_ps_256:
10001 case Intrinsic::x86_avx_vtestnzc_pd_256:
10002 IsTestPacked = true; // Fallthrough
10003 case Intrinsic::x86_sse41_ptestnzc:
10004 case Intrinsic::x86_avx_ptestnzc_256:
10006 X86CC = X86::COND_A;
10010 SDValue LHS = Op.getOperand(1);
10011 SDValue RHS = Op.getOperand(2);
10012 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10013 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10014 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10015 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10016 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10019 // SSE/AVX shift intrinsics
10020 case Intrinsic::x86_sse2_psll_w:
10021 case Intrinsic::x86_sse2_psll_d:
10022 case Intrinsic::x86_sse2_psll_q:
10023 case Intrinsic::x86_avx2_psll_w:
10024 case Intrinsic::x86_avx2_psll_d:
10025 case Intrinsic::x86_avx2_psll_q:
10026 case Intrinsic::x86_sse2_psrl_w:
10027 case Intrinsic::x86_sse2_psrl_d:
10028 case Intrinsic::x86_sse2_psrl_q:
10029 case Intrinsic::x86_avx2_psrl_w:
10030 case Intrinsic::x86_avx2_psrl_d:
10031 case Intrinsic::x86_avx2_psrl_q:
10032 case Intrinsic::x86_sse2_psra_w:
10033 case Intrinsic::x86_sse2_psra_d:
10034 case Intrinsic::x86_avx2_psra_w:
10035 case Intrinsic::x86_avx2_psra_d: {
10038 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10039 case Intrinsic::x86_sse2_psll_w:
10040 case Intrinsic::x86_sse2_psll_d:
10041 case Intrinsic::x86_sse2_psll_q:
10042 case Intrinsic::x86_avx2_psll_w:
10043 case Intrinsic::x86_avx2_psll_d:
10044 case Intrinsic::x86_avx2_psll_q:
10045 Opcode = X86ISD::VSHL;
10047 case Intrinsic::x86_sse2_psrl_w:
10048 case Intrinsic::x86_sse2_psrl_d:
10049 case Intrinsic::x86_sse2_psrl_q:
10050 case Intrinsic::x86_avx2_psrl_w:
10051 case Intrinsic::x86_avx2_psrl_d:
10052 case Intrinsic::x86_avx2_psrl_q:
10053 Opcode = X86ISD::VSRL;
10055 case Intrinsic::x86_sse2_psra_w:
10056 case Intrinsic::x86_sse2_psra_d:
10057 case Intrinsic::x86_avx2_psra_w:
10058 case Intrinsic::x86_avx2_psra_d:
10059 Opcode = X86ISD::VSRA;
10062 return DAG.getNode(Opcode, dl, Op.getValueType(),
10063 Op.getOperand(1), Op.getOperand(2));
10066 // SSE/AVX immediate shift intrinsics
10067 case Intrinsic::x86_sse2_pslli_w:
10068 case Intrinsic::x86_sse2_pslli_d:
10069 case Intrinsic::x86_sse2_pslli_q:
10070 case Intrinsic::x86_avx2_pslli_w:
10071 case Intrinsic::x86_avx2_pslli_d:
10072 case Intrinsic::x86_avx2_pslli_q:
10073 case Intrinsic::x86_sse2_psrli_w:
10074 case Intrinsic::x86_sse2_psrli_d:
10075 case Intrinsic::x86_sse2_psrli_q:
10076 case Intrinsic::x86_avx2_psrli_w:
10077 case Intrinsic::x86_avx2_psrli_d:
10078 case Intrinsic::x86_avx2_psrli_q:
10079 case Intrinsic::x86_sse2_psrai_w:
10080 case Intrinsic::x86_sse2_psrai_d:
10081 case Intrinsic::x86_avx2_psrai_w:
10082 case Intrinsic::x86_avx2_psrai_d: {
10085 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10086 case Intrinsic::x86_sse2_pslli_w:
10087 case Intrinsic::x86_sse2_pslli_d:
10088 case Intrinsic::x86_sse2_pslli_q:
10089 case Intrinsic::x86_avx2_pslli_w:
10090 case Intrinsic::x86_avx2_pslli_d:
10091 case Intrinsic::x86_avx2_pslli_q:
10092 Opcode = X86ISD::VSHLI;
10094 case Intrinsic::x86_sse2_psrli_w:
10095 case Intrinsic::x86_sse2_psrli_d:
10096 case Intrinsic::x86_sse2_psrli_q:
10097 case Intrinsic::x86_avx2_psrli_w:
10098 case Intrinsic::x86_avx2_psrli_d:
10099 case Intrinsic::x86_avx2_psrli_q:
10100 Opcode = X86ISD::VSRLI;
10102 case Intrinsic::x86_sse2_psrai_w:
10103 case Intrinsic::x86_sse2_psrai_d:
10104 case Intrinsic::x86_avx2_psrai_w:
10105 case Intrinsic::x86_avx2_psrai_d:
10106 Opcode = X86ISD::VSRAI;
10109 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10110 Op.getOperand(1), Op.getOperand(2), DAG);
10113 case Intrinsic::x86_sse42_pcmpistria128:
10114 case Intrinsic::x86_sse42_pcmpestria128:
10115 case Intrinsic::x86_sse42_pcmpistric128:
10116 case Intrinsic::x86_sse42_pcmpestric128:
10117 case Intrinsic::x86_sse42_pcmpistrio128:
10118 case Intrinsic::x86_sse42_pcmpestrio128:
10119 case Intrinsic::x86_sse42_pcmpistris128:
10120 case Intrinsic::x86_sse42_pcmpestris128:
10121 case Intrinsic::x86_sse42_pcmpistriz128:
10122 case Intrinsic::x86_sse42_pcmpestriz128: {
10126 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10127 case Intrinsic::x86_sse42_pcmpistria128:
10128 Opcode = X86ISD::PCMPISTRI;
10129 X86CC = X86::COND_A;
10131 case Intrinsic::x86_sse42_pcmpestria128:
10132 Opcode = X86ISD::PCMPESTRI;
10133 X86CC = X86::COND_A;
10135 case Intrinsic::x86_sse42_pcmpistric128:
10136 Opcode = X86ISD::PCMPISTRI;
10137 X86CC = X86::COND_B;
10139 case Intrinsic::x86_sse42_pcmpestric128:
10140 Opcode = X86ISD::PCMPESTRI;
10141 X86CC = X86::COND_B;
10143 case Intrinsic::x86_sse42_pcmpistrio128:
10144 Opcode = X86ISD::PCMPISTRI;
10145 X86CC = X86::COND_O;
10147 case Intrinsic::x86_sse42_pcmpestrio128:
10148 Opcode = X86ISD::PCMPESTRI;
10149 X86CC = X86::COND_O;
10151 case Intrinsic::x86_sse42_pcmpistris128:
10152 Opcode = X86ISD::PCMPISTRI;
10153 X86CC = X86::COND_S;
10155 case Intrinsic::x86_sse42_pcmpestris128:
10156 Opcode = X86ISD::PCMPESTRI;
10157 X86CC = X86::COND_S;
10159 case Intrinsic::x86_sse42_pcmpistriz128:
10160 Opcode = X86ISD::PCMPISTRI;
10161 X86CC = X86::COND_E;
10163 case Intrinsic::x86_sse42_pcmpestriz128:
10164 Opcode = X86ISD::PCMPESTRI;
10165 X86CC = X86::COND_E;
10168 SmallVector<SDValue, 5> NewOps;
10169 NewOps.append(Op->op_begin()+1, Op->op_end());
10170 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10171 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10172 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10173 DAG.getConstant(X86CC, MVT::i8),
10174 SDValue(PCMP.getNode(), 1));
10175 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10178 case Intrinsic::x86_sse42_pcmpistri128:
10179 case Intrinsic::x86_sse42_pcmpestri128: {
10181 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10182 Opcode = X86ISD::PCMPISTRI;
10184 Opcode = X86ISD::PCMPESTRI;
10186 SmallVector<SDValue, 5> NewOps;
10187 NewOps.append(Op->op_begin()+1, Op->op_end());
10188 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10189 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10191 case Intrinsic::x86_fma_vfmadd_ps:
10192 case Intrinsic::x86_fma_vfmadd_pd:
10193 case Intrinsic::x86_fma_vfmsub_ps:
10194 case Intrinsic::x86_fma_vfmsub_pd:
10195 case Intrinsic::x86_fma_vfnmadd_ps:
10196 case Intrinsic::x86_fma_vfnmadd_pd:
10197 case Intrinsic::x86_fma_vfnmsub_ps:
10198 case Intrinsic::x86_fma_vfnmsub_pd:
10199 case Intrinsic::x86_fma_vfmaddsub_ps:
10200 case Intrinsic::x86_fma_vfmaddsub_pd:
10201 case Intrinsic::x86_fma_vfmsubadd_ps:
10202 case Intrinsic::x86_fma_vfmsubadd_pd:
10203 case Intrinsic::x86_fma_vfmadd_ps_256:
10204 case Intrinsic::x86_fma_vfmadd_pd_256:
10205 case Intrinsic::x86_fma_vfmsub_ps_256:
10206 case Intrinsic::x86_fma_vfmsub_pd_256:
10207 case Intrinsic::x86_fma_vfnmadd_ps_256:
10208 case Intrinsic::x86_fma_vfnmadd_pd_256:
10209 case Intrinsic::x86_fma_vfnmsub_ps_256:
10210 case Intrinsic::x86_fma_vfnmsub_pd_256:
10211 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10212 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10213 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10214 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10217 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10218 case Intrinsic::x86_fma_vfmadd_ps:
10219 case Intrinsic::x86_fma_vfmadd_pd:
10220 case Intrinsic::x86_fma_vfmadd_ps_256:
10221 case Intrinsic::x86_fma_vfmadd_pd_256:
10222 Opc = X86ISD::FMADD;
10224 case Intrinsic::x86_fma_vfmsub_ps:
10225 case Intrinsic::x86_fma_vfmsub_pd:
10226 case Intrinsic::x86_fma_vfmsub_ps_256:
10227 case Intrinsic::x86_fma_vfmsub_pd_256:
10228 Opc = X86ISD::FMSUB;
10230 case Intrinsic::x86_fma_vfnmadd_ps:
10231 case Intrinsic::x86_fma_vfnmadd_pd:
10232 case Intrinsic::x86_fma_vfnmadd_ps_256:
10233 case Intrinsic::x86_fma_vfnmadd_pd_256:
10234 Opc = X86ISD::FNMADD;
10236 case Intrinsic::x86_fma_vfnmsub_ps:
10237 case Intrinsic::x86_fma_vfnmsub_pd:
10238 case Intrinsic::x86_fma_vfnmsub_ps_256:
10239 case Intrinsic::x86_fma_vfnmsub_pd_256:
10240 Opc = X86ISD::FNMSUB;
10242 case Intrinsic::x86_fma_vfmaddsub_ps:
10243 case Intrinsic::x86_fma_vfmaddsub_pd:
10244 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10245 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10246 Opc = X86ISD::FMADDSUB;
10248 case Intrinsic::x86_fma_vfmsubadd_ps:
10249 case Intrinsic::x86_fma_vfmsubadd_pd:
10250 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10251 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10252 Opc = X86ISD::FMSUBADD;
10256 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10257 Op.getOperand(2), Op.getOperand(3));
10262 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10263 DebugLoc dl = Op.getDebugLoc();
10264 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10266 default: return SDValue(); // Don't custom lower most intrinsics.
10268 // RDRAND intrinsics.
10269 case Intrinsic::x86_rdrand_16:
10270 case Intrinsic::x86_rdrand_32:
10271 case Intrinsic::x86_rdrand_64: {
10272 // Emit the node with the right value type.
10273 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10274 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10276 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10277 // return the value from Rand, which is always 0, casted to i32.
10278 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10279 DAG.getConstant(1, Op->getValueType(1)),
10280 DAG.getConstant(X86::COND_B, MVT::i32),
10281 SDValue(Result.getNode(), 1) };
10282 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10283 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10286 // Return { result, isValid, chain }.
10287 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10288 SDValue(Result.getNode(), 2));
10293 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10294 SelectionDAG &DAG) const {
10295 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10296 MFI->setReturnAddressIsTaken(true);
10298 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10299 DebugLoc dl = Op.getDebugLoc();
10302 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10304 DAG.getConstant(TD->getPointerSize(0),
10305 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
10306 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10307 DAG.getNode(ISD::ADD, dl, getPointerTy(),
10308 FrameAddr, Offset),
10309 MachinePointerInfo(), false, false, false, 0);
10312 // Just load the return address.
10313 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10314 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
10315 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10318 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10319 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10320 MFI->setFrameAddressIsTaken(true);
10322 EVT VT = Op.getValueType();
10323 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10324 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10325 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10326 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10328 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10329 MachinePointerInfo(),
10330 false, false, false, 0);
10334 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10335 SelectionDAG &DAG) const {
10336 return DAG.getIntPtrConstant(2*TD->getPointerSize(0));
10339 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10340 SDValue Chain = Op.getOperand(0);
10341 SDValue Offset = Op.getOperand(1);
10342 SDValue Handler = Op.getOperand(2);
10343 DebugLoc dl = Op.getDebugLoc();
10345 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10346 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10348 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10350 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10351 DAG.getIntPtrConstant(TD->getPointerSize(0)));
10352 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10353 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10355 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10357 return DAG.getNode(X86ISD::EH_RETURN, dl,
10359 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10362 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10363 SelectionDAG &DAG) const {
10364 DebugLoc DL = Op.getDebugLoc();
10365 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10366 DAG.getVTList(MVT::i32, MVT::Other),
10367 Op.getOperand(0), Op.getOperand(1));
10370 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10371 SelectionDAG &DAG) const {
10372 DebugLoc DL = Op.getDebugLoc();
10373 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10374 Op.getOperand(0), Op.getOperand(1));
10377 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10378 return Op.getOperand(0);
10381 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10382 SelectionDAG &DAG) const {
10383 SDValue Root = Op.getOperand(0);
10384 SDValue Trmp = Op.getOperand(1); // trampoline
10385 SDValue FPtr = Op.getOperand(2); // nested function
10386 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10387 DebugLoc dl = Op.getDebugLoc();
10389 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10390 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10392 if (Subtarget->is64Bit()) {
10393 SDValue OutChains[6];
10395 // Large code-model.
10396 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10397 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10399 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10400 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10402 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10404 // Load the pointer to the nested function into R11.
10405 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10406 SDValue Addr = Trmp;
10407 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10408 Addr, MachinePointerInfo(TrmpAddr),
10411 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10412 DAG.getConstant(2, MVT::i64));
10413 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10414 MachinePointerInfo(TrmpAddr, 2),
10417 // Load the 'nest' parameter value into R10.
10418 // R10 is specified in X86CallingConv.td
10419 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10420 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10421 DAG.getConstant(10, MVT::i64));
10422 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10423 Addr, MachinePointerInfo(TrmpAddr, 10),
10426 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10427 DAG.getConstant(12, MVT::i64));
10428 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10429 MachinePointerInfo(TrmpAddr, 12),
10432 // Jump to the nested function.
10433 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10434 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10435 DAG.getConstant(20, MVT::i64));
10436 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10437 Addr, MachinePointerInfo(TrmpAddr, 20),
10440 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10441 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10442 DAG.getConstant(22, MVT::i64));
10443 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10444 MachinePointerInfo(TrmpAddr, 22),
10447 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10449 const Function *Func =
10450 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10451 CallingConv::ID CC = Func->getCallingConv();
10456 llvm_unreachable("Unsupported calling convention");
10457 case CallingConv::C:
10458 case CallingConv::X86_StdCall: {
10459 // Pass 'nest' parameter in ECX.
10460 // Must be kept in sync with X86CallingConv.td
10461 NestReg = X86::ECX;
10463 // Check that ECX wasn't needed by an 'inreg' parameter.
10464 FunctionType *FTy = Func->getFunctionType();
10465 const AttrListPtr &Attrs = Func->getAttributes();
10467 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10468 unsigned InRegCount = 0;
10471 for (FunctionType::param_iterator I = FTy->param_begin(),
10472 E = FTy->param_end(); I != E; ++I, ++Idx)
10473 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10474 // FIXME: should only count parameters that are lowered to integers.
10475 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10477 if (InRegCount > 2) {
10478 report_fatal_error("Nest register in use - reduce number of inreg"
10484 case CallingConv::X86_FastCall:
10485 case CallingConv::X86_ThisCall:
10486 case CallingConv::Fast:
10487 // Pass 'nest' parameter in EAX.
10488 // Must be kept in sync with X86CallingConv.td
10489 NestReg = X86::EAX;
10493 SDValue OutChains[4];
10494 SDValue Addr, Disp;
10496 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10497 DAG.getConstant(10, MVT::i32));
10498 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10500 // This is storing the opcode for MOV32ri.
10501 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10502 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10503 OutChains[0] = DAG.getStore(Root, dl,
10504 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10505 Trmp, MachinePointerInfo(TrmpAddr),
10508 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10509 DAG.getConstant(1, MVT::i32));
10510 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10511 MachinePointerInfo(TrmpAddr, 1),
10514 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10515 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10516 DAG.getConstant(5, MVT::i32));
10517 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10518 MachinePointerInfo(TrmpAddr, 5),
10521 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10522 DAG.getConstant(6, MVT::i32));
10523 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10524 MachinePointerInfo(TrmpAddr, 6),
10527 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10531 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10532 SelectionDAG &DAG) const {
10534 The rounding mode is in bits 11:10 of FPSR, and has the following
10536 00 Round to nearest
10541 FLT_ROUNDS, on the other hand, expects the following:
10548 To perform the conversion, we do:
10549 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10552 MachineFunction &MF = DAG.getMachineFunction();
10553 const TargetMachine &TM = MF.getTarget();
10554 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10555 unsigned StackAlignment = TFI.getStackAlignment();
10556 EVT VT = Op.getValueType();
10557 DebugLoc DL = Op.getDebugLoc();
10559 // Save FP Control Word to stack slot
10560 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10561 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10564 MachineMemOperand *MMO =
10565 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10566 MachineMemOperand::MOStore, 2, 2);
10568 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10569 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10570 DAG.getVTList(MVT::Other),
10571 Ops, 2, MVT::i16, MMO);
10573 // Load FP Control Word from stack slot
10574 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10575 MachinePointerInfo(), false, false, false, 0);
10577 // Transform as necessary
10579 DAG.getNode(ISD::SRL, DL, MVT::i16,
10580 DAG.getNode(ISD::AND, DL, MVT::i16,
10581 CWD, DAG.getConstant(0x800, MVT::i16)),
10582 DAG.getConstant(11, MVT::i8));
10584 DAG.getNode(ISD::SRL, DL, MVT::i16,
10585 DAG.getNode(ISD::AND, DL, MVT::i16,
10586 CWD, DAG.getConstant(0x400, MVT::i16)),
10587 DAG.getConstant(9, MVT::i8));
10590 DAG.getNode(ISD::AND, DL, MVT::i16,
10591 DAG.getNode(ISD::ADD, DL, MVT::i16,
10592 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10593 DAG.getConstant(1, MVT::i16)),
10594 DAG.getConstant(3, MVT::i16));
10597 return DAG.getNode((VT.getSizeInBits() < 16 ?
10598 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10601 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10602 EVT VT = Op.getValueType();
10604 unsigned NumBits = VT.getSizeInBits();
10605 DebugLoc dl = Op.getDebugLoc();
10607 Op = Op.getOperand(0);
10608 if (VT == MVT::i8) {
10609 // Zero extend to i32 since there is not an i8 bsr.
10611 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10614 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10615 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10616 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10618 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10621 DAG.getConstant(NumBits+NumBits-1, OpVT),
10622 DAG.getConstant(X86::COND_E, MVT::i8),
10625 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10627 // Finally xor with NumBits-1.
10628 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10631 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10635 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10636 EVT VT = Op.getValueType();
10638 unsigned NumBits = VT.getSizeInBits();
10639 DebugLoc dl = Op.getDebugLoc();
10641 Op = Op.getOperand(0);
10642 if (VT == MVT::i8) {
10643 // Zero extend to i32 since there is not an i8 bsr.
10645 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10648 // Issue a bsr (scan bits in reverse).
10649 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10650 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10652 // And xor with NumBits-1.
10653 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10656 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10660 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10661 EVT VT = Op.getValueType();
10662 unsigned NumBits = VT.getSizeInBits();
10663 DebugLoc dl = Op.getDebugLoc();
10664 Op = Op.getOperand(0);
10666 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10667 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10668 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10670 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10673 DAG.getConstant(NumBits, VT),
10674 DAG.getConstant(X86::COND_E, MVT::i8),
10677 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10680 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10681 // ones, and then concatenate the result back.
10682 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10683 EVT VT = Op.getValueType();
10685 assert(VT.is256BitVector() && VT.isInteger() &&
10686 "Unsupported value type for operation");
10688 unsigned NumElems = VT.getVectorNumElements();
10689 DebugLoc dl = Op.getDebugLoc();
10691 // Extract the LHS vectors
10692 SDValue LHS = Op.getOperand(0);
10693 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10694 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10696 // Extract the RHS vectors
10697 SDValue RHS = Op.getOperand(1);
10698 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10699 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10701 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10702 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10704 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10705 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10706 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10709 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10710 assert(Op.getValueType().is256BitVector() &&
10711 Op.getValueType().isInteger() &&
10712 "Only handle AVX 256-bit vector integer operation");
10713 return Lower256IntArith(Op, DAG);
10716 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10717 assert(Op.getValueType().is256BitVector() &&
10718 Op.getValueType().isInteger() &&
10719 "Only handle AVX 256-bit vector integer operation");
10720 return Lower256IntArith(Op, DAG);
10723 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10724 SelectionDAG &DAG) {
10725 EVT VT = Op.getValueType();
10727 // Decompose 256-bit ops into smaller 128-bit ops.
10728 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10729 return Lower256IntArith(Op, DAG);
10731 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10732 "Only know how to lower V2I64/V4I64 multiply");
10734 DebugLoc dl = Op.getDebugLoc();
10736 // Ahi = psrlqi(a, 32);
10737 // Bhi = psrlqi(b, 32);
10739 // AloBlo = pmuludq(a, b);
10740 // AloBhi = pmuludq(a, Bhi);
10741 // AhiBlo = pmuludq(Ahi, b);
10743 // AloBhi = psllqi(AloBhi, 32);
10744 // AhiBlo = psllqi(AhiBlo, 32);
10745 // return AloBlo + AloBhi + AhiBlo;
10747 SDValue A = Op.getOperand(0);
10748 SDValue B = Op.getOperand(1);
10750 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10752 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10753 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10755 // Bit cast to 32-bit vectors for MULUDQ
10756 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10757 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10758 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10759 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10760 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10762 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10763 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10764 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10766 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10767 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10769 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10770 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10773 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10775 EVT VT = Op.getValueType();
10776 DebugLoc dl = Op.getDebugLoc();
10777 SDValue R = Op.getOperand(0);
10778 SDValue Amt = Op.getOperand(1);
10779 LLVMContext *Context = DAG.getContext();
10781 if (!Subtarget->hasSSE2())
10784 // Optimize shl/srl/sra with constant shift amount.
10785 if (isSplatVector(Amt.getNode())) {
10786 SDValue SclrAmt = Amt->getOperand(0);
10787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10788 uint64_t ShiftAmt = C->getZExtValue();
10790 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10791 (Subtarget->hasAVX2() &&
10792 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10793 if (Op.getOpcode() == ISD::SHL)
10794 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10795 DAG.getConstant(ShiftAmt, MVT::i32));
10796 if (Op.getOpcode() == ISD::SRL)
10797 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10798 DAG.getConstant(ShiftAmt, MVT::i32));
10799 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10800 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10801 DAG.getConstant(ShiftAmt, MVT::i32));
10804 if (VT == MVT::v16i8) {
10805 if (Op.getOpcode() == ISD::SHL) {
10806 // Make a large shift.
10807 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10808 DAG.getConstant(ShiftAmt, MVT::i32));
10809 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10810 // Zero out the rightmost bits.
10811 SmallVector<SDValue, 16> V(16,
10812 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10814 return DAG.getNode(ISD::AND, dl, VT, SHL,
10815 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10817 if (Op.getOpcode() == ISD::SRL) {
10818 // Make a large shift.
10819 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10820 DAG.getConstant(ShiftAmt, MVT::i32));
10821 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10822 // Zero out the leftmost bits.
10823 SmallVector<SDValue, 16> V(16,
10824 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10826 return DAG.getNode(ISD::AND, dl, VT, SRL,
10827 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10829 if (Op.getOpcode() == ISD::SRA) {
10830 if (ShiftAmt == 7) {
10831 // R s>> 7 === R s< 0
10832 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10833 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10836 // R s>> a === ((R u>> a) ^ m) - m
10837 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10838 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10840 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10841 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10842 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10845 llvm_unreachable("Unknown shift opcode.");
10848 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10849 if (Op.getOpcode() == ISD::SHL) {
10850 // Make a large shift.
10851 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10852 DAG.getConstant(ShiftAmt, MVT::i32));
10853 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10854 // Zero out the rightmost bits.
10855 SmallVector<SDValue, 32> V(32,
10856 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10858 return DAG.getNode(ISD::AND, dl, VT, SHL,
10859 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10861 if (Op.getOpcode() == ISD::SRL) {
10862 // Make a large shift.
10863 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10864 DAG.getConstant(ShiftAmt, MVT::i32));
10865 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10866 // Zero out the leftmost bits.
10867 SmallVector<SDValue, 32> V(32,
10868 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10870 return DAG.getNode(ISD::AND, dl, VT, SRL,
10871 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10873 if (Op.getOpcode() == ISD::SRA) {
10874 if (ShiftAmt == 7) {
10875 // R s>> 7 === R s< 0
10876 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10877 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10880 // R s>> a === ((R u>> a) ^ m) - m
10881 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10882 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10884 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10885 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10886 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10889 llvm_unreachable("Unknown shift opcode.");
10894 // Lower SHL with variable shift amount.
10895 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10896 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10897 DAG.getConstant(23, MVT::i32));
10899 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10900 Constant *C = ConstantDataVector::get(*Context, CV);
10901 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10902 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10903 MachinePointerInfo::getConstantPool(),
10904 false, false, false, 16);
10906 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10907 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10908 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10909 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10911 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10912 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10915 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10916 DAG.getConstant(5, MVT::i32));
10917 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10919 // Turn 'a' into a mask suitable for VSELECT
10920 SDValue VSelM = DAG.getConstant(0x80, VT);
10921 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10922 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10924 SDValue CM1 = DAG.getConstant(0x0f, VT);
10925 SDValue CM2 = DAG.getConstant(0x3f, VT);
10927 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10928 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10929 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10930 DAG.getConstant(4, MVT::i32), DAG);
10931 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10932 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10935 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10936 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10937 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10939 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10940 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10941 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10942 DAG.getConstant(2, MVT::i32), DAG);
10943 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10944 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10947 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10948 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10949 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10951 // return VSELECT(r, r+r, a);
10952 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10953 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10957 // Decompose 256-bit shifts into smaller 128-bit shifts.
10958 if (VT.is256BitVector()) {
10959 unsigned NumElems = VT.getVectorNumElements();
10960 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10961 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10963 // Extract the two vectors
10964 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10965 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10967 // Recreate the shift amount vectors
10968 SDValue Amt1, Amt2;
10969 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10970 // Constant shift amount
10971 SmallVector<SDValue, 4> Amt1Csts;
10972 SmallVector<SDValue, 4> Amt2Csts;
10973 for (unsigned i = 0; i != NumElems/2; ++i)
10974 Amt1Csts.push_back(Amt->getOperand(i));
10975 for (unsigned i = NumElems/2; i != NumElems; ++i)
10976 Amt2Csts.push_back(Amt->getOperand(i));
10978 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10979 &Amt1Csts[0], NumElems/2);
10980 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10981 &Amt2Csts[0], NumElems/2);
10983 // Variable shift amount
10984 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10985 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10988 // Issue new vector shifts for the smaller types
10989 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10990 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10992 // Concatenate the result back
10993 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10999 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11000 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11001 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11002 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11003 // has only one use.
11004 SDNode *N = Op.getNode();
11005 SDValue LHS = N->getOperand(0);
11006 SDValue RHS = N->getOperand(1);
11007 unsigned BaseOp = 0;
11009 DebugLoc DL = Op.getDebugLoc();
11010 switch (Op.getOpcode()) {
11011 default: llvm_unreachable("Unknown ovf instruction!");
11013 // A subtract of one will be selected as a INC. Note that INC doesn't
11014 // set CF, so we can't do this for UADDO.
11015 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11017 BaseOp = X86ISD::INC;
11018 Cond = X86::COND_O;
11021 BaseOp = X86ISD::ADD;
11022 Cond = X86::COND_O;
11025 BaseOp = X86ISD::ADD;
11026 Cond = X86::COND_B;
11029 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11030 // set CF, so we can't do this for USUBO.
11031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11033 BaseOp = X86ISD::DEC;
11034 Cond = X86::COND_O;
11037 BaseOp = X86ISD::SUB;
11038 Cond = X86::COND_O;
11041 BaseOp = X86ISD::SUB;
11042 Cond = X86::COND_B;
11045 BaseOp = X86ISD::SMUL;
11046 Cond = X86::COND_O;
11048 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11049 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11051 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11054 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11055 DAG.getConstant(X86::COND_O, MVT::i32),
11056 SDValue(Sum.getNode(), 2));
11058 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11062 // Also sets EFLAGS.
11063 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11064 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11067 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11068 DAG.getConstant(Cond, MVT::i32),
11069 SDValue(Sum.getNode(), 1));
11071 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11074 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11075 SelectionDAG &DAG) const {
11076 DebugLoc dl = Op.getDebugLoc();
11077 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11078 EVT VT = Op.getValueType();
11080 if (!Subtarget->hasSSE2() || !VT.isVector())
11083 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11084 ExtraVT.getScalarType().getSizeInBits();
11085 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11087 switch (VT.getSimpleVT().SimpleTy) {
11088 default: return SDValue();
11091 if (!Subtarget->hasAVX())
11093 if (!Subtarget->hasAVX2()) {
11094 // needs to be split
11095 unsigned NumElems = VT.getVectorNumElements();
11097 // Extract the LHS vectors
11098 SDValue LHS = Op.getOperand(0);
11099 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11100 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11102 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11103 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11105 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11106 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11107 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11109 SDValue Extra = DAG.getValueType(ExtraVT);
11111 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11112 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11114 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11119 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11120 Op.getOperand(0), ShAmt, DAG);
11121 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11127 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11128 SelectionDAG &DAG) {
11129 DebugLoc dl = Op.getDebugLoc();
11131 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11132 // There isn't any reason to disable it if the target processor supports it.
11133 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11134 SDValue Chain = Op.getOperand(0);
11135 SDValue Zero = DAG.getConstant(0, MVT::i32);
11137 DAG.getRegister(X86::ESP, MVT::i32), // Base
11138 DAG.getTargetConstant(1, MVT::i8), // Scale
11139 DAG.getRegister(0, MVT::i32), // Index
11140 DAG.getTargetConstant(0, MVT::i32), // Disp
11141 DAG.getRegister(0, MVT::i32), // Segment.
11146 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11147 array_lengthof(Ops));
11148 return SDValue(Res, 0);
11151 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11153 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11155 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11156 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11157 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11158 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11160 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11161 if (!Op1 && !Op2 && !Op3 && Op4)
11162 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11164 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11165 if (Op1 && !Op2 && !Op3 && !Op4)
11166 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11168 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11170 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11173 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11174 SelectionDAG &DAG) {
11175 DebugLoc dl = Op.getDebugLoc();
11176 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11177 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11178 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11179 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11181 // The only fence that needs an instruction is a sequentially-consistent
11182 // cross-thread fence.
11183 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11184 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11185 // no-sse2). There isn't any reason to disable it if the target processor
11187 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11188 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11190 SDValue Chain = Op.getOperand(0);
11191 SDValue Zero = DAG.getConstant(0, MVT::i32);
11193 DAG.getRegister(X86::ESP, MVT::i32), // Base
11194 DAG.getTargetConstant(1, MVT::i8), // Scale
11195 DAG.getRegister(0, MVT::i32), // Index
11196 DAG.getTargetConstant(0, MVT::i32), // Disp
11197 DAG.getRegister(0, MVT::i32), // Segment.
11202 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11203 array_lengthof(Ops));
11204 return SDValue(Res, 0);
11207 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11208 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11212 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11213 SelectionDAG &DAG) {
11214 EVT T = Op.getValueType();
11215 DebugLoc DL = Op.getDebugLoc();
11218 switch(T.getSimpleVT().SimpleTy) {
11219 default: llvm_unreachable("Invalid value type!");
11220 case MVT::i8: Reg = X86::AL; size = 1; break;
11221 case MVT::i16: Reg = X86::AX; size = 2; break;
11222 case MVT::i32: Reg = X86::EAX; size = 4; break;
11224 assert(Subtarget->is64Bit() && "Node not type legal!");
11225 Reg = X86::RAX; size = 8;
11228 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11229 Op.getOperand(2), SDValue());
11230 SDValue Ops[] = { cpIn.getValue(0),
11233 DAG.getTargetConstant(size, MVT::i8),
11234 cpIn.getValue(1) };
11235 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11236 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11237 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11240 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11244 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11245 SelectionDAG &DAG) {
11246 assert(Subtarget->is64Bit() && "Result not type legalized?");
11247 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11248 SDValue TheChain = Op.getOperand(0);
11249 DebugLoc dl = Op.getDebugLoc();
11250 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11251 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11252 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11254 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11255 DAG.getConstant(32, MVT::i8));
11257 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11260 return DAG.getMergeValues(Ops, 2, dl);
11263 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11264 EVT SrcVT = Op.getOperand(0).getValueType();
11265 EVT DstVT = Op.getValueType();
11266 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11267 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11268 assert((DstVT == MVT::i64 ||
11269 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11270 "Unexpected custom BITCAST");
11271 // i64 <=> MMX conversions are Legal.
11272 if (SrcVT==MVT::i64 && DstVT.isVector())
11274 if (DstVT==MVT::i64 && SrcVT.isVector())
11276 // MMX <=> MMX conversions are Legal.
11277 if (SrcVT.isVector() && DstVT.isVector())
11279 // All other conversions need to be expanded.
11283 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11284 SDNode *Node = Op.getNode();
11285 DebugLoc dl = Node->getDebugLoc();
11286 EVT T = Node->getValueType(0);
11287 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11288 DAG.getConstant(0, T), Node->getOperand(2));
11289 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11290 cast<AtomicSDNode>(Node)->getMemoryVT(),
11291 Node->getOperand(0),
11292 Node->getOperand(1), negOp,
11293 cast<AtomicSDNode>(Node)->getSrcValue(),
11294 cast<AtomicSDNode>(Node)->getAlignment(),
11295 cast<AtomicSDNode>(Node)->getOrdering(),
11296 cast<AtomicSDNode>(Node)->getSynchScope());
11299 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11300 SDNode *Node = Op.getNode();
11301 DebugLoc dl = Node->getDebugLoc();
11302 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11304 // Convert seq_cst store -> xchg
11305 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11306 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11307 // (The only way to get a 16-byte store is cmpxchg16b)
11308 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11309 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11310 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11311 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11312 cast<AtomicSDNode>(Node)->getMemoryVT(),
11313 Node->getOperand(0),
11314 Node->getOperand(1), Node->getOperand(2),
11315 cast<AtomicSDNode>(Node)->getMemOperand(),
11316 cast<AtomicSDNode>(Node)->getOrdering(),
11317 cast<AtomicSDNode>(Node)->getSynchScope());
11318 return Swap.getValue(1);
11320 // Other atomic stores have a simple pattern.
11324 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11325 EVT VT = Op.getNode()->getValueType(0);
11327 // Let legalize expand this if it isn't a legal type yet.
11328 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11331 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11334 bool ExtraOp = false;
11335 switch (Op.getOpcode()) {
11336 default: llvm_unreachable("Invalid code");
11337 case ISD::ADDC: Opc = X86ISD::ADD; break;
11338 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11339 case ISD::SUBC: Opc = X86ISD::SUB; break;
11340 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11344 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11346 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11347 Op.getOperand(1), Op.getOperand(2));
11350 /// LowerOperation - Provide custom lowering hooks for some operations.
11352 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11353 switch (Op.getOpcode()) {
11354 default: llvm_unreachable("Should not custom lower this!");
11355 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11356 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11357 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11358 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11359 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11360 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11361 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11362 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11363 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11364 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11365 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11366 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11367 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11368 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11369 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11370 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11371 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11372 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11373 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11374 case ISD::SHL_PARTS:
11375 case ISD::SRA_PARTS:
11376 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11377 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11378 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11379 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11380 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11381 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11382 case ISD::FABS: return LowerFABS(Op, DAG);
11383 case ISD::FNEG: return LowerFNEG(Op, DAG);
11384 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11385 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11386 case ISD::SETCC: return LowerSETCC(Op, DAG);
11387 case ISD::SELECT: return LowerSELECT(Op, DAG);
11388 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11389 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11390 case ISD::VASTART: return LowerVASTART(Op, DAG);
11391 case ISD::VAARG: return LowerVAARG(Op, DAG);
11392 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11393 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11394 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11395 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11396 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11397 case ISD::FRAME_TO_ARGS_OFFSET:
11398 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11399 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11400 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11401 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11402 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11403 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11404 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11405 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11406 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11407 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11408 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11409 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11412 case ISD::SHL: return LowerShift(Op, DAG);
11418 case ISD::UMULO: return LowerXALUO(Op, DAG);
11419 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11420 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11424 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11425 case ISD::ADD: return LowerADD(Op, DAG);
11426 case ISD::SUB: return LowerSUB(Op, DAG);
11430 static void ReplaceATOMIC_LOAD(SDNode *Node,
11431 SmallVectorImpl<SDValue> &Results,
11432 SelectionDAG &DAG) {
11433 DebugLoc dl = Node->getDebugLoc();
11434 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11436 // Convert wide load -> cmpxchg8b/cmpxchg16b
11437 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11438 // (The only way to get a 16-byte load is cmpxchg16b)
11439 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11440 SDValue Zero = DAG.getConstant(0, VT);
11441 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11442 Node->getOperand(0),
11443 Node->getOperand(1), Zero, Zero,
11444 cast<AtomicSDNode>(Node)->getMemOperand(),
11445 cast<AtomicSDNode>(Node)->getOrdering(),
11446 cast<AtomicSDNode>(Node)->getSynchScope());
11447 Results.push_back(Swap.getValue(0));
11448 Results.push_back(Swap.getValue(1));
11452 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11453 SelectionDAG &DAG, unsigned NewOp) {
11454 DebugLoc dl = Node->getDebugLoc();
11455 assert (Node->getValueType(0) == MVT::i64 &&
11456 "Only know how to expand i64 atomics");
11458 SDValue Chain = Node->getOperand(0);
11459 SDValue In1 = Node->getOperand(1);
11460 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11461 Node->getOperand(2), DAG.getIntPtrConstant(0));
11462 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11463 Node->getOperand(2), DAG.getIntPtrConstant(1));
11464 SDValue Ops[] = { Chain, In1, In2L, In2H };
11465 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11467 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11468 cast<MemSDNode>(Node)->getMemOperand());
11469 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11470 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11471 Results.push_back(Result.getValue(2));
11474 /// ReplaceNodeResults - Replace a node with an illegal result type
11475 /// with a new node built out of custom code.
11476 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11477 SmallVectorImpl<SDValue>&Results,
11478 SelectionDAG &DAG) const {
11479 DebugLoc dl = N->getDebugLoc();
11480 switch (N->getOpcode()) {
11482 llvm_unreachable("Do not know how to custom type legalize this operation!");
11483 case ISD::SIGN_EXTEND_INREG:
11488 // We don't want to expand or promote these.
11490 case ISD::FP_TO_SINT:
11491 case ISD::FP_TO_UINT: {
11492 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11494 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11497 std::pair<SDValue,SDValue> Vals =
11498 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11499 SDValue FIST = Vals.first, StackSlot = Vals.second;
11500 if (FIST.getNode() != 0) {
11501 EVT VT = N->getValueType(0);
11502 // Return a load from the stack slot.
11503 if (StackSlot.getNode() != 0)
11504 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11505 MachinePointerInfo(),
11506 false, false, false, 0));
11508 Results.push_back(FIST);
11512 case ISD::FP_ROUND: {
11513 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11514 Results.push_back(V);
11517 case ISD::READCYCLECOUNTER: {
11518 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11519 SDValue TheChain = N->getOperand(0);
11520 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11521 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11523 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11525 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11526 SDValue Ops[] = { eax, edx };
11527 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11528 Results.push_back(edx.getValue(1));
11531 case ISD::ATOMIC_CMP_SWAP: {
11532 EVT T = N->getValueType(0);
11533 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11534 bool Regs64bit = T == MVT::i128;
11535 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11536 SDValue cpInL, cpInH;
11537 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11538 DAG.getConstant(0, HalfT));
11539 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11540 DAG.getConstant(1, HalfT));
11541 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11542 Regs64bit ? X86::RAX : X86::EAX,
11544 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11545 Regs64bit ? X86::RDX : X86::EDX,
11546 cpInH, cpInL.getValue(1));
11547 SDValue swapInL, swapInH;
11548 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11549 DAG.getConstant(0, HalfT));
11550 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11551 DAG.getConstant(1, HalfT));
11552 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11553 Regs64bit ? X86::RBX : X86::EBX,
11554 swapInL, cpInH.getValue(1));
11555 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11556 Regs64bit ? X86::RCX : X86::ECX,
11557 swapInH, swapInL.getValue(1));
11558 SDValue Ops[] = { swapInH.getValue(0),
11560 swapInH.getValue(1) };
11561 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11562 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11563 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11564 X86ISD::LCMPXCHG8_DAG;
11565 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11567 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11568 Regs64bit ? X86::RAX : X86::EAX,
11569 HalfT, Result.getValue(1));
11570 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11571 Regs64bit ? X86::RDX : X86::EDX,
11572 HalfT, cpOutL.getValue(2));
11573 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11574 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11575 Results.push_back(cpOutH.getValue(1));
11578 case ISD::ATOMIC_LOAD_ADD:
11579 case ISD::ATOMIC_LOAD_AND:
11580 case ISD::ATOMIC_LOAD_NAND:
11581 case ISD::ATOMIC_LOAD_OR:
11582 case ISD::ATOMIC_LOAD_SUB:
11583 case ISD::ATOMIC_LOAD_XOR:
11584 case ISD::ATOMIC_LOAD_MAX:
11585 case ISD::ATOMIC_LOAD_MIN:
11586 case ISD::ATOMIC_LOAD_UMAX:
11587 case ISD::ATOMIC_LOAD_UMIN:
11588 case ISD::ATOMIC_SWAP: {
11590 switch (N->getOpcode()) {
11591 default: llvm_unreachable("Unexpected opcode");
11592 case ISD::ATOMIC_LOAD_ADD:
11593 Opc = X86ISD::ATOMADD64_DAG;
11595 case ISD::ATOMIC_LOAD_AND:
11596 Opc = X86ISD::ATOMAND64_DAG;
11598 case ISD::ATOMIC_LOAD_NAND:
11599 Opc = X86ISD::ATOMNAND64_DAG;
11601 case ISD::ATOMIC_LOAD_OR:
11602 Opc = X86ISD::ATOMOR64_DAG;
11604 case ISD::ATOMIC_LOAD_SUB:
11605 Opc = X86ISD::ATOMSUB64_DAG;
11607 case ISD::ATOMIC_LOAD_XOR:
11608 Opc = X86ISD::ATOMXOR64_DAG;
11610 case ISD::ATOMIC_LOAD_MAX:
11611 Opc = X86ISD::ATOMMAX64_DAG;
11613 case ISD::ATOMIC_LOAD_MIN:
11614 Opc = X86ISD::ATOMMIN64_DAG;
11616 case ISD::ATOMIC_LOAD_UMAX:
11617 Opc = X86ISD::ATOMUMAX64_DAG;
11619 case ISD::ATOMIC_LOAD_UMIN:
11620 Opc = X86ISD::ATOMUMIN64_DAG;
11622 case ISD::ATOMIC_SWAP:
11623 Opc = X86ISD::ATOMSWAP64_DAG;
11626 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11629 case ISD::ATOMIC_LOAD:
11630 ReplaceATOMIC_LOAD(N, Results, DAG);
11634 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11636 default: return NULL;
11637 case X86ISD::BSF: return "X86ISD::BSF";
11638 case X86ISD::BSR: return "X86ISD::BSR";
11639 case X86ISD::SHLD: return "X86ISD::SHLD";
11640 case X86ISD::SHRD: return "X86ISD::SHRD";
11641 case X86ISD::FAND: return "X86ISD::FAND";
11642 case X86ISD::FOR: return "X86ISD::FOR";
11643 case X86ISD::FXOR: return "X86ISD::FXOR";
11644 case X86ISD::FSRL: return "X86ISD::FSRL";
11645 case X86ISD::FILD: return "X86ISD::FILD";
11646 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11647 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11648 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11649 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11650 case X86ISD::FLD: return "X86ISD::FLD";
11651 case X86ISD::FST: return "X86ISD::FST";
11652 case X86ISD::CALL: return "X86ISD::CALL";
11653 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11654 case X86ISD::BT: return "X86ISD::BT";
11655 case X86ISD::CMP: return "X86ISD::CMP";
11656 case X86ISD::COMI: return "X86ISD::COMI";
11657 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11658 case X86ISD::SETCC: return "X86ISD::SETCC";
11659 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11660 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11661 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11662 case X86ISD::CMOV: return "X86ISD::CMOV";
11663 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11664 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11665 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11666 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11667 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11668 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11669 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11670 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11671 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11672 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11673 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11674 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11675 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11676 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11677 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11678 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11679 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11680 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11681 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11682 case X86ISD::HADD: return "X86ISD::HADD";
11683 case X86ISD::HSUB: return "X86ISD::HSUB";
11684 case X86ISD::FHADD: return "X86ISD::FHADD";
11685 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11686 case X86ISD::FMAX: return "X86ISD::FMAX";
11687 case X86ISD::FMIN: return "X86ISD::FMIN";
11688 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11689 case X86ISD::FMINC: return "X86ISD::FMINC";
11690 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11691 case X86ISD::FRCP: return "X86ISD::FRCP";
11692 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11693 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11694 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11695 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11696 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11697 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11698 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11699 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11700 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11701 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11702 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11703 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11704 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11705 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11706 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11707 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11708 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11709 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11710 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11711 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11712 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11713 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11714 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11715 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11716 case X86ISD::VSHL: return "X86ISD::VSHL";
11717 case X86ISD::VSRL: return "X86ISD::VSRL";
11718 case X86ISD::VSRA: return "X86ISD::VSRA";
11719 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11720 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11721 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11722 case X86ISD::CMPP: return "X86ISD::CMPP";
11723 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11724 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11725 case X86ISD::ADD: return "X86ISD::ADD";
11726 case X86ISD::SUB: return "X86ISD::SUB";
11727 case X86ISD::ADC: return "X86ISD::ADC";
11728 case X86ISD::SBB: return "X86ISD::SBB";
11729 case X86ISD::SMUL: return "X86ISD::SMUL";
11730 case X86ISD::UMUL: return "X86ISD::UMUL";
11731 case X86ISD::INC: return "X86ISD::INC";
11732 case X86ISD::DEC: return "X86ISD::DEC";
11733 case X86ISD::OR: return "X86ISD::OR";
11734 case X86ISD::XOR: return "X86ISD::XOR";
11735 case X86ISD::AND: return "X86ISD::AND";
11736 case X86ISD::ANDN: return "X86ISD::ANDN";
11737 case X86ISD::BLSI: return "X86ISD::BLSI";
11738 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11739 case X86ISD::BLSR: return "X86ISD::BLSR";
11740 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11741 case X86ISD::PTEST: return "X86ISD::PTEST";
11742 case X86ISD::TESTP: return "X86ISD::TESTP";
11743 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11744 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11745 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11746 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11747 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11748 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11749 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11750 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11751 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11752 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11753 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11754 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11755 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11756 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11757 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11758 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11759 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11760 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11761 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11762 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11763 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11764 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11765 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11766 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11767 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11768 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11769 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11770 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11771 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11772 case X86ISD::SAHF: return "X86ISD::SAHF";
11773 case X86ISD::RDRAND: return "X86ISD::RDRAND";
11774 case X86ISD::FMADD: return "X86ISD::FMADD";
11775 case X86ISD::FMSUB: return "X86ISD::FMSUB";
11776 case X86ISD::FNMADD: return "X86ISD::FNMADD";
11777 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
11778 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
11779 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
11783 // isLegalAddressingMode - Return true if the addressing mode represented
11784 // by AM is legal for this target, for a load/store of the specified type.
11785 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11787 // X86 supports extremely general addressing modes.
11788 CodeModel::Model M = getTargetMachine().getCodeModel();
11789 Reloc::Model R = getTargetMachine().getRelocationModel();
11791 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11792 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11797 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11799 // If a reference to this global requires an extra load, we can't fold it.
11800 if (isGlobalStubReference(GVFlags))
11803 // If BaseGV requires a register for the PIC base, we cannot also have a
11804 // BaseReg specified.
11805 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11808 // If lower 4G is not available, then we must use rip-relative addressing.
11809 if ((M != CodeModel::Small || R != Reloc::Static) &&
11810 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11814 switch (AM.Scale) {
11820 // These scales always work.
11825 // These scales are formed with basereg+scalereg. Only accept if there is
11830 default: // Other stuff never works.
11838 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11839 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11841 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11842 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11843 if (NumBits1 <= NumBits2)
11848 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11849 return Imm == (int32_t)Imm;
11852 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
11853 // Can also use sub to handle negated immediates.
11854 return Imm == (int32_t)Imm;
11857 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11858 if (!VT1.isInteger() || !VT2.isInteger())
11860 unsigned NumBits1 = VT1.getSizeInBits();
11861 unsigned NumBits2 = VT2.getSizeInBits();
11862 if (NumBits1 <= NumBits2)
11867 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11868 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11869 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11872 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11873 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11874 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11877 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11878 // i16 instructions are longer (0x66 prefix) and potentially slower.
11879 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11882 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11883 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11884 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11885 /// are assumed to be legal.
11887 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11889 // Very little shuffling can be done for 64-bit vectors right now.
11890 if (VT.getSizeInBits() == 64)
11893 // FIXME: pshufb, blends, shifts.
11894 return (VT.getVectorNumElements() == 2 ||
11895 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11896 isMOVLMask(M, VT) ||
11897 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11898 isPSHUFDMask(M, VT) ||
11899 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11900 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11901 isPALIGNRMask(M, VT, Subtarget) ||
11902 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11903 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11904 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11905 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11909 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11911 unsigned NumElts = VT.getVectorNumElements();
11912 // FIXME: This collection of masks seems suspect.
11915 if (NumElts == 4 && VT.is128BitVector()) {
11916 return (isMOVLMask(Mask, VT) ||
11917 isCommutedMOVLMask(Mask, VT, true) ||
11918 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11919 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11924 //===----------------------------------------------------------------------===//
11925 // X86 Scheduler Hooks
11926 //===----------------------------------------------------------------------===//
11928 // private utility function
11930 // Get CMPXCHG opcode for the specified data type.
11931 static unsigned getCmpXChgOpcode(EVT VT) {
11932 switch (VT.getSimpleVT().SimpleTy) {
11933 case MVT::i8: return X86::LCMPXCHG8;
11934 case MVT::i16: return X86::LCMPXCHG16;
11935 case MVT::i32: return X86::LCMPXCHG32;
11936 case MVT::i64: return X86::LCMPXCHG64;
11940 llvm_unreachable("Invalid operand size!");
11943 // Get LOAD opcode for the specified data type.
11944 static unsigned getLoadOpcode(EVT VT) {
11945 switch (VT.getSimpleVT().SimpleTy) {
11946 case MVT::i8: return X86::MOV8rm;
11947 case MVT::i16: return X86::MOV16rm;
11948 case MVT::i32: return X86::MOV32rm;
11949 case MVT::i64: return X86::MOV64rm;
11953 llvm_unreachable("Invalid operand size!");
11956 // Get opcode of the non-atomic one from the specified atomic instruction.
11957 static unsigned getNonAtomicOpcode(unsigned Opc) {
11959 case X86::ATOMAND8: return X86::AND8rr;
11960 case X86::ATOMAND16: return X86::AND16rr;
11961 case X86::ATOMAND32: return X86::AND32rr;
11962 case X86::ATOMAND64: return X86::AND64rr;
11963 case X86::ATOMOR8: return X86::OR8rr;
11964 case X86::ATOMOR16: return X86::OR16rr;
11965 case X86::ATOMOR32: return X86::OR32rr;
11966 case X86::ATOMOR64: return X86::OR64rr;
11967 case X86::ATOMXOR8: return X86::XOR8rr;
11968 case X86::ATOMXOR16: return X86::XOR16rr;
11969 case X86::ATOMXOR32: return X86::XOR32rr;
11970 case X86::ATOMXOR64: return X86::XOR64rr;
11972 llvm_unreachable("Unhandled atomic-load-op opcode!");
11975 // Get opcode of the non-atomic one from the specified atomic instruction with
11977 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
11978 unsigned &ExtraOpc) {
11980 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
11981 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
11982 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
11983 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
11984 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
11985 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
11986 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
11987 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
11988 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
11989 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
11990 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
11991 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
11992 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
11993 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
11994 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
11995 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
11996 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
11997 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
11998 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
11999 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12001 llvm_unreachable("Unhandled atomic-load-op opcode!");
12004 // Get opcode of the non-atomic one from the specified atomic instruction for
12005 // 64-bit data type on 32-bit target.
12006 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12008 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12009 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12010 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12011 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12012 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12013 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12014 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12015 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12016 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12017 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12019 llvm_unreachable("Unhandled atomic-load-op opcode!");
12022 // Get opcode of the non-atomic one from the specified atomic instruction for
12023 // 64-bit data type on 32-bit target with extra opcode.
12024 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12026 unsigned &ExtraOpc) {
12028 case X86::ATOMNAND6432:
12029 ExtraOpc = X86::NOT32r;
12030 HiOpc = X86::AND32rr;
12031 return X86::AND32rr;
12033 llvm_unreachable("Unhandled atomic-load-op opcode!");
12036 // Get pseudo CMOV opcode from the specified data type.
12037 static unsigned getPseudoCMOVOpc(EVT VT) {
12038 switch (VT.getSimpleVT().SimpleTy) {
12039 case MVT::i8: return X86::CMOV_GR8;
12040 case MVT::i16: return X86::CMOV_GR16;
12041 case MVT::i32: return X86::CMOV_GR32;
12045 llvm_unreachable("Unknown CMOV opcode!");
12048 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12049 // They will be translated into a spin-loop or compare-exchange loop from
12052 // dst = atomic-fetch-op MI.addr, MI.val
12058 // EAX = LOAD MI.addr
12060 // t1 = OP MI.val, EAX
12061 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12066 MachineBasicBlock *
12067 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12068 MachineBasicBlock *MBB) const {
12069 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12070 DebugLoc DL = MI->getDebugLoc();
12072 MachineFunction *MF = MBB->getParent();
12073 MachineRegisterInfo &MRI = MF->getRegInfo();
12075 const BasicBlock *BB = MBB->getBasicBlock();
12076 MachineFunction::iterator I = MBB;
12079 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12080 "Unexpected number of operands");
12082 assert(MI->hasOneMemOperand() &&
12083 "Expected atomic-load-op to have one memoperand");
12085 // Memory Reference
12086 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12087 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12089 unsigned DstReg, SrcReg;
12090 unsigned MemOpndSlot;
12092 unsigned CurOp = 0;
12094 DstReg = MI->getOperand(CurOp++).getReg();
12095 MemOpndSlot = CurOp;
12096 CurOp += X86::AddrNumOperands;
12097 SrcReg = MI->getOperand(CurOp++).getReg();
12099 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12100 MVT::SimpleValueType VT = *RC->vt_begin();
12101 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12103 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12104 unsigned LOADOpc = getLoadOpcode(VT);
12106 // For the atomic load-arith operator, we generate
12109 // EAX = LOAD [MI.addr]
12111 // t1 = OP MI.val, EAX
12112 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12116 MachineBasicBlock *thisMBB = MBB;
12117 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12118 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12119 MF->insert(I, mainMBB);
12120 MF->insert(I, sinkMBB);
12122 MachineInstrBuilder MIB;
12124 // Transfer the remainder of BB and its successor edges to sinkMBB.
12125 sinkMBB->splice(sinkMBB->begin(), MBB,
12126 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12127 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12130 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12131 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12132 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12133 MIB.setMemRefs(MMOBegin, MMOEnd);
12135 thisMBB->addSuccessor(mainMBB);
12138 MachineBasicBlock *origMainMBB = mainMBB;
12139 mainMBB->addLiveIn(AccPhyReg);
12141 // Copy AccPhyReg as it is used more than once.
12142 unsigned AccReg = MRI.createVirtualRegister(RC);
12143 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12144 .addReg(AccPhyReg);
12146 unsigned t1 = MRI.createVirtualRegister(RC);
12147 unsigned Opc = MI->getOpcode();
12150 llvm_unreachable("Unhandled atomic-load-op opcode!");
12151 case X86::ATOMAND8:
12152 case X86::ATOMAND16:
12153 case X86::ATOMAND32:
12154 case X86::ATOMAND64:
12156 case X86::ATOMOR16:
12157 case X86::ATOMOR32:
12158 case X86::ATOMOR64:
12159 case X86::ATOMXOR8:
12160 case X86::ATOMXOR16:
12161 case X86::ATOMXOR32:
12162 case X86::ATOMXOR64: {
12163 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12164 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12168 case X86::ATOMNAND8:
12169 case X86::ATOMNAND16:
12170 case X86::ATOMNAND32:
12171 case X86::ATOMNAND64: {
12172 unsigned t2 = MRI.createVirtualRegister(RC);
12174 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12175 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12177 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12180 case X86::ATOMMAX8:
12181 case X86::ATOMMAX16:
12182 case X86::ATOMMAX32:
12183 case X86::ATOMMAX64:
12184 case X86::ATOMMIN8:
12185 case X86::ATOMMIN16:
12186 case X86::ATOMMIN32:
12187 case X86::ATOMMIN64:
12188 case X86::ATOMUMAX8:
12189 case X86::ATOMUMAX16:
12190 case X86::ATOMUMAX32:
12191 case X86::ATOMUMAX64:
12192 case X86::ATOMUMIN8:
12193 case X86::ATOMUMIN16:
12194 case X86::ATOMUMIN32:
12195 case X86::ATOMUMIN64: {
12197 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12199 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12203 if (Subtarget->hasCMov()) {
12204 if (VT != MVT::i8) {
12206 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12210 // Promote i8 to i32 to use CMOV32
12211 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12212 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12213 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12214 unsigned t2 = MRI.createVirtualRegister(RC32);
12216 unsigned Undef = MRI.createVirtualRegister(RC32);
12217 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12219 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12222 .addImm(X86::sub_8bit);
12223 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12226 .addImm(X86::sub_8bit);
12228 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12232 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12233 .addReg(t2, 0, X86::sub_8bit);
12236 // Use pseudo select and lower them.
12237 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12238 "Invalid atomic-load-op transformation!");
12239 unsigned SelOpc = getPseudoCMOVOpc(VT);
12240 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12241 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12242 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12243 .addReg(SrcReg).addReg(AccReg)
12245 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12251 // Copy AccPhyReg back from virtual register.
12252 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12255 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12256 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12257 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12259 MIB.setMemRefs(MMOBegin, MMOEnd);
12261 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12263 mainMBB->addSuccessor(origMainMBB);
12264 mainMBB->addSuccessor(sinkMBB);
12267 sinkMBB->addLiveIn(AccPhyReg);
12269 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12270 TII->get(TargetOpcode::COPY), DstReg)
12271 .addReg(AccPhyReg);
12273 MI->eraseFromParent();
12277 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12278 // instructions. They will be translated into a spin-loop or compare-exchange
12282 // dst = atomic-fetch-op MI.addr, MI.val
12288 // EAX = LOAD [MI.addr + 0]
12289 // EDX = LOAD [MI.addr + 4]
12291 // EBX = OP MI.val.lo, EAX
12292 // ECX = OP MI.val.hi, EDX
12293 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12298 MachineBasicBlock *
12299 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12300 MachineBasicBlock *MBB) const {
12301 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12302 DebugLoc DL = MI->getDebugLoc();
12304 MachineFunction *MF = MBB->getParent();
12305 MachineRegisterInfo &MRI = MF->getRegInfo();
12307 const BasicBlock *BB = MBB->getBasicBlock();
12308 MachineFunction::iterator I = MBB;
12311 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12312 "Unexpected number of operands");
12314 assert(MI->hasOneMemOperand() &&
12315 "Expected atomic-load-op32 to have one memoperand");
12317 // Memory Reference
12318 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12319 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12321 unsigned DstLoReg, DstHiReg;
12322 unsigned SrcLoReg, SrcHiReg;
12323 unsigned MemOpndSlot;
12325 unsigned CurOp = 0;
12327 DstLoReg = MI->getOperand(CurOp++).getReg();
12328 DstHiReg = MI->getOperand(CurOp++).getReg();
12329 MemOpndSlot = CurOp;
12330 CurOp += X86::AddrNumOperands;
12331 SrcLoReg = MI->getOperand(CurOp++).getReg();
12332 SrcHiReg = MI->getOperand(CurOp++).getReg();
12334 const TargetRegisterClass *RC = &X86::GR32RegClass;
12335 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12337 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12338 unsigned LOADOpc = X86::MOV32rm;
12340 // For the atomic load-arith operator, we generate
12343 // EAX = LOAD [MI.addr + 0]
12344 // EDX = LOAD [MI.addr + 4]
12346 // EBX = OP MI.vallo, EAX
12347 // ECX = OP MI.valhi, EDX
12348 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12352 MachineBasicBlock *thisMBB = MBB;
12353 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12354 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12355 MF->insert(I, mainMBB);
12356 MF->insert(I, sinkMBB);
12358 MachineInstrBuilder MIB;
12360 // Transfer the remainder of BB and its successor edges to sinkMBB.
12361 sinkMBB->splice(sinkMBB->begin(), MBB,
12362 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12363 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12367 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12368 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12369 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12370 MIB.setMemRefs(MMOBegin, MMOEnd);
12372 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12373 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12374 if (i == X86::AddrDisp)
12375 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12377 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12379 MIB.setMemRefs(MMOBegin, MMOEnd);
12381 thisMBB->addSuccessor(mainMBB);
12384 MachineBasicBlock *origMainMBB = mainMBB;
12385 mainMBB->addLiveIn(X86::EAX);
12386 mainMBB->addLiveIn(X86::EDX);
12388 // Copy EDX:EAX as they are used more than once.
12389 unsigned LoReg = MRI.createVirtualRegister(RC);
12390 unsigned HiReg = MRI.createVirtualRegister(RC);
12391 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12392 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12394 unsigned t1L = MRI.createVirtualRegister(RC);
12395 unsigned t1H = MRI.createVirtualRegister(RC);
12397 unsigned Opc = MI->getOpcode();
12400 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12401 case X86::ATOMAND6432:
12402 case X86::ATOMOR6432:
12403 case X86::ATOMXOR6432:
12404 case X86::ATOMADD6432:
12405 case X86::ATOMSUB6432: {
12407 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12408 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12409 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12412 case X86::ATOMNAND6432: {
12413 unsigned HiOpc, NOTOpc;
12414 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12415 unsigned t2L = MRI.createVirtualRegister(RC);
12416 unsigned t2H = MRI.createVirtualRegister(RC);
12417 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12418 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12419 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12420 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12423 case X86::ATOMMAX6432:
12424 case X86::ATOMMIN6432:
12425 case X86::ATOMUMAX6432:
12426 case X86::ATOMUMIN6432: {
12428 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12429 unsigned cL = MRI.createVirtualRegister(RC8);
12430 unsigned cH = MRI.createVirtualRegister(RC8);
12431 unsigned cL32 = MRI.createVirtualRegister(RC);
12432 unsigned cH32 = MRI.createVirtualRegister(RC);
12433 unsigned cc = MRI.createVirtualRegister(RC);
12434 // cl := cmp src_lo, lo
12435 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12436 .addReg(SrcLoReg).addReg(LoReg);
12437 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12438 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12439 // ch := cmp src_hi, hi
12440 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12441 .addReg(SrcHiReg).addReg(HiReg);
12442 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12443 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12444 // cc := if (src_hi == hi) ? cl : ch;
12445 if (Subtarget->hasCMov()) {
12446 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12447 .addReg(cH32).addReg(cL32);
12449 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12450 .addReg(cH32).addReg(cL32)
12451 .addImm(X86::COND_E);
12452 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12454 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12455 if (Subtarget->hasCMov()) {
12456 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12457 .addReg(SrcLoReg).addReg(LoReg);
12458 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12459 .addReg(SrcHiReg).addReg(HiReg);
12461 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12462 .addReg(SrcLoReg).addReg(LoReg)
12463 .addImm(X86::COND_NE);
12464 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12465 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12466 .addReg(SrcHiReg).addReg(HiReg)
12467 .addImm(X86::COND_NE);
12468 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12472 case X86::ATOMSWAP6432: {
12474 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12475 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12476 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12481 // Copy EDX:EAX back from HiReg:LoReg
12482 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12483 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12484 // Copy ECX:EBX from t1H:t1L
12485 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12486 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12488 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12489 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12490 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12491 MIB.setMemRefs(MMOBegin, MMOEnd);
12493 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12495 mainMBB->addSuccessor(origMainMBB);
12496 mainMBB->addSuccessor(sinkMBB);
12499 sinkMBB->addLiveIn(X86::EAX);
12500 sinkMBB->addLiveIn(X86::EDX);
12502 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12503 TII->get(TargetOpcode::COPY), DstLoReg)
12505 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12506 TII->get(TargetOpcode::COPY), DstHiReg)
12509 MI->eraseFromParent();
12513 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12514 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12515 // in the .td file.
12516 MachineBasicBlock *
12517 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12518 unsigned numArgs, bool memArg) const {
12519 assert(Subtarget->hasSSE42() &&
12520 "Target must have SSE4.2 or AVX features enabled");
12522 DebugLoc dl = MI->getDebugLoc();
12523 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12525 if (!Subtarget->hasAVX()) {
12527 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12529 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12532 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12534 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12537 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12538 for (unsigned i = 0; i < numArgs; ++i) {
12539 MachineOperand &Op = MI->getOperand(i+1);
12540 if (!(Op.isReg() && Op.isImplicit()))
12541 MIB.addOperand(Op);
12543 BuildMI(*BB, MI, dl,
12544 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12545 .addReg(X86::XMM0);
12547 MI->eraseFromParent();
12551 MachineBasicBlock *
12552 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12553 DebugLoc dl = MI->getDebugLoc();
12554 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12556 // Address into RAX/EAX, other two args into ECX, EDX.
12557 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12558 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12559 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12560 for (int i = 0; i < X86::AddrNumOperands; ++i)
12561 MIB.addOperand(MI->getOperand(i));
12563 unsigned ValOps = X86::AddrNumOperands;
12564 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12565 .addReg(MI->getOperand(ValOps).getReg());
12566 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12567 .addReg(MI->getOperand(ValOps+1).getReg());
12569 // The instruction doesn't actually take any operands though.
12570 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12572 MI->eraseFromParent(); // The pseudo is gone now.
12576 MachineBasicBlock *
12577 X86TargetLowering::EmitVAARG64WithCustomInserter(
12579 MachineBasicBlock *MBB) const {
12580 // Emit va_arg instruction on X86-64.
12582 // Operands to this pseudo-instruction:
12583 // 0 ) Output : destination address (reg)
12584 // 1-5) Input : va_list address (addr, i64mem)
12585 // 6 ) ArgSize : Size (in bytes) of vararg type
12586 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12587 // 8 ) Align : Alignment of type
12588 // 9 ) EFLAGS (implicit-def)
12590 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12591 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12593 unsigned DestReg = MI->getOperand(0).getReg();
12594 MachineOperand &Base = MI->getOperand(1);
12595 MachineOperand &Scale = MI->getOperand(2);
12596 MachineOperand &Index = MI->getOperand(3);
12597 MachineOperand &Disp = MI->getOperand(4);
12598 MachineOperand &Segment = MI->getOperand(5);
12599 unsigned ArgSize = MI->getOperand(6).getImm();
12600 unsigned ArgMode = MI->getOperand(7).getImm();
12601 unsigned Align = MI->getOperand(8).getImm();
12603 // Memory Reference
12604 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12605 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12606 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12608 // Machine Information
12609 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12610 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12611 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12612 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12613 DebugLoc DL = MI->getDebugLoc();
12615 // struct va_list {
12618 // i64 overflow_area (address)
12619 // i64 reg_save_area (address)
12621 // sizeof(va_list) = 24
12622 // alignment(va_list) = 8
12624 unsigned TotalNumIntRegs = 6;
12625 unsigned TotalNumXMMRegs = 8;
12626 bool UseGPOffset = (ArgMode == 1);
12627 bool UseFPOffset = (ArgMode == 2);
12628 unsigned MaxOffset = TotalNumIntRegs * 8 +
12629 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12631 /* Align ArgSize to a multiple of 8 */
12632 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12633 bool NeedsAlign = (Align > 8);
12635 MachineBasicBlock *thisMBB = MBB;
12636 MachineBasicBlock *overflowMBB;
12637 MachineBasicBlock *offsetMBB;
12638 MachineBasicBlock *endMBB;
12640 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12641 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12642 unsigned OffsetReg = 0;
12644 if (!UseGPOffset && !UseFPOffset) {
12645 // If we only pull from the overflow region, we don't create a branch.
12646 // We don't need to alter control flow.
12647 OffsetDestReg = 0; // unused
12648 OverflowDestReg = DestReg;
12651 overflowMBB = thisMBB;
12654 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12655 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12656 // If not, pull from overflow_area. (branch to overflowMBB)
12661 // offsetMBB overflowMBB
12666 // Registers for the PHI in endMBB
12667 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12668 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12670 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12671 MachineFunction *MF = MBB->getParent();
12672 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12673 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12674 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12676 MachineFunction::iterator MBBIter = MBB;
12679 // Insert the new basic blocks
12680 MF->insert(MBBIter, offsetMBB);
12681 MF->insert(MBBIter, overflowMBB);
12682 MF->insert(MBBIter, endMBB);
12684 // Transfer the remainder of MBB and its successor edges to endMBB.
12685 endMBB->splice(endMBB->begin(), thisMBB,
12686 llvm::next(MachineBasicBlock::iterator(MI)),
12688 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12690 // Make offsetMBB and overflowMBB successors of thisMBB
12691 thisMBB->addSuccessor(offsetMBB);
12692 thisMBB->addSuccessor(overflowMBB);
12694 // endMBB is a successor of both offsetMBB and overflowMBB
12695 offsetMBB->addSuccessor(endMBB);
12696 overflowMBB->addSuccessor(endMBB);
12698 // Load the offset value into a register
12699 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12700 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12704 .addDisp(Disp, UseFPOffset ? 4 : 0)
12705 .addOperand(Segment)
12706 .setMemRefs(MMOBegin, MMOEnd);
12708 // Check if there is enough room left to pull this argument.
12709 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12711 .addImm(MaxOffset + 8 - ArgSizeA8);
12713 // Branch to "overflowMBB" if offset >= max
12714 // Fall through to "offsetMBB" otherwise
12715 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12716 .addMBB(overflowMBB);
12719 // In offsetMBB, emit code to use the reg_save_area.
12721 assert(OffsetReg != 0);
12723 // Read the reg_save_area address.
12724 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12725 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12730 .addOperand(Segment)
12731 .setMemRefs(MMOBegin, MMOEnd);
12733 // Zero-extend the offset
12734 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12735 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12738 .addImm(X86::sub_32bit);
12740 // Add the offset to the reg_save_area to get the final address.
12741 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12742 .addReg(OffsetReg64)
12743 .addReg(RegSaveReg);
12745 // Compute the offset for the next argument
12746 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12747 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12749 .addImm(UseFPOffset ? 16 : 8);
12751 // Store it back into the va_list.
12752 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12756 .addDisp(Disp, UseFPOffset ? 4 : 0)
12757 .addOperand(Segment)
12758 .addReg(NextOffsetReg)
12759 .setMemRefs(MMOBegin, MMOEnd);
12762 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12767 // Emit code to use overflow area
12770 // Load the overflow_area address into a register.
12771 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12772 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12777 .addOperand(Segment)
12778 .setMemRefs(MMOBegin, MMOEnd);
12780 // If we need to align it, do so. Otherwise, just copy the address
12781 // to OverflowDestReg.
12783 // Align the overflow address
12784 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12785 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12787 // aligned_addr = (addr + (align-1)) & ~(align-1)
12788 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12789 .addReg(OverflowAddrReg)
12792 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12794 .addImm(~(uint64_t)(Align-1));
12796 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12797 .addReg(OverflowAddrReg);
12800 // Compute the next overflow address after this argument.
12801 // (the overflow address should be kept 8-byte aligned)
12802 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12803 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12804 .addReg(OverflowDestReg)
12805 .addImm(ArgSizeA8);
12807 // Store the new overflow address.
12808 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12813 .addOperand(Segment)
12814 .addReg(NextAddrReg)
12815 .setMemRefs(MMOBegin, MMOEnd);
12817 // If we branched, emit the PHI to the front of endMBB.
12819 BuildMI(*endMBB, endMBB->begin(), DL,
12820 TII->get(X86::PHI), DestReg)
12821 .addReg(OffsetDestReg).addMBB(offsetMBB)
12822 .addReg(OverflowDestReg).addMBB(overflowMBB);
12825 // Erase the pseudo instruction
12826 MI->eraseFromParent();
12831 MachineBasicBlock *
12832 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12834 MachineBasicBlock *MBB) const {
12835 // Emit code to save XMM registers to the stack. The ABI says that the
12836 // number of registers to save is given in %al, so it's theoretically
12837 // possible to do an indirect jump trick to avoid saving all of them,
12838 // however this code takes a simpler approach and just executes all
12839 // of the stores if %al is non-zero. It's less code, and it's probably
12840 // easier on the hardware branch predictor, and stores aren't all that
12841 // expensive anyway.
12843 // Create the new basic blocks. One block contains all the XMM stores,
12844 // and one block is the final destination regardless of whether any
12845 // stores were performed.
12846 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12847 MachineFunction *F = MBB->getParent();
12848 MachineFunction::iterator MBBIter = MBB;
12850 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12851 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12852 F->insert(MBBIter, XMMSaveMBB);
12853 F->insert(MBBIter, EndMBB);
12855 // Transfer the remainder of MBB and its successor edges to EndMBB.
12856 EndMBB->splice(EndMBB->begin(), MBB,
12857 llvm::next(MachineBasicBlock::iterator(MI)),
12859 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12861 // The original block will now fall through to the XMM save block.
12862 MBB->addSuccessor(XMMSaveMBB);
12863 // The XMMSaveMBB will fall through to the end block.
12864 XMMSaveMBB->addSuccessor(EndMBB);
12866 // Now add the instructions.
12867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12868 DebugLoc DL = MI->getDebugLoc();
12870 unsigned CountReg = MI->getOperand(0).getReg();
12871 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12872 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12874 if (!Subtarget->isTargetWin64()) {
12875 // If %al is 0, branch around the XMM save block.
12876 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12877 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12878 MBB->addSuccessor(EndMBB);
12881 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12882 // In the XMM save block, save all the XMM argument registers.
12883 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12884 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12885 MachineMemOperand *MMO =
12886 F->getMachineMemOperand(
12887 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12888 MachineMemOperand::MOStore,
12889 /*Size=*/16, /*Align=*/16);
12890 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12891 .addFrameIndex(RegSaveFrameIndex)
12892 .addImm(/*Scale=*/1)
12893 .addReg(/*IndexReg=*/0)
12894 .addImm(/*Disp=*/Offset)
12895 .addReg(/*Segment=*/0)
12896 .addReg(MI->getOperand(i).getReg())
12897 .addMemOperand(MMO);
12900 MI->eraseFromParent(); // The pseudo instruction is gone now.
12905 // The EFLAGS operand of SelectItr might be missing a kill marker
12906 // because there were multiple uses of EFLAGS, and ISel didn't know
12907 // which to mark. Figure out whether SelectItr should have had a
12908 // kill marker, and set it if it should. Returns the correct kill
12910 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12911 MachineBasicBlock* BB,
12912 const TargetRegisterInfo* TRI) {
12913 // Scan forward through BB for a use/def of EFLAGS.
12914 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12915 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12916 const MachineInstr& mi = *miI;
12917 if (mi.readsRegister(X86::EFLAGS))
12919 if (mi.definesRegister(X86::EFLAGS))
12920 break; // Should have kill-flag - update below.
12923 // If we hit the end of the block, check whether EFLAGS is live into a
12925 if (miI == BB->end()) {
12926 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12927 sEnd = BB->succ_end();
12928 sItr != sEnd; ++sItr) {
12929 MachineBasicBlock* succ = *sItr;
12930 if (succ->isLiveIn(X86::EFLAGS))
12935 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12936 // out. SelectMI should have a kill flag on EFLAGS.
12937 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12941 MachineBasicBlock *
12942 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12943 MachineBasicBlock *BB) const {
12944 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12945 DebugLoc DL = MI->getDebugLoc();
12947 // To "insert" a SELECT_CC instruction, we actually have to insert the
12948 // diamond control-flow pattern. The incoming instruction knows the
12949 // destination vreg to set, the condition code register to branch on, the
12950 // true/false values to select between, and a branch opcode to use.
12951 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12952 MachineFunction::iterator It = BB;
12958 // cmpTY ccX, r1, r2
12960 // fallthrough --> copy0MBB
12961 MachineBasicBlock *thisMBB = BB;
12962 MachineFunction *F = BB->getParent();
12963 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12964 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12965 F->insert(It, copy0MBB);
12966 F->insert(It, sinkMBB);
12968 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12969 // live into the sink and copy blocks.
12970 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12971 if (!MI->killsRegister(X86::EFLAGS) &&
12972 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12973 copy0MBB->addLiveIn(X86::EFLAGS);
12974 sinkMBB->addLiveIn(X86::EFLAGS);
12977 // Transfer the remainder of BB and its successor edges to sinkMBB.
12978 sinkMBB->splice(sinkMBB->begin(), BB,
12979 llvm::next(MachineBasicBlock::iterator(MI)),
12981 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12983 // Add the true and fallthrough blocks as its successors.
12984 BB->addSuccessor(copy0MBB);
12985 BB->addSuccessor(sinkMBB);
12987 // Create the conditional branch instruction.
12989 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12990 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12993 // %FalseValue = ...
12994 // # fallthrough to sinkMBB
12995 copy0MBB->addSuccessor(sinkMBB);
12998 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13000 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13001 TII->get(X86::PHI), MI->getOperand(0).getReg())
13002 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13003 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13005 MI->eraseFromParent(); // The pseudo instruction is gone now.
13009 MachineBasicBlock *
13010 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13011 bool Is64Bit) const {
13012 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13013 DebugLoc DL = MI->getDebugLoc();
13014 MachineFunction *MF = BB->getParent();
13015 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13017 assert(getTargetMachine().Options.EnableSegmentedStacks);
13019 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13020 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13023 // ... [Till the alloca]
13024 // If stacklet is not large enough, jump to mallocMBB
13027 // Allocate by subtracting from RSP
13028 // Jump to continueMBB
13031 // Allocate by call to runtime
13035 // [rest of original BB]
13038 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13039 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13040 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13042 MachineRegisterInfo &MRI = MF->getRegInfo();
13043 const TargetRegisterClass *AddrRegClass =
13044 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13046 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13047 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13048 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13049 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13050 sizeVReg = MI->getOperand(1).getReg(),
13051 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13053 MachineFunction::iterator MBBIter = BB;
13056 MF->insert(MBBIter, bumpMBB);
13057 MF->insert(MBBIter, mallocMBB);
13058 MF->insert(MBBIter, continueMBB);
13060 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13061 (MachineBasicBlock::iterator(MI)), BB->end());
13062 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13064 // Add code to the main basic block to check if the stack limit has been hit,
13065 // and if so, jump to mallocMBB otherwise to bumpMBB.
13066 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13067 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13068 .addReg(tmpSPVReg).addReg(sizeVReg);
13069 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13070 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13071 .addReg(SPLimitVReg);
13072 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13074 // bumpMBB simply decreases the stack pointer, since we know the current
13075 // stacklet has enough space.
13076 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13077 .addReg(SPLimitVReg);
13078 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13079 .addReg(SPLimitVReg);
13080 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13082 // Calls into a routine in libgcc to allocate more space from the heap.
13083 const uint32_t *RegMask =
13084 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13086 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13088 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13089 .addExternalSymbol("__morestack_allocate_stack_space")
13090 .addRegMask(RegMask)
13091 .addReg(X86::RDI, RegState::Implicit)
13092 .addReg(X86::RAX, RegState::ImplicitDefine);
13094 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13096 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13097 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13098 .addExternalSymbol("__morestack_allocate_stack_space")
13099 .addRegMask(RegMask)
13100 .addReg(X86::EAX, RegState::ImplicitDefine);
13104 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13107 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13108 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13109 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13111 // Set up the CFG correctly.
13112 BB->addSuccessor(bumpMBB);
13113 BB->addSuccessor(mallocMBB);
13114 mallocMBB->addSuccessor(continueMBB);
13115 bumpMBB->addSuccessor(continueMBB);
13117 // Take care of the PHI nodes.
13118 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13119 MI->getOperand(0).getReg())
13120 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13121 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13123 // Delete the original pseudo instruction.
13124 MI->eraseFromParent();
13127 return continueMBB;
13130 MachineBasicBlock *
13131 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13132 MachineBasicBlock *BB) const {
13133 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13134 DebugLoc DL = MI->getDebugLoc();
13136 assert(!Subtarget->isTargetEnvMacho());
13138 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13139 // non-trivial part is impdef of ESP.
13141 if (Subtarget->isTargetWin64()) {
13142 if (Subtarget->isTargetCygMing()) {
13143 // ___chkstk(Mingw64):
13144 // Clobbers R10, R11, RAX and EFLAGS.
13146 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13147 .addExternalSymbol("___chkstk")
13148 .addReg(X86::RAX, RegState::Implicit)
13149 .addReg(X86::RSP, RegState::Implicit)
13150 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13151 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13152 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13154 // __chkstk(MSVCRT): does not update stack pointer.
13155 // Clobbers R10, R11 and EFLAGS.
13156 // FIXME: RAX(allocated size) might be reused and not killed.
13157 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13158 .addExternalSymbol("__chkstk")
13159 .addReg(X86::RAX, RegState::Implicit)
13160 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13161 // RAX has the offset to subtracted from RSP.
13162 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13167 const char *StackProbeSymbol =
13168 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13170 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13171 .addExternalSymbol(StackProbeSymbol)
13172 .addReg(X86::EAX, RegState::Implicit)
13173 .addReg(X86::ESP, RegState::Implicit)
13174 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13175 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13176 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13179 MI->eraseFromParent(); // The pseudo instruction is gone now.
13183 MachineBasicBlock *
13184 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13185 MachineBasicBlock *BB) const {
13186 // This is pretty easy. We're taking the value that we received from
13187 // our load from the relocation, sticking it in either RDI (x86-64)
13188 // or EAX and doing an indirect call. The return value will then
13189 // be in the normal return register.
13190 const X86InstrInfo *TII
13191 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13192 DebugLoc DL = MI->getDebugLoc();
13193 MachineFunction *F = BB->getParent();
13195 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13196 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13198 // Get a register mask for the lowered call.
13199 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13200 // proper register mask.
13201 const uint32_t *RegMask =
13202 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13203 if (Subtarget->is64Bit()) {
13204 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13205 TII->get(X86::MOV64rm), X86::RDI)
13207 .addImm(0).addReg(0)
13208 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13209 MI->getOperand(3).getTargetFlags())
13211 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13212 addDirectMem(MIB, X86::RDI);
13213 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13214 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13215 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13216 TII->get(X86::MOV32rm), X86::EAX)
13218 .addImm(0).addReg(0)
13219 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13220 MI->getOperand(3).getTargetFlags())
13222 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13223 addDirectMem(MIB, X86::EAX);
13224 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13226 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13227 TII->get(X86::MOV32rm), X86::EAX)
13228 .addReg(TII->getGlobalBaseReg(F))
13229 .addImm(0).addReg(0)
13230 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13231 MI->getOperand(3).getTargetFlags())
13233 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13234 addDirectMem(MIB, X86::EAX);
13235 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13238 MI->eraseFromParent(); // The pseudo instruction is gone now.
13242 MachineBasicBlock *
13243 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13244 MachineBasicBlock *MBB) const {
13245 DebugLoc DL = MI->getDebugLoc();
13246 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13248 MachineFunction *MF = MBB->getParent();
13249 MachineRegisterInfo &MRI = MF->getRegInfo();
13251 const BasicBlock *BB = MBB->getBasicBlock();
13252 MachineFunction::iterator I = MBB;
13255 // Memory Reference
13256 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13257 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13260 unsigned MemOpndSlot = 0;
13262 unsigned CurOp = 0;
13264 DstReg = MI->getOperand(CurOp++).getReg();
13265 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13266 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13267 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13268 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13270 MemOpndSlot = CurOp;
13272 MVT PVT = getPointerTy();
13273 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13274 "Invalid Pointer Size!");
13276 // For v = setjmp(buf), we generate
13279 // buf[Label_Offset] = ljMBB
13280 // SjLjSetup restoreMBB
13286 // v = phi(main, restore)
13291 MachineBasicBlock *thisMBB = MBB;
13292 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13293 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13294 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13295 MF->insert(I, mainMBB);
13296 MF->insert(I, sinkMBB);
13297 MF->push_back(restoreMBB);
13299 MachineInstrBuilder MIB;
13301 // Transfer the remainder of BB and its successor edges to sinkMBB.
13302 sinkMBB->splice(sinkMBB->begin(), MBB,
13303 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13304 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13307 unsigned PtrImmStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13308 const int64_t Label_Offset = 1 * PVT.getStoreSize();
13311 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrImmStoreOpc));
13312 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13313 if (i == X86::AddrDisp)
13314 MIB.addDisp(MI->getOperand(MemOpndSlot + i), Label_Offset);
13316 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13318 MIB.addMBB(restoreMBB);
13319 MIB.setMemRefs(MMOBegin, MMOEnd);
13321 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13322 .addMBB(restoreMBB);
13323 MIB.addRegMask(RegInfo->getNoPreservedMask());
13324 thisMBB->addSuccessor(mainMBB);
13325 thisMBB->addSuccessor(restoreMBB);
13329 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13330 mainMBB->addSuccessor(sinkMBB);
13333 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13334 TII->get(X86::PHI), DstReg)
13335 .addReg(mainDstReg).addMBB(mainMBB)
13336 .addReg(restoreDstReg).addMBB(restoreMBB);
13339 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13340 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13341 restoreMBB->addSuccessor(sinkMBB);
13343 MI->eraseFromParent();
13347 MachineBasicBlock *
13348 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13349 MachineBasicBlock *MBB) const {
13350 DebugLoc DL = MI->getDebugLoc();
13351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13353 MachineFunction *MF = MBB->getParent();
13354 MachineRegisterInfo &MRI = MF->getRegInfo();
13356 // Memory Reference
13357 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13358 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13360 MVT PVT = getPointerTy();
13361 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13362 "Invalid Pointer Size!");
13364 const TargetRegisterClass *RC =
13365 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13366 unsigned Tmp = MRI.createVirtualRegister(RC);
13367 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13368 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13369 unsigned SP = RegInfo->getStackRegister();
13371 MachineInstrBuilder MIB;
13373 const int64_t Label_Offset = 1 * PVT.getStoreSize();
13374 const int64_t SP_Offset = 2 * PVT.getStoreSize();
13376 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13377 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13380 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13381 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13382 MIB.addOperand(MI->getOperand(i));
13383 MIB.setMemRefs(MMOBegin, MMOEnd);
13385 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13386 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13387 if (i == X86::AddrDisp)
13388 MIB.addDisp(MI->getOperand(i), Label_Offset);
13390 MIB.addOperand(MI->getOperand(i));
13392 MIB.setMemRefs(MMOBegin, MMOEnd);
13394 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13395 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13396 if (i == X86::AddrDisp)
13397 MIB.addDisp(MI->getOperand(i), SP_Offset);
13399 MIB.addOperand(MI->getOperand(i));
13401 MIB.setMemRefs(MMOBegin, MMOEnd);
13403 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13405 MI->eraseFromParent();
13409 MachineBasicBlock *
13410 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13411 MachineBasicBlock *BB) const {
13412 switch (MI->getOpcode()) {
13413 default: llvm_unreachable("Unexpected instr type to insert");
13414 case X86::TAILJMPd64:
13415 case X86::TAILJMPr64:
13416 case X86::TAILJMPm64:
13417 llvm_unreachable("TAILJMP64 would not be touched here.");
13418 case X86::TCRETURNdi64:
13419 case X86::TCRETURNri64:
13420 case X86::TCRETURNmi64:
13422 case X86::WIN_ALLOCA:
13423 return EmitLoweredWinAlloca(MI, BB);
13424 case X86::SEG_ALLOCA_32:
13425 return EmitLoweredSegAlloca(MI, BB, false);
13426 case X86::SEG_ALLOCA_64:
13427 return EmitLoweredSegAlloca(MI, BB, true);
13428 case X86::TLSCall_32:
13429 case X86::TLSCall_64:
13430 return EmitLoweredTLSCall(MI, BB);
13431 case X86::CMOV_GR8:
13432 case X86::CMOV_FR32:
13433 case X86::CMOV_FR64:
13434 case X86::CMOV_V4F32:
13435 case X86::CMOV_V2F64:
13436 case X86::CMOV_V2I64:
13437 case X86::CMOV_V8F32:
13438 case X86::CMOV_V4F64:
13439 case X86::CMOV_V4I64:
13440 case X86::CMOV_GR16:
13441 case X86::CMOV_GR32:
13442 case X86::CMOV_RFP32:
13443 case X86::CMOV_RFP64:
13444 case X86::CMOV_RFP80:
13445 return EmitLoweredSelect(MI, BB);
13447 case X86::FP32_TO_INT16_IN_MEM:
13448 case X86::FP32_TO_INT32_IN_MEM:
13449 case X86::FP32_TO_INT64_IN_MEM:
13450 case X86::FP64_TO_INT16_IN_MEM:
13451 case X86::FP64_TO_INT32_IN_MEM:
13452 case X86::FP64_TO_INT64_IN_MEM:
13453 case X86::FP80_TO_INT16_IN_MEM:
13454 case X86::FP80_TO_INT32_IN_MEM:
13455 case X86::FP80_TO_INT64_IN_MEM: {
13456 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13457 DebugLoc DL = MI->getDebugLoc();
13459 // Change the floating point control register to use "round towards zero"
13460 // mode when truncating to an integer value.
13461 MachineFunction *F = BB->getParent();
13462 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13463 addFrameReference(BuildMI(*BB, MI, DL,
13464 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13466 // Load the old value of the high byte of the control word...
13468 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13469 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13472 // Set the high part to be round to zero...
13473 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13476 // Reload the modified control word now...
13477 addFrameReference(BuildMI(*BB, MI, DL,
13478 TII->get(X86::FLDCW16m)), CWFrameIdx);
13480 // Restore the memory image of control word to original value
13481 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13484 // Get the X86 opcode to use.
13486 switch (MI->getOpcode()) {
13487 default: llvm_unreachable("illegal opcode!");
13488 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13489 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13490 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13491 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13492 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13493 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13494 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13495 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13496 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13500 MachineOperand &Op = MI->getOperand(0);
13502 AM.BaseType = X86AddressMode::RegBase;
13503 AM.Base.Reg = Op.getReg();
13505 AM.BaseType = X86AddressMode::FrameIndexBase;
13506 AM.Base.FrameIndex = Op.getIndex();
13508 Op = MI->getOperand(1);
13510 AM.Scale = Op.getImm();
13511 Op = MI->getOperand(2);
13513 AM.IndexReg = Op.getImm();
13514 Op = MI->getOperand(3);
13515 if (Op.isGlobal()) {
13516 AM.GV = Op.getGlobal();
13518 AM.Disp = Op.getImm();
13520 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13521 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13523 // Reload the original control word now.
13524 addFrameReference(BuildMI(*BB, MI, DL,
13525 TII->get(X86::FLDCW16m)), CWFrameIdx);
13527 MI->eraseFromParent(); // The pseudo instruction is gone now.
13530 // String/text processing lowering.
13531 case X86::PCMPISTRM128REG:
13532 case X86::VPCMPISTRM128REG:
13533 case X86::PCMPISTRM128MEM:
13534 case X86::VPCMPISTRM128MEM:
13535 case X86::PCMPESTRM128REG:
13536 case X86::VPCMPESTRM128REG:
13537 case X86::PCMPESTRM128MEM:
13538 case X86::VPCMPESTRM128MEM: {
13541 switch (MI->getOpcode()) {
13542 default: llvm_unreachable("illegal opcode!");
13543 case X86::PCMPISTRM128REG:
13544 case X86::VPCMPISTRM128REG:
13545 NumArgs = 3; MemArg = false; break;
13546 case X86::PCMPISTRM128MEM:
13547 case X86::VPCMPISTRM128MEM:
13548 NumArgs = 3; MemArg = true; break;
13549 case X86::PCMPESTRM128REG:
13550 case X86::VPCMPESTRM128REG:
13551 NumArgs = 5; MemArg = false; break;
13552 case X86::PCMPESTRM128MEM:
13553 case X86::VPCMPESTRM128MEM:
13554 NumArgs = 5; MemArg = true; break;
13556 return EmitPCMP(MI, BB, NumArgs, MemArg);
13559 // Thread synchronization.
13561 return EmitMonitor(MI, BB);
13563 // Atomic Lowering.
13564 case X86::ATOMAND8:
13565 case X86::ATOMAND16:
13566 case X86::ATOMAND32:
13567 case X86::ATOMAND64:
13570 case X86::ATOMOR16:
13571 case X86::ATOMOR32:
13572 case X86::ATOMOR64:
13574 case X86::ATOMXOR16:
13575 case X86::ATOMXOR8:
13576 case X86::ATOMXOR32:
13577 case X86::ATOMXOR64:
13579 case X86::ATOMNAND8:
13580 case X86::ATOMNAND16:
13581 case X86::ATOMNAND32:
13582 case X86::ATOMNAND64:
13584 case X86::ATOMMAX8:
13585 case X86::ATOMMAX16:
13586 case X86::ATOMMAX32:
13587 case X86::ATOMMAX64:
13589 case X86::ATOMMIN8:
13590 case X86::ATOMMIN16:
13591 case X86::ATOMMIN32:
13592 case X86::ATOMMIN64:
13594 case X86::ATOMUMAX8:
13595 case X86::ATOMUMAX16:
13596 case X86::ATOMUMAX32:
13597 case X86::ATOMUMAX64:
13599 case X86::ATOMUMIN8:
13600 case X86::ATOMUMIN16:
13601 case X86::ATOMUMIN32:
13602 case X86::ATOMUMIN64:
13603 return EmitAtomicLoadArith(MI, BB);
13605 // This group does 64-bit operations on a 32-bit host.
13606 case X86::ATOMAND6432:
13607 case X86::ATOMOR6432:
13608 case X86::ATOMXOR6432:
13609 case X86::ATOMNAND6432:
13610 case X86::ATOMADD6432:
13611 case X86::ATOMSUB6432:
13612 case X86::ATOMMAX6432:
13613 case X86::ATOMMIN6432:
13614 case X86::ATOMUMAX6432:
13615 case X86::ATOMUMIN6432:
13616 case X86::ATOMSWAP6432:
13617 return EmitAtomicLoadArith6432(MI, BB);
13619 case X86::VASTART_SAVE_XMM_REGS:
13620 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13622 case X86::VAARG_64:
13623 return EmitVAARG64WithCustomInserter(MI, BB);
13625 case X86::EH_SjLj_SetJmp32:
13626 case X86::EH_SjLj_SetJmp64:
13627 return emitEHSjLjSetJmp(MI, BB);
13629 case X86::EH_SjLj_LongJmp32:
13630 case X86::EH_SjLj_LongJmp64:
13631 return emitEHSjLjLongJmp(MI, BB);
13635 //===----------------------------------------------------------------------===//
13636 // X86 Optimization Hooks
13637 //===----------------------------------------------------------------------===//
13639 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13642 const SelectionDAG &DAG,
13643 unsigned Depth) const {
13644 unsigned BitWidth = KnownZero.getBitWidth();
13645 unsigned Opc = Op.getOpcode();
13646 assert((Opc >= ISD::BUILTIN_OP_END ||
13647 Opc == ISD::INTRINSIC_WO_CHAIN ||
13648 Opc == ISD::INTRINSIC_W_CHAIN ||
13649 Opc == ISD::INTRINSIC_VOID) &&
13650 "Should use MaskedValueIsZero if you don't know whether Op"
13651 " is a target node!");
13653 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13667 // These nodes' second result is a boolean.
13668 if (Op.getResNo() == 0)
13671 case X86ISD::SETCC:
13672 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13674 case ISD::INTRINSIC_WO_CHAIN: {
13675 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13676 unsigned NumLoBits = 0;
13679 case Intrinsic::x86_sse_movmsk_ps:
13680 case Intrinsic::x86_avx_movmsk_ps_256:
13681 case Intrinsic::x86_sse2_movmsk_pd:
13682 case Intrinsic::x86_avx_movmsk_pd_256:
13683 case Intrinsic::x86_mmx_pmovmskb:
13684 case Intrinsic::x86_sse2_pmovmskb_128:
13685 case Intrinsic::x86_avx2_pmovmskb: {
13686 // High bits of movmskp{s|d}, pmovmskb are known zero.
13688 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13689 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13690 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13691 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13692 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13693 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13694 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13695 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13697 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
13706 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
13707 unsigned Depth) const {
13708 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
13709 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
13710 return Op.getValueType().getScalarType().getSizeInBits();
13716 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
13717 /// node is a GlobalAddress + offset.
13718 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
13719 const GlobalValue* &GA,
13720 int64_t &Offset) const {
13721 if (N->getOpcode() == X86ISD::Wrapper) {
13722 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
13723 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
13724 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
13728 return TargetLowering::isGAPlusOffset(N, GA, Offset);
13731 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13732 /// same as extracting the high 128-bit part of 256-bit vector and then
13733 /// inserting the result into the low part of a new 256-bit vector
13734 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13735 EVT VT = SVOp->getValueType(0);
13736 unsigned NumElems = VT.getVectorNumElements();
13738 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13739 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13740 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13741 SVOp->getMaskElt(j) >= 0)
13747 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13748 /// same as extracting the low 128-bit part of 256-bit vector and then
13749 /// inserting the result into the high part of a new 256-bit vector
13750 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13751 EVT VT = SVOp->getValueType(0);
13752 unsigned NumElems = VT.getVectorNumElements();
13754 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13755 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13756 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13757 SVOp->getMaskElt(j) >= 0)
13763 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13764 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13765 TargetLowering::DAGCombinerInfo &DCI,
13766 const X86Subtarget* Subtarget) {
13767 DebugLoc dl = N->getDebugLoc();
13768 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13769 SDValue V1 = SVOp->getOperand(0);
13770 SDValue V2 = SVOp->getOperand(1);
13771 EVT VT = SVOp->getValueType(0);
13772 unsigned NumElems = VT.getVectorNumElements();
13774 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13775 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13779 // V UNDEF BUILD_VECTOR UNDEF
13781 // CONCAT_VECTOR CONCAT_VECTOR
13784 // RESULT: V + zero extended
13786 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13787 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13788 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13791 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13794 // To match the shuffle mask, the first half of the mask should
13795 // be exactly the first vector, and all the rest a splat with the
13796 // first element of the second one.
13797 for (unsigned i = 0; i != NumElems/2; ++i)
13798 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13799 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13802 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13803 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13804 if (Ld->hasNUsesOfValue(1, 0)) {
13805 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13806 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13808 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13810 Ld->getPointerInfo(),
13811 Ld->getAlignment(),
13812 false/*isVolatile*/, true/*ReadMem*/,
13813 false/*WriteMem*/);
13814 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13818 // Emit a zeroed vector and insert the desired subvector on its
13820 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13821 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13822 return DCI.CombineTo(N, InsV);
13825 //===--------------------------------------------------------------------===//
13826 // Combine some shuffles into subvector extracts and inserts:
13829 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13830 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13831 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13832 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13833 return DCI.CombineTo(N, InsV);
13836 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13837 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13838 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13839 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13840 return DCI.CombineTo(N, InsV);
13846 /// PerformShuffleCombine - Performs several different shuffle combines.
13847 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13848 TargetLowering::DAGCombinerInfo &DCI,
13849 const X86Subtarget *Subtarget) {
13850 DebugLoc dl = N->getDebugLoc();
13851 EVT VT = N->getValueType(0);
13853 // Don't create instructions with illegal types after legalize types has run.
13854 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13855 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13858 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13859 if (Subtarget->hasAVX() && VT.is256BitVector() &&
13860 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13861 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13863 // Only handle 128 wide vector from here on.
13864 if (!VT.is128BitVector())
13867 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13868 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13869 // consecutive, non-overlapping, and in the right order.
13870 SmallVector<SDValue, 16> Elts;
13871 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13872 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13874 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13878 /// PerformTruncateCombine - Converts truncate operation to
13879 /// a sequence of vector shuffle operations.
13880 /// It is possible when we truncate 256-bit vector to 128-bit vector
13881 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13882 TargetLowering::DAGCombinerInfo &DCI,
13883 const X86Subtarget *Subtarget) {
13884 if (!DCI.isBeforeLegalizeOps())
13887 if (!Subtarget->hasAVX())
13890 EVT VT = N->getValueType(0);
13891 SDValue Op = N->getOperand(0);
13892 EVT OpVT = Op.getValueType();
13893 DebugLoc dl = N->getDebugLoc();
13895 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13897 if (Subtarget->hasAVX2()) {
13898 // AVX2: v4i64 -> v4i32
13901 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13903 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13904 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13907 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13908 DAG.getIntPtrConstant(0));
13911 // AVX: v4i64 -> v4i32
13912 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13913 DAG.getIntPtrConstant(0));
13915 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13916 DAG.getIntPtrConstant(2));
13918 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13919 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13922 static const int ShufMask1[] = {0, 2, 0, 0};
13924 SDValue Undef = DAG.getUNDEF(VT);
13925 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
13926 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
13929 static const int ShufMask2[] = {0, 1, 4, 5};
13931 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13934 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13936 if (Subtarget->hasAVX2()) {
13937 // AVX2: v8i32 -> v8i16
13939 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13942 SmallVector<SDValue,32> pshufbMask;
13943 for (unsigned i = 0; i < 2; ++i) {
13944 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13945 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13946 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13947 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13948 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13949 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13950 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13951 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13952 for (unsigned j = 0; j < 8; ++j)
13953 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13955 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13956 &pshufbMask[0], 32);
13957 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13959 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13961 static const int ShufMask[] = {0, 2, -1, -1};
13962 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13965 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13966 DAG.getIntPtrConstant(0));
13968 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13971 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13972 DAG.getIntPtrConstant(0));
13974 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13975 DAG.getIntPtrConstant(4));
13977 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13978 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13981 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13982 -1, -1, -1, -1, -1, -1, -1, -1};
13984 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13985 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
13986 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
13988 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13989 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13992 static const int ShufMask2[] = {0, 1, 4, 5};
13994 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13995 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14001 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14002 /// specific shuffle of a load can be folded into a single element load.
14003 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14004 /// shuffles have been customed lowered so we need to handle those here.
14005 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14006 TargetLowering::DAGCombinerInfo &DCI) {
14007 if (DCI.isBeforeLegalizeOps())
14010 SDValue InVec = N->getOperand(0);
14011 SDValue EltNo = N->getOperand(1);
14013 if (!isa<ConstantSDNode>(EltNo))
14016 EVT VT = InVec.getValueType();
14018 bool HasShuffleIntoBitcast = false;
14019 if (InVec.getOpcode() == ISD::BITCAST) {
14020 // Don't duplicate a load with other uses.
14021 if (!InVec.hasOneUse())
14023 EVT BCVT = InVec.getOperand(0).getValueType();
14024 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14026 InVec = InVec.getOperand(0);
14027 HasShuffleIntoBitcast = true;
14030 if (!isTargetShuffle(InVec.getOpcode()))
14033 // Don't duplicate a load with other uses.
14034 if (!InVec.hasOneUse())
14037 SmallVector<int, 16> ShuffleMask;
14039 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14043 // Select the input vector, guarding against out of range extract vector.
14044 unsigned NumElems = VT.getVectorNumElements();
14045 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14046 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14047 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14048 : InVec.getOperand(1);
14050 // If inputs to shuffle are the same for both ops, then allow 2 uses
14051 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14053 if (LdNode.getOpcode() == ISD::BITCAST) {
14054 // Don't duplicate a load with other uses.
14055 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14058 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14059 LdNode = LdNode.getOperand(0);
14062 if (!ISD::isNormalLoad(LdNode.getNode()))
14065 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14067 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14070 if (HasShuffleIntoBitcast) {
14071 // If there's a bitcast before the shuffle, check if the load type and
14072 // alignment is valid.
14073 unsigned Align = LN0->getAlignment();
14074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14075 unsigned NewAlign = TLI.getDataLayout()->
14076 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14078 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14082 // All checks match so transform back to vector_shuffle so that DAG combiner
14083 // can finish the job
14084 DebugLoc dl = N->getDebugLoc();
14086 // Create shuffle node taking into account the case that its a unary shuffle
14087 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14088 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14089 InVec.getOperand(0), Shuffle,
14091 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14092 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14096 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14097 /// generation and convert it from being a bunch of shuffles and extracts
14098 /// to a simple store and scalar loads to extract the elements.
14099 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14100 TargetLowering::DAGCombinerInfo &DCI) {
14101 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14102 if (NewOp.getNode())
14105 SDValue InputVector = N->getOperand(0);
14107 // Only operate on vectors of 4 elements, where the alternative shuffling
14108 // gets to be more expensive.
14109 if (InputVector.getValueType() != MVT::v4i32)
14112 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14113 // single use which is a sign-extend or zero-extend, and all elements are
14115 SmallVector<SDNode *, 4> Uses;
14116 unsigned ExtractedElements = 0;
14117 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14118 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14119 if (UI.getUse().getResNo() != InputVector.getResNo())
14122 SDNode *Extract = *UI;
14123 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14126 if (Extract->getValueType(0) != MVT::i32)
14128 if (!Extract->hasOneUse())
14130 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14131 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14133 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14136 // Record which element was extracted.
14137 ExtractedElements |=
14138 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14140 Uses.push_back(Extract);
14143 // If not all the elements were used, this may not be worthwhile.
14144 if (ExtractedElements != 15)
14147 // Ok, we've now decided to do the transformation.
14148 DebugLoc dl = InputVector.getDebugLoc();
14150 // Store the value to a temporary stack slot.
14151 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14152 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14153 MachinePointerInfo(), false, false, 0);
14155 // Replace each use (extract) with a load of the appropriate element.
14156 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14157 UE = Uses.end(); UI != UE; ++UI) {
14158 SDNode *Extract = *UI;
14160 // cOMpute the element's address.
14161 SDValue Idx = Extract->getOperand(1);
14163 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14164 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14165 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14166 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14168 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14169 StackPtr, OffsetVal);
14171 // Load the scalar.
14172 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14173 ScalarAddr, MachinePointerInfo(),
14174 false, false, false, 0);
14176 // Replace the exact with the load.
14177 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14180 // The replacement was made in place; don't return anything.
14184 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14186 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14187 TargetLowering::DAGCombinerInfo &DCI,
14188 const X86Subtarget *Subtarget) {
14189 DebugLoc DL = N->getDebugLoc();
14190 SDValue Cond = N->getOperand(0);
14191 // Get the LHS/RHS of the select.
14192 SDValue LHS = N->getOperand(1);
14193 SDValue RHS = N->getOperand(2);
14194 EVT VT = LHS.getValueType();
14196 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14197 // instructions match the semantics of the common C idiom x<y?x:y but not
14198 // x<=y?x:y, because of how they handle negative zero (which can be
14199 // ignored in unsafe-math mode).
14200 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14201 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14202 (Subtarget->hasSSE2() ||
14203 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14204 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14206 unsigned Opcode = 0;
14207 // Check for x CC y ? x : y.
14208 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14209 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14213 // Converting this to a min would handle NaNs incorrectly, and swapping
14214 // the operands would cause it to handle comparisons between positive
14215 // and negative zero incorrectly.
14216 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14217 if (!DAG.getTarget().Options.UnsafeFPMath &&
14218 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14220 std::swap(LHS, RHS);
14222 Opcode = X86ISD::FMIN;
14225 // Converting this to a min would handle comparisons between positive
14226 // and negative zero incorrectly.
14227 if (!DAG.getTarget().Options.UnsafeFPMath &&
14228 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14230 Opcode = X86ISD::FMIN;
14233 // Converting this to a min would handle both negative zeros and NaNs
14234 // incorrectly, but we can swap the operands to fix both.
14235 std::swap(LHS, RHS);
14239 Opcode = X86ISD::FMIN;
14243 // Converting this to a max would handle comparisons between positive
14244 // and negative zero incorrectly.
14245 if (!DAG.getTarget().Options.UnsafeFPMath &&
14246 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14248 Opcode = X86ISD::FMAX;
14251 // Converting this to a max would handle NaNs incorrectly, and swapping
14252 // the operands would cause it to handle comparisons between positive
14253 // and negative zero incorrectly.
14254 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14255 if (!DAG.getTarget().Options.UnsafeFPMath &&
14256 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14258 std::swap(LHS, RHS);
14260 Opcode = X86ISD::FMAX;
14263 // Converting this to a max would handle both negative zeros and NaNs
14264 // incorrectly, but we can swap the operands to fix both.
14265 std::swap(LHS, RHS);
14269 Opcode = X86ISD::FMAX;
14272 // Check for x CC y ? y : x -- a min/max with reversed arms.
14273 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14274 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14278 // Converting this to a min would handle comparisons between positive
14279 // and negative zero incorrectly, and swapping the operands would
14280 // cause it to handle NaNs incorrectly.
14281 if (!DAG.getTarget().Options.UnsafeFPMath &&
14282 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14283 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14285 std::swap(LHS, RHS);
14287 Opcode = X86ISD::FMIN;
14290 // Converting this to a min would handle NaNs incorrectly.
14291 if (!DAG.getTarget().Options.UnsafeFPMath &&
14292 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14294 Opcode = X86ISD::FMIN;
14297 // Converting this to a min would handle both negative zeros and NaNs
14298 // incorrectly, but we can swap the operands to fix both.
14299 std::swap(LHS, RHS);
14303 Opcode = X86ISD::FMIN;
14307 // Converting this to a max would handle NaNs incorrectly.
14308 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14310 Opcode = X86ISD::FMAX;
14313 // Converting this to a max would handle comparisons between positive
14314 // and negative zero incorrectly, and swapping the operands would
14315 // cause it to handle NaNs incorrectly.
14316 if (!DAG.getTarget().Options.UnsafeFPMath &&
14317 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14318 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14320 std::swap(LHS, RHS);
14322 Opcode = X86ISD::FMAX;
14325 // Converting this to a max would handle both negative zeros and NaNs
14326 // incorrectly, but we can swap the operands to fix both.
14327 std::swap(LHS, RHS);
14331 Opcode = X86ISD::FMAX;
14337 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14340 // If this is a select between two integer constants, try to do some
14342 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14343 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14344 // Don't do this for crazy integer types.
14345 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14346 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14347 // so that TrueC (the true value) is larger than FalseC.
14348 bool NeedsCondInvert = false;
14350 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14351 // Efficiently invertible.
14352 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14353 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14354 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14355 NeedsCondInvert = true;
14356 std::swap(TrueC, FalseC);
14359 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14360 if (FalseC->getAPIntValue() == 0 &&
14361 TrueC->getAPIntValue().isPowerOf2()) {
14362 if (NeedsCondInvert) // Invert the condition if needed.
14363 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14364 DAG.getConstant(1, Cond.getValueType()));
14366 // Zero extend the condition if needed.
14367 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14369 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14370 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14371 DAG.getConstant(ShAmt, MVT::i8));
14374 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14375 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14376 if (NeedsCondInvert) // Invert the condition if needed.
14377 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14378 DAG.getConstant(1, Cond.getValueType()));
14380 // Zero extend the condition if needed.
14381 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14382 FalseC->getValueType(0), Cond);
14383 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14384 SDValue(FalseC, 0));
14387 // Optimize cases that will turn into an LEA instruction. This requires
14388 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14389 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14390 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14391 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14393 bool isFastMultiplier = false;
14395 switch ((unsigned char)Diff) {
14397 case 1: // result = add base, cond
14398 case 2: // result = lea base( , cond*2)
14399 case 3: // result = lea base(cond, cond*2)
14400 case 4: // result = lea base( , cond*4)
14401 case 5: // result = lea base(cond, cond*4)
14402 case 8: // result = lea base( , cond*8)
14403 case 9: // result = lea base(cond, cond*8)
14404 isFastMultiplier = true;
14409 if (isFastMultiplier) {
14410 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14411 if (NeedsCondInvert) // Invert the condition if needed.
14412 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14413 DAG.getConstant(1, Cond.getValueType()));
14415 // Zero extend the condition if needed.
14416 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14418 // Scale the condition by the difference.
14420 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14421 DAG.getConstant(Diff, Cond.getValueType()));
14423 // Add the base if non-zero.
14424 if (FalseC->getAPIntValue() != 0)
14425 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14426 SDValue(FalseC, 0));
14433 // Canonicalize max and min:
14434 // (x > y) ? x : y -> (x >= y) ? x : y
14435 // (x < y) ? x : y -> (x <= y) ? x : y
14436 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14437 // the need for an extra compare
14438 // against zero. e.g.
14439 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14441 // testl %edi, %edi
14443 // cmovgl %edi, %eax
14447 // cmovsl %eax, %edi
14448 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14449 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14450 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14451 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14456 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14457 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14458 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14459 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14464 // If we know that this node is legal then we know that it is going to be
14465 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14466 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14467 // to simplify previous instructions.
14468 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14469 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14470 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14471 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14473 // Don't optimize vector selects that map to mask-registers.
14477 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14478 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14480 APInt KnownZero, KnownOne;
14481 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14482 DCI.isBeforeLegalizeOps());
14483 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14484 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14485 DCI.CommitTargetLoweringOpt(TLO);
14491 // Check whether a boolean test is testing a boolean value generated by
14492 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14495 // Simplify the following patterns:
14496 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14497 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14498 // to (Op EFLAGS Cond)
14500 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14501 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14502 // to (Op EFLAGS !Cond)
14504 // where Op could be BRCOND or CMOV.
14506 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14507 // Quit if not CMP and SUB with its value result used.
14508 if (Cmp.getOpcode() != X86ISD::CMP &&
14509 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14512 // Quit if not used as a boolean value.
14513 if (CC != X86::COND_E && CC != X86::COND_NE)
14516 // Check CMP operands. One of them should be 0 or 1 and the other should be
14517 // an SetCC or extended from it.
14518 SDValue Op1 = Cmp.getOperand(0);
14519 SDValue Op2 = Cmp.getOperand(1);
14522 const ConstantSDNode* C = 0;
14523 bool needOppositeCond = (CC == X86::COND_E);
14525 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14527 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14529 else // Quit if all operands are not constants.
14532 if (C->getZExtValue() == 1)
14533 needOppositeCond = !needOppositeCond;
14534 else if (C->getZExtValue() != 0)
14535 // Quit if the constant is neither 0 or 1.
14538 // Skip 'zext' node.
14539 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14540 SetCC = SetCC.getOperand(0);
14542 switch (SetCC.getOpcode()) {
14543 case X86ISD::SETCC:
14544 // Set the condition code or opposite one if necessary.
14545 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14546 if (needOppositeCond)
14547 CC = X86::GetOppositeBranchCondition(CC);
14548 return SetCC.getOperand(1);
14549 case X86ISD::CMOV: {
14550 // Check whether false/true value has canonical one, i.e. 0 or 1.
14551 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14552 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14553 // Quit if true value is not a constant.
14556 // Quit if false value is not a constant.
14558 // A special case for rdrand, where 0 is set if false cond is found.
14559 SDValue Op = SetCC.getOperand(0);
14560 if (Op.getOpcode() != X86ISD::RDRAND)
14563 // Quit if false value is not the constant 0 or 1.
14564 bool FValIsFalse = true;
14565 if (FVal && FVal->getZExtValue() != 0) {
14566 if (FVal->getZExtValue() != 1)
14568 // If FVal is 1, opposite cond is needed.
14569 needOppositeCond = !needOppositeCond;
14570 FValIsFalse = false;
14572 // Quit if TVal is not the constant opposite of FVal.
14573 if (FValIsFalse && TVal->getZExtValue() != 1)
14575 if (!FValIsFalse && TVal->getZExtValue() != 0)
14577 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14578 if (needOppositeCond)
14579 CC = X86::GetOppositeBranchCondition(CC);
14580 return SetCC.getOperand(3);
14587 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14588 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14589 TargetLowering::DAGCombinerInfo &DCI,
14590 const X86Subtarget *Subtarget) {
14591 DebugLoc DL = N->getDebugLoc();
14593 // If the flag operand isn't dead, don't touch this CMOV.
14594 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14597 SDValue FalseOp = N->getOperand(0);
14598 SDValue TrueOp = N->getOperand(1);
14599 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14600 SDValue Cond = N->getOperand(3);
14602 if (CC == X86::COND_E || CC == X86::COND_NE) {
14603 switch (Cond.getOpcode()) {
14607 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14608 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14609 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14615 Flags = checkBoolTestSetCCCombine(Cond, CC);
14616 if (Flags.getNode() &&
14617 // Extra check as FCMOV only supports a subset of X86 cond.
14618 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14619 SDValue Ops[] = { FalseOp, TrueOp,
14620 DAG.getConstant(CC, MVT::i8), Flags };
14621 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14622 Ops, array_lengthof(Ops));
14625 // If this is a select between two integer constants, try to do some
14626 // optimizations. Note that the operands are ordered the opposite of SELECT
14628 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14629 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14630 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14631 // larger than FalseC (the false value).
14632 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14633 CC = X86::GetOppositeBranchCondition(CC);
14634 std::swap(TrueC, FalseC);
14635 std::swap(TrueOp, FalseOp);
14638 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14639 // This is efficient for any integer data type (including i8/i16) and
14641 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14642 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14643 DAG.getConstant(CC, MVT::i8), Cond);
14645 // Zero extend the condition if needed.
14646 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14648 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14649 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14650 DAG.getConstant(ShAmt, MVT::i8));
14651 if (N->getNumValues() == 2) // Dead flag value?
14652 return DCI.CombineTo(N, Cond, SDValue());
14656 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14657 // for any integer data type, including i8/i16.
14658 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14659 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14660 DAG.getConstant(CC, MVT::i8), Cond);
14662 // Zero extend the condition if needed.
14663 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14664 FalseC->getValueType(0), Cond);
14665 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14666 SDValue(FalseC, 0));
14668 if (N->getNumValues() == 2) // Dead flag value?
14669 return DCI.CombineTo(N, Cond, SDValue());
14673 // Optimize cases that will turn into an LEA instruction. This requires
14674 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14675 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14676 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14677 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14679 bool isFastMultiplier = false;
14681 switch ((unsigned char)Diff) {
14683 case 1: // result = add base, cond
14684 case 2: // result = lea base( , cond*2)
14685 case 3: // result = lea base(cond, cond*2)
14686 case 4: // result = lea base( , cond*4)
14687 case 5: // result = lea base(cond, cond*4)
14688 case 8: // result = lea base( , cond*8)
14689 case 9: // result = lea base(cond, cond*8)
14690 isFastMultiplier = true;
14695 if (isFastMultiplier) {
14696 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14697 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14698 DAG.getConstant(CC, MVT::i8), Cond);
14699 // Zero extend the condition if needed.
14700 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14702 // Scale the condition by the difference.
14704 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14705 DAG.getConstant(Diff, Cond.getValueType()));
14707 // Add the base if non-zero.
14708 if (FalseC->getAPIntValue() != 0)
14709 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14710 SDValue(FalseC, 0));
14711 if (N->getNumValues() == 2) // Dead flag value?
14712 return DCI.CombineTo(N, Cond, SDValue());
14719 // Handle these cases:
14720 // (select (x != c), e, c) -> select (x != c), e, x),
14721 // (select (x == c), c, e) -> select (x == c), x, e)
14722 // where the c is an integer constant, and the "select" is the combination
14723 // of CMOV and CMP.
14725 // The rationale for this change is that the conditional-move from a constant
14726 // needs two instructions, however, conditional-move from a register needs
14727 // only one instruction.
14729 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
14730 // some instruction-combining opportunities. This opt needs to be
14731 // postponed as late as possible.
14733 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
14734 // the DCI.xxxx conditions are provided to postpone the optimization as
14735 // late as possible.
14737 ConstantSDNode *CmpAgainst = 0;
14738 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
14739 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
14740 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
14742 if (CC == X86::COND_NE &&
14743 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
14744 CC = X86::GetOppositeBranchCondition(CC);
14745 std::swap(TrueOp, FalseOp);
14748 if (CC == X86::COND_E &&
14749 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
14750 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
14751 DAG.getConstant(CC, MVT::i8), Cond };
14752 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
14753 array_lengthof(Ops));
14762 /// PerformMulCombine - Optimize a single multiply with constant into two
14763 /// in order to implement it with two cheaper instructions, e.g.
14764 /// LEA + SHL, LEA + LEA.
14765 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
14766 TargetLowering::DAGCombinerInfo &DCI) {
14767 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14770 EVT VT = N->getValueType(0);
14771 if (VT != MVT::i64)
14774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
14777 uint64_t MulAmt = C->getZExtValue();
14778 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
14781 uint64_t MulAmt1 = 0;
14782 uint64_t MulAmt2 = 0;
14783 if ((MulAmt % 9) == 0) {
14785 MulAmt2 = MulAmt / 9;
14786 } else if ((MulAmt % 5) == 0) {
14788 MulAmt2 = MulAmt / 5;
14789 } else if ((MulAmt % 3) == 0) {
14791 MulAmt2 = MulAmt / 3;
14794 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
14795 DebugLoc DL = N->getDebugLoc();
14797 if (isPowerOf2_64(MulAmt2) &&
14798 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
14799 // If second multiplifer is pow2, issue it first. We want the multiply by
14800 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
14802 std::swap(MulAmt1, MulAmt2);
14805 if (isPowerOf2_64(MulAmt1))
14806 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
14807 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
14809 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
14810 DAG.getConstant(MulAmt1, VT));
14812 if (isPowerOf2_64(MulAmt2))
14813 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
14814 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
14816 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
14817 DAG.getConstant(MulAmt2, VT));
14819 // Do not add new nodes to DAG combiner worklist.
14820 DCI.CombineTo(N, NewMul, false);
14825 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
14826 SDValue N0 = N->getOperand(0);
14827 SDValue N1 = N->getOperand(1);
14828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
14829 EVT VT = N0.getValueType();
14831 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
14832 // since the result of setcc_c is all zero's or all ones.
14833 if (VT.isInteger() && !VT.isVector() &&
14834 N1C && N0.getOpcode() == ISD::AND &&
14835 N0.getOperand(1).getOpcode() == ISD::Constant) {
14836 SDValue N00 = N0.getOperand(0);
14837 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
14838 ((N00.getOpcode() == ISD::ANY_EXTEND ||
14839 N00.getOpcode() == ISD::ZERO_EXTEND) &&
14840 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
14841 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
14842 APInt ShAmt = N1C->getAPIntValue();
14843 Mask = Mask.shl(ShAmt);
14845 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
14846 N00, DAG.getConstant(Mask, VT));
14851 // Hardware support for vector shifts is sparse which makes us scalarize the
14852 // vector operations in many cases. Also, on sandybridge ADD is faster than
14854 // (shl V, 1) -> add V,V
14855 if (isSplatVector(N1.getNode())) {
14856 assert(N0.getValueType().isVector() && "Invalid vector shift type");
14857 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
14858 // We shift all of the values by one. In many cases we do not have
14859 // hardware support for this operation. This is better expressed as an ADD
14861 if (N1C && (1 == N1C->getZExtValue())) {
14862 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
14869 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
14871 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
14872 TargetLowering::DAGCombinerInfo &DCI,
14873 const X86Subtarget *Subtarget) {
14874 EVT VT = N->getValueType(0);
14875 if (N->getOpcode() == ISD::SHL) {
14876 SDValue V = PerformSHLCombine(N, DAG);
14877 if (V.getNode()) return V;
14880 // On X86 with SSE2 support, we can transform this to a vector shift if
14881 // all elements are shifted by the same amount. We can't do this in legalize
14882 // because the a constant vector is typically transformed to a constant pool
14883 // so we have no knowledge of the shift amount.
14884 if (!Subtarget->hasSSE2())
14887 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14888 (!Subtarget->hasAVX2() ||
14889 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14892 SDValue ShAmtOp = N->getOperand(1);
14893 EVT EltVT = VT.getVectorElementType();
14894 DebugLoc DL = N->getDebugLoc();
14895 SDValue BaseShAmt = SDValue();
14896 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14897 unsigned NumElts = VT.getVectorNumElements();
14899 for (; i != NumElts; ++i) {
14900 SDValue Arg = ShAmtOp.getOperand(i);
14901 if (Arg.getOpcode() == ISD::UNDEF) continue;
14905 // Handle the case where the build_vector is all undef
14906 // FIXME: Should DAG allow this?
14910 for (; i != NumElts; ++i) {
14911 SDValue Arg = ShAmtOp.getOperand(i);
14912 if (Arg.getOpcode() == ISD::UNDEF) continue;
14913 if (Arg != BaseShAmt) {
14917 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14918 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14919 SDValue InVec = ShAmtOp.getOperand(0);
14920 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14921 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14923 for (; i != NumElts; ++i) {
14924 SDValue Arg = InVec.getOperand(i);
14925 if (Arg.getOpcode() == ISD::UNDEF) continue;
14929 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14931 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14932 if (C->getZExtValue() == SplatIdx)
14933 BaseShAmt = InVec.getOperand(1);
14936 if (BaseShAmt.getNode() == 0) {
14937 // Don't create instructions with illegal types after legalize
14939 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14940 !DCI.isBeforeLegalize())
14943 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14944 DAG.getIntPtrConstant(0));
14949 // The shift amount is an i32.
14950 if (EltVT.bitsGT(MVT::i32))
14951 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14952 else if (EltVT.bitsLT(MVT::i32))
14953 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14955 // The shift amount is identical so we can do a vector shift.
14956 SDValue ValOp = N->getOperand(0);
14957 switch (N->getOpcode()) {
14959 llvm_unreachable("Unknown shift opcode!");
14961 switch (VT.getSimpleVT().SimpleTy) {
14962 default: return SDValue();
14969 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14972 switch (VT.getSimpleVT().SimpleTy) {
14973 default: return SDValue();
14978 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14981 switch (VT.getSimpleVT().SimpleTy) {
14982 default: return SDValue();
14989 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14995 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14996 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14997 // and friends. Likewise for OR -> CMPNEQSS.
14998 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14999 TargetLowering::DAGCombinerInfo &DCI,
15000 const X86Subtarget *Subtarget) {
15003 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15004 // we're requiring SSE2 for both.
15005 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15006 SDValue N0 = N->getOperand(0);
15007 SDValue N1 = N->getOperand(1);
15008 SDValue CMP0 = N0->getOperand(1);
15009 SDValue CMP1 = N1->getOperand(1);
15010 DebugLoc DL = N->getDebugLoc();
15012 // The SETCCs should both refer to the same CMP.
15013 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15016 SDValue CMP00 = CMP0->getOperand(0);
15017 SDValue CMP01 = CMP0->getOperand(1);
15018 EVT VT = CMP00.getValueType();
15020 if (VT == MVT::f32 || VT == MVT::f64) {
15021 bool ExpectingFlags = false;
15022 // Check for any users that want flags:
15023 for (SDNode::use_iterator UI = N->use_begin(),
15025 !ExpectingFlags && UI != UE; ++UI)
15026 switch (UI->getOpcode()) {
15031 ExpectingFlags = true;
15033 case ISD::CopyToReg:
15034 case ISD::SIGN_EXTEND:
15035 case ISD::ZERO_EXTEND:
15036 case ISD::ANY_EXTEND:
15040 if (!ExpectingFlags) {
15041 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15042 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15044 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15045 X86::CondCode tmp = cc0;
15050 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15051 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15052 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15053 X86ISD::NodeType NTOperator = is64BitFP ?
15054 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15055 // FIXME: need symbolic constants for these magic numbers.
15056 // See X86ATTInstPrinter.cpp:printSSECC().
15057 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15058 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15059 DAG.getConstant(x86cc, MVT::i8));
15060 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15062 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15063 DAG.getConstant(1, MVT::i32));
15064 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15065 return OneBitOfTruth;
15073 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15074 /// so it can be folded inside ANDNP.
15075 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15076 EVT VT = N->getValueType(0);
15078 // Match direct AllOnes for 128 and 256-bit vectors
15079 if (ISD::isBuildVectorAllOnes(N))
15082 // Look through a bit convert.
15083 if (N->getOpcode() == ISD::BITCAST)
15084 N = N->getOperand(0).getNode();
15086 // Sometimes the operand may come from a insert_subvector building a 256-bit
15088 if (VT.is256BitVector() &&
15089 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15090 SDValue V1 = N->getOperand(0);
15091 SDValue V2 = N->getOperand(1);
15093 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15094 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15095 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15096 ISD::isBuildVectorAllOnes(V2.getNode()))
15103 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15104 TargetLowering::DAGCombinerInfo &DCI,
15105 const X86Subtarget *Subtarget) {
15106 if (DCI.isBeforeLegalizeOps())
15109 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15113 EVT VT = N->getValueType(0);
15115 // Create ANDN, BLSI, and BLSR instructions
15116 // BLSI is X & (-X)
15117 // BLSR is X & (X-1)
15118 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15119 SDValue N0 = N->getOperand(0);
15120 SDValue N1 = N->getOperand(1);
15121 DebugLoc DL = N->getDebugLoc();
15123 // Check LHS for not
15124 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15125 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15126 // Check RHS for not
15127 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15128 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15130 // Check LHS for neg
15131 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15132 isZero(N0.getOperand(0)))
15133 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15135 // Check RHS for neg
15136 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15137 isZero(N1.getOperand(0)))
15138 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15140 // Check LHS for X-1
15141 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15142 isAllOnes(N0.getOperand(1)))
15143 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15145 // Check RHS for X-1
15146 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15147 isAllOnes(N1.getOperand(1)))
15148 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15153 // Want to form ANDNP nodes:
15154 // 1) In the hopes of then easily combining them with OR and AND nodes
15155 // to form PBLEND/PSIGN.
15156 // 2) To match ANDN packed intrinsics
15157 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15160 SDValue N0 = N->getOperand(0);
15161 SDValue N1 = N->getOperand(1);
15162 DebugLoc DL = N->getDebugLoc();
15164 // Check LHS for vnot
15165 if (N0.getOpcode() == ISD::XOR &&
15166 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15167 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15168 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15170 // Check RHS for vnot
15171 if (N1.getOpcode() == ISD::XOR &&
15172 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15173 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15174 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15179 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15180 TargetLowering::DAGCombinerInfo &DCI,
15181 const X86Subtarget *Subtarget) {
15182 if (DCI.isBeforeLegalizeOps())
15185 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15189 EVT VT = N->getValueType(0);
15191 SDValue N0 = N->getOperand(0);
15192 SDValue N1 = N->getOperand(1);
15194 // look for psign/blend
15195 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15196 if (!Subtarget->hasSSSE3() ||
15197 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15200 // Canonicalize pandn to RHS
15201 if (N0.getOpcode() == X86ISD::ANDNP)
15203 // or (and (m, y), (pandn m, x))
15204 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15205 SDValue Mask = N1.getOperand(0);
15206 SDValue X = N1.getOperand(1);
15208 if (N0.getOperand(0) == Mask)
15209 Y = N0.getOperand(1);
15210 if (N0.getOperand(1) == Mask)
15211 Y = N0.getOperand(0);
15213 // Check to see if the mask appeared in both the AND and ANDNP and
15217 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15218 // Look through mask bitcast.
15219 if (Mask.getOpcode() == ISD::BITCAST)
15220 Mask = Mask.getOperand(0);
15221 if (X.getOpcode() == ISD::BITCAST)
15222 X = X.getOperand(0);
15223 if (Y.getOpcode() == ISD::BITCAST)
15224 Y = Y.getOperand(0);
15226 EVT MaskVT = Mask.getValueType();
15228 // Validate that the Mask operand is a vector sra node.
15229 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15230 // there is no psrai.b
15231 if (Mask.getOpcode() != X86ISD::VSRAI)
15234 // Check that the SRA is all signbits.
15235 SDValue SraC = Mask.getOperand(1);
15236 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15237 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15238 if ((SraAmt + 1) != EltBits)
15241 DebugLoc DL = N->getDebugLoc();
15243 // Now we know we at least have a plendvb with the mask val. See if
15244 // we can form a psignb/w/d.
15245 // psign = x.type == y.type == mask.type && y = sub(0, x);
15246 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15247 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15248 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15249 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15250 "Unsupported VT for PSIGN");
15251 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15252 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15254 // PBLENDVB only available on SSE 4.1
15255 if (!Subtarget->hasSSE41())
15258 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15260 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15261 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15262 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15263 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15264 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15268 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15271 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15272 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15274 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15276 if (!N0.hasOneUse() || !N1.hasOneUse())
15279 SDValue ShAmt0 = N0.getOperand(1);
15280 if (ShAmt0.getValueType() != MVT::i8)
15282 SDValue ShAmt1 = N1.getOperand(1);
15283 if (ShAmt1.getValueType() != MVT::i8)
15285 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15286 ShAmt0 = ShAmt0.getOperand(0);
15287 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15288 ShAmt1 = ShAmt1.getOperand(0);
15290 DebugLoc DL = N->getDebugLoc();
15291 unsigned Opc = X86ISD::SHLD;
15292 SDValue Op0 = N0.getOperand(0);
15293 SDValue Op1 = N1.getOperand(0);
15294 if (ShAmt0.getOpcode() == ISD::SUB) {
15295 Opc = X86ISD::SHRD;
15296 std::swap(Op0, Op1);
15297 std::swap(ShAmt0, ShAmt1);
15300 unsigned Bits = VT.getSizeInBits();
15301 if (ShAmt1.getOpcode() == ISD::SUB) {
15302 SDValue Sum = ShAmt1.getOperand(0);
15303 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15304 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15305 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15306 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15307 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15308 return DAG.getNode(Opc, DL, VT,
15310 DAG.getNode(ISD::TRUNCATE, DL,
15313 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15314 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15316 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15317 return DAG.getNode(Opc, DL, VT,
15318 N0.getOperand(0), N1.getOperand(0),
15319 DAG.getNode(ISD::TRUNCATE, DL,
15326 // Generate NEG and CMOV for integer abs.
15327 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15328 EVT VT = N->getValueType(0);
15330 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15331 // 8-bit integer abs to NEG and CMOV.
15332 if (VT.isInteger() && VT.getSizeInBits() == 8)
15335 SDValue N0 = N->getOperand(0);
15336 SDValue N1 = N->getOperand(1);
15337 DebugLoc DL = N->getDebugLoc();
15339 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15340 // and change it to SUB and CMOV.
15341 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15342 N0.getOpcode() == ISD::ADD &&
15343 N0.getOperand(1) == N1 &&
15344 N1.getOpcode() == ISD::SRA &&
15345 N1.getOperand(0) == N0.getOperand(0))
15346 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15347 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15348 // Generate SUB & CMOV.
15349 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15350 DAG.getConstant(0, VT), N0.getOperand(0));
15352 SDValue Ops[] = { N0.getOperand(0), Neg,
15353 DAG.getConstant(X86::COND_GE, MVT::i8),
15354 SDValue(Neg.getNode(), 1) };
15355 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15356 Ops, array_lengthof(Ops));
15361 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15362 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15363 TargetLowering::DAGCombinerInfo &DCI,
15364 const X86Subtarget *Subtarget) {
15365 if (DCI.isBeforeLegalizeOps())
15368 if (Subtarget->hasCMov()) {
15369 SDValue RV = performIntegerAbsCombine(N, DAG);
15374 // Try forming BMI if it is available.
15375 if (!Subtarget->hasBMI())
15378 EVT VT = N->getValueType(0);
15380 if (VT != MVT::i32 && VT != MVT::i64)
15383 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15385 // Create BLSMSK instructions by finding X ^ (X-1)
15386 SDValue N0 = N->getOperand(0);
15387 SDValue N1 = N->getOperand(1);
15388 DebugLoc DL = N->getDebugLoc();
15390 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15391 isAllOnes(N0.getOperand(1)))
15392 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15394 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15395 isAllOnes(N1.getOperand(1)))
15396 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15401 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15402 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15403 TargetLowering::DAGCombinerInfo &DCI,
15404 const X86Subtarget *Subtarget) {
15405 LoadSDNode *Ld = cast<LoadSDNode>(N);
15406 EVT RegVT = Ld->getValueType(0);
15407 EVT MemVT = Ld->getMemoryVT();
15408 DebugLoc dl = Ld->getDebugLoc();
15409 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15411 ISD::LoadExtType Ext = Ld->getExtensionType();
15413 // If this is a vector EXT Load then attempt to optimize it using a
15414 // shuffle. We need SSE4 for the shuffles.
15415 // TODO: It is possible to support ZExt by zeroing the undef values
15416 // during the shuffle phase or after the shuffle.
15417 if (RegVT.isVector() && RegVT.isInteger() &&
15418 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
15419 assert(MemVT != RegVT && "Cannot extend to the same type");
15420 assert(MemVT.isVector() && "Must load a vector from memory");
15422 unsigned NumElems = RegVT.getVectorNumElements();
15423 unsigned RegSz = RegVT.getSizeInBits();
15424 unsigned MemSz = MemVT.getSizeInBits();
15425 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15427 // All sizes must be a power of two.
15428 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15431 // Attempt to load the original value using scalar loads.
15432 // Find the largest scalar type that divides the total loaded size.
15433 MVT SclrLoadTy = MVT::i8;
15434 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15435 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15436 MVT Tp = (MVT::SimpleValueType)tp;
15437 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15442 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15443 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15445 SclrLoadTy = MVT::f64;
15447 // Calculate the number of scalar loads that we need to perform
15448 // in order to load our vector from memory.
15449 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15451 // Represent our vector as a sequence of elements which are the
15452 // largest scalar that we can load.
15453 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15454 RegSz/SclrLoadTy.getSizeInBits());
15456 // Represent the data using the same element type that is stored in
15457 // memory. In practice, we ''widen'' MemVT.
15458 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15459 RegSz/MemVT.getScalarType().getSizeInBits());
15461 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15462 "Invalid vector type");
15464 // We can't shuffle using an illegal type.
15465 if (!TLI.isTypeLegal(WideVecVT))
15468 SmallVector<SDValue, 8> Chains;
15469 SDValue Ptr = Ld->getBasePtr();
15470 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15471 TLI.getPointerTy());
15472 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15474 for (unsigned i = 0; i < NumLoads; ++i) {
15475 // Perform a single load.
15476 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15477 Ptr, Ld->getPointerInfo(),
15478 Ld->isVolatile(), Ld->isNonTemporal(),
15479 Ld->isInvariant(), Ld->getAlignment());
15480 Chains.push_back(ScalarLoad.getValue(1));
15481 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15482 // another round of DAGCombining.
15484 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15486 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15487 ScalarLoad, DAG.getIntPtrConstant(i));
15489 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15492 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15495 // Bitcast the loaded value to a vector of the original element type, in
15496 // the size of the target vector type.
15497 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15498 unsigned SizeRatio = RegSz/MemSz;
15500 // Redistribute the loaded elements into the different locations.
15501 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15502 for (unsigned i = 0; i != NumElems; ++i)
15503 ShuffleVec[i*SizeRatio] = i;
15505 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15506 DAG.getUNDEF(WideVecVT),
15509 // Bitcast to the requested type.
15510 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15511 // Replace the original load with the new sequence
15512 // and return the new chain.
15513 return DCI.CombineTo(N, Shuff, TF, true);
15519 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15520 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15521 const X86Subtarget *Subtarget) {
15522 StoreSDNode *St = cast<StoreSDNode>(N);
15523 EVT VT = St->getValue().getValueType();
15524 EVT StVT = St->getMemoryVT();
15525 DebugLoc dl = St->getDebugLoc();
15526 SDValue StoredVal = St->getOperand(1);
15527 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15529 // If we are saving a concatenation of two XMM registers, perform two stores.
15530 // On Sandy Bridge, 256-bit memory operations are executed by two
15531 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15532 // memory operation.
15533 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15534 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15535 StoredVal.getNumOperands() == 2) {
15536 SDValue Value0 = StoredVal.getOperand(0);
15537 SDValue Value1 = StoredVal.getOperand(1);
15539 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15540 SDValue Ptr0 = St->getBasePtr();
15541 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15543 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15544 St->getPointerInfo(), St->isVolatile(),
15545 St->isNonTemporal(), St->getAlignment());
15546 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15547 St->getPointerInfo(), St->isVolatile(),
15548 St->isNonTemporal(), St->getAlignment());
15549 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15552 // Optimize trunc store (of multiple scalars) to shuffle and store.
15553 // First, pack all of the elements in one place. Next, store to memory
15554 // in fewer chunks.
15555 if (St->isTruncatingStore() && VT.isVector()) {
15556 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15557 unsigned NumElems = VT.getVectorNumElements();
15558 assert(StVT != VT && "Cannot truncate to the same type");
15559 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15560 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15562 // From, To sizes and ElemCount must be pow of two
15563 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15564 // We are going to use the original vector elt for storing.
15565 // Accumulated smaller vector elements must be a multiple of the store size.
15566 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15568 unsigned SizeRatio = FromSz / ToSz;
15570 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15572 // Create a type on which we perform the shuffle
15573 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15574 StVT.getScalarType(), NumElems*SizeRatio);
15576 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15578 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15579 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15580 for (unsigned i = 0; i != NumElems; ++i)
15581 ShuffleVec[i] = i * SizeRatio;
15583 // Can't shuffle using an illegal type.
15584 if (!TLI.isTypeLegal(WideVecVT))
15587 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15588 DAG.getUNDEF(WideVecVT),
15590 // At this point all of the data is stored at the bottom of the
15591 // register. We now need to save it to mem.
15593 // Find the largest store unit
15594 MVT StoreType = MVT::i8;
15595 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15596 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15597 MVT Tp = (MVT::SimpleValueType)tp;
15598 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15602 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15603 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15604 (64 <= NumElems * ToSz))
15605 StoreType = MVT::f64;
15607 // Bitcast the original vector into a vector of store-size units
15608 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15609 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15610 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15611 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15612 SmallVector<SDValue, 8> Chains;
15613 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15614 TLI.getPointerTy());
15615 SDValue Ptr = St->getBasePtr();
15617 // Perform one or more big stores into memory.
15618 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15619 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15620 StoreType, ShuffWide,
15621 DAG.getIntPtrConstant(i));
15622 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15623 St->getPointerInfo(), St->isVolatile(),
15624 St->isNonTemporal(), St->getAlignment());
15625 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15626 Chains.push_back(Ch);
15629 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15634 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15635 // the FP state in cases where an emms may be missing.
15636 // A preferable solution to the general problem is to figure out the right
15637 // places to insert EMMS. This qualifies as a quick hack.
15639 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15640 if (VT.getSizeInBits() != 64)
15643 const Function *F = DAG.getMachineFunction().getFunction();
15644 bool NoImplicitFloatOps = F->getFnAttributes().
15645 hasAttribute(Attributes::NoImplicitFloat);
15646 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15647 && Subtarget->hasSSE2();
15648 if ((VT.isVector() ||
15649 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15650 isa<LoadSDNode>(St->getValue()) &&
15651 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15652 St->getChain().hasOneUse() && !St->isVolatile()) {
15653 SDNode* LdVal = St->getValue().getNode();
15654 LoadSDNode *Ld = 0;
15655 int TokenFactorIndex = -1;
15656 SmallVector<SDValue, 8> Ops;
15657 SDNode* ChainVal = St->getChain().getNode();
15658 // Must be a store of a load. We currently handle two cases: the load
15659 // is a direct child, and it's under an intervening TokenFactor. It is
15660 // possible to dig deeper under nested TokenFactors.
15661 if (ChainVal == LdVal)
15662 Ld = cast<LoadSDNode>(St->getChain());
15663 else if (St->getValue().hasOneUse() &&
15664 ChainVal->getOpcode() == ISD::TokenFactor) {
15665 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15666 if (ChainVal->getOperand(i).getNode() == LdVal) {
15667 TokenFactorIndex = i;
15668 Ld = cast<LoadSDNode>(St->getValue());
15670 Ops.push_back(ChainVal->getOperand(i));
15674 if (!Ld || !ISD::isNormalLoad(Ld))
15677 // If this is not the MMX case, i.e. we are just turning i64 load/store
15678 // into f64 load/store, avoid the transformation if there are multiple
15679 // uses of the loaded value.
15680 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15683 DebugLoc LdDL = Ld->getDebugLoc();
15684 DebugLoc StDL = N->getDebugLoc();
15685 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15686 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15688 if (Subtarget->is64Bit() || F64IsLegal) {
15689 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15690 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15691 Ld->getPointerInfo(), Ld->isVolatile(),
15692 Ld->isNonTemporal(), Ld->isInvariant(),
15693 Ld->getAlignment());
15694 SDValue NewChain = NewLd.getValue(1);
15695 if (TokenFactorIndex != -1) {
15696 Ops.push_back(NewChain);
15697 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15700 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
15701 St->getPointerInfo(),
15702 St->isVolatile(), St->isNonTemporal(),
15703 St->getAlignment());
15706 // Otherwise, lower to two pairs of 32-bit loads / stores.
15707 SDValue LoAddr = Ld->getBasePtr();
15708 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
15709 DAG.getConstant(4, MVT::i32));
15711 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
15712 Ld->getPointerInfo(),
15713 Ld->isVolatile(), Ld->isNonTemporal(),
15714 Ld->isInvariant(), Ld->getAlignment());
15715 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
15716 Ld->getPointerInfo().getWithOffset(4),
15717 Ld->isVolatile(), Ld->isNonTemporal(),
15719 MinAlign(Ld->getAlignment(), 4));
15721 SDValue NewChain = LoLd.getValue(1);
15722 if (TokenFactorIndex != -1) {
15723 Ops.push_back(LoLd);
15724 Ops.push_back(HiLd);
15725 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
15729 LoAddr = St->getBasePtr();
15730 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
15731 DAG.getConstant(4, MVT::i32));
15733 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
15734 St->getPointerInfo(),
15735 St->isVolatile(), St->isNonTemporal(),
15736 St->getAlignment());
15737 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
15738 St->getPointerInfo().getWithOffset(4),
15740 St->isNonTemporal(),
15741 MinAlign(St->getAlignment(), 4));
15742 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
15747 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
15748 /// and return the operands for the horizontal operation in LHS and RHS. A
15749 /// horizontal operation performs the binary operation on successive elements
15750 /// of its first operand, then on successive elements of its second operand,
15751 /// returning the resulting values in a vector. For example, if
15752 /// A = < float a0, float a1, float a2, float a3 >
15754 /// B = < float b0, float b1, float b2, float b3 >
15755 /// then the result of doing a horizontal operation on A and B is
15756 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
15757 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
15758 /// A horizontal-op B, for some already available A and B, and if so then LHS is
15759 /// set to A, RHS to B, and the routine returns 'true'.
15760 /// Note that the binary operation should have the property that if one of the
15761 /// operands is UNDEF then the result is UNDEF.
15762 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
15763 // Look for the following pattern: if
15764 // A = < float a0, float a1, float a2, float a3 >
15765 // B = < float b0, float b1, float b2, float b3 >
15767 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
15768 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
15769 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
15770 // which is A horizontal-op B.
15772 // At least one of the operands should be a vector shuffle.
15773 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
15774 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
15777 EVT VT = LHS.getValueType();
15779 assert((VT.is128BitVector() || VT.is256BitVector()) &&
15780 "Unsupported vector type for horizontal add/sub");
15782 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
15783 // operate independently on 128-bit lanes.
15784 unsigned NumElts = VT.getVectorNumElements();
15785 unsigned NumLanes = VT.getSizeInBits()/128;
15786 unsigned NumLaneElts = NumElts / NumLanes;
15787 assert((NumLaneElts % 2 == 0) &&
15788 "Vector type should have an even number of elements in each lane");
15789 unsigned HalfLaneElts = NumLaneElts/2;
15791 // View LHS in the form
15792 // LHS = VECTOR_SHUFFLE A, B, LMask
15793 // If LHS is not a shuffle then pretend it is the shuffle
15794 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
15795 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
15798 SmallVector<int, 16> LMask(NumElts);
15799 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15800 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
15801 A = LHS.getOperand(0);
15802 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
15803 B = LHS.getOperand(1);
15804 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
15805 std::copy(Mask.begin(), Mask.end(), LMask.begin());
15807 if (LHS.getOpcode() != ISD::UNDEF)
15809 for (unsigned i = 0; i != NumElts; ++i)
15813 // Likewise, view RHS in the form
15814 // RHS = VECTOR_SHUFFLE C, D, RMask
15816 SmallVector<int, 16> RMask(NumElts);
15817 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
15818 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
15819 C = RHS.getOperand(0);
15820 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
15821 D = RHS.getOperand(1);
15822 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
15823 std::copy(Mask.begin(), Mask.end(), RMask.begin());
15825 if (RHS.getOpcode() != ISD::UNDEF)
15827 for (unsigned i = 0; i != NumElts; ++i)
15831 // Check that the shuffles are both shuffling the same vectors.
15832 if (!(A == C && B == D) && !(A == D && B == C))
15835 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
15836 if (!A.getNode() && !B.getNode())
15839 // If A and B occur in reverse order in RHS, then "swap" them (which means
15840 // rewriting the mask).
15842 CommuteVectorShuffleMask(RMask, NumElts);
15844 // At this point LHS and RHS are equivalent to
15845 // LHS = VECTOR_SHUFFLE A, B, LMask
15846 // RHS = VECTOR_SHUFFLE A, B, RMask
15847 // Check that the masks correspond to performing a horizontal operation.
15848 for (unsigned i = 0; i != NumElts; ++i) {
15849 int LIdx = LMask[i], RIdx = RMask[i];
15851 // Ignore any UNDEF components.
15852 if (LIdx < 0 || RIdx < 0 ||
15853 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
15854 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
15857 // Check that successive elements are being operated on. If not, this is
15858 // not a horizontal operation.
15859 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
15860 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
15861 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
15862 if (!(LIdx == Index && RIdx == Index + 1) &&
15863 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
15867 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
15868 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
15872 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
15873 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
15874 const X86Subtarget *Subtarget) {
15875 EVT VT = N->getValueType(0);
15876 SDValue LHS = N->getOperand(0);
15877 SDValue RHS = N->getOperand(1);
15879 // Try to synthesize horizontal adds from adds of shuffles.
15880 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15881 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15882 isHorizontalBinOp(LHS, RHS, true))
15883 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
15887 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
15888 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
15889 const X86Subtarget *Subtarget) {
15890 EVT VT = N->getValueType(0);
15891 SDValue LHS = N->getOperand(0);
15892 SDValue RHS = N->getOperand(1);
15894 // Try to synthesize horizontal subs from subs of shuffles.
15895 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
15896 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
15897 isHorizontalBinOp(LHS, RHS, false))
15898 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
15902 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
15903 /// X86ISD::FXOR nodes.
15904 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
15905 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
15906 // F[X]OR(0.0, x) -> x
15907 // F[X]OR(x, 0.0) -> x
15908 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15909 if (C->getValueAPF().isPosZero())
15910 return N->getOperand(1);
15911 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15912 if (C->getValueAPF().isPosZero())
15913 return N->getOperand(0);
15917 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
15918 /// X86ISD::FMAX nodes.
15919 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
15920 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
15922 // Only perform optimizations if UnsafeMath is used.
15923 if (!DAG.getTarget().Options.UnsafeFPMath)
15926 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
15927 // into FMINC and FMAXC, which are Commutative operations.
15928 unsigned NewOp = 0;
15929 switch (N->getOpcode()) {
15930 default: llvm_unreachable("unknown opcode");
15931 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
15932 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
15935 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
15936 N->getOperand(0), N->getOperand(1));
15940 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
15941 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
15942 // FAND(0.0, x) -> 0.0
15943 // FAND(x, 0.0) -> 0.0
15944 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
15945 if (C->getValueAPF().isPosZero())
15946 return N->getOperand(0);
15947 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
15948 if (C->getValueAPF().isPosZero())
15949 return N->getOperand(1);
15953 static SDValue PerformBTCombine(SDNode *N,
15955 TargetLowering::DAGCombinerInfo &DCI) {
15956 // BT ignores high bits in the bit index operand.
15957 SDValue Op1 = N->getOperand(1);
15958 if (Op1.hasOneUse()) {
15959 unsigned BitWidth = Op1.getValueSizeInBits();
15960 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
15961 APInt KnownZero, KnownOne;
15962 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
15963 !DCI.isBeforeLegalizeOps());
15964 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15965 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
15966 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
15967 DCI.CommitTargetLoweringOpt(TLO);
15972 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
15973 SDValue Op = N->getOperand(0);
15974 if (Op.getOpcode() == ISD::BITCAST)
15975 Op = Op.getOperand(0);
15976 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
15977 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
15978 VT.getVectorElementType().getSizeInBits() ==
15979 OpVT.getVectorElementType().getSizeInBits()) {
15980 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
15985 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
15986 TargetLowering::DAGCombinerInfo &DCI,
15987 const X86Subtarget *Subtarget) {
15988 if (!DCI.isBeforeLegalizeOps())
15991 if (!Subtarget->hasAVX())
15994 EVT VT = N->getValueType(0);
15995 SDValue Op = N->getOperand(0);
15996 EVT OpVT = Op.getValueType();
15997 DebugLoc dl = N->getDebugLoc();
15999 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16000 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16002 if (Subtarget->hasAVX2())
16003 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16005 // Optimize vectors in AVX mode
16006 // Sign extend v8i16 to v8i32 and
16009 // Divide input vector into two parts
16010 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16011 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16012 // concat the vectors to original VT
16014 unsigned NumElems = OpVT.getVectorNumElements();
16015 SDValue Undef = DAG.getUNDEF(OpVT);
16017 SmallVector<int,8> ShufMask1(NumElems, -1);
16018 for (unsigned i = 0; i != NumElems/2; ++i)
16021 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16023 SmallVector<int,8> ShufMask2(NumElems, -1);
16024 for (unsigned i = 0; i != NumElems/2; ++i)
16025 ShufMask2[i] = i + NumElems/2;
16027 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16029 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16030 VT.getVectorNumElements()/2);
16032 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16033 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16035 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16040 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16041 const X86Subtarget* Subtarget) {
16042 DebugLoc dl = N->getDebugLoc();
16043 EVT VT = N->getValueType(0);
16045 // Let legalize expand this if it isn't a legal type yet.
16046 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16049 EVT ScalarVT = VT.getScalarType();
16050 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16051 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16054 SDValue A = N->getOperand(0);
16055 SDValue B = N->getOperand(1);
16056 SDValue C = N->getOperand(2);
16058 bool NegA = (A.getOpcode() == ISD::FNEG);
16059 bool NegB = (B.getOpcode() == ISD::FNEG);
16060 bool NegC = (C.getOpcode() == ISD::FNEG);
16062 // Negative multiplication when NegA xor NegB
16063 bool NegMul = (NegA != NegB);
16065 A = A.getOperand(0);
16067 B = B.getOperand(0);
16069 C = C.getOperand(0);
16073 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16075 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16077 return DAG.getNode(Opcode, dl, VT, A, B, C);
16080 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16081 TargetLowering::DAGCombinerInfo &DCI,
16082 const X86Subtarget *Subtarget) {
16083 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16084 // (and (i32 x86isd::setcc_carry), 1)
16085 // This eliminates the zext. This transformation is necessary because
16086 // ISD::SETCC is always legalized to i8.
16087 DebugLoc dl = N->getDebugLoc();
16088 SDValue N0 = N->getOperand(0);
16089 EVT VT = N->getValueType(0);
16090 EVT OpVT = N0.getValueType();
16092 if (N0.getOpcode() == ISD::AND &&
16094 N0.getOperand(0).hasOneUse()) {
16095 SDValue N00 = N0.getOperand(0);
16096 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16098 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16099 if (!C || C->getZExtValue() != 1)
16101 return DAG.getNode(ISD::AND, dl, VT,
16102 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16103 N00.getOperand(0), N00.getOperand(1)),
16104 DAG.getConstant(1, VT));
16107 // Optimize vectors in AVX mode:
16110 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16111 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16112 // Concat upper and lower parts.
16115 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16116 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16117 // Concat upper and lower parts.
16119 if (!DCI.isBeforeLegalizeOps())
16122 if (!Subtarget->hasAVX())
16125 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16126 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16128 if (Subtarget->hasAVX2())
16129 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16131 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16132 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16133 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16135 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16136 VT.getVectorNumElements()/2);
16138 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16139 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16141 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16147 // Optimize x == -y --> x+y == 0
16148 // x != -y --> x+y != 0
16149 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16150 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16151 SDValue LHS = N->getOperand(0);
16152 SDValue RHS = N->getOperand(1);
16154 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16156 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16157 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16158 LHS.getValueType(), RHS, LHS.getOperand(1));
16159 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16160 addV, DAG.getConstant(0, addV.getValueType()), CC);
16162 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16163 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16164 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16165 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16166 RHS.getValueType(), LHS, RHS.getOperand(1));
16167 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16168 addV, DAG.getConstant(0, addV.getValueType()), CC);
16173 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16174 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16175 TargetLowering::DAGCombinerInfo &DCI,
16176 const X86Subtarget *Subtarget) {
16177 DebugLoc DL = N->getDebugLoc();
16178 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16179 SDValue EFLAGS = N->getOperand(1);
16181 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16182 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16184 if (CC == X86::COND_B)
16185 return DAG.getNode(ISD::AND, DL, MVT::i8,
16186 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16187 DAG.getConstant(CC, MVT::i8), EFLAGS),
16188 DAG.getConstant(1, MVT::i8));
16192 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16193 if (Flags.getNode()) {
16194 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16195 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16201 // Optimize branch condition evaluation.
16203 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16204 TargetLowering::DAGCombinerInfo &DCI,
16205 const X86Subtarget *Subtarget) {
16206 DebugLoc DL = N->getDebugLoc();
16207 SDValue Chain = N->getOperand(0);
16208 SDValue Dest = N->getOperand(1);
16209 SDValue EFLAGS = N->getOperand(3);
16210 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16214 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16215 if (Flags.getNode()) {
16216 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16217 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16224 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
16225 SDValue Op0 = N->getOperand(0);
16226 EVT InVT = Op0->getValueType(0);
16228 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
16229 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16230 DebugLoc dl = N->getDebugLoc();
16231 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16232 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
16233 // Notice that we use SINT_TO_FP because we know that the high bits
16234 // are zero and SINT_TO_FP is better supported by the hardware.
16235 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16241 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16242 const X86TargetLowering *XTLI) {
16243 SDValue Op0 = N->getOperand(0);
16244 EVT InVT = Op0->getValueType(0);
16246 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16247 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16248 DebugLoc dl = N->getDebugLoc();
16249 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16250 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16251 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16254 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16255 // a 32-bit target where SSE doesn't support i64->FP operations.
16256 if (Op0.getOpcode() == ISD::LOAD) {
16257 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16258 EVT VT = Ld->getValueType(0);
16259 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16260 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16261 !XTLI->getSubtarget()->is64Bit() &&
16262 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16263 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16264 Ld->getChain(), Op0, DAG);
16265 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16272 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
16273 EVT VT = N->getValueType(0);
16275 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
16276 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
16277 DebugLoc dl = N->getDebugLoc();
16278 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16279 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
16280 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
16286 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16287 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16288 X86TargetLowering::DAGCombinerInfo &DCI) {
16289 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16290 // the result is either zero or one (depending on the input carry bit).
16291 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16292 if (X86::isZeroNode(N->getOperand(0)) &&
16293 X86::isZeroNode(N->getOperand(1)) &&
16294 // We don't have a good way to replace an EFLAGS use, so only do this when
16296 SDValue(N, 1).use_empty()) {
16297 DebugLoc DL = N->getDebugLoc();
16298 EVT VT = N->getValueType(0);
16299 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16300 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16301 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16302 DAG.getConstant(X86::COND_B,MVT::i8),
16304 DAG.getConstant(1, VT));
16305 return DCI.CombineTo(N, Res1, CarryOut);
16311 // fold (add Y, (sete X, 0)) -> adc 0, Y
16312 // (add Y, (setne X, 0)) -> sbb -1, Y
16313 // (sub (sete X, 0), Y) -> sbb 0, Y
16314 // (sub (setne X, 0), Y) -> adc -1, Y
16315 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16316 DebugLoc DL = N->getDebugLoc();
16318 // Look through ZExts.
16319 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16320 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16323 SDValue SetCC = Ext.getOperand(0);
16324 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16327 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16328 if (CC != X86::COND_E && CC != X86::COND_NE)
16331 SDValue Cmp = SetCC.getOperand(1);
16332 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16333 !X86::isZeroNode(Cmp.getOperand(1)) ||
16334 !Cmp.getOperand(0).getValueType().isInteger())
16337 SDValue CmpOp0 = Cmp.getOperand(0);
16338 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16339 DAG.getConstant(1, CmpOp0.getValueType()));
16341 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16342 if (CC == X86::COND_NE)
16343 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16344 DL, OtherVal.getValueType(), OtherVal,
16345 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16346 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16347 DL, OtherVal.getValueType(), OtherVal,
16348 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16351 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16352 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16353 const X86Subtarget *Subtarget) {
16354 EVT VT = N->getValueType(0);
16355 SDValue Op0 = N->getOperand(0);
16356 SDValue Op1 = N->getOperand(1);
16358 // Try to synthesize horizontal adds from adds of shuffles.
16359 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16360 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16361 isHorizontalBinOp(Op0, Op1, true))
16362 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16364 return OptimizeConditionalInDecrement(N, DAG);
16367 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16368 const X86Subtarget *Subtarget) {
16369 SDValue Op0 = N->getOperand(0);
16370 SDValue Op1 = N->getOperand(1);
16372 // X86 can't encode an immediate LHS of a sub. See if we can push the
16373 // negation into a preceding instruction.
16374 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16375 // If the RHS of the sub is a XOR with one use and a constant, invert the
16376 // immediate. Then add one to the LHS of the sub so we can turn
16377 // X-Y -> X+~Y+1, saving one register.
16378 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16379 isa<ConstantSDNode>(Op1.getOperand(1))) {
16380 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16381 EVT VT = Op0.getValueType();
16382 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16384 DAG.getConstant(~XorC, VT));
16385 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16386 DAG.getConstant(C->getAPIntValue()+1, VT));
16390 // Try to synthesize horizontal adds from adds of shuffles.
16391 EVT VT = N->getValueType(0);
16392 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16393 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16394 isHorizontalBinOp(Op0, Op1, true))
16395 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16397 return OptimizeConditionalInDecrement(N, DAG);
16400 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16401 DAGCombinerInfo &DCI) const {
16402 SelectionDAG &DAG = DCI.DAG;
16403 switch (N->getOpcode()) {
16405 case ISD::EXTRACT_VECTOR_ELT:
16406 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16408 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16409 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16410 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16411 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16412 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16413 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16416 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16417 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16418 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16419 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16420 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16421 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16422 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
16423 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16424 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
16425 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16426 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16428 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16430 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16431 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16432 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16433 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16434 case ISD::ANY_EXTEND:
16435 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16436 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16437 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16438 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16439 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16440 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16441 case X86ISD::SHUFP: // Handle all target specific shuffles
16442 case X86ISD::PALIGN:
16443 case X86ISD::UNPCKH:
16444 case X86ISD::UNPCKL:
16445 case X86ISD::MOVHLPS:
16446 case X86ISD::MOVLHPS:
16447 case X86ISD::PSHUFD:
16448 case X86ISD::PSHUFHW:
16449 case X86ISD::PSHUFLW:
16450 case X86ISD::MOVSS:
16451 case X86ISD::MOVSD:
16452 case X86ISD::VPERMILP:
16453 case X86ISD::VPERM2X128:
16454 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16455 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16461 /// isTypeDesirableForOp - Return true if the target has native support for
16462 /// the specified value type and it is 'desirable' to use the type for the
16463 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16464 /// instruction encodings are longer and some i16 instructions are slow.
16465 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16466 if (!isTypeLegal(VT))
16468 if (VT != MVT::i16)
16475 case ISD::SIGN_EXTEND:
16476 case ISD::ZERO_EXTEND:
16477 case ISD::ANY_EXTEND:
16490 /// IsDesirableToPromoteOp - This method query the target whether it is
16491 /// beneficial for dag combiner to promote the specified node. If true, it
16492 /// should return the desired promotion type by reference.
16493 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16494 EVT VT = Op.getValueType();
16495 if (VT != MVT::i16)
16498 bool Promote = false;
16499 bool Commute = false;
16500 switch (Op.getOpcode()) {
16503 LoadSDNode *LD = cast<LoadSDNode>(Op);
16504 // If the non-extending load has a single use and it's not live out, then it
16505 // might be folded.
16506 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16507 Op.hasOneUse()*/) {
16508 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16509 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16510 // The only case where we'd want to promote LOAD (rather then it being
16511 // promoted as an operand is when it's only use is liveout.
16512 if (UI->getOpcode() != ISD::CopyToReg)
16519 case ISD::SIGN_EXTEND:
16520 case ISD::ZERO_EXTEND:
16521 case ISD::ANY_EXTEND:
16526 SDValue N0 = Op.getOperand(0);
16527 // Look out for (store (shl (load), x)).
16528 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16541 SDValue N0 = Op.getOperand(0);
16542 SDValue N1 = Op.getOperand(1);
16543 if (!Commute && MayFoldLoad(N1))
16545 // Avoid disabling potential load folding opportunities.
16546 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16548 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16558 //===----------------------------------------------------------------------===//
16559 // X86 Inline Assembly Support
16560 //===----------------------------------------------------------------------===//
16563 // Helper to match a string separated by whitespace.
16564 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16565 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16567 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16568 StringRef piece(*args[i]);
16569 if (!s.startswith(piece)) // Check if the piece matches.
16572 s = s.substr(piece.size());
16573 StringRef::size_type pos = s.find_first_not_of(" \t");
16574 if (pos == 0) // We matched a prefix.
16582 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16585 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16586 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16588 std::string AsmStr = IA->getAsmString();
16590 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16591 if (!Ty || Ty->getBitWidth() % 16 != 0)
16594 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16595 SmallVector<StringRef, 4> AsmPieces;
16596 SplitString(AsmStr, AsmPieces, ";\n");
16598 switch (AsmPieces.size()) {
16599 default: return false;
16601 // FIXME: this should verify that we are targeting a 486 or better. If not,
16602 // we will turn this bswap into something that will be lowered to logical
16603 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16604 // lower so don't worry about this.
16606 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16607 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16608 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16609 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16610 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16611 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16612 // No need to check constraints, nothing other than the equivalent of
16613 // "=r,0" would be valid here.
16614 return IntrinsicLowering::LowerToByteSwap(CI);
16617 // rorw $$8, ${0:w} --> llvm.bswap.i16
16618 if (CI->getType()->isIntegerTy(16) &&
16619 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16620 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16621 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16623 const std::string &ConstraintsStr = IA->getConstraintString();
16624 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16625 std::sort(AsmPieces.begin(), AsmPieces.end());
16626 if (AsmPieces.size() == 4 &&
16627 AsmPieces[0] == "~{cc}" &&
16628 AsmPieces[1] == "~{dirflag}" &&
16629 AsmPieces[2] == "~{flags}" &&
16630 AsmPieces[3] == "~{fpsr}")
16631 return IntrinsicLowering::LowerToByteSwap(CI);
16635 if (CI->getType()->isIntegerTy(32) &&
16636 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16637 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16638 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16639 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16641 const std::string &ConstraintsStr = IA->getConstraintString();
16642 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16643 std::sort(AsmPieces.begin(), AsmPieces.end());
16644 if (AsmPieces.size() == 4 &&
16645 AsmPieces[0] == "~{cc}" &&
16646 AsmPieces[1] == "~{dirflag}" &&
16647 AsmPieces[2] == "~{flags}" &&
16648 AsmPieces[3] == "~{fpsr}")
16649 return IntrinsicLowering::LowerToByteSwap(CI);
16652 if (CI->getType()->isIntegerTy(64)) {
16653 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16654 if (Constraints.size() >= 2 &&
16655 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16656 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16657 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16658 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16659 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16660 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16661 return IntrinsicLowering::LowerToByteSwap(CI);
16671 /// getConstraintType - Given a constraint letter, return the type of
16672 /// constraint it is for this target.
16673 X86TargetLowering::ConstraintType
16674 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16675 if (Constraint.size() == 1) {
16676 switch (Constraint[0]) {
16687 return C_RegisterClass;
16711 return TargetLowering::getConstraintType(Constraint);
16714 /// Examine constraint type and operand type and determine a weight value.
16715 /// This object must already have been set up with the operand type
16716 /// and the current alternative constraint selected.
16717 TargetLowering::ConstraintWeight
16718 X86TargetLowering::getSingleConstraintMatchWeight(
16719 AsmOperandInfo &info, const char *constraint) const {
16720 ConstraintWeight weight = CW_Invalid;
16721 Value *CallOperandVal = info.CallOperandVal;
16722 // If we don't have a value, we can't do a match,
16723 // but allow it at the lowest weight.
16724 if (CallOperandVal == NULL)
16726 Type *type = CallOperandVal->getType();
16727 // Look at the constraint type.
16728 switch (*constraint) {
16730 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16741 if (CallOperandVal->getType()->isIntegerTy())
16742 weight = CW_SpecificReg;
16747 if (type->isFloatingPointTy())
16748 weight = CW_SpecificReg;
16751 if (type->isX86_MMXTy() && Subtarget->hasMMX())
16752 weight = CW_SpecificReg;
16756 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
16757 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
16758 weight = CW_Register;
16761 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
16762 if (C->getZExtValue() <= 31)
16763 weight = CW_Constant;
16767 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16768 if (C->getZExtValue() <= 63)
16769 weight = CW_Constant;
16773 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16774 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
16775 weight = CW_Constant;
16779 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16780 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
16781 weight = CW_Constant;
16785 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16786 if (C->getZExtValue() <= 3)
16787 weight = CW_Constant;
16791 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16792 if (C->getZExtValue() <= 0xff)
16793 weight = CW_Constant;
16798 if (dyn_cast<ConstantFP>(CallOperandVal)) {
16799 weight = CW_Constant;
16803 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16804 if ((C->getSExtValue() >= -0x80000000LL) &&
16805 (C->getSExtValue() <= 0x7fffffffLL))
16806 weight = CW_Constant;
16810 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
16811 if (C->getZExtValue() <= 0xffffffff)
16812 weight = CW_Constant;
16819 /// LowerXConstraint - try to replace an X constraint, which matches anything,
16820 /// with another that has more specific requirements based on the type of the
16821 /// corresponding operand.
16822 const char *X86TargetLowering::
16823 LowerXConstraint(EVT ConstraintVT) const {
16824 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
16825 // 'f' like normal targets.
16826 if (ConstraintVT.isFloatingPoint()) {
16827 if (Subtarget->hasSSE2())
16829 if (Subtarget->hasSSE1())
16833 return TargetLowering::LowerXConstraint(ConstraintVT);
16836 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16837 /// vector. If it is invalid, don't add anything to Ops.
16838 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16839 std::string &Constraint,
16840 std::vector<SDValue>&Ops,
16841 SelectionDAG &DAG) const {
16842 SDValue Result(0, 0);
16844 // Only support length 1 constraints for now.
16845 if (Constraint.length() > 1) return;
16847 char ConstraintLetter = Constraint[0];
16848 switch (ConstraintLetter) {
16851 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16852 if (C->getZExtValue() <= 31) {
16853 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16860 if (C->getZExtValue() <= 63) {
16861 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16868 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
16869 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16876 if (C->getZExtValue() <= 255) {
16877 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16883 // 32-bit signed value
16884 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16885 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16886 C->getSExtValue())) {
16887 // Widen to 64 bits here to get it sign extended.
16888 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
16891 // FIXME gcc accepts some relocatable values here too, but only in certain
16892 // memory models; it's complicated.
16897 // 32-bit unsigned value
16898 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
16899 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
16900 C->getZExtValue())) {
16901 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
16905 // FIXME gcc accepts some relocatable values here too, but only in certain
16906 // memory models; it's complicated.
16910 // Literal immediates are always ok.
16911 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
16912 // Widen to 64 bits here to get it sign extended.
16913 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
16917 // In any sort of PIC mode addresses need to be computed at runtime by
16918 // adding in a register or some sort of table lookup. These can't
16919 // be used as immediates.
16920 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
16923 // If we are in non-pic codegen mode, we allow the address of a global (with
16924 // an optional displacement) to be used with 'i'.
16925 GlobalAddressSDNode *GA = 0;
16926 int64_t Offset = 0;
16928 // Match either (GA), (GA+C), (GA+C1+C2), etc.
16930 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
16931 Offset += GA->getOffset();
16933 } else if (Op.getOpcode() == ISD::ADD) {
16934 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16935 Offset += C->getZExtValue();
16936 Op = Op.getOperand(0);
16939 } else if (Op.getOpcode() == ISD::SUB) {
16940 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
16941 Offset += -C->getZExtValue();
16942 Op = Op.getOperand(0);
16947 // Otherwise, this isn't something we can handle, reject it.
16951 const GlobalValue *GV = GA->getGlobal();
16952 // If we require an extra load to get this address, as in PIC mode, we
16953 // can't accept it.
16954 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
16955 getTargetMachine())))
16958 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
16959 GA->getValueType(0), Offset);
16964 if (Result.getNode()) {
16965 Ops.push_back(Result);
16968 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16971 std::pair<unsigned, const TargetRegisterClass*>
16972 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
16974 // First, see if this is a constraint that directly corresponds to an LLVM
16976 if (Constraint.size() == 1) {
16977 // GCC Constraint Letters
16978 switch (Constraint[0]) {
16980 // TODO: Slight differences here in allocation order and leaving
16981 // RIP in the class. Do they matter any more here than they do
16982 // in the normal allocation?
16983 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
16984 if (Subtarget->is64Bit()) {
16985 if (VT == MVT::i32 || VT == MVT::f32)
16986 return std::make_pair(0U, &X86::GR32RegClass);
16987 if (VT == MVT::i16)
16988 return std::make_pair(0U, &X86::GR16RegClass);
16989 if (VT == MVT::i8 || VT == MVT::i1)
16990 return std::make_pair(0U, &X86::GR8RegClass);
16991 if (VT == MVT::i64 || VT == MVT::f64)
16992 return std::make_pair(0U, &X86::GR64RegClass);
16995 // 32-bit fallthrough
16996 case 'Q': // Q_REGS
16997 if (VT == MVT::i32 || VT == MVT::f32)
16998 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
16999 if (VT == MVT::i16)
17000 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17001 if (VT == MVT::i8 || VT == MVT::i1)
17002 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17003 if (VT == MVT::i64)
17004 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17006 case 'r': // GENERAL_REGS
17007 case 'l': // INDEX_REGS
17008 if (VT == MVT::i8 || VT == MVT::i1)
17009 return std::make_pair(0U, &X86::GR8RegClass);
17010 if (VT == MVT::i16)
17011 return std::make_pair(0U, &X86::GR16RegClass);
17012 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17013 return std::make_pair(0U, &X86::GR32RegClass);
17014 return std::make_pair(0U, &X86::GR64RegClass);
17015 case 'R': // LEGACY_REGS
17016 if (VT == MVT::i8 || VT == MVT::i1)
17017 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17018 if (VT == MVT::i16)
17019 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17020 if (VT == MVT::i32 || !Subtarget->is64Bit())
17021 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17022 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17023 case 'f': // FP Stack registers.
17024 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17025 // value to the correct fpstack register class.
17026 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17027 return std::make_pair(0U, &X86::RFP32RegClass);
17028 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17029 return std::make_pair(0U, &X86::RFP64RegClass);
17030 return std::make_pair(0U, &X86::RFP80RegClass);
17031 case 'y': // MMX_REGS if MMX allowed.
17032 if (!Subtarget->hasMMX()) break;
17033 return std::make_pair(0U, &X86::VR64RegClass);
17034 case 'Y': // SSE_REGS if SSE2 allowed
17035 if (!Subtarget->hasSSE2()) break;
17037 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17038 if (!Subtarget->hasSSE1()) break;
17040 switch (VT.getSimpleVT().SimpleTy) {
17042 // Scalar SSE types.
17045 return std::make_pair(0U, &X86::FR32RegClass);
17048 return std::make_pair(0U, &X86::FR64RegClass);
17056 return std::make_pair(0U, &X86::VR128RegClass);
17064 return std::make_pair(0U, &X86::VR256RegClass);
17070 // Use the default implementation in TargetLowering to convert the register
17071 // constraint into a member of a register class.
17072 std::pair<unsigned, const TargetRegisterClass*> Res;
17073 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17075 // Not found as a standard register?
17076 if (Res.second == 0) {
17077 // Map st(0) -> st(7) -> ST0
17078 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17079 tolower(Constraint[1]) == 's' &&
17080 tolower(Constraint[2]) == 't' &&
17081 Constraint[3] == '(' &&
17082 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17083 Constraint[5] == ')' &&
17084 Constraint[6] == '}') {
17086 Res.first = X86::ST0+Constraint[4]-'0';
17087 Res.second = &X86::RFP80RegClass;
17091 // GCC allows "st(0)" to be called just plain "st".
17092 if (StringRef("{st}").equals_lower(Constraint)) {
17093 Res.first = X86::ST0;
17094 Res.second = &X86::RFP80RegClass;
17099 if (StringRef("{flags}").equals_lower(Constraint)) {
17100 Res.first = X86::EFLAGS;
17101 Res.second = &X86::CCRRegClass;
17105 // 'A' means EAX + EDX.
17106 if (Constraint == "A") {
17107 Res.first = X86::EAX;
17108 Res.second = &X86::GR32_ADRegClass;
17114 // Otherwise, check to see if this is a register class of the wrong value
17115 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17116 // turn into {ax},{dx}.
17117 if (Res.second->hasType(VT))
17118 return Res; // Correct type already, nothing to do.
17120 // All of the single-register GCC register classes map their values onto
17121 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17122 // really want an 8-bit or 32-bit register, map to the appropriate register
17123 // class and return the appropriate register.
17124 if (Res.second == &X86::GR16RegClass) {
17125 if (VT == MVT::i8) {
17126 unsigned DestReg = 0;
17127 switch (Res.first) {
17129 case X86::AX: DestReg = X86::AL; break;
17130 case X86::DX: DestReg = X86::DL; break;
17131 case X86::CX: DestReg = X86::CL; break;
17132 case X86::BX: DestReg = X86::BL; break;
17135 Res.first = DestReg;
17136 Res.second = &X86::GR8RegClass;
17138 } else if (VT == MVT::i32) {
17139 unsigned DestReg = 0;
17140 switch (Res.first) {
17142 case X86::AX: DestReg = X86::EAX; break;
17143 case X86::DX: DestReg = X86::EDX; break;
17144 case X86::CX: DestReg = X86::ECX; break;
17145 case X86::BX: DestReg = X86::EBX; break;
17146 case X86::SI: DestReg = X86::ESI; break;
17147 case X86::DI: DestReg = X86::EDI; break;
17148 case X86::BP: DestReg = X86::EBP; break;
17149 case X86::SP: DestReg = X86::ESP; break;
17152 Res.first = DestReg;
17153 Res.second = &X86::GR32RegClass;
17155 } else if (VT == MVT::i64) {
17156 unsigned DestReg = 0;
17157 switch (Res.first) {
17159 case X86::AX: DestReg = X86::RAX; break;
17160 case X86::DX: DestReg = X86::RDX; break;
17161 case X86::CX: DestReg = X86::RCX; break;
17162 case X86::BX: DestReg = X86::RBX; break;
17163 case X86::SI: DestReg = X86::RSI; break;
17164 case X86::DI: DestReg = X86::RDI; break;
17165 case X86::BP: DestReg = X86::RBP; break;
17166 case X86::SP: DestReg = X86::RSP; break;
17169 Res.first = DestReg;
17170 Res.second = &X86::GR64RegClass;
17173 } else if (Res.second == &X86::FR32RegClass ||
17174 Res.second == &X86::FR64RegClass ||
17175 Res.second == &X86::VR128RegClass) {
17176 // Handle references to XMM physical registers that got mapped into the
17177 // wrong class. This can happen with constraints like {xmm0} where the
17178 // target independent register mapper will just pick the first match it can
17179 // find, ignoring the required type.
17181 if (VT == MVT::f32 || VT == MVT::i32)
17182 Res.second = &X86::FR32RegClass;
17183 else if (VT == MVT::f64 || VT == MVT::i64)
17184 Res.second = &X86::FR64RegClass;
17185 else if (X86::VR128RegClass.hasType(VT))
17186 Res.second = &X86::VR128RegClass;
17187 else if (X86::VR256RegClass.hasType(VT))
17188 Res.second = &X86::VR256RegClass;