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"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.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();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, 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 i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
874 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
875 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
876 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
877 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
878 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
879 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
880 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
886 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
905 // Do not attempt to custom lower non-128-bit vectors
906 if (!VT.is128BitVector())
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
920 if (Subtarget->is64Bit()) {
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927 MVT VT = (MVT::SimpleValueType)i;
929 // Do not attempt to promote non-128-bit vectors
930 if (!VT.is128BitVector())
933 setOperationAction(ISD::AND, VT, Promote);
934 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
935 setOperationAction(ISD::OR, VT, Promote);
936 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
937 setOperationAction(ISD::XOR, VT, Promote);
938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
939 setOperationAction(ISD::LOAD, VT, Promote);
940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
941 setOperationAction(ISD::SELECT, VT, Promote);
942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
945 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // Custom lower v2i64 and v2f64 selects.
948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
958 // As there is no 64-bit GPR available, we need build a special custom
959 // sequence to convert from v2i32 to v2f32.
960 if (!Subtarget->is64Bit())
961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
969 if (Subtarget->hasSSE41()) {
970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
973 setOperationAction(ISD::FRINT, MVT::f32, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
976 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
992 // FIXME: Do we need to handle scalar-to-vector here?
993 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1001 // i8 and i16 vectors are custom , because the source register and source
1002 // source memory operand types are not the same width. f32 vectors are
1003 // custom since the immediate controlling the insert encodes additional
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015 // FIXME: these should be Legal but thats only for the case where
1016 // the index is constant. For now custom expand to deal with that.
1017 if (Subtarget->is64Bit()) {
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1023 if (Subtarget->hasSSE2()) {
1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1033 if (Subtarget->hasInt256()) {
1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1052 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1053 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1054 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1060 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1061 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1062 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1064 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1065 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1075 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1078 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1088 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1090 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1092 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1094 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1095 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1096 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1098 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1099 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1100 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1102 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1104 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1105 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1107 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1110 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1111 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1114 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1115 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1116 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1118 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1119 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1120 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1122 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1123 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1124 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1125 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1127 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1128 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1129 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1130 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1131 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1132 setOperationAction(ISD::FMA, MVT::f32, Legal);
1133 setOperationAction(ISD::FMA, MVT::f64, Legal);
1136 if (Subtarget->hasInt256()) {
1137 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1138 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1139 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1140 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1142 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1143 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1144 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1145 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1147 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1148 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1149 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1150 // Don't lower v32i8 because there is no 128-bit byte mul
1152 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1154 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1155 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1157 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1158 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1160 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1162 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1163 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1164 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1165 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1167 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1168 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1169 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1170 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1172 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1173 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1174 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1175 // Don't lower v32i8 because there is no 128-bit byte mul
1177 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1178 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1180 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1181 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1186 // Custom lower several nodes for 256-bit types.
1187 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1188 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1189 MVT VT = (MVT::SimpleValueType)i;
1191 // Extract subvector is special because the value type
1192 // (result) is 128-bit but the source is 256-bit wide.
1193 if (VT.is128BitVector())
1194 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1196 // Do not attempt to custom lower other non-256-bit vectors
1197 if (!VT.is256BitVector())
1200 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1201 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1202 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1203 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1204 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1205 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1206 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1209 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1210 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1211 MVT VT = (MVT::SimpleValueType)i;
1213 // Do not attempt to promote non-256-bit vectors
1214 if (!VT.is256BitVector())
1217 setOperationAction(ISD::AND, VT, Promote);
1218 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1219 setOperationAction(ISD::OR, VT, Promote);
1220 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1221 setOperationAction(ISD::XOR, VT, Promote);
1222 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1223 setOperationAction(ISD::LOAD, VT, Promote);
1224 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1225 setOperationAction(ISD::SELECT, VT, Promote);
1226 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1230 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1231 // of this type with custom code.
1232 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1233 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1234 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1238 // We want to custom lower some of our intrinsics.
1239 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1240 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1242 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1243 // handle type legalization for these operations here.
1245 // FIXME: We really should do custom legalization for addition and
1246 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1247 // than generic legalization for 64-bit multiplication-with-overflow, though.
1248 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1249 // Add/Sub/Mul with overflow operations are custom lowered.
1251 setOperationAction(ISD::SADDO, VT, Custom);
1252 setOperationAction(ISD::UADDO, VT, Custom);
1253 setOperationAction(ISD::SSUBO, VT, Custom);
1254 setOperationAction(ISD::USUBO, VT, Custom);
1255 setOperationAction(ISD::SMULO, VT, Custom);
1256 setOperationAction(ISD::UMULO, VT, Custom);
1259 // There are no 8-bit 3-address imul/mul instructions
1260 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1261 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1263 if (!Subtarget->is64Bit()) {
1264 // These libcalls are not available in 32-bit.
1265 setLibcallName(RTLIB::SHL_I128, 0);
1266 setLibcallName(RTLIB::SRL_I128, 0);
1267 setLibcallName(RTLIB::SRA_I128, 0);
1270 // We have target-specific dag combine patterns for the following nodes:
1271 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1272 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1273 setTargetDAGCombine(ISD::VSELECT);
1274 setTargetDAGCombine(ISD::SELECT);
1275 setTargetDAGCombine(ISD::SHL);
1276 setTargetDAGCombine(ISD::SRA);
1277 setTargetDAGCombine(ISD::SRL);
1278 setTargetDAGCombine(ISD::OR);
1279 setTargetDAGCombine(ISD::AND);
1280 setTargetDAGCombine(ISD::ADD);
1281 setTargetDAGCombine(ISD::FADD);
1282 setTargetDAGCombine(ISD::FSUB);
1283 setTargetDAGCombine(ISD::FMA);
1284 setTargetDAGCombine(ISD::SUB);
1285 setTargetDAGCombine(ISD::LOAD);
1286 setTargetDAGCombine(ISD::STORE);
1287 setTargetDAGCombine(ISD::ZERO_EXTEND);
1288 setTargetDAGCombine(ISD::ANY_EXTEND);
1289 setTargetDAGCombine(ISD::SIGN_EXTEND);
1290 setTargetDAGCombine(ISD::TRUNCATE);
1291 setTargetDAGCombine(ISD::SINT_TO_FP);
1292 setTargetDAGCombine(ISD::SETCC);
1293 if (Subtarget->is64Bit())
1294 setTargetDAGCombine(ISD::MUL);
1295 setTargetDAGCombine(ISD::XOR);
1297 computeRegisterProperties();
1299 // On Darwin, -Os means optimize for size without hurting performance,
1300 // do not reduce the limit.
1301 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1302 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1303 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1304 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1305 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1306 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1307 setPrefLoopAlignment(4); // 2^4 bytes.
1308 benefitFromCodePlacementOpt = true;
1310 // Predictable cmov don't hurt on atom because it's in-order.
1311 predictableSelectIsExpensive = !Subtarget->isAtom();
1313 setPrefFunctionAlignment(4); // 2^4 bytes.
1316 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1317 if (!VT.isVector()) return MVT::i8;
1318 return VT.changeVectorElementTypeToInteger();
1321 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1322 /// the desired ByVal argument alignment.
1323 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1326 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1327 if (VTy->getBitWidth() == 128)
1329 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1330 unsigned EltAlign = 0;
1331 getMaxByValAlign(ATy->getElementType(), EltAlign);
1332 if (EltAlign > MaxAlign)
1333 MaxAlign = EltAlign;
1334 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1335 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1336 unsigned EltAlign = 0;
1337 getMaxByValAlign(STy->getElementType(i), EltAlign);
1338 if (EltAlign > MaxAlign)
1339 MaxAlign = EltAlign;
1346 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1347 /// function arguments in the caller parameter area. For X86, aggregates
1348 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1349 /// are at 4-byte boundaries.
1350 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1351 if (Subtarget->is64Bit()) {
1352 // Max of 8 and alignment of type.
1353 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1360 if (Subtarget->hasSSE1())
1361 getMaxByValAlign(Ty, Align);
1365 /// getOptimalMemOpType - Returns the target specific optimal type for load
1366 /// and store operations as a result of memset, memcpy, and memmove
1367 /// lowering. If DstAlign is zero that means it's safe to destination
1368 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1369 /// means there isn't a need to check it against alignment requirement,
1370 /// probably because the source does not need to be loaded. If 'IsMemset' is
1371 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1372 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1373 /// source is constant so it does not need to be loaded.
1374 /// It returns EVT::Other if the type should be determined using generic
1375 /// target-independent logic.
1377 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1378 unsigned DstAlign, unsigned SrcAlign,
1379 bool IsMemset, bool ZeroMemset,
1381 MachineFunction &MF) const {
1382 const Function *F = MF.getFunction();
1383 if ((!IsMemset || ZeroMemset) &&
1384 !F->getFnAttributes().hasAttribute(Attribute::NoImplicitFloat)) {
1386 (Subtarget->isUnalignedMemAccessFast() ||
1387 ((DstAlign == 0 || DstAlign >= 16) &&
1388 (SrcAlign == 0 || SrcAlign >= 16)))) {
1390 if (Subtarget->hasInt256())
1392 if (Subtarget->hasFp256())
1395 if (Subtarget->hasSSE2())
1397 if (Subtarget->hasSSE1())
1399 } else if (!MemcpyStrSrc && Size >= 8 &&
1400 !Subtarget->is64Bit() &&
1401 Subtarget->hasSSE2()) {
1402 // Do not use f64 to lower memcpy if source is string constant. It's
1403 // better to use i32 to avoid the loads.
1407 if (Subtarget->is64Bit() && Size >= 8)
1412 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1414 return X86ScalarSSEf32;
1415 else if (VT == MVT::f64)
1416 return X86ScalarSSEf64;
1421 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1423 *Fast = Subtarget->isUnalignedMemAccessFast();
1427 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1428 /// current function. The returned value is a member of the
1429 /// MachineJumpTableInfo::JTEntryKind enum.
1430 unsigned X86TargetLowering::getJumpTableEncoding() const {
1431 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1433 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1434 Subtarget->isPICStyleGOT())
1435 return MachineJumpTableInfo::EK_Custom32;
1437 // Otherwise, use the normal jump table encoding heuristics.
1438 return TargetLowering::getJumpTableEncoding();
1442 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1443 const MachineBasicBlock *MBB,
1444 unsigned uid,MCContext &Ctx) const{
1445 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1446 Subtarget->isPICStyleGOT());
1447 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1449 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1450 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1453 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1455 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1456 SelectionDAG &DAG) const {
1457 if (!Subtarget->is64Bit())
1458 // This doesn't have DebugLoc associated with it, but is not really the
1459 // same as a Register.
1460 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1464 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1465 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1467 const MCExpr *X86TargetLowering::
1468 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1469 MCContext &Ctx) const {
1470 // X86-64 uses RIP relative addressing based on the jump table label.
1471 if (Subtarget->isPICStyleRIPRel())
1472 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1474 // Otherwise, the reference is relative to the PIC base.
1475 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1478 // FIXME: Why this routine is here? Move to RegInfo!
1479 std::pair<const TargetRegisterClass*, uint8_t>
1480 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1481 const TargetRegisterClass *RRC = 0;
1483 switch (VT.SimpleTy) {
1485 return TargetLowering::findRepresentativeClass(VT);
1486 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1487 RRC = Subtarget->is64Bit() ?
1488 (const TargetRegisterClass*)&X86::GR64RegClass :
1489 (const TargetRegisterClass*)&X86::GR32RegClass;
1492 RRC = &X86::VR64RegClass;
1494 case MVT::f32: case MVT::f64:
1495 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1496 case MVT::v4f32: case MVT::v2f64:
1497 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1499 RRC = &X86::VR128RegClass;
1502 return std::make_pair(RRC, Cost);
1505 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1506 unsigned &Offset) const {
1507 if (!Subtarget->isTargetLinux())
1510 if (Subtarget->is64Bit()) {
1511 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1513 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1525 //===----------------------------------------------------------------------===//
1526 // Return Value Calling Convention Implementation
1527 //===----------------------------------------------------------------------===//
1529 #include "X86GenCallingConv.inc"
1532 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1533 MachineFunction &MF, bool isVarArg,
1534 const SmallVectorImpl<ISD::OutputArg> &Outs,
1535 LLVMContext &Context) const {
1536 SmallVector<CCValAssign, 16> RVLocs;
1537 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1539 return CCInfo.CheckReturn(Outs, RetCC_X86);
1543 X86TargetLowering::LowerReturn(SDValue Chain,
1544 CallingConv::ID CallConv, bool isVarArg,
1545 const SmallVectorImpl<ISD::OutputArg> &Outs,
1546 const SmallVectorImpl<SDValue> &OutVals,
1547 DebugLoc dl, SelectionDAG &DAG) const {
1548 MachineFunction &MF = DAG.getMachineFunction();
1549 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1551 SmallVector<CCValAssign, 16> RVLocs;
1552 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1553 RVLocs, *DAG.getContext());
1554 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1556 // Add the regs to the liveout set for the function.
1557 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1558 for (unsigned i = 0; i != RVLocs.size(); ++i)
1559 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1560 MRI.addLiveOut(RVLocs[i].getLocReg());
1564 SmallVector<SDValue, 6> RetOps;
1565 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1566 // Operand #1 = Bytes To Pop
1567 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1570 // Copy the result values into the output registers.
1571 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1572 CCValAssign &VA = RVLocs[i];
1573 assert(VA.isRegLoc() && "Can only return in registers!");
1574 SDValue ValToCopy = OutVals[i];
1575 EVT ValVT = ValToCopy.getValueType();
1577 // Promote values to the appropriate types
1578 if (VA.getLocInfo() == CCValAssign::SExt)
1579 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1580 else if (VA.getLocInfo() == CCValAssign::ZExt)
1581 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1582 else if (VA.getLocInfo() == CCValAssign::AExt)
1583 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1584 else if (VA.getLocInfo() == CCValAssign::BCvt)
1585 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1587 // If this is x86-64, and we disabled SSE, we can't return FP values,
1588 // or SSE or MMX vectors.
1589 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1590 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1591 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1592 report_fatal_error("SSE register return with SSE disabled");
1594 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1595 // llvm-gcc has never done it right and no one has noticed, so this
1596 // should be OK for now.
1597 if (ValVT == MVT::f64 &&
1598 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1599 report_fatal_error("SSE2 register return with SSE2 disabled");
1601 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1602 // the RET instruction and handled by the FP Stackifier.
1603 if (VA.getLocReg() == X86::ST0 ||
1604 VA.getLocReg() == X86::ST1) {
1605 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1606 // change the value to the FP stack register class.
1607 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1608 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1609 RetOps.push_back(ValToCopy);
1610 // Don't emit a copytoreg.
1614 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1615 // which is returned in RAX / RDX.
1616 if (Subtarget->is64Bit()) {
1617 if (ValVT == MVT::x86mmx) {
1618 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1619 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1620 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1622 // If we don't have SSE2 available, convert to v4f32 so the generated
1623 // register is legal.
1624 if (!Subtarget->hasSSE2())
1625 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1630 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1631 Flag = Chain.getValue(1);
1634 // The x86-64 ABI for returning structs by value requires that we copy
1635 // the sret argument into %rax for the return. We saved the argument into
1636 // a virtual register in the entry block, so now we copy the value out
1638 if (Subtarget->is64Bit() &&
1639 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1640 MachineFunction &MF = DAG.getMachineFunction();
1641 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1642 unsigned Reg = FuncInfo->getSRetReturnReg();
1644 "SRetReturnReg should have been set in LowerFormalArguments().");
1645 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1647 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1648 Flag = Chain.getValue(1);
1650 // RAX now acts like a return value.
1651 MRI.addLiveOut(X86::RAX);
1654 RetOps[0] = Chain; // Update chain.
1656 // Add the flag if we have it.
1658 RetOps.push_back(Flag);
1660 return DAG.getNode(X86ISD::RET_FLAG, dl,
1661 MVT::Other, &RetOps[0], RetOps.size());
1664 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1665 if (N->getNumValues() != 1)
1667 if (!N->hasNUsesOfValue(1, 0))
1670 SDValue TCChain = Chain;
1671 SDNode *Copy = *N->use_begin();
1672 if (Copy->getOpcode() == ISD::CopyToReg) {
1673 // If the copy has a glue operand, we conservatively assume it isn't safe to
1674 // perform a tail call.
1675 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1677 TCChain = Copy->getOperand(0);
1678 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1681 bool HasRet = false;
1682 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1684 if (UI->getOpcode() != X86ISD::RET_FLAG)
1697 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1698 ISD::NodeType ExtendKind) const {
1700 // TODO: Is this also valid on 32-bit?
1701 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1702 ReturnMVT = MVT::i8;
1704 ReturnMVT = MVT::i32;
1706 MVT MinVT = getRegisterType(ReturnMVT);
1707 return VT.bitsLT(MinVT) ? MinVT : VT;
1710 /// LowerCallResult - Lower the result values of a call into the
1711 /// appropriate copies out of appropriate physical registers.
1714 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1715 CallingConv::ID CallConv, bool isVarArg,
1716 const SmallVectorImpl<ISD::InputArg> &Ins,
1717 DebugLoc dl, SelectionDAG &DAG,
1718 SmallVectorImpl<SDValue> &InVals) const {
1720 // Assign locations to each value returned by this call.
1721 SmallVector<CCValAssign, 16> RVLocs;
1722 bool Is64Bit = Subtarget->is64Bit();
1723 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1724 getTargetMachine(), RVLocs, *DAG.getContext());
1725 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1727 // Copy all of the result registers out of their specified physreg.
1728 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1729 CCValAssign &VA = RVLocs[i];
1730 EVT CopyVT = VA.getValVT();
1732 // If this is x86-64, and we disabled SSE, we can't return FP values
1733 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1734 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1735 report_fatal_error("SSE register return with SSE disabled");
1740 // If this is a call to a function that returns an fp value on the floating
1741 // point stack, we must guarantee the value is popped from the stack, so
1742 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1743 // if the return value is not used. We use the FpPOP_RETVAL instruction
1745 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1746 // If we prefer to use the value in xmm registers, copy it out as f80 and
1747 // use a truncate to move it from fp stack reg to xmm reg.
1748 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1749 SDValue Ops[] = { Chain, InFlag };
1750 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1751 MVT::Other, MVT::Glue, Ops, 2), 1);
1752 Val = Chain.getValue(0);
1754 // Round the f80 to the right size, which also moves it to the appropriate
1756 if (CopyVT != VA.getValVT())
1757 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1758 // This truncation won't change the value.
1759 DAG.getIntPtrConstant(1));
1761 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1762 CopyVT, InFlag).getValue(1);
1763 Val = Chain.getValue(0);
1765 InFlag = Chain.getValue(2);
1766 InVals.push_back(Val);
1772 //===----------------------------------------------------------------------===//
1773 // C & StdCall & Fast Calling Convention implementation
1774 //===----------------------------------------------------------------------===//
1775 // StdCall calling convention seems to be standard for many Windows' API
1776 // routines and around. It differs from C calling convention just a little:
1777 // callee should clean up the stack, not caller. Symbols should be also
1778 // decorated in some fancy way :) It doesn't support any vector arguments.
1779 // For info on fast calling convention see Fast Calling Convention (tail call)
1780 // implementation LowerX86_32FastCCCallTo.
1782 /// CallIsStructReturn - Determines whether a call uses struct return
1784 enum StructReturnType {
1789 static StructReturnType
1790 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1792 return NotStructReturn;
1794 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1795 if (!Flags.isSRet())
1796 return NotStructReturn;
1797 if (Flags.isInReg())
1798 return RegStructReturn;
1799 return StackStructReturn;
1802 /// ArgsAreStructReturn - Determines whether a function uses struct
1803 /// return semantics.
1804 static StructReturnType
1805 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1807 return NotStructReturn;
1809 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1810 if (!Flags.isSRet())
1811 return NotStructReturn;
1812 if (Flags.isInReg())
1813 return RegStructReturn;
1814 return StackStructReturn;
1817 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1818 /// by "Src" to address "Dst" with size and alignment information specified by
1819 /// the specific parameter attribute. The copy will be passed as a byval
1820 /// function parameter.
1822 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1823 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1825 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1827 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1828 /*isVolatile*/false, /*AlwaysInline=*/true,
1829 MachinePointerInfo(), MachinePointerInfo());
1832 /// IsTailCallConvention - Return true if the calling convention is one that
1833 /// supports tail call optimization.
1834 static bool IsTailCallConvention(CallingConv::ID CC) {
1835 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1836 CC == CallingConv::HiPE);
1839 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1840 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1844 CallingConv::ID CalleeCC = CS.getCallingConv();
1845 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1851 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1852 /// a tailcall target by changing its ABI.
1853 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1854 bool GuaranteedTailCallOpt) {
1855 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1859 X86TargetLowering::LowerMemArgument(SDValue Chain,
1860 CallingConv::ID CallConv,
1861 const SmallVectorImpl<ISD::InputArg> &Ins,
1862 DebugLoc dl, SelectionDAG &DAG,
1863 const CCValAssign &VA,
1864 MachineFrameInfo *MFI,
1866 // Create the nodes corresponding to a load from this parameter slot.
1867 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1868 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1869 getTargetMachine().Options.GuaranteedTailCallOpt);
1870 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1873 // If value is passed by pointer we have address passed instead of the value
1875 if (VA.getLocInfo() == CCValAssign::Indirect)
1876 ValVT = VA.getLocVT();
1878 ValVT = VA.getValVT();
1880 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1881 // changed with more analysis.
1882 // In case of tail call optimization mark all arguments mutable. Since they
1883 // could be overwritten by lowering of arguments in case of a tail call.
1884 if (Flags.isByVal()) {
1885 unsigned Bytes = Flags.getByValSize();
1886 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1887 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1888 return DAG.getFrameIndex(FI, getPointerTy());
1890 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1891 VA.getLocMemOffset(), isImmutable);
1892 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1893 return DAG.getLoad(ValVT, dl, Chain, FIN,
1894 MachinePointerInfo::getFixedStack(FI),
1895 false, false, false, 0);
1900 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1901 CallingConv::ID CallConv,
1903 const SmallVectorImpl<ISD::InputArg> &Ins,
1906 SmallVectorImpl<SDValue> &InVals)
1908 MachineFunction &MF = DAG.getMachineFunction();
1909 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1911 const Function* Fn = MF.getFunction();
1912 if (Fn->hasExternalLinkage() &&
1913 Subtarget->isTargetCygMing() &&
1914 Fn->getName() == "main")
1915 FuncInfo->setForceFramePointer(true);
1917 MachineFrameInfo *MFI = MF.getFrameInfo();
1918 bool Is64Bit = Subtarget->is64Bit();
1919 bool IsWindows = Subtarget->isTargetWindows();
1920 bool IsWin64 = Subtarget->isTargetWin64();
1922 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1923 "Var args not supported with calling convention fastcc, ghc or hipe");
1925 // Assign locations to all of the incoming arguments.
1926 SmallVector<CCValAssign, 16> ArgLocs;
1927 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1928 ArgLocs, *DAG.getContext());
1930 // Allocate shadow area for Win64
1932 CCInfo.AllocateStack(32, 8);
1935 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1937 unsigned LastVal = ~0U;
1939 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1940 CCValAssign &VA = ArgLocs[i];
1941 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1943 assert(VA.getValNo() != LastVal &&
1944 "Don't support value assigned to multiple locs yet");
1946 LastVal = VA.getValNo();
1948 if (VA.isRegLoc()) {
1949 EVT RegVT = VA.getLocVT();
1950 const TargetRegisterClass *RC;
1951 if (RegVT == MVT::i32)
1952 RC = &X86::GR32RegClass;
1953 else if (Is64Bit && RegVT == MVT::i64)
1954 RC = &X86::GR64RegClass;
1955 else if (RegVT == MVT::f32)
1956 RC = &X86::FR32RegClass;
1957 else if (RegVT == MVT::f64)
1958 RC = &X86::FR64RegClass;
1959 else if (RegVT.is256BitVector())
1960 RC = &X86::VR256RegClass;
1961 else if (RegVT.is128BitVector())
1962 RC = &X86::VR128RegClass;
1963 else if (RegVT == MVT::x86mmx)
1964 RC = &X86::VR64RegClass;
1966 llvm_unreachable("Unknown argument type!");
1968 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1969 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1971 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1972 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1974 if (VA.getLocInfo() == CCValAssign::SExt)
1975 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1976 DAG.getValueType(VA.getValVT()));
1977 else if (VA.getLocInfo() == CCValAssign::ZExt)
1978 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1979 DAG.getValueType(VA.getValVT()));
1980 else if (VA.getLocInfo() == CCValAssign::BCvt)
1981 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1983 if (VA.isExtInLoc()) {
1984 // Handle MMX values passed in XMM regs.
1985 if (RegVT.isVector()) {
1986 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1989 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1992 assert(VA.isMemLoc());
1993 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1996 // If value is passed via pointer - do a load.
1997 if (VA.getLocInfo() == CCValAssign::Indirect)
1998 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1999 MachinePointerInfo(), false, false, false, 0);
2001 InVals.push_back(ArgValue);
2004 // The x86-64 ABI for returning structs by value requires that we copy
2005 // the sret argument into %rax for the return. Save the argument into
2006 // a virtual register so that we can access it from the return points.
2007 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2008 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2009 unsigned Reg = FuncInfo->getSRetReturnReg();
2011 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2012 FuncInfo->setSRetReturnReg(Reg);
2014 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2015 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2018 unsigned StackSize = CCInfo.getNextStackOffset();
2019 // Align stack specially for tail calls.
2020 if (FuncIsMadeTailCallSafe(CallConv,
2021 MF.getTarget().Options.GuaranteedTailCallOpt))
2022 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2024 // If the function takes variable number of arguments, make a frame index for
2025 // the start of the first vararg value... for expansion of llvm.va_start.
2027 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2028 CallConv != CallingConv::X86_ThisCall)) {
2029 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2032 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2034 // FIXME: We should really autogenerate these arrays
2035 static const uint16_t GPR64ArgRegsWin64[] = {
2036 X86::RCX, X86::RDX, X86::R8, X86::R9
2038 static const uint16_t GPR64ArgRegs64Bit[] = {
2039 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2041 static const uint16_t XMMArgRegs64Bit[] = {
2042 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2045 const uint16_t *GPR64ArgRegs;
2046 unsigned NumXMMRegs = 0;
2049 // The XMM registers which might contain var arg parameters are shadowed
2050 // in their paired GPR. So we only need to save the GPR to their home
2052 TotalNumIntRegs = 4;
2053 GPR64ArgRegs = GPR64ArgRegsWin64;
2055 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2056 GPR64ArgRegs = GPR64ArgRegs64Bit;
2058 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2061 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2064 bool NoImplicitFloatOps = Fn->getFnAttributes().
2065 hasAttribute(Attribute::NoImplicitFloat);
2066 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2067 "SSE register cannot be used when SSE is disabled!");
2068 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2069 NoImplicitFloatOps) &&
2070 "SSE register cannot be used when SSE is disabled!");
2071 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2072 !Subtarget->hasSSE1())
2073 // Kernel mode asks for SSE to be disabled, so don't push them
2075 TotalNumXMMRegs = 0;
2078 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2079 // Get to the caller-allocated home save location. Add 8 to account
2080 // for the return address.
2081 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2082 FuncInfo->setRegSaveFrameIndex(
2083 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2084 // Fixup to set vararg frame on shadow area (4 x i64).
2086 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2088 // For X86-64, if there are vararg parameters that are passed via
2089 // registers, then we must store them to their spots on the stack so
2090 // they may be loaded by deferencing the result of va_next.
2091 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2092 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2093 FuncInfo->setRegSaveFrameIndex(
2094 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2098 // Store the integer parameter registers.
2099 SmallVector<SDValue, 8> MemOps;
2100 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2102 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2103 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2104 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2105 DAG.getIntPtrConstant(Offset));
2106 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2107 &X86::GR64RegClass);
2108 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2110 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2111 MachinePointerInfo::getFixedStack(
2112 FuncInfo->getRegSaveFrameIndex(), Offset),
2114 MemOps.push_back(Store);
2118 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2119 // Now store the XMM (fp + vector) parameter registers.
2120 SmallVector<SDValue, 11> SaveXMMOps;
2121 SaveXMMOps.push_back(Chain);
2123 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2124 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2125 SaveXMMOps.push_back(ALVal);
2127 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2128 FuncInfo->getRegSaveFrameIndex()));
2129 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2130 FuncInfo->getVarArgsFPOffset()));
2132 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2133 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2134 &X86::VR128RegClass);
2135 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2136 SaveXMMOps.push_back(Val);
2138 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2140 &SaveXMMOps[0], SaveXMMOps.size()));
2143 if (!MemOps.empty())
2144 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2145 &MemOps[0], MemOps.size());
2149 // Some CCs need callee pop.
2150 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2151 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2152 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2154 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2155 // If this is an sret function, the return should pop the hidden pointer.
2156 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2157 argsAreStructReturn(Ins) == StackStructReturn)
2158 FuncInfo->setBytesToPopOnReturn(4);
2162 // RegSaveFrameIndex is X86-64 only.
2163 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2164 if (CallConv == CallingConv::X86_FastCall ||
2165 CallConv == CallingConv::X86_ThisCall)
2166 // fastcc functions can't have varargs.
2167 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2170 FuncInfo->setArgumentStackSize(StackSize);
2176 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2177 SDValue StackPtr, SDValue Arg,
2178 DebugLoc dl, SelectionDAG &DAG,
2179 const CCValAssign &VA,
2180 ISD::ArgFlagsTy Flags) const {
2181 unsigned LocMemOffset = VA.getLocMemOffset();
2182 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2183 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2184 if (Flags.isByVal())
2185 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2187 return DAG.getStore(Chain, dl, Arg, PtrOff,
2188 MachinePointerInfo::getStack(LocMemOffset),
2192 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2193 /// optimization is performed and it is required.
2195 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2196 SDValue &OutRetAddr, SDValue Chain,
2197 bool IsTailCall, bool Is64Bit,
2198 int FPDiff, DebugLoc dl) const {
2199 // Adjust the Return address stack slot.
2200 EVT VT = getPointerTy();
2201 OutRetAddr = getReturnAddressFrameIndex(DAG);
2203 // Load the "old" Return address.
2204 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2205 false, false, false, 0);
2206 return SDValue(OutRetAddr.getNode(), 1);
2209 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2210 /// optimization is performed and it is required (FPDiff!=0).
2212 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2213 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2214 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2215 // Store the return address to the appropriate stack slot.
2216 if (!FPDiff) return Chain;
2217 // Calculate the new stack slot for the return address.
2218 int NewReturnAddrFI =
2219 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2220 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2221 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2222 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2228 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2229 SmallVectorImpl<SDValue> &InVals) const {
2230 SelectionDAG &DAG = CLI.DAG;
2231 DebugLoc &dl = CLI.DL;
2232 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2233 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2234 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2235 SDValue Chain = CLI.Chain;
2236 SDValue Callee = CLI.Callee;
2237 CallingConv::ID CallConv = CLI.CallConv;
2238 bool &isTailCall = CLI.IsTailCall;
2239 bool isVarArg = CLI.IsVarArg;
2241 MachineFunction &MF = DAG.getMachineFunction();
2242 bool Is64Bit = Subtarget->is64Bit();
2243 bool IsWin64 = Subtarget->isTargetWin64();
2244 bool IsWindows = Subtarget->isTargetWindows();
2245 StructReturnType SR = callIsStructReturn(Outs);
2246 bool IsSibcall = false;
2248 if (MF.getTarget().Options.DisableTailCalls)
2252 // Check if it's really possible to do a tail call.
2253 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2254 isVarArg, SR != NotStructReturn,
2255 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2256 Outs, OutVals, Ins, DAG);
2258 // Sibcalls are automatically detected tailcalls which do not require
2260 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2267 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2268 "Var args not supported with calling convention fastcc, ghc or hipe");
2270 // Analyze operands of the call, assigning locations to each operand.
2271 SmallVector<CCValAssign, 16> ArgLocs;
2272 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2273 ArgLocs, *DAG.getContext());
2275 // Allocate shadow area for Win64
2277 CCInfo.AllocateStack(32, 8);
2280 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2282 // Get a count of how many bytes are to be pushed on the stack.
2283 unsigned NumBytes = CCInfo.getNextStackOffset();
2285 // This is a sibcall. The memory operands are available in caller's
2286 // own caller's stack.
2288 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2289 IsTailCallConvention(CallConv))
2290 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2293 if (isTailCall && !IsSibcall) {
2294 // Lower arguments at fp - stackoffset + fpdiff.
2295 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2296 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2298 FPDiff = NumBytesCallerPushed - NumBytes;
2300 // Set the delta of movement of the returnaddr stackslot.
2301 // But only set if delta is greater than previous delta.
2302 if (FPDiff < X86Info->getTCReturnAddrDelta())
2303 X86Info->setTCReturnAddrDelta(FPDiff);
2307 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2309 SDValue RetAddrFrIdx;
2310 // Load return address for tail calls.
2311 if (isTailCall && FPDiff)
2312 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2313 Is64Bit, FPDiff, dl);
2315 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2316 SmallVector<SDValue, 8> MemOpChains;
2319 // Walk the register/memloc assignments, inserting copies/loads. In the case
2320 // of tail call optimization arguments are handle later.
2321 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2322 CCValAssign &VA = ArgLocs[i];
2323 EVT RegVT = VA.getLocVT();
2324 SDValue Arg = OutVals[i];
2325 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2326 bool isByVal = Flags.isByVal();
2328 // Promote the value if needed.
2329 switch (VA.getLocInfo()) {
2330 default: llvm_unreachable("Unknown loc info!");
2331 case CCValAssign::Full: break;
2332 case CCValAssign::SExt:
2333 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2335 case CCValAssign::ZExt:
2336 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2338 case CCValAssign::AExt:
2339 if (RegVT.is128BitVector()) {
2340 // Special case: passing MMX values in XMM registers.
2341 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2342 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2343 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2345 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2347 case CCValAssign::BCvt:
2348 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2350 case CCValAssign::Indirect: {
2351 // Store the argument.
2352 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2353 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2354 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2355 MachinePointerInfo::getFixedStack(FI),
2362 if (VA.isRegLoc()) {
2363 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2364 if (isVarArg && IsWin64) {
2365 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2366 // shadow reg if callee is a varargs function.
2367 unsigned ShadowReg = 0;
2368 switch (VA.getLocReg()) {
2369 case X86::XMM0: ShadowReg = X86::RCX; break;
2370 case X86::XMM1: ShadowReg = X86::RDX; break;
2371 case X86::XMM2: ShadowReg = X86::R8; break;
2372 case X86::XMM3: ShadowReg = X86::R9; break;
2375 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2377 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2378 assert(VA.isMemLoc());
2379 if (StackPtr.getNode() == 0)
2380 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2382 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2383 dl, DAG, VA, Flags));
2387 if (!MemOpChains.empty())
2388 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2389 &MemOpChains[0], MemOpChains.size());
2391 if (Subtarget->isPICStyleGOT()) {
2392 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2395 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2396 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2398 // If we are tail calling and generating PIC/GOT style code load the
2399 // address of the callee into ECX. The value in ecx is used as target of
2400 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2401 // for tail calls on PIC/GOT architectures. Normally we would just put the
2402 // address of GOT into ebx and then call target@PLT. But for tail calls
2403 // ebx would be restored (since ebx is callee saved) before jumping to the
2406 // Note: The actual moving to ECX is done further down.
2407 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2408 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2409 !G->getGlobal()->hasProtectedVisibility())
2410 Callee = LowerGlobalAddress(Callee, DAG);
2411 else if (isa<ExternalSymbolSDNode>(Callee))
2412 Callee = LowerExternalSymbol(Callee, DAG);
2416 if (Is64Bit && isVarArg && !IsWin64) {
2417 // From AMD64 ABI document:
2418 // For calls that may call functions that use varargs or stdargs
2419 // (prototype-less calls or calls to functions containing ellipsis (...) in
2420 // the declaration) %al is used as hidden argument to specify the number
2421 // of SSE registers used. The contents of %al do not need to match exactly
2422 // the number of registers, but must be an ubound on the number of SSE
2423 // registers used and is in the range 0 - 8 inclusive.
2425 // Count the number of XMM registers allocated.
2426 static const uint16_t XMMArgRegs[] = {
2427 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2428 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2430 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2431 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2432 && "SSE registers cannot be used when SSE is disabled");
2434 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2435 DAG.getConstant(NumXMMRegs, MVT::i8)));
2438 // For tail calls lower the arguments to the 'real' stack slot.
2440 // Force all the incoming stack arguments to be loaded from the stack
2441 // before any new outgoing arguments are stored to the stack, because the
2442 // outgoing stack slots may alias the incoming argument stack slots, and
2443 // the alias isn't otherwise explicit. This is slightly more conservative
2444 // than necessary, because it means that each store effectively depends
2445 // on every argument instead of just those arguments it would clobber.
2446 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2448 SmallVector<SDValue, 8> MemOpChains2;
2451 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2452 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2453 CCValAssign &VA = ArgLocs[i];
2456 assert(VA.isMemLoc());
2457 SDValue Arg = OutVals[i];
2458 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2459 // Create frame index.
2460 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2461 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2462 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2463 FIN = DAG.getFrameIndex(FI, getPointerTy());
2465 if (Flags.isByVal()) {
2466 // Copy relative to framepointer.
2467 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2468 if (StackPtr.getNode() == 0)
2469 StackPtr = DAG.getCopyFromReg(Chain, dl,
2470 RegInfo->getStackRegister(),
2472 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2474 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2478 // Store relative to framepointer.
2479 MemOpChains2.push_back(
2480 DAG.getStore(ArgChain, dl, Arg, FIN,
2481 MachinePointerInfo::getFixedStack(FI),
2487 if (!MemOpChains2.empty())
2488 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2489 &MemOpChains2[0], MemOpChains2.size());
2491 // Store the return address to the appropriate stack slot.
2492 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2493 getPointerTy(), RegInfo->getSlotSize(),
2497 // Build a sequence of copy-to-reg nodes chained together with token chain
2498 // and flag operands which copy the outgoing args into registers.
2500 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2501 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2502 RegsToPass[i].second, InFlag);
2503 InFlag = Chain.getValue(1);
2506 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2507 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2508 // In the 64-bit large code model, we have to make all calls
2509 // through a register, since the call instruction's 32-bit
2510 // pc-relative offset may not be large enough to hold the whole
2512 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2513 // If the callee is a GlobalAddress node (quite common, every direct call
2514 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2517 // We should use extra load for direct calls to dllimported functions in
2519 const GlobalValue *GV = G->getGlobal();
2520 if (!GV->hasDLLImportLinkage()) {
2521 unsigned char OpFlags = 0;
2522 bool ExtraLoad = false;
2523 unsigned WrapperKind = ISD::DELETED_NODE;
2525 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2526 // external symbols most go through the PLT in PIC mode. If the symbol
2527 // has hidden or protected visibility, or if it is static or local, then
2528 // we don't need to use the PLT - we can directly call it.
2529 if (Subtarget->isTargetELF() &&
2530 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2531 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2532 OpFlags = X86II::MO_PLT;
2533 } else if (Subtarget->isPICStyleStubAny() &&
2534 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2535 (!Subtarget->getTargetTriple().isMacOSX() ||
2536 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2537 // PC-relative references to external symbols should go through $stub,
2538 // unless we're building with the leopard linker or later, which
2539 // automatically synthesizes these stubs.
2540 OpFlags = X86II::MO_DARWIN_STUB;
2541 } else if (Subtarget->isPICStyleRIPRel() &&
2542 isa<Function>(GV) &&
2543 cast<Function>(GV)->getFnAttributes().
2544 hasAttribute(Attribute::NonLazyBind)) {
2545 // If the function is marked as non-lazy, generate an indirect call
2546 // which loads from the GOT directly. This avoids runtime overhead
2547 // at the cost of eager binding (and one extra byte of encoding).
2548 OpFlags = X86II::MO_GOTPCREL;
2549 WrapperKind = X86ISD::WrapperRIP;
2553 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2554 G->getOffset(), OpFlags);
2556 // Add a wrapper if needed.
2557 if (WrapperKind != ISD::DELETED_NODE)
2558 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2559 // Add extra indirection if needed.
2561 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2562 MachinePointerInfo::getGOT(),
2563 false, false, false, 0);
2565 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2566 unsigned char OpFlags = 0;
2568 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2569 // external symbols should go through the PLT.
2570 if (Subtarget->isTargetELF() &&
2571 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2572 OpFlags = X86II::MO_PLT;
2573 } else if (Subtarget->isPICStyleStubAny() &&
2574 (!Subtarget->getTargetTriple().isMacOSX() ||
2575 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2576 // PC-relative references to external symbols should go through $stub,
2577 // unless we're building with the leopard linker or later, which
2578 // automatically synthesizes these stubs.
2579 OpFlags = X86II::MO_DARWIN_STUB;
2582 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2586 // Returns a chain & a flag for retval copy to use.
2587 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2588 SmallVector<SDValue, 8> Ops;
2590 if (!IsSibcall && isTailCall) {
2591 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2592 DAG.getIntPtrConstant(0, true), InFlag);
2593 InFlag = Chain.getValue(1);
2596 Ops.push_back(Chain);
2597 Ops.push_back(Callee);
2600 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2602 // Add argument registers to the end of the list so that they are known live
2604 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2605 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2606 RegsToPass[i].second.getValueType()));
2608 // Add a register mask operand representing the call-preserved registers.
2609 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2610 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2611 assert(Mask && "Missing call preserved mask for calling convention");
2612 Ops.push_back(DAG.getRegisterMask(Mask));
2614 if (InFlag.getNode())
2615 Ops.push_back(InFlag);
2619 //// If this is the first return lowered for this function, add the regs
2620 //// to the liveout set for the function.
2621 // This isn't right, although it's probably harmless on x86; liveouts
2622 // should be computed from returns not tail calls. Consider a void
2623 // function making a tail call to a function returning int.
2624 return DAG.getNode(X86ISD::TC_RETURN, dl,
2625 NodeTys, &Ops[0], Ops.size());
2628 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2629 InFlag = Chain.getValue(1);
2631 // Create the CALLSEQ_END node.
2632 unsigned NumBytesForCalleeToPush;
2633 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2634 getTargetMachine().Options.GuaranteedTailCallOpt))
2635 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2636 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2637 SR == StackStructReturn)
2638 // If this is a call to a struct-return function, the callee
2639 // pops the hidden struct pointer, so we have to push it back.
2640 // This is common for Darwin/X86, Linux & Mingw32 targets.
2641 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2642 NumBytesForCalleeToPush = 4;
2644 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2646 // Returns a flag for retval copy to use.
2648 Chain = DAG.getCALLSEQ_END(Chain,
2649 DAG.getIntPtrConstant(NumBytes, true),
2650 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2653 InFlag = Chain.getValue(1);
2656 // Handle result values, copying them out of physregs into vregs that we
2658 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2659 Ins, dl, DAG, InVals);
2662 //===----------------------------------------------------------------------===//
2663 // Fast Calling Convention (tail call) implementation
2664 //===----------------------------------------------------------------------===//
2666 // Like std call, callee cleans arguments, convention except that ECX is
2667 // reserved for storing the tail called function address. Only 2 registers are
2668 // free for argument passing (inreg). Tail call optimization is performed
2670 // * tailcallopt is enabled
2671 // * caller/callee are fastcc
2672 // On X86_64 architecture with GOT-style position independent code only local
2673 // (within module) calls are supported at the moment.
2674 // To keep the stack aligned according to platform abi the function
2675 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2676 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2677 // If a tail called function callee has more arguments than the caller the
2678 // caller needs to make sure that there is room to move the RETADDR to. This is
2679 // achieved by reserving an area the size of the argument delta right after the
2680 // original REtADDR, but before the saved framepointer or the spilled registers
2681 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2693 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2694 /// for a 16 byte align requirement.
2696 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2697 SelectionDAG& DAG) const {
2698 MachineFunction &MF = DAG.getMachineFunction();
2699 const TargetMachine &TM = MF.getTarget();
2700 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2701 unsigned StackAlignment = TFI.getStackAlignment();
2702 uint64_t AlignMask = StackAlignment - 1;
2703 int64_t Offset = StackSize;
2704 unsigned SlotSize = RegInfo->getSlotSize();
2705 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2706 // Number smaller than 12 so just add the difference.
2707 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2709 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2710 Offset = ((~AlignMask) & Offset) + StackAlignment +
2711 (StackAlignment-SlotSize);
2716 /// MatchingStackOffset - Return true if the given stack call argument is
2717 /// already available in the same position (relatively) of the caller's
2718 /// incoming argument stack.
2720 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2721 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2722 const X86InstrInfo *TII) {
2723 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2725 if (Arg.getOpcode() == ISD::CopyFromReg) {
2726 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2727 if (!TargetRegisterInfo::isVirtualRegister(VR))
2729 MachineInstr *Def = MRI->getVRegDef(VR);
2732 if (!Flags.isByVal()) {
2733 if (!TII->isLoadFromStackSlot(Def, FI))
2736 unsigned Opcode = Def->getOpcode();
2737 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2738 Def->getOperand(1).isFI()) {
2739 FI = Def->getOperand(1).getIndex();
2740 Bytes = Flags.getByValSize();
2744 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2745 if (Flags.isByVal())
2746 // ByVal argument is passed in as a pointer but it's now being
2747 // dereferenced. e.g.
2748 // define @foo(%struct.X* %A) {
2749 // tail call @bar(%struct.X* byval %A)
2752 SDValue Ptr = Ld->getBasePtr();
2753 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2756 FI = FINode->getIndex();
2757 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2758 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2759 FI = FINode->getIndex();
2760 Bytes = Flags.getByValSize();
2764 assert(FI != INT_MAX);
2765 if (!MFI->isFixedObjectIndex(FI))
2767 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2770 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2771 /// for tail call optimization. Targets which want to do tail call
2772 /// optimization should implement this function.
2774 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2775 CallingConv::ID CalleeCC,
2777 bool isCalleeStructRet,
2778 bool isCallerStructRet,
2780 const SmallVectorImpl<ISD::OutputArg> &Outs,
2781 const SmallVectorImpl<SDValue> &OutVals,
2782 const SmallVectorImpl<ISD::InputArg> &Ins,
2783 SelectionDAG& DAG) const {
2784 if (!IsTailCallConvention(CalleeCC) &&
2785 CalleeCC != CallingConv::C)
2788 // If -tailcallopt is specified, make fastcc functions tail-callable.
2789 const MachineFunction &MF = DAG.getMachineFunction();
2790 const Function *CallerF = DAG.getMachineFunction().getFunction();
2792 // If the function return type is x86_fp80 and the callee return type is not,
2793 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2794 // perform a tailcall optimization here.
2795 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2798 CallingConv::ID CallerCC = CallerF->getCallingConv();
2799 bool CCMatch = CallerCC == CalleeCC;
2801 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2802 if (IsTailCallConvention(CalleeCC) && CCMatch)
2807 // Look for obvious safe cases to perform tail call optimization that do not
2808 // require ABI changes. This is what gcc calls sibcall.
2810 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2811 // emit a special epilogue.
2812 if (RegInfo->needsStackRealignment(MF))
2815 // Also avoid sibcall optimization if either caller or callee uses struct
2816 // return semantics.
2817 if (isCalleeStructRet || isCallerStructRet)
2820 // An stdcall caller is expected to clean up its arguments; the callee
2821 // isn't going to do that.
2822 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2825 // Do not sibcall optimize vararg calls unless all arguments are passed via
2827 if (isVarArg && !Outs.empty()) {
2829 // Optimizing for varargs on Win64 is unlikely to be safe without
2830 // additional testing.
2831 if (Subtarget->isTargetWin64())
2834 SmallVector<CCValAssign, 16> ArgLocs;
2835 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2836 getTargetMachine(), ArgLocs, *DAG.getContext());
2838 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2839 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2840 if (!ArgLocs[i].isRegLoc())
2844 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2845 // stack. Therefore, if it's not used by the call it is not safe to optimize
2846 // this into a sibcall.
2847 bool Unused = false;
2848 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2855 SmallVector<CCValAssign, 16> RVLocs;
2856 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2857 getTargetMachine(), RVLocs, *DAG.getContext());
2858 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2859 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2860 CCValAssign &VA = RVLocs[i];
2861 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2866 // If the calling conventions do not match, then we'd better make sure the
2867 // results are returned in the same way as what the caller expects.
2869 SmallVector<CCValAssign, 16> RVLocs1;
2870 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2871 getTargetMachine(), RVLocs1, *DAG.getContext());
2872 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2874 SmallVector<CCValAssign, 16> RVLocs2;
2875 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2876 getTargetMachine(), RVLocs2, *DAG.getContext());
2877 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2879 if (RVLocs1.size() != RVLocs2.size())
2881 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2882 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2884 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2886 if (RVLocs1[i].isRegLoc()) {
2887 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2890 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2896 // If the callee takes no arguments then go on to check the results of the
2898 if (!Outs.empty()) {
2899 // Check if stack adjustment is needed. For now, do not do this if any
2900 // argument is passed on the stack.
2901 SmallVector<CCValAssign, 16> ArgLocs;
2902 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2903 getTargetMachine(), ArgLocs, *DAG.getContext());
2905 // Allocate shadow area for Win64
2906 if (Subtarget->isTargetWin64()) {
2907 CCInfo.AllocateStack(32, 8);
2910 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2911 if (CCInfo.getNextStackOffset()) {
2912 MachineFunction &MF = DAG.getMachineFunction();
2913 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2916 // Check if the arguments are already laid out in the right way as
2917 // the caller's fixed stack objects.
2918 MachineFrameInfo *MFI = MF.getFrameInfo();
2919 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2920 const X86InstrInfo *TII =
2921 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2922 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2923 CCValAssign &VA = ArgLocs[i];
2924 SDValue Arg = OutVals[i];
2925 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2926 if (VA.getLocInfo() == CCValAssign::Indirect)
2928 if (!VA.isRegLoc()) {
2929 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2936 // If the tailcall address may be in a register, then make sure it's
2937 // possible to register allocate for it. In 32-bit, the call address can
2938 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2939 // callee-saved registers are restored. These happen to be the same
2940 // registers used to pass 'inreg' arguments so watch out for those.
2941 if (!Subtarget->is64Bit() &&
2942 !isa<GlobalAddressSDNode>(Callee) &&
2943 !isa<ExternalSymbolSDNode>(Callee)) {
2944 unsigned NumInRegs = 0;
2945 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2946 CCValAssign &VA = ArgLocs[i];
2949 unsigned Reg = VA.getLocReg();
2952 case X86::EAX: case X86::EDX: case X86::ECX:
2953 if (++NumInRegs == 3)
2965 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2966 const TargetLibraryInfo *libInfo) const {
2967 return X86::createFastISel(funcInfo, libInfo);
2970 //===----------------------------------------------------------------------===//
2971 // Other Lowering Hooks
2972 //===----------------------------------------------------------------------===//
2974 static bool MayFoldLoad(SDValue Op) {
2975 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2978 static bool MayFoldIntoStore(SDValue Op) {
2979 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2982 static bool isTargetShuffle(unsigned Opcode) {
2984 default: return false;
2985 case X86ISD::PSHUFD:
2986 case X86ISD::PSHUFHW:
2987 case X86ISD::PSHUFLW:
2989 case X86ISD::PALIGN:
2990 case X86ISD::MOVLHPS:
2991 case X86ISD::MOVLHPD:
2992 case X86ISD::MOVHLPS:
2993 case X86ISD::MOVLPS:
2994 case X86ISD::MOVLPD:
2995 case X86ISD::MOVSHDUP:
2996 case X86ISD::MOVSLDUP:
2997 case X86ISD::MOVDDUP:
3000 case X86ISD::UNPCKL:
3001 case X86ISD::UNPCKH:
3002 case X86ISD::VPERMILP:
3003 case X86ISD::VPERM2X128:
3004 case X86ISD::VPERMI:
3009 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3010 SDValue V1, SelectionDAG &DAG) {
3012 default: llvm_unreachable("Unknown x86 shuffle node");
3013 case X86ISD::MOVSHDUP:
3014 case X86ISD::MOVSLDUP:
3015 case X86ISD::MOVDDUP:
3016 return DAG.getNode(Opc, dl, VT, V1);
3020 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3021 SDValue V1, unsigned TargetMask,
3022 SelectionDAG &DAG) {
3024 default: llvm_unreachable("Unknown x86 shuffle node");
3025 case X86ISD::PSHUFD:
3026 case X86ISD::PSHUFHW:
3027 case X86ISD::PSHUFLW:
3028 case X86ISD::VPERMILP:
3029 case X86ISD::VPERMI:
3030 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3034 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3035 SDValue V1, SDValue V2, unsigned TargetMask,
3036 SelectionDAG &DAG) {
3038 default: llvm_unreachable("Unknown x86 shuffle node");
3039 case X86ISD::PALIGN:
3041 case X86ISD::VPERM2X128:
3042 return DAG.getNode(Opc, dl, VT, V1, V2,
3043 DAG.getConstant(TargetMask, MVT::i8));
3047 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3048 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3050 default: llvm_unreachable("Unknown x86 shuffle node");
3051 case X86ISD::MOVLHPS:
3052 case X86ISD::MOVLHPD:
3053 case X86ISD::MOVHLPS:
3054 case X86ISD::MOVLPS:
3055 case X86ISD::MOVLPD:
3058 case X86ISD::UNPCKL:
3059 case X86ISD::UNPCKH:
3060 return DAG.getNode(Opc, dl, VT, V1, V2);
3064 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3065 MachineFunction &MF = DAG.getMachineFunction();
3066 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3067 int ReturnAddrIndex = FuncInfo->getRAIndex();
3069 if (ReturnAddrIndex == 0) {
3070 // Set up a frame object for the return address.
3071 unsigned SlotSize = RegInfo->getSlotSize();
3072 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3074 FuncInfo->setRAIndex(ReturnAddrIndex);
3077 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3080 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3081 bool hasSymbolicDisplacement) {
3082 // Offset should fit into 32 bit immediate field.
3083 if (!isInt<32>(Offset))
3086 // If we don't have a symbolic displacement - we don't have any extra
3088 if (!hasSymbolicDisplacement)
3091 // FIXME: Some tweaks might be needed for medium code model.
3092 if (M != CodeModel::Small && M != CodeModel::Kernel)
3095 // For small code model we assume that latest object is 16MB before end of 31
3096 // bits boundary. We may also accept pretty large negative constants knowing
3097 // that all objects are in the positive half of address space.
3098 if (M == CodeModel::Small && Offset < 16*1024*1024)
3101 // For kernel code model we know that all object resist in the negative half
3102 // of 32bits address space. We may not accept negative offsets, since they may
3103 // be just off and we may accept pretty large positive ones.
3104 if (M == CodeModel::Kernel && Offset > 0)
3110 /// isCalleePop - Determines whether the callee is required to pop its
3111 /// own arguments. Callee pop is necessary to support tail calls.
3112 bool X86::isCalleePop(CallingConv::ID CallingConv,
3113 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3117 switch (CallingConv) {
3120 case CallingConv::X86_StdCall:
3122 case CallingConv::X86_FastCall:
3124 case CallingConv::X86_ThisCall:
3126 case CallingConv::Fast:
3128 case CallingConv::GHC:
3130 case CallingConv::HiPE:
3135 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3136 /// specific condition code, returning the condition code and the LHS/RHS of the
3137 /// comparison to make.
3138 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3139 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3141 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3142 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3143 // X > -1 -> X == 0, jump !sign.
3144 RHS = DAG.getConstant(0, RHS.getValueType());
3145 return X86::COND_NS;
3147 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3148 // X < 0 -> X == 0, jump on sign.
3151 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3153 RHS = DAG.getConstant(0, RHS.getValueType());
3154 return X86::COND_LE;
3158 switch (SetCCOpcode) {
3159 default: llvm_unreachable("Invalid integer condition!");
3160 case ISD::SETEQ: return X86::COND_E;
3161 case ISD::SETGT: return X86::COND_G;
3162 case ISD::SETGE: return X86::COND_GE;
3163 case ISD::SETLT: return X86::COND_L;
3164 case ISD::SETLE: return X86::COND_LE;
3165 case ISD::SETNE: return X86::COND_NE;
3166 case ISD::SETULT: return X86::COND_B;
3167 case ISD::SETUGT: return X86::COND_A;
3168 case ISD::SETULE: return X86::COND_BE;
3169 case ISD::SETUGE: return X86::COND_AE;
3173 // First determine if it is required or is profitable to flip the operands.
3175 // If LHS is a foldable load, but RHS is not, flip the condition.
3176 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3177 !ISD::isNON_EXTLoad(RHS.getNode())) {
3178 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3179 std::swap(LHS, RHS);
3182 switch (SetCCOpcode) {
3188 std::swap(LHS, RHS);
3192 // On a floating point condition, the flags are set as follows:
3194 // 0 | 0 | 0 | X > Y
3195 // 0 | 0 | 1 | X < Y
3196 // 1 | 0 | 0 | X == Y
3197 // 1 | 1 | 1 | unordered
3198 switch (SetCCOpcode) {
3199 default: llvm_unreachable("Condcode should be pre-legalized away");
3201 case ISD::SETEQ: return X86::COND_E;
3202 case ISD::SETOLT: // flipped
3204 case ISD::SETGT: return X86::COND_A;
3205 case ISD::SETOLE: // flipped
3207 case ISD::SETGE: return X86::COND_AE;
3208 case ISD::SETUGT: // flipped
3210 case ISD::SETLT: return X86::COND_B;
3211 case ISD::SETUGE: // flipped
3213 case ISD::SETLE: return X86::COND_BE;
3215 case ISD::SETNE: return X86::COND_NE;
3216 case ISD::SETUO: return X86::COND_P;
3217 case ISD::SETO: return X86::COND_NP;
3219 case ISD::SETUNE: return X86::COND_INVALID;
3223 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3224 /// code. Current x86 isa includes the following FP cmov instructions:
3225 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3226 static bool hasFPCMov(unsigned X86CC) {
3242 /// isFPImmLegal - Returns true if the target can instruction select the
3243 /// specified FP immediate natively. If false, the legalizer will
3244 /// materialize the FP immediate as a load from a constant pool.
3245 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3246 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3247 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3253 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3254 /// the specified range (L, H].
3255 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3256 return (Val < 0) || (Val >= Low && Val < Hi);
3259 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3260 /// specified value.
3261 static bool isUndefOrEqual(int Val, int CmpVal) {
3262 return (Val < 0 || Val == CmpVal);
3265 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3266 /// from position Pos and ending in Pos+Size, falls within the specified
3267 /// sequential range (L, L+Pos]. or is undef.
3268 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3269 unsigned Pos, unsigned Size, int Low) {
3270 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3271 if (!isUndefOrEqual(Mask[i], Low))
3276 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3277 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3278 /// the second operand.
3279 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3280 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3281 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3282 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3283 return (Mask[0] < 2 && Mask[1] < 2);
3287 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3288 /// is suitable for input to PSHUFHW.
3289 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3290 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3293 // Lower quadword copied in order or undef.
3294 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3297 // Upper quadword shuffled.
3298 for (unsigned i = 4; i != 8; ++i)
3299 if (!isUndefOrInRange(Mask[i], 4, 8))
3302 if (VT == MVT::v16i16) {
3303 // Lower quadword copied in order or undef.
3304 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3307 // Upper quadword shuffled.
3308 for (unsigned i = 12; i != 16; ++i)
3309 if (!isUndefOrInRange(Mask[i], 12, 16))
3316 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3317 /// is suitable for input to PSHUFLW.
3318 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3319 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3322 // Upper quadword copied in order.
3323 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3326 // Lower quadword shuffled.
3327 for (unsigned i = 0; i != 4; ++i)
3328 if (!isUndefOrInRange(Mask[i], 0, 4))
3331 if (VT == MVT::v16i16) {
3332 // Upper quadword copied in order.
3333 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3336 // Lower quadword shuffled.
3337 for (unsigned i = 8; i != 12; ++i)
3338 if (!isUndefOrInRange(Mask[i], 8, 12))
3345 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3346 /// is suitable for input to PALIGNR.
3347 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3348 const X86Subtarget *Subtarget) {
3349 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3350 (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3353 unsigned NumElts = VT.getVectorNumElements();
3354 unsigned NumLanes = VT.getSizeInBits()/128;
3355 unsigned NumLaneElts = NumElts/NumLanes;
3357 // Do not handle 64-bit element shuffles with palignr.
3358 if (NumLaneElts == 2)
3361 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3363 for (i = 0; i != NumLaneElts; ++i) {
3368 // Lane is all undef, go to next lane
3369 if (i == NumLaneElts)
3372 int Start = Mask[i+l];
3374 // Make sure its in this lane in one of the sources
3375 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3376 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3379 // If not lane 0, then we must match lane 0
3380 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3383 // Correct second source to be contiguous with first source
3384 if (Start >= (int)NumElts)
3385 Start -= NumElts - NumLaneElts;
3387 // Make sure we're shifting in the right direction.
3388 if (Start <= (int)(i+l))
3393 // Check the rest of the elements to see if they are consecutive.
3394 for (++i; i != NumLaneElts; ++i) {
3395 int Idx = Mask[i+l];
3397 // Make sure its in this lane
3398 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3399 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3402 // If not lane 0, then we must match lane 0
3403 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3406 if (Idx >= (int)NumElts)
3407 Idx -= NumElts - NumLaneElts;
3409 if (!isUndefOrEqual(Idx, Start+i))
3418 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3419 /// the two vector operands have swapped position.
3420 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3421 unsigned NumElems) {
3422 for (unsigned i = 0; i != NumElems; ++i) {
3426 else if (idx < (int)NumElems)
3427 Mask[i] = idx + NumElems;
3429 Mask[i] = idx - NumElems;
3433 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3434 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3435 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3436 /// reverse of what x86 shuffles want.
3437 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3438 bool Commuted = false) {
3439 if (!HasFp256 && VT.getSizeInBits() == 256)
3442 unsigned NumElems = VT.getVectorNumElements();
3443 unsigned NumLanes = VT.getSizeInBits()/128;
3444 unsigned NumLaneElems = NumElems/NumLanes;
3446 if (NumLaneElems != 2 && NumLaneElems != 4)
3449 // VSHUFPSY divides the resulting vector into 4 chunks.
3450 // The sources are also splitted into 4 chunks, and each destination
3451 // chunk must come from a different source chunk.
3453 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3454 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3456 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3457 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3459 // VSHUFPDY divides the resulting vector into 4 chunks.
3460 // The sources are also splitted into 4 chunks, and each destination
3461 // chunk must come from a different source chunk.
3463 // SRC1 => X3 X2 X1 X0
3464 // SRC2 => Y3 Y2 Y1 Y0
3466 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3468 unsigned HalfLaneElems = NumLaneElems/2;
3469 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3470 for (unsigned i = 0; i != NumLaneElems; ++i) {
3471 int Idx = Mask[i+l];
3472 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3473 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3475 // For VSHUFPSY, the mask of the second half must be the same as the
3476 // first but with the appropriate offsets. This works in the same way as
3477 // VPERMILPS works with masks.
3478 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3480 if (!isUndefOrEqual(Idx, Mask[i]+l))
3488 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3489 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3490 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3491 if (!VT.is128BitVector())
3494 unsigned NumElems = VT.getVectorNumElements();
3499 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3500 return isUndefOrEqual(Mask[0], 6) &&
3501 isUndefOrEqual(Mask[1], 7) &&
3502 isUndefOrEqual(Mask[2], 2) &&
3503 isUndefOrEqual(Mask[3], 3);
3506 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3507 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3509 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3510 if (!VT.is128BitVector())
3513 unsigned NumElems = VT.getVectorNumElements();
3518 return isUndefOrEqual(Mask[0], 2) &&
3519 isUndefOrEqual(Mask[1], 3) &&
3520 isUndefOrEqual(Mask[2], 2) &&
3521 isUndefOrEqual(Mask[3], 3);
3524 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3525 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3526 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3527 if (!VT.is128BitVector())
3530 unsigned NumElems = VT.getVectorNumElements();
3532 if (NumElems != 2 && NumElems != 4)
3535 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3536 if (!isUndefOrEqual(Mask[i], i + NumElems))
3539 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3540 if (!isUndefOrEqual(Mask[i], i))
3546 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3548 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3549 if (!VT.is128BitVector())
3552 unsigned NumElems = VT.getVectorNumElements();
3554 if (NumElems != 2 && NumElems != 4)
3557 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3558 if (!isUndefOrEqual(Mask[i], i))
3561 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3562 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3569 // Some special combinations that can be optimized.
3572 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3573 SelectionDAG &DAG) {
3574 EVT VT = SVOp->getValueType(0);
3575 DebugLoc dl = SVOp->getDebugLoc();
3577 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3580 ArrayRef<int> Mask = SVOp->getMask();
3582 // These are the special masks that may be optimized.
3583 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3584 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3585 bool MatchEvenMask = true;
3586 bool MatchOddMask = true;
3587 for (int i=0; i<8; ++i) {
3588 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3589 MatchEvenMask = false;
3590 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3591 MatchOddMask = false;
3594 if (!MatchEvenMask && !MatchOddMask)
3597 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3599 SDValue Op0 = SVOp->getOperand(0);
3600 SDValue Op1 = SVOp->getOperand(1);
3602 if (MatchEvenMask) {
3603 // Shift the second operand right to 32 bits.
3604 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3605 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3607 // Shift the first operand left to 32 bits.
3608 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3609 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3611 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3612 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3615 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3616 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3617 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3618 bool HasInt256, 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 (!HasInt256 || (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;
3635 i != (l+1)*NumLaneElts;
3638 int BitI1 = Mask[i+1];
3639 if (!isUndefOrEqual(BitI, j))
3642 if (!isUndefOrEqual(BitI1, NumElts))
3645 if (!isUndefOrEqual(BitI1, j + NumElts))
3654 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3655 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3656 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3657 bool HasInt256, bool V2IsSplat = false) {
3658 unsigned NumElts = VT.getVectorNumElements();
3660 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3661 "Unsupported vector type for unpckh");
3663 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3664 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3667 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3668 // independently on 128-bit lanes.
3669 unsigned NumLanes = VT.getSizeInBits()/128;
3670 unsigned NumLaneElts = NumElts/NumLanes;
3672 for (unsigned l = 0; l != NumLanes; ++l) {
3673 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3674 i != (l+1)*NumLaneElts; i += 2, ++j) {
3676 int BitI1 = Mask[i+1];
3677 if (!isUndefOrEqual(BitI, j))
3680 if (isUndefOrEqual(BitI1, NumElts))
3683 if (!isUndefOrEqual(BitI1, j+NumElts))
3691 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3692 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3694 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3696 unsigned NumElts = VT.getVectorNumElements();
3698 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3699 "Unsupported vector type for unpckh");
3701 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3702 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3705 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3706 // FIXME: Need a better way to get rid of this, there's no latency difference
3707 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3708 // the former later. We should also remove the "_undef" special mask.
3709 if (NumElts == 4 && VT.getSizeInBits() == 256)
3712 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3713 // independently on 128-bit lanes.
3714 unsigned NumLanes = VT.getSizeInBits()/128;
3715 unsigned NumLaneElts = NumElts/NumLanes;
3717 for (unsigned l = 0; l != NumLanes; ++l) {
3718 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3719 i != (l+1)*NumLaneElts;
3722 int BitI1 = Mask[i+1];
3724 if (!isUndefOrEqual(BitI, j))
3726 if (!isUndefOrEqual(BitI1, j))
3734 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3735 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3737 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3738 unsigned NumElts = VT.getVectorNumElements();
3740 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3741 "Unsupported vector type for unpckh");
3743 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3744 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3747 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3748 // independently on 128-bit lanes.
3749 unsigned NumLanes = VT.getSizeInBits()/128;
3750 unsigned NumLaneElts = NumElts/NumLanes;
3752 for (unsigned l = 0; l != NumLanes; ++l) {
3753 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3754 i != (l+1)*NumLaneElts; i += 2, ++j) {
3756 int BitI1 = Mask[i+1];
3757 if (!isUndefOrEqual(BitI, j))
3759 if (!isUndefOrEqual(BitI1, j))
3766 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3767 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3768 /// MOVSD, and MOVD, i.e. setting the lowest element.
3769 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3770 if (VT.getVectorElementType().getSizeInBits() < 32)
3772 if (!VT.is128BitVector())
3775 unsigned NumElts = VT.getVectorNumElements();
3777 if (!isUndefOrEqual(Mask[0], NumElts))
3780 for (unsigned i = 1; i != NumElts; ++i)
3781 if (!isUndefOrEqual(Mask[i], i))
3787 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3788 /// as permutations between 128-bit chunks or halves. As an example: this
3790 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3791 /// The first half comes from the second half of V1 and the second half from the
3792 /// the second half of V2.
3793 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3794 if (!HasFp256 || !VT.is256BitVector())
3797 // The shuffle result is divided into half A and half B. In total the two
3798 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3799 // B must come from C, D, E or F.
3800 unsigned HalfSize = VT.getVectorNumElements()/2;
3801 bool MatchA = false, MatchB = false;
3803 // Check if A comes from one of C, D, E, F.
3804 for (unsigned Half = 0; Half != 4; ++Half) {
3805 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3811 // Check if B comes from one of C, D, E, F.
3812 for (unsigned Half = 0; Half != 4; ++Half) {
3813 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3819 return MatchA && MatchB;
3822 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3823 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3824 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3825 EVT VT = SVOp->getValueType(0);
3827 unsigned HalfSize = VT.getVectorNumElements()/2;
3829 unsigned FstHalf = 0, SndHalf = 0;
3830 for (unsigned i = 0; i < HalfSize; ++i) {
3831 if (SVOp->getMaskElt(i) > 0) {
3832 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3836 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3837 if (SVOp->getMaskElt(i) > 0) {
3838 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3843 return (FstHalf | (SndHalf << 4));
3846 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3848 /// Note that VPERMIL mask matching is different depending whether theunderlying
3849 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3850 /// to the same elements of the low, but to the higher half of the source.
3851 /// In VPERMILPD the two lanes could be shuffled independently of each other
3852 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3853 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3857 unsigned NumElts = VT.getVectorNumElements();
3858 // Only match 256-bit with 32/64-bit types
3859 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3862 unsigned NumLanes = VT.getSizeInBits()/128;
3863 unsigned LaneSize = NumElts/NumLanes;
3864 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3865 for (unsigned i = 0; i != LaneSize; ++i) {
3866 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3868 if (NumElts != 8 || l == 0)
3870 // VPERMILPS handling
3873 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3881 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3882 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3883 /// element of vector 2 and the other elements to come from vector 1 in order.
3884 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3885 bool V2IsSplat = false, bool V2IsUndef = false) {
3886 if (!VT.is128BitVector())
3889 unsigned NumOps = VT.getVectorNumElements();
3890 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3893 if (!isUndefOrEqual(Mask[0], 0))
3896 for (unsigned i = 1; i != NumOps; ++i)
3897 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3898 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3899 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3905 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3906 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3907 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3908 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3909 const X86Subtarget *Subtarget) {
3910 if (!Subtarget->hasSSE3())
3913 unsigned NumElems = VT.getVectorNumElements();
3915 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3916 (VT.getSizeInBits() == 256 && NumElems != 8))
3919 // "i+1" is the value the indexed mask element must have
3920 for (unsigned i = 0; i != NumElems; i += 2)
3921 if (!isUndefOrEqual(Mask[i], i+1) ||
3922 !isUndefOrEqual(Mask[i+1], i+1))
3928 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3930 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3931 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3932 const X86Subtarget *Subtarget) {
3933 if (!Subtarget->hasSSE3())
3936 unsigned NumElems = VT.getVectorNumElements();
3938 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3939 (VT.getSizeInBits() == 256 && NumElems != 8))
3942 // "i" is the value the indexed mask element must have
3943 for (unsigned i = 0; i != NumElems; i += 2)
3944 if (!isUndefOrEqual(Mask[i], i) ||
3945 !isUndefOrEqual(Mask[i+1], i))
3951 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3952 /// specifies a shuffle of elements that is suitable for input to 256-bit
3953 /// version of MOVDDUP.
3954 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3955 if (!HasFp256 || !VT.is256BitVector())
3958 unsigned NumElts = VT.getVectorNumElements();
3962 for (unsigned i = 0; i != NumElts/2; ++i)
3963 if (!isUndefOrEqual(Mask[i], 0))
3965 for (unsigned i = NumElts/2; i != NumElts; ++i)
3966 if (!isUndefOrEqual(Mask[i], NumElts/2))
3971 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to 128-bit
3973 /// version of MOVDDUP.
3974 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3975 if (!VT.is128BitVector())
3978 unsigned e = VT.getVectorNumElements() / 2;
3979 for (unsigned i = 0; i != e; ++i)
3980 if (!isUndefOrEqual(Mask[i], i))
3982 for (unsigned i = 0; i != e; ++i)
3983 if (!isUndefOrEqual(Mask[e+i], i))
3988 /// isVEXTRACTF128Index - Return true if the specified
3989 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3990 /// suitable for input to VEXTRACTF128.
3991 bool X86::isVEXTRACTF128Index(SDNode *N) {
3992 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3995 // The index should be aligned on a 128-bit boundary.
3997 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3999 unsigned VL = N->getValueType(0).getVectorNumElements();
4000 unsigned VBits = N->getValueType(0).getSizeInBits();
4001 unsigned ElSize = VBits / VL;
4002 bool Result = (Index * ElSize) % 128 == 0;
4007 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4008 /// operand specifies a subvector insert that is suitable for input to
4010 bool X86::isVINSERTF128Index(SDNode *N) {
4011 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4014 // The index should be aligned on a 128-bit boundary.
4016 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4018 unsigned VL = N->getValueType(0).getVectorNumElements();
4019 unsigned VBits = N->getValueType(0).getSizeInBits();
4020 unsigned ElSize = VBits / VL;
4021 bool Result = (Index * ElSize) % 128 == 0;
4026 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4027 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4028 /// Handles 128-bit and 256-bit.
4029 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4030 EVT VT = N->getValueType(0);
4032 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4033 "Unsupported vector type for PSHUF/SHUFP");
4035 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4036 // independently on 128-bit lanes.
4037 unsigned NumElts = VT.getVectorNumElements();
4038 unsigned NumLanes = VT.getSizeInBits()/128;
4039 unsigned NumLaneElts = NumElts/NumLanes;
4041 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4042 "Only supports 2 or 4 elements per lane");
4044 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4046 for (unsigned i = 0; i != NumElts; ++i) {
4047 int Elt = N->getMaskElt(i);
4048 if (Elt < 0) continue;
4049 Elt &= NumLaneElts - 1;
4050 unsigned ShAmt = (i << Shift) % 8;
4051 Mask |= Elt << ShAmt;
4057 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4058 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4059 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4060 EVT VT = N->getValueType(0);
4062 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4063 "Unsupported vector type for PSHUFHW");
4065 unsigned NumElts = VT.getVectorNumElements();
4068 for (unsigned l = 0; l != NumElts; l += 8) {
4069 // 8 nodes per lane, but we only care about the last 4.
4070 for (unsigned i = 0; i < 4; ++i) {
4071 int Elt = N->getMaskElt(l+i+4);
4072 if (Elt < 0) continue;
4073 Elt &= 0x3; // only 2-bits.
4074 Mask |= Elt << (i * 2);
4081 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4082 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4083 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4084 EVT VT = N->getValueType(0);
4086 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4087 "Unsupported vector type for PSHUFHW");
4089 unsigned NumElts = VT.getVectorNumElements();
4092 for (unsigned l = 0; l != NumElts; l += 8) {
4093 // 8 nodes per lane, but we only care about the first 4.
4094 for (unsigned i = 0; i < 4; ++i) {
4095 int Elt = N->getMaskElt(l+i);
4096 if (Elt < 0) continue;
4097 Elt &= 0x3; // only 2-bits
4098 Mask |= Elt << (i * 2);
4105 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4106 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4107 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4108 EVT VT = SVOp->getValueType(0);
4109 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4111 unsigned NumElts = VT.getVectorNumElements();
4112 unsigned NumLanes = VT.getSizeInBits()/128;
4113 unsigned NumLaneElts = NumElts/NumLanes;
4117 for (i = 0; i != NumElts; ++i) {
4118 Val = SVOp->getMaskElt(i);
4122 if (Val >= (int)NumElts)
4123 Val -= NumElts - NumLaneElts;
4125 assert(Val - i > 0 && "PALIGNR imm should be positive");
4126 return (Val - i) * EltSize;
4129 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4130 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4132 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4133 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4134 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4137 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4139 EVT VecVT = N->getOperand(0).getValueType();
4140 EVT ElVT = VecVT.getVectorElementType();
4142 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4143 return Index / NumElemsPerChunk;
4146 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4147 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4149 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4150 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4151 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4154 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4156 EVT VecVT = N->getValueType(0);
4157 EVT ElVT = VecVT.getVectorElementType();
4159 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4160 return Index / NumElemsPerChunk;
4163 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4164 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4165 /// Handles 256-bit.
4166 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4167 EVT VT = N->getValueType(0);
4169 unsigned NumElts = VT.getVectorNumElements();
4171 assert((VT.is256BitVector() && NumElts == 4) &&
4172 "Unsupported vector type for VPERMQ/VPERMPD");
4175 for (unsigned i = 0; i != NumElts; ++i) {
4176 int Elt = N->getMaskElt(i);
4179 Mask |= Elt << (i*2);
4184 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4186 bool X86::isZeroNode(SDValue Elt) {
4187 return ((isa<ConstantSDNode>(Elt) &&
4188 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4189 (isa<ConstantFPSDNode>(Elt) &&
4190 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4193 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4194 /// their permute mask.
4195 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4196 SelectionDAG &DAG) {
4197 EVT VT = SVOp->getValueType(0);
4198 unsigned NumElems = VT.getVectorNumElements();
4199 SmallVector<int, 8> MaskVec;
4201 for (unsigned i = 0; i != NumElems; ++i) {
4202 int Idx = SVOp->getMaskElt(i);
4204 if (Idx < (int)NumElems)
4209 MaskVec.push_back(Idx);
4211 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4212 SVOp->getOperand(0), &MaskVec[0]);
4215 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4216 /// match movhlps. The lower half elements should come from upper half of
4217 /// V1 (and in order), and the upper half elements should come from the upper
4218 /// half of V2 (and in order).
4219 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4220 if (!VT.is128BitVector())
4222 if (VT.getVectorNumElements() != 4)
4224 for (unsigned i = 0, e = 2; i != e; ++i)
4225 if (!isUndefOrEqual(Mask[i], i+2))
4227 for (unsigned i = 2; i != 4; ++i)
4228 if (!isUndefOrEqual(Mask[i], i+4))
4233 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4234 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4236 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4237 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4239 N = N->getOperand(0).getNode();
4240 if (!ISD::isNON_EXTLoad(N))
4243 *LD = cast<LoadSDNode>(N);
4247 // Test whether the given value is a vector value which will be legalized
4249 static bool WillBeConstantPoolLoad(SDNode *N) {
4250 if (N->getOpcode() != ISD::BUILD_VECTOR)
4253 // Check for any non-constant elements.
4254 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4255 switch (N->getOperand(i).getNode()->getOpcode()) {
4257 case ISD::ConstantFP:
4264 // Vectors of all-zeros and all-ones are materialized with special
4265 // instructions rather than being loaded.
4266 return !ISD::isBuildVectorAllZeros(N) &&
4267 !ISD::isBuildVectorAllOnes(N);
4270 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4271 /// match movlp{s|d}. The lower half elements should come from lower half of
4272 /// V1 (and in order), and the upper half elements should come from the upper
4273 /// half of V2 (and in order). And since V1 will become the source of the
4274 /// MOVLP, it must be either a vector load or a scalar load to vector.
4275 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4276 ArrayRef<int> Mask, EVT VT) {
4277 if (!VT.is128BitVector())
4280 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4282 // Is V2 is a vector load, don't do this transformation. We will try to use
4283 // load folding shufps op.
4284 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4287 unsigned NumElems = VT.getVectorNumElements();
4289 if (NumElems != 2 && NumElems != 4)
4291 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4292 if (!isUndefOrEqual(Mask[i], i))
4294 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4295 if (!isUndefOrEqual(Mask[i], i+NumElems))
4300 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4302 static bool isSplatVector(SDNode *N) {
4303 if (N->getOpcode() != ISD::BUILD_VECTOR)
4306 SDValue SplatValue = N->getOperand(0);
4307 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4308 if (N->getOperand(i) != SplatValue)
4313 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4314 /// to an zero vector.
4315 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4316 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4317 SDValue V1 = N->getOperand(0);
4318 SDValue V2 = N->getOperand(1);
4319 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4320 for (unsigned i = 0; i != NumElems; ++i) {
4321 int Idx = N->getMaskElt(i);
4322 if (Idx >= (int)NumElems) {
4323 unsigned Opc = V2.getOpcode();
4324 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4326 if (Opc != ISD::BUILD_VECTOR ||
4327 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4329 } else if (Idx >= 0) {
4330 unsigned Opc = V1.getOpcode();
4331 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4333 if (Opc != ISD::BUILD_VECTOR ||
4334 !X86::isZeroNode(V1.getOperand(Idx)))
4341 /// getZeroVector - Returns a vector of specified type with all zero elements.
4343 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4344 SelectionDAG &DAG, DebugLoc dl) {
4345 assert(VT.isVector() && "Expected a vector type");
4346 unsigned Size = VT.getSizeInBits();
4348 // Always build SSE zero vectors as <4 x i32> bitcasted
4349 // to their dest type. This ensures they get CSE'd.
4351 if (Size == 128) { // SSE
4352 if (Subtarget->hasSSE2()) { // SSE2
4353 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4354 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4356 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4357 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4359 } else if (Size == 256) { // AVX
4360 if (Subtarget->hasInt256()) { // AVX2
4361 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4362 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4363 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4365 // 256-bit logic and arithmetic instructions in AVX are all
4366 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4367 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4368 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4369 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4372 llvm_unreachable("Unexpected vector type");
4374 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4377 /// getOnesVector - Returns a vector of specified type with all bits set.
4378 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4379 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4380 /// Then bitcast to their original type, ensuring they get CSE'd.
4381 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4383 assert(VT.isVector() && "Expected a vector type");
4384 unsigned Size = VT.getSizeInBits();
4386 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4389 if (HasInt256) { // AVX2
4390 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4391 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4393 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4394 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4396 } else if (Size == 128) {
4397 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4399 llvm_unreachable("Unexpected vector type");
4401 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4404 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4405 /// that point to V2 points to its first element.
4406 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4407 for (unsigned i = 0; i != NumElems; ++i) {
4408 if (Mask[i] > (int)NumElems) {
4414 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4415 /// operation of specified width.
4416 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4418 unsigned NumElems = VT.getVectorNumElements();
4419 SmallVector<int, 8> Mask;
4420 Mask.push_back(NumElems);
4421 for (unsigned i = 1; i != NumElems; ++i)
4423 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4426 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4427 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4429 unsigned NumElems = VT.getVectorNumElements();
4430 SmallVector<int, 8> Mask;
4431 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4433 Mask.push_back(i + NumElems);
4435 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4438 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4439 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4441 unsigned NumElems = VT.getVectorNumElements();
4442 SmallVector<int, 8> Mask;
4443 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4444 Mask.push_back(i + Half);
4445 Mask.push_back(i + NumElems + Half);
4447 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4450 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4451 // a generic shuffle instruction because the target has no such instructions.
4452 // Generate shuffles which repeat i16 and i8 several times until they can be
4453 // represented by v4f32 and then be manipulated by target suported shuffles.
4454 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4455 EVT VT = V.getValueType();
4456 int NumElems = VT.getVectorNumElements();
4457 DebugLoc dl = V.getDebugLoc();
4459 while (NumElems > 4) {
4460 if (EltNo < NumElems/2) {
4461 V = getUnpackl(DAG, dl, VT, V, V);
4463 V = getUnpackh(DAG, dl, VT, V, V);
4464 EltNo -= NumElems/2;
4471 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4472 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4473 EVT VT = V.getValueType();
4474 DebugLoc dl = V.getDebugLoc();
4475 unsigned Size = VT.getSizeInBits();
4478 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4479 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4480 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4482 } else if (Size == 256) {
4483 // To use VPERMILPS to splat scalars, the second half of indicies must
4484 // refer to the higher part, which is a duplication of the lower one,
4485 // because VPERMILPS can only handle in-lane permutations.
4486 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4487 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4489 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4490 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4493 llvm_unreachable("Vector size not supported");
4495 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4498 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4499 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4500 EVT SrcVT = SV->getValueType(0);
4501 SDValue V1 = SV->getOperand(0);
4502 DebugLoc dl = SV->getDebugLoc();
4504 int EltNo = SV->getSplatIndex();
4505 int NumElems = SrcVT.getVectorNumElements();
4506 unsigned Size = SrcVT.getSizeInBits();
4508 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4509 "Unknown how to promote splat for type");
4511 // Extract the 128-bit part containing the splat element and update
4512 // the splat element index when it refers to the higher register.
4514 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4515 if (EltNo >= NumElems/2)
4516 EltNo -= NumElems/2;
4519 // All i16 and i8 vector types can't be used directly by a generic shuffle
4520 // instruction because the target has no such instruction. Generate shuffles
4521 // which repeat i16 and i8 several times until they fit in i32, and then can
4522 // be manipulated by target suported shuffles.
4523 EVT EltVT = SrcVT.getVectorElementType();
4524 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4525 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4527 // Recreate the 256-bit vector and place the same 128-bit vector
4528 // into the low and high part. This is necessary because we want
4529 // to use VPERM* to shuffle the vectors
4531 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4534 return getLegalSplat(DAG, V1, EltNo);
4537 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4538 /// vector of zero or undef vector. This produces a shuffle where the low
4539 /// element of V2 is swizzled into the zero/undef vector, landing at element
4540 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4541 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4543 const X86Subtarget *Subtarget,
4544 SelectionDAG &DAG) {
4545 EVT VT = V2.getValueType();
4547 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4548 unsigned NumElems = VT.getVectorNumElements();
4549 SmallVector<int, 16> MaskVec;
4550 for (unsigned i = 0; i != NumElems; ++i)
4551 // If this is the insertion idx, put the low elt of V2 here.
4552 MaskVec.push_back(i == Idx ? NumElems : i);
4553 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4556 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4557 /// target specific opcode. Returns true if the Mask could be calculated.
4558 /// Sets IsUnary to true if only uses one source.
4559 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4560 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4561 unsigned NumElems = VT.getVectorNumElements();
4565 switch(N->getOpcode()) {
4567 ImmN = N->getOperand(N->getNumOperands()-1);
4568 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4570 case X86ISD::UNPCKH:
4571 DecodeUNPCKHMask(VT, Mask);
4573 case X86ISD::UNPCKL:
4574 DecodeUNPCKLMask(VT, Mask);
4576 case X86ISD::MOVHLPS:
4577 DecodeMOVHLPSMask(NumElems, Mask);
4579 case X86ISD::MOVLHPS:
4580 DecodeMOVLHPSMask(NumElems, Mask);
4582 case X86ISD::PSHUFD:
4583 case X86ISD::VPERMILP:
4584 ImmN = N->getOperand(N->getNumOperands()-1);
4585 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4588 case X86ISD::PSHUFHW:
4589 ImmN = N->getOperand(N->getNumOperands()-1);
4590 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4593 case X86ISD::PSHUFLW:
4594 ImmN = N->getOperand(N->getNumOperands()-1);
4595 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4598 case X86ISD::VPERMI:
4599 ImmN = N->getOperand(N->getNumOperands()-1);
4600 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4604 case X86ISD::MOVSD: {
4605 // The index 0 always comes from the first element of the second source,
4606 // this is why MOVSS and MOVSD are used in the first place. The other
4607 // elements come from the other positions of the first source vector
4608 Mask.push_back(NumElems);
4609 for (unsigned i = 1; i != NumElems; ++i) {
4614 case X86ISD::VPERM2X128:
4615 ImmN = N->getOperand(N->getNumOperands()-1);
4616 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617 if (Mask.empty()) return false;
4619 case X86ISD::MOVDDUP:
4620 case X86ISD::MOVLHPD:
4621 case X86ISD::MOVLPD:
4622 case X86ISD::MOVLPS:
4623 case X86ISD::MOVSHDUP:
4624 case X86ISD::MOVSLDUP:
4625 case X86ISD::PALIGN:
4626 // Not yet implemented
4628 default: llvm_unreachable("unknown target shuffle node");
4634 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4635 /// element of the result of the vector shuffle.
4636 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4639 return SDValue(); // Limit search depth.
4641 SDValue V = SDValue(N, 0);
4642 EVT VT = V.getValueType();
4643 unsigned Opcode = V.getOpcode();
4645 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4646 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4647 int Elt = SV->getMaskElt(Index);
4650 return DAG.getUNDEF(VT.getVectorElementType());
4652 unsigned NumElems = VT.getVectorNumElements();
4653 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4654 : SV->getOperand(1);
4655 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4658 // Recurse into target specific vector shuffles to find scalars.
4659 if (isTargetShuffle(Opcode)) {
4660 MVT ShufVT = V.getValueType().getSimpleVT();
4661 unsigned NumElems = ShufVT.getVectorNumElements();
4662 SmallVector<int, 16> ShuffleMask;
4665 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4668 int Elt = ShuffleMask[Index];
4670 return DAG.getUNDEF(ShufVT.getVectorElementType());
4672 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4674 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4678 // Actual nodes that may contain scalar elements
4679 if (Opcode == ISD::BITCAST) {
4680 V = V.getOperand(0);
4681 EVT SrcVT = V.getValueType();
4682 unsigned NumElems = VT.getVectorNumElements();
4684 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4688 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4689 return (Index == 0) ? V.getOperand(0)
4690 : DAG.getUNDEF(VT.getVectorElementType());
4692 if (V.getOpcode() == ISD::BUILD_VECTOR)
4693 return V.getOperand(Index);
4698 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4699 /// shuffle operation which come from a consecutively from a zero. The
4700 /// search can start in two different directions, from left or right.
4702 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4703 bool ZerosFromLeft, SelectionDAG &DAG) {
4705 for (i = 0; i != NumElems; ++i) {
4706 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4707 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4708 if (!(Elt.getNode() &&
4709 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4716 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4717 /// correspond consecutively to elements from one of the vector operands,
4718 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4720 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4721 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4722 unsigned NumElems, unsigned &OpNum) {
4723 bool SeenV1 = false;
4724 bool SeenV2 = false;
4726 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4727 int Idx = SVOp->getMaskElt(i);
4728 // Ignore undef indicies
4732 if (Idx < (int)NumElems)
4737 // Only accept consecutive elements from the same vector
4738 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4742 OpNum = SeenV1 ? 0 : 1;
4746 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4747 /// logical left shift of a vector.
4748 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4749 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4750 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4751 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4752 false /* check zeros from right */, DAG);
4758 // Considering the elements in the mask that are not consecutive zeros,
4759 // check if they consecutively come from only one of the source vectors.
4761 // V1 = {X, A, B, C} 0
4763 // vector_shuffle V1, V2 <1, 2, 3, X>
4765 if (!isShuffleMaskConsecutive(SVOp,
4766 0, // Mask Start Index
4767 NumElems-NumZeros, // Mask End Index(exclusive)
4768 NumZeros, // Where to start looking in the src vector
4769 NumElems, // Number of elements in vector
4770 OpSrc)) // Which source operand ?
4775 ShVal = SVOp->getOperand(OpSrc);
4779 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4780 /// logical left shift of a vector.
4781 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4782 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4783 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4784 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4785 true /* check zeros from left */, DAG);
4791 // Considering the elements in the mask that are not consecutive zeros,
4792 // check if they consecutively come from only one of the source vectors.
4794 // 0 { A, B, X, X } = V2
4796 // vector_shuffle V1, V2 <X, X, 4, 5>
4798 if (!isShuffleMaskConsecutive(SVOp,
4799 NumZeros, // Mask Start Index
4800 NumElems, // Mask End Index(exclusive)
4801 0, // Where to start looking in the src vector
4802 NumElems, // Number of elements in vector
4803 OpSrc)) // Which source operand ?
4808 ShVal = SVOp->getOperand(OpSrc);
4812 /// isVectorShift - Returns true if the shuffle can be implemented as a
4813 /// logical left or right shift of a vector.
4814 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4815 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4816 // Although the logic below support any bitwidth size, there are no
4817 // shift instructions which handle more than 128-bit vectors.
4818 if (!SVOp->getValueType(0).is128BitVector())
4821 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4822 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4828 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4830 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4831 unsigned NumNonZero, unsigned NumZero,
4833 const X86Subtarget* Subtarget,
4834 const TargetLowering &TLI) {
4838 DebugLoc dl = Op.getDebugLoc();
4841 for (unsigned i = 0; i < 16; ++i) {
4842 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4843 if (ThisIsNonZero && First) {
4845 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4847 V = DAG.getUNDEF(MVT::v8i16);
4852 SDValue ThisElt(0, 0), LastElt(0, 0);
4853 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4854 if (LastIsNonZero) {
4855 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4856 MVT::i16, Op.getOperand(i-1));
4858 if (ThisIsNonZero) {
4859 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4860 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4861 ThisElt, DAG.getConstant(8, MVT::i8));
4863 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4867 if (ThisElt.getNode())
4868 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4869 DAG.getIntPtrConstant(i/2));
4873 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4876 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4878 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4879 unsigned NumNonZero, unsigned NumZero,
4881 const X86Subtarget* Subtarget,
4882 const TargetLowering &TLI) {
4886 DebugLoc dl = Op.getDebugLoc();
4889 for (unsigned i = 0; i < 8; ++i) {
4890 bool isNonZero = (NonZeros & (1 << i)) != 0;
4894 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4896 V = DAG.getUNDEF(MVT::v8i16);
4899 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4900 MVT::v8i16, V, Op.getOperand(i),
4901 DAG.getIntPtrConstant(i));
4908 /// getVShift - Return a vector logical shift node.
4910 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4911 unsigned NumBits, SelectionDAG &DAG,
4912 const TargetLowering &TLI, DebugLoc dl) {
4913 assert(VT.is128BitVector() && "Unknown type for VShift");
4914 EVT ShVT = MVT::v2i64;
4915 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4916 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4917 return DAG.getNode(ISD::BITCAST, dl, VT,
4918 DAG.getNode(Opc, dl, ShVT, SrcOp,
4919 DAG.getConstant(NumBits,
4920 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4924 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4925 SelectionDAG &DAG) const {
4927 // Check if the scalar load can be widened into a vector load. And if
4928 // the address is "base + cst" see if the cst can be "absorbed" into
4929 // the shuffle mask.
4930 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4931 SDValue Ptr = LD->getBasePtr();
4932 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4934 EVT PVT = LD->getValueType(0);
4935 if (PVT != MVT::i32 && PVT != MVT::f32)
4940 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4941 FI = FINode->getIndex();
4943 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4944 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4945 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4946 Offset = Ptr.getConstantOperandVal(1);
4947 Ptr = Ptr.getOperand(0);
4952 // FIXME: 256-bit vector instructions don't require a strict alignment,
4953 // improve this code to support it better.
4954 unsigned RequiredAlign = VT.getSizeInBits()/8;
4955 SDValue Chain = LD->getChain();
4956 // Make sure the stack object alignment is at least 16 or 32.
4957 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4958 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4959 if (MFI->isFixedObjectIndex(FI)) {
4960 // Can't change the alignment. FIXME: It's possible to compute
4961 // the exact stack offset and reference FI + adjust offset instead.
4962 // If someone *really* cares about this. That's the way to implement it.
4965 MFI->setObjectAlignment(FI, RequiredAlign);
4969 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4970 // Ptr + (Offset & ~15).
4973 if ((Offset % RequiredAlign) & 3)
4975 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4977 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4978 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4980 int EltNo = (Offset - StartOffset) >> 2;
4981 unsigned NumElems = VT.getVectorNumElements();
4983 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4984 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4985 LD->getPointerInfo().getWithOffset(StartOffset),
4986 false, false, false, 0);
4988 SmallVector<int, 8> Mask;
4989 for (unsigned i = 0; i != NumElems; ++i)
4990 Mask.push_back(EltNo);
4992 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4998 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4999 /// vector of type 'VT', see if the elements can be replaced by a single large
5000 /// load which has the same value as a build_vector whose operands are 'elts'.
5002 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5004 /// FIXME: we'd also like to handle the case where the last elements are zero
5005 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5006 /// There's even a handy isZeroNode for that purpose.
5007 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5008 DebugLoc &DL, SelectionDAG &DAG) {
5009 EVT EltVT = VT.getVectorElementType();
5010 unsigned NumElems = Elts.size();
5012 LoadSDNode *LDBase = NULL;
5013 unsigned LastLoadedElt = -1U;
5015 // For each element in the initializer, see if we've found a load or an undef.
5016 // If we don't find an initial load element, or later load elements are
5017 // non-consecutive, bail out.
5018 for (unsigned i = 0; i < NumElems; ++i) {
5019 SDValue Elt = Elts[i];
5021 if (!Elt.getNode() ||
5022 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5025 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5027 LDBase = cast<LoadSDNode>(Elt.getNode());
5031 if (Elt.getOpcode() == ISD::UNDEF)
5034 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5035 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5040 // If we have found an entire vector of loads and undefs, then return a large
5041 // load of the entire vector width starting at the base pointer. If we found
5042 // consecutive loads for the low half, generate a vzext_load node.
5043 if (LastLoadedElt == NumElems - 1) {
5044 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5045 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5046 LDBase->getPointerInfo(),
5047 LDBase->isVolatile(), LDBase->isNonTemporal(),
5048 LDBase->isInvariant(), 0);
5049 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5050 LDBase->getPointerInfo(),
5051 LDBase->isVolatile(), LDBase->isNonTemporal(),
5052 LDBase->isInvariant(), LDBase->getAlignment());
5054 if (NumElems == 4 && LastLoadedElt == 1 &&
5055 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5056 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5057 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5059 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5060 LDBase->getPointerInfo(),
5061 LDBase->getAlignment(),
5062 false/*isVolatile*/, true/*ReadMem*/,
5065 // Make sure the newly-created LOAD is in the same position as LDBase in
5066 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5067 // update uses of LDBase's output chain to use the TokenFactor.
5068 if (LDBase->hasAnyUseOfValue(1)) {
5069 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5070 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5071 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5072 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5073 SDValue(ResNode.getNode(), 1));
5076 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5081 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5082 /// to generate a splat value for the following cases:
5083 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5084 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5085 /// a scalar load, or a constant.
5086 /// The VBROADCAST node is returned when a pattern is found,
5087 /// or SDValue() otherwise.
5089 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5090 if (!Subtarget->hasFp256())
5093 EVT VT = Op.getValueType();
5094 DebugLoc dl = Op.getDebugLoc();
5096 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5097 "Unsupported vector type for broadcast.");
5102 switch (Op.getOpcode()) {
5104 // Unknown pattern found.
5107 case ISD::BUILD_VECTOR: {
5108 // The BUILD_VECTOR node must be a splat.
5109 if (!isSplatVector(Op.getNode()))
5112 Ld = Op.getOperand(0);
5113 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5114 Ld.getOpcode() == ISD::ConstantFP);
5116 // The suspected load node has several users. Make sure that all
5117 // of its users are from the BUILD_VECTOR node.
5118 // Constants may have multiple users.
5119 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5124 case ISD::VECTOR_SHUFFLE: {
5125 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5127 // Shuffles must have a splat mask where the first element is
5129 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5132 SDValue Sc = Op.getOperand(0);
5133 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5134 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5136 if (!Subtarget->hasInt256())
5139 // Use the register form of the broadcast instruction available on AVX2.
5140 if (VT.is256BitVector())
5141 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5142 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5145 Ld = Sc.getOperand(0);
5146 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5147 Ld.getOpcode() == ISD::ConstantFP);
5149 // The scalar_to_vector node and the suspected
5150 // load node must have exactly one user.
5151 // Constants may have multiple users.
5152 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5158 bool Is256 = VT.is256BitVector();
5160 // Handle the broadcasting a single constant scalar from the constant pool
5161 // into a vector. On Sandybridge it is still better to load a constant vector
5162 // from the constant pool and not to broadcast it from a scalar.
5163 if (ConstSplatVal && Subtarget->hasInt256()) {
5164 EVT CVT = Ld.getValueType();
5165 assert(!CVT.isVector() && "Must not broadcast a vector type");
5166 unsigned ScalarSize = CVT.getSizeInBits();
5168 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5169 const Constant *C = 0;
5170 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5171 C = CI->getConstantIntValue();
5172 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5173 C = CF->getConstantFPValue();
5175 assert(C && "Invalid constant type");
5177 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5178 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5179 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5180 MachinePointerInfo::getConstantPool(),
5181 false, false, false, Alignment);
5183 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5187 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5188 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5190 // Handle AVX2 in-register broadcasts.
5191 if (!IsLoad && Subtarget->hasInt256() &&
5192 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5193 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5195 // The scalar source must be a normal load.
5199 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5200 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5203 // double since there is no vbroadcastsd xmm
5204 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5205 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5206 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5209 // Unsupported broadcast.
5214 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5215 EVT VT = Op.getValueType();
5217 // Skip if insert_vec_elt is not supported.
5218 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5221 DebugLoc DL = Op.getDebugLoc();
5222 unsigned NumElems = Op.getNumOperands();
5226 SmallVector<unsigned, 4> InsertIndices;
5227 SmallVector<int, 8> Mask(NumElems, -1);
5229 for (unsigned i = 0; i != NumElems; ++i) {
5230 unsigned Opc = Op.getOperand(i).getOpcode();
5232 if (Opc == ISD::UNDEF)
5235 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5236 // Quit if more than 1 elements need inserting.
5237 if (InsertIndices.size() > 1)
5240 InsertIndices.push_back(i);
5244 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5245 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5247 // Quit if extracted from vector of different type.
5248 if (ExtractedFromVec.getValueType() != VT)
5251 // Quit if non-constant index.
5252 if (!isa<ConstantSDNode>(ExtIdx))
5255 if (VecIn1.getNode() == 0)
5256 VecIn1 = ExtractedFromVec;
5257 else if (VecIn1 != ExtractedFromVec) {
5258 if (VecIn2.getNode() == 0)
5259 VecIn2 = ExtractedFromVec;
5260 else if (VecIn2 != ExtractedFromVec)
5261 // Quit if more than 2 vectors to shuffle
5265 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5267 if (ExtractedFromVec == VecIn1)
5269 else if (ExtractedFromVec == VecIn2)
5270 Mask[i] = Idx + NumElems;
5273 if (VecIn1.getNode() == 0)
5276 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5277 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5278 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5279 unsigned Idx = InsertIndices[i];
5280 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5281 DAG.getIntPtrConstant(Idx));
5288 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5289 DebugLoc dl = Op.getDebugLoc();
5291 EVT VT = Op.getValueType();
5292 EVT ExtVT = VT.getVectorElementType();
5293 unsigned NumElems = Op.getNumOperands();
5295 // Vectors containing all zeros can be matched by pxor and xorps later
5296 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5297 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5298 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5299 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5302 return getZeroVector(VT, Subtarget, DAG, dl);
5305 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5306 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5307 // vpcmpeqd on 256-bit vectors.
5308 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5309 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5312 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5315 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5316 if (Broadcast.getNode())
5319 unsigned EVTBits = ExtVT.getSizeInBits();
5321 unsigned NumZero = 0;
5322 unsigned NumNonZero = 0;
5323 unsigned NonZeros = 0;
5324 bool IsAllConstants = true;
5325 SmallSet<SDValue, 8> Values;
5326 for (unsigned i = 0; i < NumElems; ++i) {
5327 SDValue Elt = Op.getOperand(i);
5328 if (Elt.getOpcode() == ISD::UNDEF)
5331 if (Elt.getOpcode() != ISD::Constant &&
5332 Elt.getOpcode() != ISD::ConstantFP)
5333 IsAllConstants = false;
5334 if (X86::isZeroNode(Elt))
5337 NonZeros |= (1 << i);
5342 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5343 if (NumNonZero == 0)
5344 return DAG.getUNDEF(VT);
5346 // Special case for single non-zero, non-undef, element.
5347 if (NumNonZero == 1) {
5348 unsigned Idx = CountTrailingZeros_32(NonZeros);
5349 SDValue Item = Op.getOperand(Idx);
5351 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5352 // the value are obviously zero, truncate the value to i32 and do the
5353 // insertion that way. Only do this if the value is non-constant or if the
5354 // value is a constant being inserted into element 0. It is cheaper to do
5355 // a constant pool load than it is to do a movd + shuffle.
5356 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5357 (!IsAllConstants || Idx == 0)) {
5358 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5360 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5361 EVT VecVT = MVT::v4i32;
5362 unsigned VecElts = 4;
5364 // Truncate the value (which may itself be a constant) to i32, and
5365 // convert it to a vector with movd (S2V+shuffle to zero extend).
5366 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5367 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5368 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5370 // Now we have our 32-bit value zero extended in the low element of
5371 // a vector. If Idx != 0, swizzle it into place.
5373 SmallVector<int, 4> Mask;
5374 Mask.push_back(Idx);
5375 for (unsigned i = 1; i != VecElts; ++i)
5377 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5380 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5384 // If we have a constant or non-constant insertion into the low element of
5385 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5386 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5387 // depending on what the source datatype is.
5390 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5392 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5393 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5394 if (VT.is256BitVector()) {
5395 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5396 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5397 Item, DAG.getIntPtrConstant(0));
5399 assert(VT.is128BitVector() && "Expected an SSE value type!");
5400 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5401 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5402 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5405 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5406 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5407 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5408 if (VT.is256BitVector()) {
5409 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5410 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5412 assert(VT.is128BitVector() && "Expected an SSE value type!");
5413 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5415 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5419 // Is it a vector logical left shift?
5420 if (NumElems == 2 && Idx == 1 &&
5421 X86::isZeroNode(Op.getOperand(0)) &&
5422 !X86::isZeroNode(Op.getOperand(1))) {
5423 unsigned NumBits = VT.getSizeInBits();
5424 return getVShift(true, VT,
5425 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5426 VT, Op.getOperand(1)),
5427 NumBits/2, DAG, *this, dl);
5430 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5433 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5434 // is a non-constant being inserted into an element other than the low one,
5435 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5436 // movd/movss) to move this into the low element, then shuffle it into
5438 if (EVTBits == 32) {
5439 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5441 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5442 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5443 SmallVector<int, 8> MaskVec;
5444 for (unsigned i = 0; i != NumElems; ++i)
5445 MaskVec.push_back(i == Idx ? 0 : 1);
5446 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5450 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5451 if (Values.size() == 1) {
5452 if (EVTBits == 32) {
5453 // Instead of a shuffle like this:
5454 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5455 // Check if it's possible to issue this instead.
5456 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5457 unsigned Idx = CountTrailingZeros_32(NonZeros);
5458 SDValue Item = Op.getOperand(Idx);
5459 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5460 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5465 // A vector full of immediates; various special cases are already
5466 // handled, so this is best done with a single constant-pool load.
5470 // For AVX-length vectors, build the individual 128-bit pieces and use
5471 // shuffles to put them in place.
5472 if (VT.is256BitVector()) {
5473 SmallVector<SDValue, 32> V;
5474 for (unsigned i = 0; i != NumElems; ++i)
5475 V.push_back(Op.getOperand(i));
5477 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5479 // Build both the lower and upper subvector.
5480 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5481 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5484 // Recreate the wider vector with the lower and upper part.
5485 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5488 // Let legalizer expand 2-wide build_vectors.
5489 if (EVTBits == 64) {
5490 if (NumNonZero == 1) {
5491 // One half is zero or undef.
5492 unsigned Idx = CountTrailingZeros_32(NonZeros);
5493 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5494 Op.getOperand(Idx));
5495 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5500 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5501 if (EVTBits == 8 && NumElems == 16) {
5502 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5504 if (V.getNode()) return V;
5507 if (EVTBits == 16 && NumElems == 8) {
5508 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5510 if (V.getNode()) return V;
5513 // If element VT is == 32 bits, turn it into a number of shuffles.
5514 SmallVector<SDValue, 8> V(NumElems);
5515 if (NumElems == 4 && NumZero > 0) {
5516 for (unsigned i = 0; i < 4; ++i) {
5517 bool isZero = !(NonZeros & (1 << i));
5519 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5521 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5524 for (unsigned i = 0; i < 2; ++i) {
5525 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5528 V[i] = V[i*2]; // Must be a zero vector.
5531 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5534 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5537 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5542 bool Reverse1 = (NonZeros & 0x3) == 2;
5543 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5547 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5548 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5550 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5553 if (Values.size() > 1 && VT.is128BitVector()) {
5554 // Check for a build vector of consecutive loads.
5555 for (unsigned i = 0; i < NumElems; ++i)
5556 V[i] = Op.getOperand(i);
5558 // Check for elements which are consecutive loads.
5559 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5563 // Check for a build vector from mostly shuffle plus few inserting.
5564 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5568 // For SSE 4.1, use insertps to put the high elements into the low element.
5569 if (getSubtarget()->hasSSE41()) {
5571 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5572 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5574 Result = DAG.getUNDEF(VT);
5576 for (unsigned i = 1; i < NumElems; ++i) {
5577 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5578 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5579 Op.getOperand(i), DAG.getIntPtrConstant(i));
5584 // Otherwise, expand into a number of unpckl*, start by extending each of
5585 // our (non-undef) elements to the full vector width with the element in the
5586 // bottom slot of the vector (which generates no code for SSE).
5587 for (unsigned i = 0; i < NumElems; ++i) {
5588 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5589 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5591 V[i] = DAG.getUNDEF(VT);
5594 // Next, we iteratively mix elements, e.g. for v4f32:
5595 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5596 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5597 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5598 unsigned EltStride = NumElems >> 1;
5599 while (EltStride != 0) {
5600 for (unsigned i = 0; i < EltStride; ++i) {
5601 // If V[i+EltStride] is undef and this is the first round of mixing,
5602 // then it is safe to just drop this shuffle: V[i] is already in the
5603 // right place, the one element (since it's the first round) being
5604 // inserted as undef can be dropped. This isn't safe for successive
5605 // rounds because they will permute elements within both vectors.
5606 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5607 EltStride == NumElems/2)
5610 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5619 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5620 // to create 256-bit vectors from two other 128-bit ones.
5621 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5622 DebugLoc dl = Op.getDebugLoc();
5623 EVT ResVT = Op.getValueType();
5625 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5627 SDValue V1 = Op.getOperand(0);
5628 SDValue V2 = Op.getOperand(1);
5629 unsigned NumElems = ResVT.getVectorNumElements();
5631 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5634 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5635 assert(Op.getNumOperands() == 2);
5637 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5638 // from two other 128-bit ones.
5639 return LowerAVXCONCAT_VECTORS(Op, DAG);
5642 // Try to lower a shuffle node into a simple blend instruction.
5644 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5645 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5646 SDValue V1 = SVOp->getOperand(0);
5647 SDValue V2 = SVOp->getOperand(1);
5648 DebugLoc dl = SVOp->getDebugLoc();
5649 EVT VT = SVOp->getValueType(0);
5650 EVT EltVT = VT.getVectorElementType();
5651 unsigned NumElems = VT.getVectorNumElements();
5653 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5655 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5658 // Check the mask for BLEND and build the value.
5659 unsigned MaskValue = 0;
5660 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5661 unsigned NumLanes = (NumElems-1)/8 + 1;
5662 unsigned NumElemsInLane = NumElems / NumLanes;
5664 // Blend for v16i16 should be symetric for the both lanes.
5665 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5667 int SndLaneEltIdx = (NumLanes == 2) ?
5668 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5669 int EltIdx = SVOp->getMaskElt(i);
5671 if ((EltIdx == -1 || EltIdx == (int)i) &&
5672 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5675 if (((unsigned)EltIdx == (i + NumElems)) &&
5676 (SndLaneEltIdx == -1 ||
5677 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5678 MaskValue |= (1<<i);
5683 // Convert i32 vectors to floating point if it is not AVX2.
5684 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5686 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5687 BlendVT = EVT::getVectorVT(*DAG.getContext(),
5688 EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5690 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5691 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5694 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5695 DAG.getConstant(MaskValue, MVT::i32));
5696 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5699 // v8i16 shuffles - Prefer shuffles in the following order:
5700 // 1. [all] pshuflw, pshufhw, optional move
5701 // 2. [ssse3] 1 x pshufb
5702 // 3. [ssse3] 2 x pshufb + 1 x por
5703 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5705 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5706 SelectionDAG &DAG) {
5707 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5708 SDValue V1 = SVOp->getOperand(0);
5709 SDValue V2 = SVOp->getOperand(1);
5710 DebugLoc dl = SVOp->getDebugLoc();
5711 SmallVector<int, 8> MaskVals;
5713 // Determine if more than 1 of the words in each of the low and high quadwords
5714 // of the result come from the same quadword of one of the two inputs. Undef
5715 // mask values count as coming from any quadword, for better codegen.
5716 unsigned LoQuad[] = { 0, 0, 0, 0 };
5717 unsigned HiQuad[] = { 0, 0, 0, 0 };
5718 std::bitset<4> InputQuads;
5719 for (unsigned i = 0; i < 8; ++i) {
5720 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5721 int EltIdx = SVOp->getMaskElt(i);
5722 MaskVals.push_back(EltIdx);
5731 InputQuads.set(EltIdx / 4);
5734 int BestLoQuad = -1;
5735 unsigned MaxQuad = 1;
5736 for (unsigned i = 0; i < 4; ++i) {
5737 if (LoQuad[i] > MaxQuad) {
5739 MaxQuad = LoQuad[i];
5743 int BestHiQuad = -1;
5745 for (unsigned i = 0; i < 4; ++i) {
5746 if (HiQuad[i] > MaxQuad) {
5748 MaxQuad = HiQuad[i];
5752 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5753 // of the two input vectors, shuffle them into one input vector so only a
5754 // single pshufb instruction is necessary. If There are more than 2 input
5755 // quads, disable the next transformation since it does not help SSSE3.
5756 bool V1Used = InputQuads[0] || InputQuads[1];
5757 bool V2Used = InputQuads[2] || InputQuads[3];
5758 if (Subtarget->hasSSSE3()) {
5759 if (InputQuads.count() == 2 && V1Used && V2Used) {
5760 BestLoQuad = InputQuads[0] ? 0 : 1;
5761 BestHiQuad = InputQuads[2] ? 2 : 3;
5763 if (InputQuads.count() > 2) {
5769 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5770 // the shuffle mask. If a quad is scored as -1, that means that it contains
5771 // words from all 4 input quadwords.
5773 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5775 BestLoQuad < 0 ? 0 : BestLoQuad,
5776 BestHiQuad < 0 ? 1 : BestHiQuad
5778 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5779 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5780 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5781 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5783 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5784 // source words for the shuffle, to aid later transformations.
5785 bool AllWordsInNewV = true;
5786 bool InOrder[2] = { true, true };
5787 for (unsigned i = 0; i != 8; ++i) {
5788 int idx = MaskVals[i];
5790 InOrder[i/4] = false;
5791 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5793 AllWordsInNewV = false;
5797 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5798 if (AllWordsInNewV) {
5799 for (int i = 0; i != 8; ++i) {
5800 int idx = MaskVals[i];
5803 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5804 if ((idx != i) && idx < 4)
5806 if ((idx != i) && idx > 3)
5815 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5816 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5817 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5818 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5819 unsigned TargetMask = 0;
5820 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5821 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5822 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5823 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5824 getShufflePSHUFLWImmediate(SVOp);
5825 V1 = NewV.getOperand(0);
5826 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5830 // If we have SSSE3, and all words of the result are from 1 input vector,
5831 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5832 // is present, fall back to case 4.
5833 if (Subtarget->hasSSSE3()) {
5834 SmallVector<SDValue,16> pshufbMask;
5836 // If we have elements from both input vectors, set the high bit of the
5837 // shuffle mask element to zero out elements that come from V2 in the V1
5838 // mask, and elements that come from V1 in the V2 mask, so that the two
5839 // results can be OR'd together.
5840 bool TwoInputs = V1Used && V2Used;
5841 for (unsigned i = 0; i != 8; ++i) {
5842 int EltIdx = MaskVals[i] * 2;
5843 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5844 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5845 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5846 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5848 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5849 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5850 DAG.getNode(ISD::BUILD_VECTOR, dl,
5851 MVT::v16i8, &pshufbMask[0], 16));
5853 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5855 // Calculate the shuffle mask for the second input, shuffle it, and
5856 // OR it with the first shuffled input.
5858 for (unsigned i = 0; i != 8; ++i) {
5859 int EltIdx = MaskVals[i] * 2;
5860 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5861 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5862 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5863 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5865 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5866 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5867 DAG.getNode(ISD::BUILD_VECTOR, dl,
5868 MVT::v16i8, &pshufbMask[0], 16));
5869 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5870 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5873 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5874 // and update MaskVals with new element order.
5875 std::bitset<8> InOrder;
5876 if (BestLoQuad >= 0) {
5877 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5878 for (int i = 0; i != 4; ++i) {
5879 int idx = MaskVals[i];
5882 } else if ((idx / 4) == BestLoQuad) {
5887 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5890 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5892 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5894 getShufflePSHUFLWImmediate(SVOp), DAG);
5898 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5899 // and update MaskVals with the new element order.
5900 if (BestHiQuad >= 0) {
5901 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5902 for (unsigned i = 4; i != 8; ++i) {
5903 int idx = MaskVals[i];
5906 } else if ((idx / 4) == BestHiQuad) {
5907 MaskV[i] = (idx & 3) + 4;
5911 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5914 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5915 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5916 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5918 getShufflePSHUFHWImmediate(SVOp), DAG);
5922 // In case BestHi & BestLo were both -1, which means each quadword has a word
5923 // from each of the four input quadwords, calculate the InOrder bitvector now
5924 // before falling through to the insert/extract cleanup.
5925 if (BestLoQuad == -1 && BestHiQuad == -1) {
5927 for (int i = 0; i != 8; ++i)
5928 if (MaskVals[i] < 0 || MaskVals[i] == i)
5932 // The other elements are put in the right place using pextrw and pinsrw.
5933 for (unsigned i = 0; i != 8; ++i) {
5936 int EltIdx = MaskVals[i];
5939 SDValue ExtOp = (EltIdx < 8) ?
5940 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5941 DAG.getIntPtrConstant(EltIdx)) :
5942 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5943 DAG.getIntPtrConstant(EltIdx - 8));
5944 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5945 DAG.getIntPtrConstant(i));
5950 // v16i8 shuffles - Prefer shuffles in the following order:
5951 // 1. [ssse3] 1 x pshufb
5952 // 2. [ssse3] 2 x pshufb + 1 x por
5953 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5955 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5957 const X86TargetLowering &TLI) {
5958 SDValue V1 = SVOp->getOperand(0);
5959 SDValue V2 = SVOp->getOperand(1);
5960 DebugLoc dl = SVOp->getDebugLoc();
5961 ArrayRef<int> MaskVals = SVOp->getMask();
5963 // If we have SSSE3, case 1 is generated when all result bytes come from
5964 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5965 // present, fall back to case 3.
5967 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5968 if (TLI.getSubtarget()->hasSSSE3()) {
5969 SmallVector<SDValue,16> pshufbMask;
5971 // If all result elements are from one input vector, then only translate
5972 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5974 // Otherwise, we have elements from both input vectors, and must zero out
5975 // elements that come from V2 in the first mask, and V1 in the second mask
5976 // so that we can OR them together.
5977 for (unsigned i = 0; i != 16; ++i) {
5978 int EltIdx = MaskVals[i];
5979 if (EltIdx < 0 || EltIdx >= 16)
5981 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5983 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5984 DAG.getNode(ISD::BUILD_VECTOR, dl,
5985 MVT::v16i8, &pshufbMask[0], 16));
5987 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5988 // the 2nd operand if it's undefined or zero.
5989 if (V2.getOpcode() == ISD::UNDEF ||
5990 ISD::isBuildVectorAllZeros(V2.getNode()))
5993 // Calculate the shuffle mask for the second input, shuffle it, and
5994 // OR it with the first shuffled input.
5996 for (unsigned i = 0; i != 16; ++i) {
5997 int EltIdx = MaskVals[i];
5998 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5999 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6001 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6002 DAG.getNode(ISD::BUILD_VECTOR, dl,
6003 MVT::v16i8, &pshufbMask[0], 16));
6004 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6007 // No SSSE3 - Calculate in place words and then fix all out of place words
6008 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6009 // the 16 different words that comprise the two doublequadword input vectors.
6010 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6011 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6013 for (int i = 0; i != 8; ++i) {
6014 int Elt0 = MaskVals[i*2];
6015 int Elt1 = MaskVals[i*2+1];
6017 // This word of the result is all undef, skip it.
6018 if (Elt0 < 0 && Elt1 < 0)
6021 // This word of the result is already in the correct place, skip it.
6022 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6025 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6026 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6029 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6030 // using a single extract together, load it and store it.
6031 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6032 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6033 DAG.getIntPtrConstant(Elt1 / 2));
6034 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6035 DAG.getIntPtrConstant(i));
6039 // If Elt1 is defined, extract it from the appropriate source. If the
6040 // source byte is not also odd, shift the extracted word left 8 bits
6041 // otherwise clear the bottom 8 bits if we need to do an or.
6043 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6044 DAG.getIntPtrConstant(Elt1 / 2));
6045 if ((Elt1 & 1) == 0)
6046 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6048 TLI.getShiftAmountTy(InsElt.getValueType())));
6050 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6051 DAG.getConstant(0xFF00, MVT::i16));
6053 // If Elt0 is defined, extract it from the appropriate source. If the
6054 // source byte is not also even, shift the extracted word right 8 bits. If
6055 // Elt1 was also defined, OR the extracted values together before
6056 // inserting them in the result.
6058 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6059 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6060 if ((Elt0 & 1) != 0)
6061 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6063 TLI.getShiftAmountTy(InsElt0.getValueType())));
6065 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6066 DAG.getConstant(0x00FF, MVT::i16));
6067 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6070 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6071 DAG.getIntPtrConstant(i));
6073 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6076 // v32i8 shuffles - Translate to VPSHUFB if possible.
6078 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6079 const X86Subtarget *Subtarget,
6080 SelectionDAG &DAG) {
6081 EVT VT = SVOp->getValueType(0);
6082 SDValue V1 = SVOp->getOperand(0);
6083 SDValue V2 = SVOp->getOperand(1);
6084 DebugLoc dl = SVOp->getDebugLoc();
6085 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6087 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6088 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6089 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6091 // VPSHUFB may be generated if
6092 // (1) one of input vector is undefined or zeroinitializer.
6093 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6094 // And (2) the mask indexes don't cross the 128-bit lane.
6095 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6096 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6099 if (V1IsAllZero && !V2IsAllZero) {
6100 CommuteVectorShuffleMask(MaskVals, 32);
6103 SmallVector<SDValue, 32> pshufbMask;
6104 for (unsigned i = 0; i != 32; i++) {
6105 int EltIdx = MaskVals[i];
6106 if (EltIdx < 0 || EltIdx >= 32)
6109 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6110 // Cross lane is not allowed.
6114 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6116 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6117 DAG.getNode(ISD::BUILD_VECTOR, dl,
6118 MVT::v32i8, &pshufbMask[0], 32));
6121 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6122 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6123 /// done when every pair / quad of shuffle mask elements point to elements in
6124 /// the right sequence. e.g.
6125 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6127 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6128 SelectionDAG &DAG, DebugLoc dl) {
6129 MVT VT = SVOp->getValueType(0).getSimpleVT();
6130 unsigned NumElems = VT.getVectorNumElements();
6133 switch (VT.SimpleTy) {
6134 default: llvm_unreachable("Unexpected!");
6135 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6136 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6137 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6138 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6139 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6140 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6143 SmallVector<int, 8> MaskVec;
6144 for (unsigned i = 0; i != NumElems; i += Scale) {
6146 for (unsigned j = 0; j != Scale; ++j) {
6147 int EltIdx = SVOp->getMaskElt(i+j);
6151 StartIdx = (EltIdx / Scale);
6152 if (EltIdx != (int)(StartIdx*Scale + j))
6155 MaskVec.push_back(StartIdx);
6158 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6159 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6160 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6163 /// getVZextMovL - Return a zero-extending vector move low node.
6165 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6166 SDValue SrcOp, SelectionDAG &DAG,
6167 const X86Subtarget *Subtarget, DebugLoc dl) {
6168 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6169 LoadSDNode *LD = NULL;
6170 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6171 LD = dyn_cast<LoadSDNode>(SrcOp);
6173 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6175 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6176 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6177 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6178 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6179 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6181 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6182 return DAG.getNode(ISD::BITCAST, dl, VT,
6183 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6184 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6192 return DAG.getNode(ISD::BITCAST, dl, VT,
6193 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6194 DAG.getNode(ISD::BITCAST, dl,
6198 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6199 /// which could not be matched by any known target speficic shuffle
6201 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6203 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6204 if (NewOp.getNode())
6207 EVT VT = SVOp->getValueType(0);
6209 unsigned NumElems = VT.getVectorNumElements();
6210 unsigned NumLaneElems = NumElems / 2;
6212 DebugLoc dl = SVOp->getDebugLoc();
6213 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6214 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6217 SmallVector<int, 16> Mask;
6218 for (unsigned l = 0; l < 2; ++l) {
6219 // Build a shuffle mask for the output, discovering on the fly which
6220 // input vectors to use as shuffle operands (recorded in InputUsed).
6221 // If building a suitable shuffle vector proves too hard, then bail
6222 // out with UseBuildVector set.
6223 bool UseBuildVector = false;
6224 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6225 unsigned LaneStart = l * NumLaneElems;
6226 for (unsigned i = 0; i != NumLaneElems; ++i) {
6227 // The mask element. This indexes into the input.
6228 int Idx = SVOp->getMaskElt(i+LaneStart);
6230 // the mask element does not index into any input vector.
6235 // The input vector this mask element indexes into.
6236 int Input = Idx / NumLaneElems;
6238 // Turn the index into an offset from the start of the input vector.
6239 Idx -= Input * NumLaneElems;
6241 // Find or create a shuffle vector operand to hold this input.
6243 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6244 if (InputUsed[OpNo] == Input)
6245 // This input vector is already an operand.
6247 if (InputUsed[OpNo] < 0) {
6248 // Create a new operand for this input vector.
6249 InputUsed[OpNo] = Input;
6254 if (OpNo >= array_lengthof(InputUsed)) {
6255 // More than two input vectors used! Give up on trying to create a
6256 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6257 UseBuildVector = true;
6261 // Add the mask index for the new shuffle vector.
6262 Mask.push_back(Idx + OpNo * NumLaneElems);
6265 if (UseBuildVector) {
6266 SmallVector<SDValue, 16> SVOps;
6267 for (unsigned i = 0; i != NumLaneElems; ++i) {
6268 // The mask element. This indexes into the input.
6269 int Idx = SVOp->getMaskElt(i+LaneStart);
6271 SVOps.push_back(DAG.getUNDEF(EltVT));
6275 // The input vector this mask element indexes into.
6276 int Input = Idx / NumElems;
6278 // Turn the index into an offset from the start of the input vector.
6279 Idx -= Input * NumElems;
6281 // Extract the vector element by hand.
6282 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6283 SVOp->getOperand(Input),
6284 DAG.getIntPtrConstant(Idx)));
6287 // Construct the output using a BUILD_VECTOR.
6288 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6290 } else if (InputUsed[0] < 0) {
6291 // No input vectors were used! The result is undefined.
6292 Output[l] = DAG.getUNDEF(NVT);
6294 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6295 (InputUsed[0] % 2) * NumLaneElems,
6297 // If only one input was used, use an undefined vector for the other.
6298 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6299 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6300 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6301 // At least one input vector was used. Create a new shuffle vector.
6302 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6308 // Concatenate the result back
6309 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6312 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6313 /// 4 elements, and match them with several different shuffle types.
6315 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6316 SDValue V1 = SVOp->getOperand(0);
6317 SDValue V2 = SVOp->getOperand(1);
6318 DebugLoc dl = SVOp->getDebugLoc();
6319 EVT VT = SVOp->getValueType(0);
6321 assert(VT.is128BitVector() && "Unsupported vector size");
6323 std::pair<int, int> Locs[4];
6324 int Mask1[] = { -1, -1, -1, -1 };
6325 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6329 for (unsigned i = 0; i != 4; ++i) {
6330 int Idx = PermMask[i];
6332 Locs[i] = std::make_pair(-1, -1);
6334 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6336 Locs[i] = std::make_pair(0, NumLo);
6340 Locs[i] = std::make_pair(1, NumHi);
6342 Mask1[2+NumHi] = Idx;
6348 if (NumLo <= 2 && NumHi <= 2) {
6349 // If no more than two elements come from either vector. This can be
6350 // implemented with two shuffles. First shuffle gather the elements.
6351 // The second shuffle, which takes the first shuffle as both of its
6352 // vector operands, put the elements into the right order.
6353 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6355 int Mask2[] = { -1, -1, -1, -1 };
6357 for (unsigned i = 0; i != 4; ++i)
6358 if (Locs[i].first != -1) {
6359 unsigned Idx = (i < 2) ? 0 : 4;
6360 Idx += Locs[i].first * 2 + Locs[i].second;
6364 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6367 if (NumLo == 3 || NumHi == 3) {
6368 // Otherwise, we must have three elements from one vector, call it X, and
6369 // one element from the other, call it Y. First, use a shufps to build an
6370 // intermediate vector with the one element from Y and the element from X
6371 // that will be in the same half in the final destination (the indexes don't
6372 // matter). Then, use a shufps to build the final vector, taking the half
6373 // containing the element from Y from the intermediate, and the other half
6376 // Normalize it so the 3 elements come from V1.
6377 CommuteVectorShuffleMask(PermMask, 4);
6381 // Find the element from V2.
6383 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6384 int Val = PermMask[HiIndex];
6391 Mask1[0] = PermMask[HiIndex];
6393 Mask1[2] = PermMask[HiIndex^1];
6395 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6398 Mask1[0] = PermMask[0];
6399 Mask1[1] = PermMask[1];
6400 Mask1[2] = HiIndex & 1 ? 6 : 4;
6401 Mask1[3] = HiIndex & 1 ? 4 : 6;
6402 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6405 Mask1[0] = HiIndex & 1 ? 2 : 0;
6406 Mask1[1] = HiIndex & 1 ? 0 : 2;
6407 Mask1[2] = PermMask[2];
6408 Mask1[3] = PermMask[3];
6413 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6416 // Break it into (shuffle shuffle_hi, shuffle_lo).
6417 int LoMask[] = { -1, -1, -1, -1 };
6418 int HiMask[] = { -1, -1, -1, -1 };
6420 int *MaskPtr = LoMask;
6421 unsigned MaskIdx = 0;
6424 for (unsigned i = 0; i != 4; ++i) {
6431 int Idx = PermMask[i];
6433 Locs[i] = std::make_pair(-1, -1);
6434 } else if (Idx < 4) {
6435 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6436 MaskPtr[LoIdx] = Idx;
6439 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6440 MaskPtr[HiIdx] = Idx;
6445 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6446 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6447 int MaskOps[] = { -1, -1, -1, -1 };
6448 for (unsigned i = 0; i != 4; ++i)
6449 if (Locs[i].first != -1)
6450 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6451 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6454 static bool MayFoldVectorLoad(SDValue V) {
6455 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6456 V = V.getOperand(0);
6458 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6459 V = V.getOperand(0);
6460 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6461 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6462 // BUILD_VECTOR (load), undef
6463 V = V.getOperand(0);
6465 return MayFoldLoad(V);
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470 EVT VT = Op.getValueType();
6472 // Canonizalize to v2f64.
6473 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474 return DAG.getNode(ISD::BITCAST, dl, VT,
6475 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6482 SDValue V1 = Op.getOperand(0);
6483 SDValue V2 = Op.getOperand(1);
6484 EVT VT = Op.getValueType();
6486 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6488 if (HasSSE2 && VT == MVT::v2f64)
6489 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6491 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492 return DAG.getNode(ISD::BITCAST, dl, VT,
6493 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500 SDValue V1 = Op.getOperand(0);
6501 SDValue V2 = Op.getOperand(1);
6502 EVT VT = Op.getValueType();
6504 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505 "unsupported shuffle type");
6507 if (V2.getOpcode() == ISD::UNDEF)
6511 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6515 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6516 SDValue V1 = Op.getOperand(0);
6517 SDValue V2 = Op.getOperand(1);
6518 EVT VT = Op.getValueType();
6519 unsigned NumElems = VT.getVectorNumElements();
6521 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6522 // operand of these instructions is only memory, so check if there's a
6523 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6525 bool CanFoldLoad = false;
6527 // Trivial case, when V2 comes from a load.
6528 if (MayFoldVectorLoad(V2))
6531 // When V1 is a load, it can be folded later into a store in isel, example:
6532 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6534 // (MOVLPSmr addr:$src1, VR128:$src2)
6535 // So, recognize this potential and also use MOVLPS or MOVLPD
6536 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6539 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6541 if (HasSSE2 && NumElems == 2)
6542 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6545 // If we don't care about the second element, proceed to use movss.
6546 if (SVOp->getMaskElt(1) != -1)
6547 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6550 // movl and movlp will both match v2i64, but v2i64 is never matched by
6551 // movl earlier because we make it strict to avoid messing with the movlp load
6552 // folding logic (see the code above getMOVLP call). Match it here then,
6553 // this is horrible, but will stay like this until we move all shuffle
6554 // matching to x86 specific nodes. Note that for the 1st condition all
6555 // types are matched with movsd.
6557 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6558 // as to remove this logic from here, as much as possible
6559 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6560 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6561 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6564 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6566 // Invert the operand order and use SHUFPS to match it.
6567 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6568 getShuffleSHUFImmediate(SVOp), DAG);
6571 // Reduce a vector shuffle to zext.
6573 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6574 // PMOVZX is only available from SSE41.
6575 if (!Subtarget->hasSSE41())
6578 EVT VT = Op.getValueType();
6580 // Only AVX2 support 256-bit vector integer extending.
6581 if (!Subtarget->hasInt256() && VT.is256BitVector())
6584 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6585 DebugLoc DL = Op.getDebugLoc();
6586 SDValue V1 = Op.getOperand(0);
6587 SDValue V2 = Op.getOperand(1);
6588 unsigned NumElems = VT.getVectorNumElements();
6590 // Extending is an unary operation and the element type of the source vector
6591 // won't be equal to or larger than i64.
6592 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6593 VT.getVectorElementType() == MVT::i64)
6596 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6597 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6598 while ((1U << Shift) < NumElems) {
6599 if (SVOp->getMaskElt(1U << Shift) == 1)
6602 // The maximal ratio is 8, i.e. from i8 to i64.
6607 // Check the shuffle mask.
6608 unsigned Mask = (1U << Shift) - 1;
6609 for (unsigned i = 0; i != NumElems; ++i) {
6610 int EltIdx = SVOp->getMaskElt(i);
6611 if ((i & Mask) != 0 && EltIdx != -1)
6613 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6617 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6618 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6619 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6621 if (!isTypeLegal(NVT))
6624 // Simplify the operand as it's prepared to be fed into shuffle.
6625 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6626 if (V1.getOpcode() == ISD::BITCAST &&
6627 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6628 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6630 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6631 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6632 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6633 ConstantSDNode *CIdx =
6634 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6635 // If it's foldable, i.e. normal load with single use, we will let code
6636 // selection to fold it. Otherwise, we will short the conversion sequence.
6637 if (CIdx && CIdx->getZExtValue() == 0 &&
6638 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6639 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6642 return DAG.getNode(ISD::BITCAST, DL, VT,
6643 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6647 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6648 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6649 EVT VT = Op.getValueType();
6650 DebugLoc dl = Op.getDebugLoc();
6651 SDValue V1 = Op.getOperand(0);
6652 SDValue V2 = Op.getOperand(1);
6654 if (isZeroShuffle(SVOp))
6655 return getZeroVector(VT, Subtarget, DAG, dl);
6657 // Handle splat operations
6658 if (SVOp->isSplat()) {
6659 unsigned NumElem = VT.getVectorNumElements();
6660 int Size = VT.getSizeInBits();
6662 // Use vbroadcast whenever the splat comes from a foldable load
6663 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6664 if (Broadcast.getNode())
6667 // Handle splats by matching through known shuffle masks
6668 if ((Size == 128 && NumElem <= 4) ||
6669 (Size == 256 && NumElem <= 8))
6672 // All remaning splats are promoted to target supported vector shuffles.
6673 return PromoteSplat(SVOp, DAG);
6676 // Check integer expanding shuffles.
6677 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6678 if (NewOp.getNode())
6681 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6683 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6684 VT == MVT::v16i16 || VT == MVT::v32i8) {
6685 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6686 if (NewOp.getNode())
6687 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6688 } else if ((VT == MVT::v4i32 ||
6689 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6690 // FIXME: Figure out a cleaner way to do this.
6691 // Try to make use of movq to zero out the top part.
6692 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6693 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6694 if (NewOp.getNode()) {
6695 EVT NewVT = NewOp.getValueType();
6696 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6697 NewVT, true, false))
6698 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6699 DAG, Subtarget, dl);
6701 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6702 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6703 if (NewOp.getNode()) {
6704 EVT NewVT = NewOp.getValueType();
6705 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6706 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6707 DAG, Subtarget, dl);
6715 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6716 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6717 SDValue V1 = Op.getOperand(0);
6718 SDValue V2 = Op.getOperand(1);
6719 EVT VT = Op.getValueType();
6720 DebugLoc dl = Op.getDebugLoc();
6721 unsigned NumElems = VT.getVectorNumElements();
6722 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6723 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6724 bool V1IsSplat = false;
6725 bool V2IsSplat = false;
6726 bool HasSSE2 = Subtarget->hasSSE2();
6727 bool HasFp256 = Subtarget->hasFp256();
6728 bool HasInt256 = Subtarget->hasInt256();
6729 MachineFunction &MF = DAG.getMachineFunction();
6730 bool OptForSize = MF.getFunction()->getFnAttributes().
6731 hasAttribute(Attribute::OptimizeForSize);
6733 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6735 if (V1IsUndef && V2IsUndef)
6736 return DAG.getUNDEF(VT);
6738 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6740 // Vector shuffle lowering takes 3 steps:
6742 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6743 // narrowing and commutation of operands should be handled.
6744 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6746 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6747 // so the shuffle can be broken into other shuffles and the legalizer can
6748 // try the lowering again.
6750 // The general idea is that no vector_shuffle operation should be left to
6751 // be matched during isel, all of them must be converted to a target specific
6754 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6755 // narrowing and commutation of operands should be handled. The actual code
6756 // doesn't include all of those, work in progress...
6757 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6758 if (NewOp.getNode())
6761 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6763 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6764 // unpckh_undef). Only use pshufd if speed is more important than size.
6765 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6766 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6767 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6768 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6770 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6771 V2IsUndef && MayFoldVectorLoad(V1))
6772 return getMOVDDup(Op, dl, V1, DAG);
6774 if (isMOVHLPS_v_undef_Mask(M, VT))
6775 return getMOVHighToLow(Op, dl, DAG);
6777 // Use to match splats
6778 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6779 (VT == MVT::v2f64 || VT == MVT::v2i64))
6780 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6782 if (isPSHUFDMask(M, VT)) {
6783 // The actual implementation will match the mask in the if above and then
6784 // during isel it can match several different instructions, not only pshufd
6785 // as its name says, sad but true, emulate the behavior for now...
6786 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6787 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6789 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6791 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6792 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6794 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6795 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6798 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6802 // Check if this can be converted into a logical shift.
6803 bool isLeft = false;
6806 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6807 if (isShift && ShVal.hasOneUse()) {
6808 // If the shifted value has multiple uses, it may be cheaper to use
6809 // v_set0 + movlhps or movhlps, etc.
6810 EVT EltVT = VT.getVectorElementType();
6811 ShAmt *= EltVT.getSizeInBits();
6812 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6815 if (isMOVLMask(M, VT)) {
6816 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6817 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6818 if (!isMOVLPMask(M, VT)) {
6819 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6820 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6822 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6823 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6827 // FIXME: fold these into legal mask.
6828 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6829 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6831 if (isMOVHLPSMask(M, VT))
6832 return getMOVHighToLow(Op, dl, DAG);
6834 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6835 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6837 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6838 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6840 if (isMOVLPMask(M, VT))
6841 return getMOVLP(Op, dl, DAG, HasSSE2);
6843 if (ShouldXformToMOVHLPS(M, VT) ||
6844 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6845 return CommuteVectorShuffle(SVOp, DAG);
6848 // No better options. Use a vshldq / vsrldq.
6849 EVT EltVT = VT.getVectorElementType();
6850 ShAmt *= EltVT.getSizeInBits();
6851 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6854 bool Commuted = false;
6855 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6856 // 1,1,1,1 -> v8i16 though.
6857 V1IsSplat = isSplatVector(V1.getNode());
6858 V2IsSplat = isSplatVector(V2.getNode());
6860 // Canonicalize the splat or undef, if present, to be on the RHS.
6861 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6862 CommuteVectorShuffleMask(M, NumElems);
6864 std::swap(V1IsSplat, V2IsSplat);
6868 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6869 // Shuffling low element of v1 into undef, just return v1.
6872 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6873 // the instruction selector will not match, so get a canonical MOVL with
6874 // swapped operands to undo the commute.
6875 return getMOVL(DAG, dl, VT, V2, V1);
6878 if (isUNPCKLMask(M, VT, HasInt256))
6879 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6881 if (isUNPCKHMask(M, VT, HasInt256))
6882 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6885 // Normalize mask so all entries that point to V2 points to its first
6886 // element then try to match unpck{h|l} again. If match, return a
6887 // new vector_shuffle with the corrected mask.p
6888 SmallVector<int, 8> NewMask(M.begin(), M.end());
6889 NormalizeMask(NewMask, NumElems);
6890 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6891 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6892 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6893 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6897 // Commute is back and try unpck* again.
6898 // FIXME: this seems wrong.
6899 CommuteVectorShuffleMask(M, NumElems);
6901 std::swap(V1IsSplat, V2IsSplat);
6904 if (isUNPCKLMask(M, VT, HasInt256))
6905 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6907 if (isUNPCKHMask(M, VT, HasInt256))
6908 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6911 // Normalize the node to match x86 shuffle ops if needed
6912 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6913 return CommuteVectorShuffle(SVOp, DAG);
6915 // The checks below are all present in isShuffleMaskLegal, but they are
6916 // inlined here right now to enable us to directly emit target specific
6917 // nodes, and remove one by one until they don't return Op anymore.
6919 if (isPALIGNRMask(M, VT, Subtarget))
6920 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6921 getShufflePALIGNRImmediate(SVOp),
6924 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6925 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6926 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6927 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6930 if (isPSHUFHWMask(M, VT, HasInt256))
6931 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6932 getShufflePSHUFHWImmediate(SVOp),
6935 if (isPSHUFLWMask(M, VT, HasInt256))
6936 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6937 getShufflePSHUFLWImmediate(SVOp),
6940 if (isSHUFPMask(M, VT, HasFp256))
6941 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6942 getShuffleSHUFImmediate(SVOp), DAG);
6944 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6945 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6946 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6947 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6949 //===--------------------------------------------------------------------===//
6950 // Generate target specific nodes for 128 or 256-bit shuffles only
6951 // supported in the AVX instruction set.
6954 // Handle VMOVDDUPY permutations
6955 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6956 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6958 // Handle VPERMILPS/D* permutations
6959 if (isVPERMILPMask(M, VT, HasFp256)) {
6960 if (HasInt256 && VT == MVT::v8i32)
6961 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6962 getShuffleSHUFImmediate(SVOp), DAG);
6963 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6964 getShuffleSHUFImmediate(SVOp), DAG);
6967 // Handle VPERM2F128/VPERM2I128 permutations
6968 if (isVPERM2X128Mask(M, VT, HasFp256))
6969 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6970 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6972 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6973 if (BlendOp.getNode())
6976 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6977 SmallVector<SDValue, 8> permclMask;
6978 for (unsigned i = 0; i != 8; ++i) {
6979 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6981 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6983 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6984 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6985 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6988 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6989 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6990 getShuffleCLImmediate(SVOp), DAG);
6992 //===--------------------------------------------------------------------===//
6993 // Since no target specific shuffle was selected for this generic one,
6994 // lower it into other known shuffles. FIXME: this isn't true yet, but
6995 // this is the plan.
6998 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6999 if (VT == MVT::v8i16) {
7000 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7001 if (NewOp.getNode())
7005 if (VT == MVT::v16i8) {
7006 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7007 if (NewOp.getNode())
7011 if (VT == MVT::v32i8) {
7012 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7013 if (NewOp.getNode())
7017 // Handle all 128-bit wide vectors with 4 elements, and match them with
7018 // several different shuffle types.
7019 if (NumElems == 4 && VT.is128BitVector())
7020 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7022 // Handle general 256-bit shuffles
7023 if (VT.is256BitVector())
7024 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7030 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7031 SelectionDAG &DAG) const {
7032 EVT VT = Op.getValueType();
7033 DebugLoc dl = Op.getDebugLoc();
7035 if (!Op.getOperand(0).getValueType().is128BitVector())
7038 if (VT.getSizeInBits() == 8) {
7039 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7040 Op.getOperand(0), Op.getOperand(1));
7041 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7042 DAG.getValueType(VT));
7043 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7046 if (VT.getSizeInBits() == 16) {
7047 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7048 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7050 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7051 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7052 DAG.getNode(ISD::BITCAST, dl,
7056 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7057 Op.getOperand(0), Op.getOperand(1));
7058 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7059 DAG.getValueType(VT));
7060 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7063 if (VT == MVT::f32) {
7064 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7065 // the result back to FR32 register. It's only worth matching if the
7066 // result has a single use which is a store or a bitcast to i32. And in
7067 // the case of a store, it's not worth it if the index is a constant 0,
7068 // because a MOVSSmr can be used instead, which is smaller and faster.
7069 if (!Op.hasOneUse())
7071 SDNode *User = *Op.getNode()->use_begin();
7072 if ((User->getOpcode() != ISD::STORE ||
7073 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7074 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7075 (User->getOpcode() != ISD::BITCAST ||
7076 User->getValueType(0) != MVT::i32))
7078 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7079 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7082 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7085 if (VT == MVT::i32 || VT == MVT::i64) {
7086 // ExtractPS/pextrq works with constant index.
7087 if (isa<ConstantSDNode>(Op.getOperand(1)))
7094 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7095 SelectionDAG &DAG) const {
7096 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7099 SDValue Vec = Op.getOperand(0);
7100 EVT VecVT = Vec.getValueType();
7102 // If this is a 256-bit vector result, first extract the 128-bit vector and
7103 // then extract the element from the 128-bit vector.
7104 if (VecVT.is256BitVector()) {
7105 DebugLoc dl = Op.getNode()->getDebugLoc();
7106 unsigned NumElems = VecVT.getVectorNumElements();
7107 SDValue Idx = Op.getOperand(1);
7108 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7110 // Get the 128-bit vector.
7111 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7113 if (IdxVal >= NumElems/2)
7114 IdxVal -= NumElems/2;
7115 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7116 DAG.getConstant(IdxVal, MVT::i32));
7119 assert(VecVT.is128BitVector() && "Unexpected vector length");
7121 if (Subtarget->hasSSE41()) {
7122 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7127 EVT VT = Op.getValueType();
7128 DebugLoc dl = Op.getDebugLoc();
7129 // TODO: handle v16i8.
7130 if (VT.getSizeInBits() == 16) {
7131 SDValue Vec = Op.getOperand(0);
7132 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7134 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7135 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7136 DAG.getNode(ISD::BITCAST, dl,
7139 // Transform it so it match pextrw which produces a 32-bit result.
7140 EVT EltVT = MVT::i32;
7141 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7142 Op.getOperand(0), Op.getOperand(1));
7143 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7144 DAG.getValueType(VT));
7145 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7148 if (VT.getSizeInBits() == 32) {
7149 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7153 // SHUFPS the element to the lowest double word, then movss.
7154 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7155 EVT VVT = Op.getOperand(0).getValueType();
7156 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7157 DAG.getUNDEF(VVT), Mask);
7158 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7159 DAG.getIntPtrConstant(0));
7162 if (VT.getSizeInBits() == 64) {
7163 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7164 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7165 // to match extract_elt for f64.
7166 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7170 // UNPCKHPD the element to the lowest double word, then movsd.
7171 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7172 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7173 int Mask[2] = { 1, -1 };
7174 EVT VVT = Op.getOperand(0).getValueType();
7175 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7176 DAG.getUNDEF(VVT), Mask);
7177 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7178 DAG.getIntPtrConstant(0));
7185 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7186 SelectionDAG &DAG) const {
7187 EVT VT = Op.getValueType();
7188 EVT EltVT = VT.getVectorElementType();
7189 DebugLoc dl = Op.getDebugLoc();
7191 SDValue N0 = Op.getOperand(0);
7192 SDValue N1 = Op.getOperand(1);
7193 SDValue N2 = Op.getOperand(2);
7195 if (!VT.is128BitVector())
7198 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7199 isa<ConstantSDNode>(N2)) {
7201 if (VT == MVT::v8i16)
7202 Opc = X86ISD::PINSRW;
7203 else if (VT == MVT::v16i8)
7204 Opc = X86ISD::PINSRB;
7206 Opc = X86ISD::PINSRB;
7208 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7210 if (N1.getValueType() != MVT::i32)
7211 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7212 if (N2.getValueType() != MVT::i32)
7213 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7214 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7217 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7218 // Bits [7:6] of the constant are the source select. This will always be
7219 // zero here. The DAG Combiner may combine an extract_elt index into these
7220 // bits. For example (insert (extract, 3), 2) could be matched by putting
7221 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7222 // Bits [5:4] of the constant are the destination select. This is the
7223 // value of the incoming immediate.
7224 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7225 // combine either bitwise AND or insert of float 0.0 to set these bits.
7226 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7227 // Create this as a scalar to vector..
7228 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7229 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7232 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7233 // PINSR* works with constant index.
7240 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7241 EVT VT = Op.getValueType();
7242 EVT EltVT = VT.getVectorElementType();
7244 DebugLoc dl = Op.getDebugLoc();
7245 SDValue N0 = Op.getOperand(0);
7246 SDValue N1 = Op.getOperand(1);
7247 SDValue N2 = Op.getOperand(2);
7249 // If this is a 256-bit vector result, first extract the 128-bit vector,
7250 // insert the element into the extracted half and then place it back.
7251 if (VT.is256BitVector()) {
7252 if (!isa<ConstantSDNode>(N2))
7255 // Get the desired 128-bit vector half.
7256 unsigned NumElems = VT.getVectorNumElements();
7257 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7258 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7260 // Insert the element into the desired half.
7261 bool Upper = IdxVal >= NumElems/2;
7262 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7263 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7265 // Insert the changed part back to the 256-bit vector
7266 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7269 if (Subtarget->hasSSE41())
7270 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7272 if (EltVT == MVT::i8)
7275 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7276 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7277 // as its second argument.
7278 if (N1.getValueType() != MVT::i32)
7279 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7280 if (N2.getValueType() != MVT::i32)
7281 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7282 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7287 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7288 LLVMContext *Context = DAG.getContext();
7289 DebugLoc dl = Op.getDebugLoc();
7290 EVT OpVT = Op.getValueType();
7292 // If this is a 256-bit vector result, first insert into a 128-bit
7293 // vector and then insert into the 256-bit vector.
7294 if (!OpVT.is128BitVector()) {
7295 // Insert into a 128-bit vector.
7296 EVT VT128 = EVT::getVectorVT(*Context,
7297 OpVT.getVectorElementType(),
7298 OpVT.getVectorNumElements() / 2);
7300 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7302 // Insert the 128-bit vector.
7303 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7306 if (OpVT == MVT::v1i64 &&
7307 Op.getOperand(0).getValueType() == MVT::i64)
7308 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7310 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7311 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7312 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7313 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7316 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7317 // a simple subregister reference or explicit instructions to grab
7318 // upper bits of a vector.
7319 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7320 SelectionDAG &DAG) {
7321 if (Subtarget->hasFp256()) {
7322 DebugLoc dl = Op.getNode()->getDebugLoc();
7323 SDValue Vec = Op.getNode()->getOperand(0);
7324 SDValue Idx = Op.getNode()->getOperand(1);
7326 if (Op.getNode()->getValueType(0).is128BitVector() &&
7327 Vec.getNode()->getValueType(0).is256BitVector() &&
7328 isa<ConstantSDNode>(Idx)) {
7329 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7330 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7336 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7337 // simple superregister reference or explicit instructions to insert
7338 // the upper bits of a vector.
7339 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7340 SelectionDAG &DAG) {
7341 if (Subtarget->hasFp256()) {
7342 DebugLoc dl = Op.getNode()->getDebugLoc();
7343 SDValue Vec = Op.getNode()->getOperand(0);
7344 SDValue SubVec = Op.getNode()->getOperand(1);
7345 SDValue Idx = Op.getNode()->getOperand(2);
7347 if (Op.getNode()->getValueType(0).is256BitVector() &&
7348 SubVec.getNode()->getValueType(0).is128BitVector() &&
7349 isa<ConstantSDNode>(Idx)) {
7350 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7351 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7357 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7358 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7359 // one of the above mentioned nodes. It has to be wrapped because otherwise
7360 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7361 // be used to form addressing mode. These wrapped nodes will be selected
7364 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7365 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7367 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7369 unsigned char OpFlag = 0;
7370 unsigned WrapperKind = X86ISD::Wrapper;
7371 CodeModel::Model M = getTargetMachine().getCodeModel();
7373 if (Subtarget->isPICStyleRIPRel() &&
7374 (M == CodeModel::Small || M == CodeModel::Kernel))
7375 WrapperKind = X86ISD::WrapperRIP;
7376 else if (Subtarget->isPICStyleGOT())
7377 OpFlag = X86II::MO_GOTOFF;
7378 else if (Subtarget->isPICStyleStubPIC())
7379 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7381 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7383 CP->getOffset(), OpFlag);
7384 DebugLoc DL = CP->getDebugLoc();
7385 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7386 // With PIC, the address is actually $g + Offset.
7388 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7389 DAG.getNode(X86ISD::GlobalBaseReg,
7390 DebugLoc(), getPointerTy()),
7397 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7398 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7400 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7402 unsigned char OpFlag = 0;
7403 unsigned WrapperKind = X86ISD::Wrapper;
7404 CodeModel::Model M = getTargetMachine().getCodeModel();
7406 if (Subtarget->isPICStyleRIPRel() &&
7407 (M == CodeModel::Small || M == CodeModel::Kernel))
7408 WrapperKind = X86ISD::WrapperRIP;
7409 else if (Subtarget->isPICStyleGOT())
7410 OpFlag = X86II::MO_GOTOFF;
7411 else if (Subtarget->isPICStyleStubPIC())
7412 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7414 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7416 DebugLoc DL = JT->getDebugLoc();
7417 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7419 // With PIC, the address is actually $g + Offset.
7421 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7422 DAG.getNode(X86ISD::GlobalBaseReg,
7423 DebugLoc(), getPointerTy()),
7430 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7431 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7433 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7435 unsigned char OpFlag = 0;
7436 unsigned WrapperKind = X86ISD::Wrapper;
7437 CodeModel::Model M = getTargetMachine().getCodeModel();
7439 if (Subtarget->isPICStyleRIPRel() &&
7440 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7441 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7442 OpFlag = X86II::MO_GOTPCREL;
7443 WrapperKind = X86ISD::WrapperRIP;
7444 } else if (Subtarget->isPICStyleGOT()) {
7445 OpFlag = X86II::MO_GOT;
7446 } else if (Subtarget->isPICStyleStubPIC()) {
7447 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7448 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7449 OpFlag = X86II::MO_DARWIN_NONLAZY;
7452 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7454 DebugLoc DL = Op.getDebugLoc();
7455 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7457 // With PIC, the address is actually $g + Offset.
7458 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7459 !Subtarget->is64Bit()) {
7460 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461 DAG.getNode(X86ISD::GlobalBaseReg,
7462 DebugLoc(), getPointerTy()),
7466 // For symbols that require a load from a stub to get the address, emit the
7468 if (isGlobalStubReference(OpFlag))
7469 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7470 MachinePointerInfo::getGOT(), false, false, false, 0);
7476 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7477 // Create the TargetBlockAddressAddress node.
7478 unsigned char OpFlags =
7479 Subtarget->ClassifyBlockAddressReference();
7480 CodeModel::Model M = getTargetMachine().getCodeModel();
7481 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7482 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7483 DebugLoc dl = Op.getDebugLoc();
7484 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7487 if (Subtarget->isPICStyleRIPRel() &&
7488 (M == CodeModel::Small || M == CodeModel::Kernel))
7489 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7491 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7493 // With PIC, the address is actually $g + Offset.
7494 if (isGlobalRelativeToPICBase(OpFlags)) {
7495 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7496 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7504 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7506 SelectionDAG &DAG) const {
7507 // Create the TargetGlobalAddress node, folding in the constant
7508 // offset if it is legal.
7509 unsigned char OpFlags =
7510 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7511 CodeModel::Model M = getTargetMachine().getCodeModel();
7513 if (OpFlags == X86II::MO_NO_FLAG &&
7514 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7515 // A direct static reference to a global.
7516 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7519 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7522 if (Subtarget->isPICStyleRIPRel() &&
7523 (M == CodeModel::Small || M == CodeModel::Kernel))
7524 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7526 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7528 // With PIC, the address is actually $g + Offset.
7529 if (isGlobalRelativeToPICBase(OpFlags)) {
7530 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7531 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7535 // For globals that require a load from a stub to get the address, emit the
7537 if (isGlobalStubReference(OpFlags))
7538 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7539 MachinePointerInfo::getGOT(), false, false, false, 0);
7541 // If there was a non-zero offset that we didn't fold, create an explicit
7544 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7545 DAG.getConstant(Offset, getPointerTy()));
7551 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7552 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7553 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7554 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7558 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7559 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7560 unsigned char OperandFlags, bool LocalDynamic = false) {
7561 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7562 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7563 DebugLoc dl = GA->getDebugLoc();
7564 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7565 GA->getValueType(0),
7569 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7573 SDValue Ops[] = { Chain, TGA, *InFlag };
7574 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7576 SDValue Ops[] = { Chain, TGA };
7577 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7580 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7581 MFI->setAdjustsStack(true);
7583 SDValue Flag = Chain.getValue(1);
7584 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7587 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7589 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7592 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7593 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7594 DAG.getNode(X86ISD::GlobalBaseReg,
7595 DebugLoc(), PtrVT), InFlag);
7596 InFlag = Chain.getValue(1);
7598 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7601 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7603 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7605 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7606 X86::RAX, X86II::MO_TLSGD);
7609 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7613 DebugLoc dl = GA->getDebugLoc();
7615 // Get the start address of the TLS block for this module.
7616 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7617 .getInfo<X86MachineFunctionInfo>();
7618 MFI->incNumLocalDynamicTLSAccesses();
7622 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7623 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7626 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7627 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7628 InFlag = Chain.getValue(1);
7629 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7630 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7633 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7637 unsigned char OperandFlags = X86II::MO_DTPOFF;
7638 unsigned WrapperKind = X86ISD::Wrapper;
7639 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7640 GA->getValueType(0),
7641 GA->getOffset(), OperandFlags);
7642 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7644 // Add x@dtpoff with the base.
7645 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7648 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7649 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7650 const EVT PtrVT, TLSModel::Model model,
7651 bool is64Bit, bool isPIC) {
7652 DebugLoc dl = GA->getDebugLoc();
7654 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7655 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7656 is64Bit ? 257 : 256));
7658 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7659 DAG.getIntPtrConstant(0),
7660 MachinePointerInfo(Ptr),
7661 false, false, false, 0);
7663 unsigned char OperandFlags = 0;
7664 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7666 unsigned WrapperKind = X86ISD::Wrapper;
7667 if (model == TLSModel::LocalExec) {
7668 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7669 } else if (model == TLSModel::InitialExec) {
7671 OperandFlags = X86II::MO_GOTTPOFF;
7672 WrapperKind = X86ISD::WrapperRIP;
7674 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7677 llvm_unreachable("Unexpected model");
7680 // emit "addl x@ntpoff,%eax" (local exec)
7681 // or "addl x@indntpoff,%eax" (initial exec)
7682 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7683 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7684 GA->getValueType(0),
7685 GA->getOffset(), OperandFlags);
7686 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7688 if (model == TLSModel::InitialExec) {
7689 if (isPIC && !is64Bit) {
7690 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7691 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7695 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7696 MachinePointerInfo::getGOT(), false, false, false,
7700 // The address of the thread local variable is the add of the thread
7701 // pointer with the offset of the variable.
7702 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7706 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7708 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7709 const GlobalValue *GV = GA->getGlobal();
7711 if (Subtarget->isTargetELF()) {
7712 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7715 case TLSModel::GeneralDynamic:
7716 if (Subtarget->is64Bit())
7717 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7718 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7719 case TLSModel::LocalDynamic:
7720 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7721 Subtarget->is64Bit());
7722 case TLSModel::InitialExec:
7723 case TLSModel::LocalExec:
7724 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7725 Subtarget->is64Bit(),
7726 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7728 llvm_unreachable("Unknown TLS model.");
7731 if (Subtarget->isTargetDarwin()) {
7732 // Darwin only has one model of TLS. Lower to that.
7733 unsigned char OpFlag = 0;
7734 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7735 X86ISD::WrapperRIP : X86ISD::Wrapper;
7737 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7739 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7740 !Subtarget->is64Bit();
7742 OpFlag = X86II::MO_TLVP_PIC_BASE;
7744 OpFlag = X86II::MO_TLVP;
7745 DebugLoc DL = Op.getDebugLoc();
7746 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7747 GA->getValueType(0),
7748 GA->getOffset(), OpFlag);
7749 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7751 // With PIC32, the address is actually $g + Offset.
7753 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7754 DAG.getNode(X86ISD::GlobalBaseReg,
7755 DebugLoc(), getPointerTy()),
7758 // Lowering the machine isd will make sure everything is in the right
7760 SDValue Chain = DAG.getEntryNode();
7761 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7762 SDValue Args[] = { Chain, Offset };
7763 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7765 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7766 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7767 MFI->setAdjustsStack(true);
7769 // And our return value (tls address) is in the standard call return value
7771 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7772 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7776 if (Subtarget->isTargetWindows()) {
7777 // Just use the implicit TLS architecture
7778 // Need to generate someting similar to:
7779 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7781 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7782 // mov rcx, qword [rdx+rcx*8]
7783 // mov eax, .tls$:tlsvar
7784 // [rax+rcx] contains the address
7785 // Windows 64bit: gs:0x58
7786 // Windows 32bit: fs:__tls_array
7788 // If GV is an alias then use the aliasee for determining
7789 // thread-localness.
7790 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7791 GV = GA->resolveAliasedGlobal(false);
7792 DebugLoc dl = GA->getDebugLoc();
7793 SDValue Chain = DAG.getEntryNode();
7795 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7796 // %gs:0x58 (64-bit).
7797 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7798 ? Type::getInt8PtrTy(*DAG.getContext(),
7800 : Type::getInt32PtrTy(*DAG.getContext(),
7803 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7804 Subtarget->is64Bit()
7805 ? DAG.getIntPtrConstant(0x58)
7806 : DAG.getExternalSymbol("_tls_array",
7808 MachinePointerInfo(Ptr),
7809 false, false, false, 0);
7811 // Load the _tls_index variable
7812 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7813 if (Subtarget->is64Bit())
7814 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7815 IDX, MachinePointerInfo(), MVT::i32,
7818 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7819 false, false, false, 0);
7821 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7823 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7825 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7826 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7827 false, false, false, 0);
7829 // Get the offset of start of .tls section
7830 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7831 GA->getValueType(0),
7832 GA->getOffset(), X86II::MO_SECREL);
7833 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7835 // The address of the thread local variable is the add of the thread
7836 // pointer with the offset of the variable.
7837 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7840 llvm_unreachable("TLS not implemented for this target.");
7843 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7844 /// and take a 2 x i32 value to shift plus a shift amount.
7845 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7846 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7847 EVT VT = Op.getValueType();
7848 unsigned VTBits = VT.getSizeInBits();
7849 DebugLoc dl = Op.getDebugLoc();
7850 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7851 SDValue ShOpLo = Op.getOperand(0);
7852 SDValue ShOpHi = Op.getOperand(1);
7853 SDValue ShAmt = Op.getOperand(2);
7854 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7855 DAG.getConstant(VTBits - 1, MVT::i8))
7856 : DAG.getConstant(0, VT);
7859 if (Op.getOpcode() == ISD::SHL_PARTS) {
7860 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7861 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7863 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7864 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7867 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7868 DAG.getConstant(VTBits, MVT::i8));
7869 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7870 AndNode, DAG.getConstant(0, MVT::i8));
7873 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7874 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7875 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7877 if (Op.getOpcode() == ISD::SHL_PARTS) {
7878 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7881 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7882 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7885 SDValue Ops[2] = { Lo, Hi };
7886 return DAG.getMergeValues(Ops, 2, dl);
7889 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7890 SelectionDAG &DAG) const {
7891 EVT SrcVT = Op.getOperand(0).getValueType();
7893 if (SrcVT.isVector())
7896 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7897 "Unknown SINT_TO_FP to lower!");
7899 // These are really Legal; return the operand so the caller accepts it as
7901 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7903 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7904 Subtarget->is64Bit()) {
7908 DebugLoc dl = Op.getDebugLoc();
7909 unsigned Size = SrcVT.getSizeInBits()/8;
7910 MachineFunction &MF = DAG.getMachineFunction();
7911 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7912 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7913 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7915 MachinePointerInfo::getFixedStack(SSFI),
7917 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7920 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7922 SelectionDAG &DAG) const {
7924 DebugLoc DL = Op.getDebugLoc();
7926 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7928 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7930 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7932 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7934 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7935 MachineMemOperand *MMO;
7937 int SSFI = FI->getIndex();
7939 DAG.getMachineFunction()
7940 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7941 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7943 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7944 StackSlot = StackSlot.getOperand(1);
7946 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7947 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7949 Tys, Ops, array_lengthof(Ops),
7953 Chain = Result.getValue(1);
7954 SDValue InFlag = Result.getValue(2);
7956 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7957 // shouldn't be necessary except that RFP cannot be live across
7958 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7959 MachineFunction &MF = DAG.getMachineFunction();
7960 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7961 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963 Tys = DAG.getVTList(MVT::Other);
7965 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7967 MachineMemOperand *MMO =
7968 DAG.getMachineFunction()
7969 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7970 MachineMemOperand::MOStore, SSFISize, SSFISize);
7972 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7973 Ops, array_lengthof(Ops),
7974 Op.getValueType(), MMO);
7975 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7976 MachinePointerInfo::getFixedStack(SSFI),
7977 false, false, false, 0);
7983 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7984 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7985 SelectionDAG &DAG) const {
7986 // This algorithm is not obvious. Here it is what we're trying to output:
7989 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7990 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7994 pshufd $0x4e, %xmm0, %xmm1
7999 DebugLoc dl = Op.getDebugLoc();
8000 LLVMContext *Context = DAG.getContext();
8002 // Build some magic constants.
8003 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8004 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8005 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8007 SmallVector<Constant*,2> CV1;
8009 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8011 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8012 Constant *C1 = ConstantVector::get(CV1);
8013 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8015 // Load the 64-bit value into an XMM register.
8016 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8018 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8019 MachinePointerInfo::getConstantPool(),
8020 false, false, false, 16);
8021 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8022 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8025 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8026 MachinePointerInfo::getConstantPool(),
8027 false, false, false, 16);
8028 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8029 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8032 if (Subtarget->hasSSE3()) {
8033 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8034 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8036 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8037 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8039 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8040 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8044 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8045 DAG.getIntPtrConstant(0));
8048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8050 SelectionDAG &DAG) const {
8051 DebugLoc dl = Op.getDebugLoc();
8052 // FP constant to bias correct the final result.
8053 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8056 // Load the 32-bit value into an XMM register.
8057 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8060 // Zero out the upper parts of the register.
8061 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8063 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8064 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8065 DAG.getIntPtrConstant(0));
8067 // Or the load with the bias.
8068 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8069 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8072 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8073 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8074 MVT::v2f64, Bias)));
8075 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8076 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8077 DAG.getIntPtrConstant(0));
8079 // Subtract the bias.
8080 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8082 // Handle final rounding.
8083 EVT DestVT = Op.getValueType();
8085 if (DestVT.bitsLT(MVT::f64))
8086 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8087 DAG.getIntPtrConstant(0));
8088 if (DestVT.bitsGT(MVT::f64))
8089 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8091 // Handle final rounding.
8095 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8096 SelectionDAG &DAG) const {
8097 SDValue N0 = Op.getOperand(0);
8098 EVT SVT = N0.getValueType();
8099 DebugLoc dl = Op.getDebugLoc();
8101 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8102 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8103 "Custom UINT_TO_FP is not supported!");
8105 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8106 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8107 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8110 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8111 SelectionDAG &DAG) const {
8112 SDValue N0 = Op.getOperand(0);
8113 DebugLoc dl = Op.getDebugLoc();
8115 if (Op.getValueType().isVector())
8116 return lowerUINT_TO_FP_vec(Op, DAG);
8118 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8119 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8120 // the optimization here.
8121 if (DAG.SignBitIsZero(N0))
8122 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8124 EVT SrcVT = N0.getValueType();
8125 EVT DstVT = Op.getValueType();
8126 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8127 return LowerUINT_TO_FP_i64(Op, DAG);
8128 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8129 return LowerUINT_TO_FP_i32(Op, DAG);
8130 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8133 // Make a 64-bit buffer, and use it to build an FILD.
8134 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8135 if (SrcVT == MVT::i32) {
8136 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8137 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8138 getPointerTy(), StackSlot, WordOff);
8139 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8140 StackSlot, MachinePointerInfo(),
8142 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8143 OffsetSlot, MachinePointerInfo(),
8145 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8149 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8150 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8151 StackSlot, MachinePointerInfo(),
8153 // For i64 source, we need to add the appropriate power of 2 if the input
8154 // was negative. This is the same as the optimization in
8155 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8156 // we must be careful to do the computation in x87 extended precision, not
8157 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8158 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8159 MachineMemOperand *MMO =
8160 DAG.getMachineFunction()
8161 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8162 MachineMemOperand::MOLoad, 8, 8);
8164 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8165 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8166 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8169 APInt FF(32, 0x5F800000ULL);
8171 // Check whether the sign bit is set.
8172 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8173 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8176 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8177 SDValue FudgePtr = DAG.getConstantPool(
8178 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8181 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8182 SDValue Zero = DAG.getIntPtrConstant(0);
8183 SDValue Four = DAG.getIntPtrConstant(4);
8184 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8186 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8188 // Load the value out, extending it from f32 to f80.
8189 // FIXME: Avoid the extend by constructing the right constant pool?
8190 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8191 FudgePtr, MachinePointerInfo::getConstantPool(),
8192 MVT::f32, false, false, 4);
8193 // Extend everything to 80 bits to force it to be done on x87.
8194 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8195 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8198 std::pair<SDValue,SDValue> X86TargetLowering::
8199 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8200 DebugLoc DL = Op.getDebugLoc();
8202 EVT DstTy = Op.getValueType();
8204 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8205 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8209 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8210 DstTy.getSimpleVT() >= MVT::i16 &&
8211 "Unknown FP_TO_INT to lower!");
8213 // These are really Legal.
8214 if (DstTy == MVT::i32 &&
8215 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8216 return std::make_pair(SDValue(), SDValue());
8217 if (Subtarget->is64Bit() &&
8218 DstTy == MVT::i64 &&
8219 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8220 return std::make_pair(SDValue(), SDValue());
8222 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8223 // stack slot, or into the FTOL runtime function.
8224 MachineFunction &MF = DAG.getMachineFunction();
8225 unsigned MemSize = DstTy.getSizeInBits()/8;
8226 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8227 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8230 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8231 Opc = X86ISD::WIN_FTOL;
8233 switch (DstTy.getSimpleVT().SimpleTy) {
8234 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8235 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8236 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8237 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8240 SDValue Chain = DAG.getEntryNode();
8241 SDValue Value = Op.getOperand(0);
8242 EVT TheVT = Op.getOperand(0).getValueType();
8243 // FIXME This causes a redundant load/store if the SSE-class value is already
8244 // in memory, such as if it is on the callstack.
8245 if (isScalarFPTypeInSSEReg(TheVT)) {
8246 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8247 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8248 MachinePointerInfo::getFixedStack(SSFI),
8250 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8252 Chain, StackSlot, DAG.getValueType(TheVT)
8255 MachineMemOperand *MMO =
8256 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8257 MachineMemOperand::MOLoad, MemSize, MemSize);
8258 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8260 Chain = Value.getValue(1);
8261 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8262 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8265 MachineMemOperand *MMO =
8266 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8267 MachineMemOperand::MOStore, MemSize, MemSize);
8269 if (Opc != X86ISD::WIN_FTOL) {
8270 // Build the FP_TO_INT*_IN_MEM
8271 SDValue Ops[] = { Chain, Value, StackSlot };
8272 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8273 Ops, 3, DstTy, MMO);
8274 return std::make_pair(FIST, StackSlot);
8276 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8277 DAG.getVTList(MVT::Other, MVT::Glue),
8279 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8280 MVT::i32, ftol.getValue(1));
8281 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8282 MVT::i32, eax.getValue(2));
8283 SDValue Ops[] = { eax, edx };
8284 SDValue pair = IsReplace
8285 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8286 : DAG.getMergeValues(Ops, 2, DL);
8287 return std::make_pair(pair, SDValue());
8291 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8292 DebugLoc DL = Op.getDebugLoc();
8293 EVT VT = Op.getValueType();
8294 SDValue In = Op.getOperand(0);
8295 EVT SVT = In.getValueType();
8297 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8298 VT.getVectorNumElements() != SVT.getVectorNumElements())
8301 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8303 // AVX2 has better support of integer extending.
8304 if (Subtarget->hasInt256())
8305 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8307 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8308 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8309 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8310 DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8312 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8315 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8316 DebugLoc DL = Op.getDebugLoc();
8317 EVT VT = Op.getValueType();
8318 EVT SVT = Op.getOperand(0).getValueType();
8320 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8321 VT.getVectorNumElements() != SVT.getVectorNumElements())
8324 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8326 unsigned NumElems = VT.getVectorNumElements();
8327 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8330 SDValue In = Op.getOperand(0);
8331 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8332 // Prepare truncation shuffle mask
8333 for (unsigned i = 0; i != NumElems; ++i)
8335 SDValue V = DAG.getVectorShuffle(NVT, DL,
8336 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8337 DAG.getUNDEF(NVT), &MaskVec[0]);
8338 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8339 DAG.getIntPtrConstant(0));
8342 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8343 SelectionDAG &DAG) const {
8344 if (Op.getValueType().isVector()) {
8345 if (Op.getValueType() == MVT::v8i16)
8346 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8347 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8348 MVT::v8i32, Op.getOperand(0)));
8352 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8353 /*IsSigned=*/ true, /*IsReplace=*/ false);
8354 SDValue FIST = Vals.first, StackSlot = Vals.second;
8355 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8356 if (FIST.getNode() == 0) return Op;
8358 if (StackSlot.getNode())
8360 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8361 FIST, StackSlot, MachinePointerInfo(),
8362 false, false, false, 0);
8364 // The node is the result.
8368 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8369 SelectionDAG &DAG) const {
8370 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8371 /*IsSigned=*/ false, /*IsReplace=*/ false);
8372 SDValue FIST = Vals.first, StackSlot = Vals.second;
8373 assert(FIST.getNode() && "Unexpected failure");
8375 if (StackSlot.getNode())
8377 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8378 FIST, StackSlot, MachinePointerInfo(),
8379 false, false, false, 0);
8381 // The node is the result.
8385 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8386 SelectionDAG &DAG) const {
8387 DebugLoc DL = Op.getDebugLoc();
8388 EVT VT = Op.getValueType();
8389 SDValue In = Op.getOperand(0);
8390 EVT SVT = In.getValueType();
8392 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8394 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8395 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8396 In, DAG.getUNDEF(SVT)));
8399 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8400 LLVMContext *Context = DAG.getContext();
8401 DebugLoc dl = Op.getDebugLoc();
8402 EVT VT = Op.getValueType();
8404 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8405 if (VT.isVector()) {
8406 EltVT = VT.getVectorElementType();
8407 NumElts = VT.getVectorNumElements();
8410 if (EltVT == MVT::f64)
8411 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8413 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8414 C = ConstantVector::getSplat(NumElts, C);
8415 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8416 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8417 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8418 MachinePointerInfo::getConstantPool(),
8419 false, false, false, Alignment);
8420 if (VT.isVector()) {
8421 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8422 return DAG.getNode(ISD::BITCAST, dl, VT,
8423 DAG.getNode(ISD::AND, dl, ANDVT,
8424 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8426 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8428 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8431 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8432 LLVMContext *Context = DAG.getContext();
8433 DebugLoc dl = Op.getDebugLoc();
8434 EVT VT = Op.getValueType();
8436 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8437 if (VT.isVector()) {
8438 EltVT = VT.getVectorElementType();
8439 NumElts = VT.getVectorNumElements();
8442 if (EltVT == MVT::f64)
8443 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8445 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8446 C = ConstantVector::getSplat(NumElts, C);
8447 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8448 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8449 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8450 MachinePointerInfo::getConstantPool(),
8451 false, false, false, Alignment);
8452 if (VT.isVector()) {
8453 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8454 return DAG.getNode(ISD::BITCAST, dl, VT,
8455 DAG.getNode(ISD::XOR, dl, XORVT,
8456 DAG.getNode(ISD::BITCAST, dl, XORVT,
8458 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8461 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8464 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8465 LLVMContext *Context = DAG.getContext();
8466 SDValue Op0 = Op.getOperand(0);
8467 SDValue Op1 = Op.getOperand(1);
8468 DebugLoc dl = Op.getDebugLoc();
8469 EVT VT = Op.getValueType();
8470 EVT SrcVT = Op1.getValueType();
8472 // If second operand is smaller, extend it first.
8473 if (SrcVT.bitsLT(VT)) {
8474 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8477 // And if it is bigger, shrink it first.
8478 if (SrcVT.bitsGT(VT)) {
8479 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8483 // At this point the operands and the result should have the same
8484 // type, and that won't be f80 since that is not custom lowered.
8486 // First get the sign bit of second operand.
8487 SmallVector<Constant*,4> CV;
8488 if (SrcVT == MVT::f64) {
8489 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8490 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8492 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8493 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8495 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8497 Constant *C = ConstantVector::get(CV);
8498 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8499 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8500 MachinePointerInfo::getConstantPool(),
8501 false, false, false, 16);
8502 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8504 // Shift sign bit right or left if the two operands have different types.
8505 if (SrcVT.bitsGT(VT)) {
8506 // Op0 is MVT::f32, Op1 is MVT::f64.
8507 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8508 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8509 DAG.getConstant(32, MVT::i32));
8510 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8511 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8512 DAG.getIntPtrConstant(0));
8515 // Clear first operand sign bit.
8517 if (VT == MVT::f64) {
8518 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8519 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8521 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8522 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8524 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8526 C = ConstantVector::get(CV);
8527 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8528 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8529 MachinePointerInfo::getConstantPool(),
8530 false, false, false, 16);
8531 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8533 // Or the value with the sign bit.
8534 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8538 SDValue N0 = Op.getOperand(0);
8539 DebugLoc dl = Op.getDebugLoc();
8540 EVT VT = Op.getValueType();
8542 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8543 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8544 DAG.getConstant(1, VT));
8545 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8550 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8551 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8553 if (!Subtarget->hasSSE41())
8556 if (!Op->hasOneUse())
8559 SDNode *N = Op.getNode();
8560 DebugLoc DL = N->getDebugLoc();
8562 SmallVector<SDValue, 8> Opnds;
8563 DenseMap<SDValue, unsigned> VecInMap;
8564 EVT VT = MVT::Other;
8566 // Recognize a special case where a vector is casted into wide integer to
8568 Opnds.push_back(N->getOperand(0));
8569 Opnds.push_back(N->getOperand(1));
8571 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8572 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8573 // BFS traverse all OR'd operands.
8574 if (I->getOpcode() == ISD::OR) {
8575 Opnds.push_back(I->getOperand(0));
8576 Opnds.push_back(I->getOperand(1));
8577 // Re-evaluate the number of nodes to be traversed.
8578 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8582 // Quit if a non-EXTRACT_VECTOR_ELT
8583 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8586 // Quit if without a constant index.
8587 SDValue Idx = I->getOperand(1);
8588 if (!isa<ConstantSDNode>(Idx))
8591 SDValue ExtractedFromVec = I->getOperand(0);
8592 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8593 if (M == VecInMap.end()) {
8594 VT = ExtractedFromVec.getValueType();
8595 // Quit if not 128/256-bit vector.
8596 if (!VT.is128BitVector() && !VT.is256BitVector())
8598 // Quit if not the same type.
8599 if (VecInMap.begin() != VecInMap.end() &&
8600 VT != VecInMap.begin()->first.getValueType())
8602 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8604 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8607 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8608 "Not extracted from 128-/256-bit vector.");
8610 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8611 SmallVector<SDValue, 8> VecIns;
8613 for (DenseMap<SDValue, unsigned>::const_iterator
8614 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8615 // Quit if not all elements are used.
8616 if (I->second != FullMask)
8618 VecIns.push_back(I->first);
8621 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8623 // Cast all vectors into TestVT for PTEST.
8624 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8625 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8627 // If more than one full vectors are evaluated, OR them first before PTEST.
8628 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8629 // Each iteration will OR 2 nodes and append the result until there is only
8630 // 1 node left, i.e. the final OR'd value of all vectors.
8631 SDValue LHS = VecIns[Slot];
8632 SDValue RHS = VecIns[Slot + 1];
8633 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8636 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8637 VecIns.back(), VecIns.back());
8640 /// Emit nodes that will be selected as "test Op0,Op0", or something
8642 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8643 SelectionDAG &DAG) const {
8644 DebugLoc dl = Op.getDebugLoc();
8646 // CF and OF aren't always set the way we want. Determine which
8647 // of these we need.
8648 bool NeedCF = false;
8649 bool NeedOF = false;
8652 case X86::COND_A: case X86::COND_AE:
8653 case X86::COND_B: case X86::COND_BE:
8656 case X86::COND_G: case X86::COND_GE:
8657 case X86::COND_L: case X86::COND_LE:
8658 case X86::COND_O: case X86::COND_NO:
8663 // See if we can use the EFLAGS value from the operand instead of
8664 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8665 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8666 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8667 // Emit a CMP with 0, which is the TEST pattern.
8668 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8669 DAG.getConstant(0, Op.getValueType()));
8671 unsigned Opcode = 0;
8672 unsigned NumOperands = 0;
8674 // Truncate operations may prevent the merge of the SETCC instruction
8675 // and the arithmetic intruction before it. Attempt to truncate the operands
8676 // of the arithmetic instruction and use a reduced bit-width instruction.
8677 bool NeedTruncation = false;
8678 SDValue ArithOp = Op;
8679 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8680 SDValue Arith = Op->getOperand(0);
8681 // Both the trunc and the arithmetic op need to have one user each.
8682 if (Arith->hasOneUse())
8683 switch (Arith.getOpcode()) {
8690 NeedTruncation = true;
8696 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8697 // which may be the result of a CAST. We use the variable 'Op', which is the
8698 // non-casted variable when we check for possible users.
8699 switch (ArithOp.getOpcode()) {
8701 // Due to an isel shortcoming, be conservative if this add is likely to be
8702 // selected as part of a load-modify-store instruction. When the root node
8703 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8704 // uses of other nodes in the match, such as the ADD in this case. This
8705 // leads to the ADD being left around and reselected, with the result being
8706 // two adds in the output. Alas, even if none our users are stores, that
8707 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8708 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8709 // climbing the DAG back to the root, and it doesn't seem to be worth the
8711 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8712 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8713 if (UI->getOpcode() != ISD::CopyToReg &&
8714 UI->getOpcode() != ISD::SETCC &&
8715 UI->getOpcode() != ISD::STORE)
8718 if (ConstantSDNode *C =
8719 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8720 // An add of one will be selected as an INC.
8721 if (C->getAPIntValue() == 1) {
8722 Opcode = X86ISD::INC;
8727 // An add of negative one (subtract of one) will be selected as a DEC.
8728 if (C->getAPIntValue().isAllOnesValue()) {
8729 Opcode = X86ISD::DEC;
8735 // Otherwise use a regular EFLAGS-setting add.
8736 Opcode = X86ISD::ADD;
8740 // If the primary and result isn't used, don't bother using X86ISD::AND,
8741 // because a TEST instruction will be better.
8742 bool NonFlagUse = false;
8743 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8744 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8746 unsigned UOpNo = UI.getOperandNo();
8747 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8748 // Look pass truncate.
8749 UOpNo = User->use_begin().getOperandNo();
8750 User = *User->use_begin();
8753 if (User->getOpcode() != ISD::BRCOND &&
8754 User->getOpcode() != ISD::SETCC &&
8755 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8768 // Due to the ISEL shortcoming noted above, be conservative if this op is
8769 // likely to be selected as part of a load-modify-store instruction.
8770 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8771 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8772 if (UI->getOpcode() == ISD::STORE)
8775 // Otherwise use a regular EFLAGS-setting instruction.
8776 switch (ArithOp.getOpcode()) {
8777 default: llvm_unreachable("unexpected operator!");
8778 case ISD::SUB: Opcode = X86ISD::SUB; break;
8779 case ISD::XOR: Opcode = X86ISD::XOR; break;
8780 case ISD::AND: Opcode = X86ISD::AND; break;
8782 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8783 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8784 if (EFLAGS.getNode())
8787 Opcode = X86ISD::OR;
8801 return SDValue(Op.getNode(), 1);
8807 // If we found that truncation is beneficial, perform the truncation and
8809 if (NeedTruncation) {
8810 EVT VT = Op.getValueType();
8811 SDValue WideVal = Op->getOperand(0);
8812 EVT WideVT = WideVal.getValueType();
8813 unsigned ConvertedOp = 0;
8814 // Use a target machine opcode to prevent further DAGCombine
8815 // optimizations that may separate the arithmetic operations
8816 // from the setcc node.
8817 switch (WideVal.getOpcode()) {
8819 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8820 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8821 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8822 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8823 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8827 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8828 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8829 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8830 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8831 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8837 // Emit a CMP with 0, which is the TEST pattern.
8838 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8839 DAG.getConstant(0, Op.getValueType()));
8841 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8842 SmallVector<SDValue, 4> Ops;
8843 for (unsigned i = 0; i != NumOperands; ++i)
8844 Ops.push_back(Op.getOperand(i));
8846 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8847 DAG.ReplaceAllUsesWith(Op, New);
8848 return SDValue(New.getNode(), 1);
8851 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8853 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8854 SelectionDAG &DAG) const {
8855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8856 if (C->getAPIntValue() == 0)
8857 return EmitTest(Op0, X86CC, DAG);
8859 DebugLoc dl = Op0.getDebugLoc();
8860 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8861 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8862 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8863 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8864 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8866 return SDValue(Sub.getNode(), 1);
8868 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8871 /// Convert a comparison if required by the subtarget.
8872 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8873 SelectionDAG &DAG) const {
8874 // If the subtarget does not support the FUCOMI instruction, floating-point
8875 // comparisons have to be converted.
8876 if (Subtarget->hasCMov() ||
8877 Cmp.getOpcode() != X86ISD::CMP ||
8878 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8879 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8882 // The instruction selector will select an FUCOM instruction instead of
8883 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8884 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8885 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8886 DebugLoc dl = Cmp.getDebugLoc();
8887 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8888 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8889 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8890 DAG.getConstant(8, MVT::i8));
8891 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8892 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8895 static bool isAllOnes(SDValue V) {
8896 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8897 return C && C->isAllOnesValue();
8900 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8901 /// if it's possible.
8902 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8903 DebugLoc dl, SelectionDAG &DAG) const {
8904 SDValue Op0 = And.getOperand(0);
8905 SDValue Op1 = And.getOperand(1);
8906 if (Op0.getOpcode() == ISD::TRUNCATE)
8907 Op0 = Op0.getOperand(0);
8908 if (Op1.getOpcode() == ISD::TRUNCATE)
8909 Op1 = Op1.getOperand(0);
8912 if (Op1.getOpcode() == ISD::SHL)
8913 std::swap(Op0, Op1);
8914 if (Op0.getOpcode() == ISD::SHL) {
8915 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8916 if (And00C->getZExtValue() == 1) {
8917 // If we looked past a truncate, check that it's only truncating away
8919 unsigned BitWidth = Op0.getValueSizeInBits();
8920 unsigned AndBitWidth = And.getValueSizeInBits();
8921 if (BitWidth > AndBitWidth) {
8923 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8924 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8928 RHS = Op0.getOperand(1);
8930 } else if (Op1.getOpcode() == ISD::Constant) {
8931 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8932 uint64_t AndRHSVal = AndRHS->getZExtValue();
8933 SDValue AndLHS = Op0;
8935 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8936 LHS = AndLHS.getOperand(0);
8937 RHS = AndLHS.getOperand(1);
8940 // Use BT if the immediate can't be encoded in a TEST instruction.
8941 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8943 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8947 if (LHS.getNode()) {
8948 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
8949 // the condition code later.
8950 bool Invert = false;
8951 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
8953 LHS = LHS.getOperand(0);
8956 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8957 // instruction. Since the shift amount is in-range-or-undefined, we know
8958 // that doing a bittest on the i32 value is ok. We extend to i32 because
8959 // the encoding for the i16 version is larger than the i32 version.
8960 // Also promote i16 to i32 for performance / code size reason.
8961 if (LHS.getValueType() == MVT::i8 ||
8962 LHS.getValueType() == MVT::i16)
8963 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8965 // If the operand types disagree, extend the shift amount to match. Since
8966 // BT ignores high bits (like shifts) we can use anyextend.
8967 if (LHS.getValueType() != RHS.getValueType())
8968 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8970 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8971 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8972 // Flip the condition if the LHS was a not instruction
8974 Cond = X86::GetOppositeBranchCondition(Cond);
8975 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8976 DAG.getConstant(Cond, MVT::i8), BT);
8982 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8984 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8986 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8987 SDValue Op0 = Op.getOperand(0);
8988 SDValue Op1 = Op.getOperand(1);
8989 DebugLoc dl = Op.getDebugLoc();
8990 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8992 // Optimize to BT if possible.
8993 // Lower (X & (1 << N)) == 0 to BT(X, N).
8994 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8995 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8996 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8997 Op1.getOpcode() == ISD::Constant &&
8998 cast<ConstantSDNode>(Op1)->isNullValue() &&
8999 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9000 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9001 if (NewSetCC.getNode())
9005 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9007 if (Op1.getOpcode() == ISD::Constant &&
9008 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9009 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9010 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9012 // If the input is a setcc, then reuse the input setcc or use a new one with
9013 // the inverted condition.
9014 if (Op0.getOpcode() == X86ISD::SETCC) {
9015 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9016 bool Invert = (CC == ISD::SETNE) ^
9017 cast<ConstantSDNode>(Op1)->isNullValue();
9018 if (!Invert) return Op0;
9020 CCode = X86::GetOppositeBranchCondition(CCode);
9021 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9022 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9026 bool isFP = Op1.getValueType().isFloatingPoint();
9027 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9028 if (X86CC == X86::COND_INVALID)
9031 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9032 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9033 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9034 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9037 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9038 // ones, and then concatenate the result back.
9039 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9040 EVT VT = Op.getValueType();
9042 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9043 "Unsupported value type for operation");
9045 unsigned NumElems = VT.getVectorNumElements();
9046 DebugLoc dl = Op.getDebugLoc();
9047 SDValue CC = Op.getOperand(2);
9049 // Extract the LHS vectors
9050 SDValue LHS = Op.getOperand(0);
9051 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9052 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9054 // Extract the RHS vectors
9055 SDValue RHS = Op.getOperand(1);
9056 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9057 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9059 // Issue the operation on the smaller types and concatenate the result back
9060 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9061 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9062 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9063 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9064 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9069 SDValue Op0 = Op.getOperand(0);
9070 SDValue Op1 = Op.getOperand(1);
9071 SDValue CC = Op.getOperand(2);
9072 EVT VT = Op.getValueType();
9073 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9074 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9075 DebugLoc dl = Op.getDebugLoc();
9079 EVT EltVT = Op0.getValueType().getVectorElementType();
9080 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9086 // SSE Condition code mapping:
9095 switch (SetCCOpcode) {
9096 default: llvm_unreachable("Unexpected SETCC condition");
9098 case ISD::SETEQ: SSECC = 0; break;
9100 case ISD::SETGT: Swap = true; // Fallthrough
9102 case ISD::SETOLT: SSECC = 1; break;
9104 case ISD::SETGE: Swap = true; // Fallthrough
9106 case ISD::SETOLE: SSECC = 2; break;
9107 case ISD::SETUO: SSECC = 3; break;
9109 case ISD::SETNE: SSECC = 4; break;
9110 case ISD::SETULE: Swap = true; // Fallthrough
9111 case ISD::SETUGE: SSECC = 5; break;
9112 case ISD::SETULT: Swap = true; // Fallthrough
9113 case ISD::SETUGT: SSECC = 6; break;
9114 case ISD::SETO: SSECC = 7; break;
9116 case ISD::SETONE: SSECC = 8; break;
9119 std::swap(Op0, Op1);
9121 // In the two special cases we can't handle, emit two comparisons.
9124 unsigned CombineOpc;
9125 if (SetCCOpcode == ISD::SETUEQ) {
9126 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9128 assert(SetCCOpcode == ISD::SETONE);
9129 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9132 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9133 DAG.getConstant(CC0, MVT::i8));
9134 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9135 DAG.getConstant(CC1, MVT::i8));
9136 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9138 // Handle all other FP comparisons here.
9139 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9140 DAG.getConstant(SSECC, MVT::i8));
9143 // Break 256-bit integer vector compare into smaller ones.
9144 if (VT.is256BitVector() && !Subtarget->hasInt256())
9145 return Lower256IntVSETCC(Op, DAG);
9147 // We are handling one of the integer comparisons here. Since SSE only has
9148 // GT and EQ comparisons for integer, swapping operands and multiple
9149 // operations may be required for some comparisons.
9151 bool Swap = false, Invert = false, FlipSigns = false;
9153 switch (SetCCOpcode) {
9154 default: llvm_unreachable("Unexpected SETCC condition");
9155 case ISD::SETNE: Invert = true;
9156 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9157 case ISD::SETLT: Swap = true;
9158 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9159 case ISD::SETGE: Swap = true;
9160 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9161 case ISD::SETULT: Swap = true;
9162 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9163 case ISD::SETUGE: Swap = true;
9164 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9167 std::swap(Op0, Op1);
9169 // Check that the operation in question is available (most are plain SSE2,
9170 // but PCMPGTQ and PCMPEQQ have different requirements).
9171 if (VT == MVT::v2i64) {
9172 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9174 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9175 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9176 // pcmpeqd + 2 shuffles + pand.
9177 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9179 // First cast everything to the right type,
9180 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9181 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9184 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9186 // Make sure the lower and upper halves are both all-ones.
9187 const int Mask1[] = { 0, 0, 2, 2 };
9188 SDValue S1 = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask1);
9189 const int Mask2[] = { 1, 1, 3, 3 };
9190 SDValue S2 = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask2);
9191 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, S1, S2);
9194 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9196 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9200 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9201 // bits of the inputs before performing those operations.
9203 EVT EltVT = VT.getVectorElementType();
9204 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9206 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9207 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9209 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9210 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9213 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9215 // If the logical-not of the result is required, perform that now.
9217 Result = DAG.getNOT(dl, Result, VT);
9222 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9223 static bool isX86LogicalCmp(SDValue Op) {
9224 unsigned Opc = Op.getNode()->getOpcode();
9225 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9226 Opc == X86ISD::SAHF)
9228 if (Op.getResNo() == 1 &&
9229 (Opc == X86ISD::ADD ||
9230 Opc == X86ISD::SUB ||
9231 Opc == X86ISD::ADC ||
9232 Opc == X86ISD::SBB ||
9233 Opc == X86ISD::SMUL ||
9234 Opc == X86ISD::UMUL ||
9235 Opc == X86ISD::INC ||
9236 Opc == X86ISD::DEC ||
9237 Opc == X86ISD::OR ||
9238 Opc == X86ISD::XOR ||
9239 Opc == X86ISD::AND))
9242 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9248 static bool isZero(SDValue V) {
9249 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9250 return C && C->isNullValue();
9253 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9254 if (V.getOpcode() != ISD::TRUNCATE)
9257 SDValue VOp0 = V.getOperand(0);
9258 unsigned InBits = VOp0.getValueSizeInBits();
9259 unsigned Bits = V.getValueSizeInBits();
9260 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9263 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9264 bool addTest = true;
9265 SDValue Cond = Op.getOperand(0);
9266 SDValue Op1 = Op.getOperand(1);
9267 SDValue Op2 = Op.getOperand(2);
9268 DebugLoc DL = Op.getDebugLoc();
9271 if (Cond.getOpcode() == ISD::SETCC) {
9272 SDValue NewCond = LowerSETCC(Cond, DAG);
9273 if (NewCond.getNode())
9277 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9278 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9279 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9280 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9281 if (Cond.getOpcode() == X86ISD::SETCC &&
9282 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9283 isZero(Cond.getOperand(1).getOperand(1))) {
9284 SDValue Cmp = Cond.getOperand(1);
9286 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9288 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9289 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9290 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9292 SDValue CmpOp0 = Cmp.getOperand(0);
9293 // Apply further optimizations for special cases
9294 // (select (x != 0), -1, 0) -> neg & sbb
9295 // (select (x == 0), 0, -1) -> neg & sbb
9296 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9297 if (YC->isNullValue() &&
9298 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9299 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9300 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9301 DAG.getConstant(0, CmpOp0.getValueType()),
9303 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9304 DAG.getConstant(X86::COND_B, MVT::i8),
9305 SDValue(Neg.getNode(), 1));
9309 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9310 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9311 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9313 SDValue Res = // Res = 0 or -1.
9314 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9315 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9317 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9318 Res = DAG.getNOT(DL, Res, Res.getValueType());
9320 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9321 if (N2C == 0 || !N2C->isNullValue())
9322 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9327 // Look past (and (setcc_carry (cmp ...)), 1).
9328 if (Cond.getOpcode() == ISD::AND &&
9329 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9330 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9331 if (C && C->getAPIntValue() == 1)
9332 Cond = Cond.getOperand(0);
9335 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9336 // setting operand in place of the X86ISD::SETCC.
9337 unsigned CondOpcode = Cond.getOpcode();
9338 if (CondOpcode == X86ISD::SETCC ||
9339 CondOpcode == X86ISD::SETCC_CARRY) {
9340 CC = Cond.getOperand(0);
9342 SDValue Cmp = Cond.getOperand(1);
9343 unsigned Opc = Cmp.getOpcode();
9344 EVT VT = Op.getValueType();
9346 bool IllegalFPCMov = false;
9347 if (VT.isFloatingPoint() && !VT.isVector() &&
9348 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9349 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9351 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9352 Opc == X86ISD::BT) { // FIXME
9356 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9357 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9358 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9359 Cond.getOperand(0).getValueType() != MVT::i8)) {
9360 SDValue LHS = Cond.getOperand(0);
9361 SDValue RHS = Cond.getOperand(1);
9365 switch (CondOpcode) {
9366 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9367 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9368 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9369 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9370 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9371 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9372 default: llvm_unreachable("unexpected overflowing operator");
9374 if (CondOpcode == ISD::UMULO)
9375 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9378 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9380 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9382 if (CondOpcode == ISD::UMULO)
9383 Cond = X86Op.getValue(2);
9385 Cond = X86Op.getValue(1);
9387 CC = DAG.getConstant(X86Cond, MVT::i8);
9392 // Look pass the truncate if the high bits are known zero.
9393 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9394 Cond = Cond.getOperand(0);
9396 // We know the result of AND is compared against zero. Try to match
9398 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9399 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9400 if (NewSetCC.getNode()) {
9401 CC = NewSetCC.getOperand(0);
9402 Cond = NewSetCC.getOperand(1);
9409 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9410 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9413 // a < b ? -1 : 0 -> RES = ~setcc_carry
9414 // a < b ? 0 : -1 -> RES = setcc_carry
9415 // a >= b ? -1 : 0 -> RES = setcc_carry
9416 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9417 if (Cond.getOpcode() == X86ISD::SUB) {
9418 Cond = ConvertCmpIfNecessary(Cond, DAG);
9419 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9421 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9422 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9423 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9424 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9425 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9426 return DAG.getNOT(DL, Res, Res.getValueType());
9431 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9432 // widen the cmov and push the truncate through. This avoids introducing a new
9433 // branch during isel and doesn't add any extensions.
9434 if (Op.getValueType() == MVT::i8 &&
9435 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9436 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9437 if (T1.getValueType() == T2.getValueType() &&
9438 // Blacklist CopyFromReg to avoid partial register stalls.
9439 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9440 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9441 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9442 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9446 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9447 // condition is true.
9448 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9449 SDValue Ops[] = { Op2, Op1, CC, Cond };
9450 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9453 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9454 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9455 // from the AND / OR.
9456 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9457 Opc = Op.getOpcode();
9458 if (Opc != ISD::OR && Opc != ISD::AND)
9460 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9461 Op.getOperand(0).hasOneUse() &&
9462 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9463 Op.getOperand(1).hasOneUse());
9466 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9467 // 1 and that the SETCC node has a single use.
9468 static bool isXor1OfSetCC(SDValue Op) {
9469 if (Op.getOpcode() != ISD::XOR)
9471 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9472 if (N1C && N1C->getAPIntValue() == 1) {
9473 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9474 Op.getOperand(0).hasOneUse();
9479 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9480 bool addTest = true;
9481 SDValue Chain = Op.getOperand(0);
9482 SDValue Cond = Op.getOperand(1);
9483 SDValue Dest = Op.getOperand(2);
9484 DebugLoc dl = Op.getDebugLoc();
9486 bool Inverted = false;
9488 if (Cond.getOpcode() == ISD::SETCC) {
9489 // Check for setcc([su]{add,sub,mul}o == 0).
9490 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9491 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9492 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9493 Cond.getOperand(0).getResNo() == 1 &&
9494 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9495 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9496 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9497 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9498 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9499 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9501 Cond = Cond.getOperand(0);
9503 SDValue NewCond = LowerSETCC(Cond, DAG);
9504 if (NewCond.getNode())
9509 // FIXME: LowerXALUO doesn't handle these!!
9510 else if (Cond.getOpcode() == X86ISD::ADD ||
9511 Cond.getOpcode() == X86ISD::SUB ||
9512 Cond.getOpcode() == X86ISD::SMUL ||
9513 Cond.getOpcode() == X86ISD::UMUL)
9514 Cond = LowerXALUO(Cond, DAG);
9517 // Look pass (and (setcc_carry (cmp ...)), 1).
9518 if (Cond.getOpcode() == ISD::AND &&
9519 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9520 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9521 if (C && C->getAPIntValue() == 1)
9522 Cond = Cond.getOperand(0);
9525 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9526 // setting operand in place of the X86ISD::SETCC.
9527 unsigned CondOpcode = Cond.getOpcode();
9528 if (CondOpcode == X86ISD::SETCC ||
9529 CondOpcode == X86ISD::SETCC_CARRY) {
9530 CC = Cond.getOperand(0);
9532 SDValue Cmp = Cond.getOperand(1);
9533 unsigned Opc = Cmp.getOpcode();
9534 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9535 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9539 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9543 // These can only come from an arithmetic instruction with overflow,
9544 // e.g. SADDO, UADDO.
9545 Cond = Cond.getNode()->getOperand(1);
9551 CondOpcode = Cond.getOpcode();
9552 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9553 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9554 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9555 Cond.getOperand(0).getValueType() != MVT::i8)) {
9556 SDValue LHS = Cond.getOperand(0);
9557 SDValue RHS = Cond.getOperand(1);
9561 switch (CondOpcode) {
9562 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9563 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9564 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9565 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9566 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9567 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9568 default: llvm_unreachable("unexpected overflowing operator");
9571 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9572 if (CondOpcode == ISD::UMULO)
9573 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9576 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9578 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9580 if (CondOpcode == ISD::UMULO)
9581 Cond = X86Op.getValue(2);
9583 Cond = X86Op.getValue(1);
9585 CC = DAG.getConstant(X86Cond, MVT::i8);
9589 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9590 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9591 if (CondOpc == ISD::OR) {
9592 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9593 // two branches instead of an explicit OR instruction with a
9595 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9596 isX86LogicalCmp(Cmp)) {
9597 CC = Cond.getOperand(0).getOperand(0);
9598 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9599 Chain, Dest, CC, Cmp);
9600 CC = Cond.getOperand(1).getOperand(0);
9604 } else { // ISD::AND
9605 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9606 // two branches instead of an explicit AND instruction with a
9607 // separate test. However, we only do this if this block doesn't
9608 // have a fall-through edge, because this requires an explicit
9609 // jmp when the condition is false.
9610 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9611 isX86LogicalCmp(Cmp) &&
9612 Op.getNode()->hasOneUse()) {
9613 X86::CondCode CCode =
9614 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9615 CCode = X86::GetOppositeBranchCondition(CCode);
9616 CC = DAG.getConstant(CCode, MVT::i8);
9617 SDNode *User = *Op.getNode()->use_begin();
9618 // Look for an unconditional branch following this conditional branch.
9619 // We need this because we need to reverse the successors in order
9620 // to implement FCMP_OEQ.
9621 if (User->getOpcode() == ISD::BR) {
9622 SDValue FalseBB = User->getOperand(1);
9624 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9625 assert(NewBR == User);
9629 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9630 Chain, Dest, CC, Cmp);
9631 X86::CondCode CCode =
9632 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9633 CCode = X86::GetOppositeBranchCondition(CCode);
9634 CC = DAG.getConstant(CCode, MVT::i8);
9640 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9641 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9642 // It should be transformed during dag combiner except when the condition
9643 // is set by a arithmetics with overflow node.
9644 X86::CondCode CCode =
9645 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9646 CCode = X86::GetOppositeBranchCondition(CCode);
9647 CC = DAG.getConstant(CCode, MVT::i8);
9648 Cond = Cond.getOperand(0).getOperand(1);
9650 } else if (Cond.getOpcode() == ISD::SETCC &&
9651 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9652 // For FCMP_OEQ, we can emit
9653 // two branches instead of an explicit AND instruction with a
9654 // separate test. However, we only do this if this block doesn't
9655 // have a fall-through edge, because this requires an explicit
9656 // jmp when the condition is false.
9657 if (Op.getNode()->hasOneUse()) {
9658 SDNode *User = *Op.getNode()->use_begin();
9659 // Look for an unconditional branch following this conditional branch.
9660 // We need this because we need to reverse the successors in order
9661 // to implement FCMP_OEQ.
9662 if (User->getOpcode() == ISD::BR) {
9663 SDValue FalseBB = User->getOperand(1);
9665 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9666 assert(NewBR == User);
9670 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9671 Cond.getOperand(0), Cond.getOperand(1));
9672 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9673 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9674 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9675 Chain, Dest, CC, Cmp);
9676 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9681 } else if (Cond.getOpcode() == ISD::SETCC &&
9682 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9683 // For FCMP_UNE, we can emit
9684 // two branches instead of an explicit AND instruction with a
9685 // separate test. However, we only do this if this block doesn't
9686 // have a fall-through edge, because this requires an explicit
9687 // jmp when the condition is false.
9688 if (Op.getNode()->hasOneUse()) {
9689 SDNode *User = *Op.getNode()->use_begin();
9690 // Look for an unconditional branch following this conditional branch.
9691 // We need this because we need to reverse the successors in order
9692 // to implement FCMP_UNE.
9693 if (User->getOpcode() == ISD::BR) {
9694 SDValue FalseBB = User->getOperand(1);
9696 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9697 assert(NewBR == User);
9700 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9701 Cond.getOperand(0), Cond.getOperand(1));
9702 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9703 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9704 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9705 Chain, Dest, CC, Cmp);
9706 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9716 // Look pass the truncate if the high bits are known zero.
9717 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9718 Cond = Cond.getOperand(0);
9720 // We know the result of AND is compared against zero. Try to match
9722 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9723 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9724 if (NewSetCC.getNode()) {
9725 CC = NewSetCC.getOperand(0);
9726 Cond = NewSetCC.getOperand(1);
9733 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9734 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9736 Cond = ConvertCmpIfNecessary(Cond, DAG);
9737 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9738 Chain, Dest, CC, Cond);
9741 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9742 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9743 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9744 // that the guard pages used by the OS virtual memory manager are allocated in
9745 // correct sequence.
9747 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9748 SelectionDAG &DAG) const {
9749 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9750 getTargetMachine().Options.EnableSegmentedStacks) &&
9751 "This should be used only on Windows targets or when segmented stacks "
9753 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9754 DebugLoc dl = Op.getDebugLoc();
9757 SDValue Chain = Op.getOperand(0);
9758 SDValue Size = Op.getOperand(1);
9759 // FIXME: Ensure alignment here
9761 bool Is64Bit = Subtarget->is64Bit();
9762 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9764 if (getTargetMachine().Options.EnableSegmentedStacks) {
9765 MachineFunction &MF = DAG.getMachineFunction();
9766 MachineRegisterInfo &MRI = MF.getRegInfo();
9769 // The 64 bit implementation of segmented stacks needs to clobber both r10
9770 // r11. This makes it impossible to use it along with nested parameters.
9771 const Function *F = MF.getFunction();
9773 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9775 if (I->hasNestAttr())
9776 report_fatal_error("Cannot use segmented stacks with functions that "
9777 "have nested arguments.");
9780 const TargetRegisterClass *AddrRegClass =
9781 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9782 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9783 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9784 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9785 DAG.getRegister(Vreg, SPTy));
9786 SDValue Ops1[2] = { Value, Chain };
9787 return DAG.getMergeValues(Ops1, 2, dl);
9790 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9792 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9793 Flag = Chain.getValue(1);
9794 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9796 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9797 Flag = Chain.getValue(1);
9799 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9802 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9803 return DAG.getMergeValues(Ops1, 2, dl);
9807 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9808 MachineFunction &MF = DAG.getMachineFunction();
9809 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9811 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9812 DebugLoc DL = Op.getDebugLoc();
9814 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9815 // vastart just stores the address of the VarArgsFrameIndex slot into the
9816 // memory location argument.
9817 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9819 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9820 MachinePointerInfo(SV), false, false, 0);
9824 // gp_offset (0 - 6 * 8)
9825 // fp_offset (48 - 48 + 8 * 16)
9826 // overflow_arg_area (point to parameters coming in memory).
9828 SmallVector<SDValue, 8> MemOps;
9829 SDValue FIN = Op.getOperand(1);
9831 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9832 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9834 FIN, MachinePointerInfo(SV), false, false, 0);
9835 MemOps.push_back(Store);
9838 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9839 FIN, DAG.getIntPtrConstant(4));
9840 Store = DAG.getStore(Op.getOperand(0), DL,
9841 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9843 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9844 MemOps.push_back(Store);
9846 // Store ptr to overflow_arg_area
9847 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9848 FIN, DAG.getIntPtrConstant(4));
9849 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9851 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9852 MachinePointerInfo(SV, 8),
9854 MemOps.push_back(Store);
9856 // Store ptr to reg_save_area.
9857 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9858 FIN, DAG.getIntPtrConstant(8));
9859 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9861 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9862 MachinePointerInfo(SV, 16), false, false, 0);
9863 MemOps.push_back(Store);
9864 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9865 &MemOps[0], MemOps.size());
9868 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9869 assert(Subtarget->is64Bit() &&
9870 "LowerVAARG only handles 64-bit va_arg!");
9871 assert((Subtarget->isTargetLinux() ||
9872 Subtarget->isTargetDarwin()) &&
9873 "Unhandled target in LowerVAARG");
9874 assert(Op.getNode()->getNumOperands() == 4);
9875 SDValue Chain = Op.getOperand(0);
9876 SDValue SrcPtr = Op.getOperand(1);
9877 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9878 unsigned Align = Op.getConstantOperandVal(3);
9879 DebugLoc dl = Op.getDebugLoc();
9881 EVT ArgVT = Op.getNode()->getValueType(0);
9882 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9883 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9886 // Decide which area this value should be read from.
9887 // TODO: Implement the AMD64 ABI in its entirety. This simple
9888 // selection mechanism works only for the basic types.
9889 if (ArgVT == MVT::f80) {
9890 llvm_unreachable("va_arg for f80 not yet implemented");
9891 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9892 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9893 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9894 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9896 llvm_unreachable("Unhandled argument type in LowerVAARG");
9900 // Sanity Check: Make sure using fp_offset makes sense.
9901 assert(!getTargetMachine().Options.UseSoftFloat &&
9902 !(DAG.getMachineFunction()
9903 .getFunction()->getFnAttributes()
9904 .hasAttribute(Attribute::NoImplicitFloat)) &&
9905 Subtarget->hasSSE1());
9908 // Insert VAARG_64 node into the DAG
9909 // VAARG_64 returns two values: Variable Argument Address, Chain
9910 SmallVector<SDValue, 11> InstOps;
9911 InstOps.push_back(Chain);
9912 InstOps.push_back(SrcPtr);
9913 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9914 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9915 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9916 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9917 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9918 VTs, &InstOps[0], InstOps.size(),
9920 MachinePointerInfo(SV),
9925 Chain = VAARG.getValue(1);
9927 // Load the next argument and return it
9928 return DAG.getLoad(ArgVT, dl,
9931 MachinePointerInfo(),
9932 false, false, false, 0);
9935 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9936 SelectionDAG &DAG) {
9937 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9938 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9939 SDValue Chain = Op.getOperand(0);
9940 SDValue DstPtr = Op.getOperand(1);
9941 SDValue SrcPtr = Op.getOperand(2);
9942 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9943 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9944 DebugLoc DL = Op.getDebugLoc();
9946 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9947 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9949 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9952 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9953 // may or may not be a constant. Takes immediate version of shift as input.
9954 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9955 SDValue SrcOp, SDValue ShAmt,
9956 SelectionDAG &DAG) {
9957 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9959 if (isa<ConstantSDNode>(ShAmt)) {
9960 // Constant may be a TargetConstant. Use a regular constant.
9961 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9963 default: llvm_unreachable("Unknown target vector shift node");
9967 return DAG.getNode(Opc, dl, VT, SrcOp,
9968 DAG.getConstant(ShiftAmt, MVT::i32));
9972 // Change opcode to non-immediate version
9974 default: llvm_unreachable("Unknown target vector shift node");
9975 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9976 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9977 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9980 // Need to build a vector containing shift amount
9981 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9984 ShOps[1] = DAG.getConstant(0, MVT::i32);
9985 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9986 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9988 // The return type has to be a 128-bit type with the same element
9989 // type as the input type.
9990 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9991 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9993 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9994 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9997 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9998 DebugLoc dl = Op.getDebugLoc();
9999 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10001 default: return SDValue(); // Don't custom lower most intrinsics.
10002 // Comparison intrinsics.
10003 case Intrinsic::x86_sse_comieq_ss:
10004 case Intrinsic::x86_sse_comilt_ss:
10005 case Intrinsic::x86_sse_comile_ss:
10006 case Intrinsic::x86_sse_comigt_ss:
10007 case Intrinsic::x86_sse_comige_ss:
10008 case Intrinsic::x86_sse_comineq_ss:
10009 case Intrinsic::x86_sse_ucomieq_ss:
10010 case Intrinsic::x86_sse_ucomilt_ss:
10011 case Intrinsic::x86_sse_ucomile_ss:
10012 case Intrinsic::x86_sse_ucomigt_ss:
10013 case Intrinsic::x86_sse_ucomige_ss:
10014 case Intrinsic::x86_sse_ucomineq_ss:
10015 case Intrinsic::x86_sse2_comieq_sd:
10016 case Intrinsic::x86_sse2_comilt_sd:
10017 case Intrinsic::x86_sse2_comile_sd:
10018 case Intrinsic::x86_sse2_comigt_sd:
10019 case Intrinsic::x86_sse2_comige_sd:
10020 case Intrinsic::x86_sse2_comineq_sd:
10021 case Intrinsic::x86_sse2_ucomieq_sd:
10022 case Intrinsic::x86_sse2_ucomilt_sd:
10023 case Intrinsic::x86_sse2_ucomile_sd:
10024 case Intrinsic::x86_sse2_ucomigt_sd:
10025 case Intrinsic::x86_sse2_ucomige_sd:
10026 case Intrinsic::x86_sse2_ucomineq_sd: {
10030 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10031 case Intrinsic::x86_sse_comieq_ss:
10032 case Intrinsic::x86_sse2_comieq_sd:
10033 Opc = X86ISD::COMI;
10036 case Intrinsic::x86_sse_comilt_ss:
10037 case Intrinsic::x86_sse2_comilt_sd:
10038 Opc = X86ISD::COMI;
10041 case Intrinsic::x86_sse_comile_ss:
10042 case Intrinsic::x86_sse2_comile_sd:
10043 Opc = X86ISD::COMI;
10046 case Intrinsic::x86_sse_comigt_ss:
10047 case Intrinsic::x86_sse2_comigt_sd:
10048 Opc = X86ISD::COMI;
10051 case Intrinsic::x86_sse_comige_ss:
10052 case Intrinsic::x86_sse2_comige_sd:
10053 Opc = X86ISD::COMI;
10056 case Intrinsic::x86_sse_comineq_ss:
10057 case Intrinsic::x86_sse2_comineq_sd:
10058 Opc = X86ISD::COMI;
10061 case Intrinsic::x86_sse_ucomieq_ss:
10062 case Intrinsic::x86_sse2_ucomieq_sd:
10063 Opc = X86ISD::UCOMI;
10066 case Intrinsic::x86_sse_ucomilt_ss:
10067 case Intrinsic::x86_sse2_ucomilt_sd:
10068 Opc = X86ISD::UCOMI;
10071 case Intrinsic::x86_sse_ucomile_ss:
10072 case Intrinsic::x86_sse2_ucomile_sd:
10073 Opc = X86ISD::UCOMI;
10076 case Intrinsic::x86_sse_ucomigt_ss:
10077 case Intrinsic::x86_sse2_ucomigt_sd:
10078 Opc = X86ISD::UCOMI;
10081 case Intrinsic::x86_sse_ucomige_ss:
10082 case Intrinsic::x86_sse2_ucomige_sd:
10083 Opc = X86ISD::UCOMI;
10086 case Intrinsic::x86_sse_ucomineq_ss:
10087 case Intrinsic::x86_sse2_ucomineq_sd:
10088 Opc = X86ISD::UCOMI;
10093 SDValue LHS = Op.getOperand(1);
10094 SDValue RHS = Op.getOperand(2);
10095 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10096 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10097 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10098 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10099 DAG.getConstant(X86CC, MVT::i8), Cond);
10100 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10103 // Arithmetic intrinsics.
10104 case Intrinsic::x86_sse2_pmulu_dq:
10105 case Intrinsic::x86_avx2_pmulu_dq:
10106 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10107 Op.getOperand(1), Op.getOperand(2));
10109 // SSE2/AVX2 sub with unsigned saturation intrinsics
10110 case Intrinsic::x86_sse2_psubus_b:
10111 case Intrinsic::x86_sse2_psubus_w:
10112 case Intrinsic::x86_avx2_psubus_b:
10113 case Intrinsic::x86_avx2_psubus_w:
10114 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10115 Op.getOperand(1), Op.getOperand(2));
10117 // SSE3/AVX horizontal add/sub intrinsics
10118 case Intrinsic::x86_sse3_hadd_ps:
10119 case Intrinsic::x86_sse3_hadd_pd:
10120 case Intrinsic::x86_avx_hadd_ps_256:
10121 case Intrinsic::x86_avx_hadd_pd_256:
10122 case Intrinsic::x86_sse3_hsub_ps:
10123 case Intrinsic::x86_sse3_hsub_pd:
10124 case Intrinsic::x86_avx_hsub_ps_256:
10125 case Intrinsic::x86_avx_hsub_pd_256:
10126 case Intrinsic::x86_ssse3_phadd_w_128:
10127 case Intrinsic::x86_ssse3_phadd_d_128:
10128 case Intrinsic::x86_avx2_phadd_w:
10129 case Intrinsic::x86_avx2_phadd_d:
10130 case Intrinsic::x86_ssse3_phsub_w_128:
10131 case Intrinsic::x86_ssse3_phsub_d_128:
10132 case Intrinsic::x86_avx2_phsub_w:
10133 case Intrinsic::x86_avx2_phsub_d: {
10136 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10137 case Intrinsic::x86_sse3_hadd_ps:
10138 case Intrinsic::x86_sse3_hadd_pd:
10139 case Intrinsic::x86_avx_hadd_ps_256:
10140 case Intrinsic::x86_avx_hadd_pd_256:
10141 Opcode = X86ISD::FHADD;
10143 case Intrinsic::x86_sse3_hsub_ps:
10144 case Intrinsic::x86_sse3_hsub_pd:
10145 case Intrinsic::x86_avx_hsub_ps_256:
10146 case Intrinsic::x86_avx_hsub_pd_256:
10147 Opcode = X86ISD::FHSUB;
10149 case Intrinsic::x86_ssse3_phadd_w_128:
10150 case Intrinsic::x86_ssse3_phadd_d_128:
10151 case Intrinsic::x86_avx2_phadd_w:
10152 case Intrinsic::x86_avx2_phadd_d:
10153 Opcode = X86ISD::HADD;
10155 case Intrinsic::x86_ssse3_phsub_w_128:
10156 case Intrinsic::x86_ssse3_phsub_d_128:
10157 case Intrinsic::x86_avx2_phsub_w:
10158 case Intrinsic::x86_avx2_phsub_d:
10159 Opcode = X86ISD::HSUB;
10162 return DAG.getNode(Opcode, dl, Op.getValueType(),
10163 Op.getOperand(1), Op.getOperand(2));
10166 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10167 case Intrinsic::x86_sse2_pmaxu_b:
10168 case Intrinsic::x86_sse41_pmaxuw:
10169 case Intrinsic::x86_sse41_pmaxud:
10170 case Intrinsic::x86_avx2_pmaxu_b:
10171 case Intrinsic::x86_avx2_pmaxu_w:
10172 case Intrinsic::x86_avx2_pmaxu_d:
10173 return DAG.getNode(X86ISD::UMAX, dl, Op.getValueType(),
10174 Op.getOperand(1), Op.getOperand(2));
10175 case Intrinsic::x86_sse2_pminu_b:
10176 case Intrinsic::x86_sse41_pminuw:
10177 case Intrinsic::x86_sse41_pminud:
10178 case Intrinsic::x86_avx2_pminu_b:
10179 case Intrinsic::x86_avx2_pminu_w:
10180 case Intrinsic::x86_avx2_pminu_d:
10181 return DAG.getNode(X86ISD::UMIN, dl, Op.getValueType(),
10182 Op.getOperand(1), Op.getOperand(2));
10183 case Intrinsic::x86_sse41_pmaxsb:
10184 case Intrinsic::x86_sse2_pmaxs_w:
10185 case Intrinsic::x86_sse41_pmaxsd:
10186 case Intrinsic::x86_avx2_pmaxs_b:
10187 case Intrinsic::x86_avx2_pmaxs_w:
10188 case Intrinsic::x86_avx2_pmaxs_d:
10189 return DAG.getNode(X86ISD::SMAX, dl, Op.getValueType(),
10190 Op.getOperand(1), Op.getOperand(2));
10191 case Intrinsic::x86_sse41_pminsb:
10192 case Intrinsic::x86_sse2_pmins_w:
10193 case Intrinsic::x86_sse41_pminsd:
10194 case Intrinsic::x86_avx2_pmins_b:
10195 case Intrinsic::x86_avx2_pmins_w:
10196 case Intrinsic::x86_avx2_pmins_d:
10197 return DAG.getNode(X86ISD::SMIN, dl, Op.getValueType(),
10198 Op.getOperand(1), Op.getOperand(2));
10200 // AVX2 variable shift intrinsics
10201 case Intrinsic::x86_avx2_psllv_d:
10202 case Intrinsic::x86_avx2_psllv_q:
10203 case Intrinsic::x86_avx2_psllv_d_256:
10204 case Intrinsic::x86_avx2_psllv_q_256:
10205 case Intrinsic::x86_avx2_psrlv_d:
10206 case Intrinsic::x86_avx2_psrlv_q:
10207 case Intrinsic::x86_avx2_psrlv_d_256:
10208 case Intrinsic::x86_avx2_psrlv_q_256:
10209 case Intrinsic::x86_avx2_psrav_d:
10210 case Intrinsic::x86_avx2_psrav_d_256: {
10213 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10214 case Intrinsic::x86_avx2_psllv_d:
10215 case Intrinsic::x86_avx2_psllv_q:
10216 case Intrinsic::x86_avx2_psllv_d_256:
10217 case Intrinsic::x86_avx2_psllv_q_256:
10220 case Intrinsic::x86_avx2_psrlv_d:
10221 case Intrinsic::x86_avx2_psrlv_q:
10222 case Intrinsic::x86_avx2_psrlv_d_256:
10223 case Intrinsic::x86_avx2_psrlv_q_256:
10226 case Intrinsic::x86_avx2_psrav_d:
10227 case Intrinsic::x86_avx2_psrav_d_256:
10231 return DAG.getNode(Opcode, dl, Op.getValueType(),
10232 Op.getOperand(1), Op.getOperand(2));
10235 case Intrinsic::x86_ssse3_pshuf_b_128:
10236 case Intrinsic::x86_avx2_pshuf_b:
10237 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10238 Op.getOperand(1), Op.getOperand(2));
10240 case Intrinsic::x86_ssse3_psign_b_128:
10241 case Intrinsic::x86_ssse3_psign_w_128:
10242 case Intrinsic::x86_ssse3_psign_d_128:
10243 case Intrinsic::x86_avx2_psign_b:
10244 case Intrinsic::x86_avx2_psign_w:
10245 case Intrinsic::x86_avx2_psign_d:
10246 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10247 Op.getOperand(1), Op.getOperand(2));
10249 case Intrinsic::x86_sse41_insertps:
10250 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10251 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10253 case Intrinsic::x86_avx_vperm2f128_ps_256:
10254 case Intrinsic::x86_avx_vperm2f128_pd_256:
10255 case Intrinsic::x86_avx_vperm2f128_si_256:
10256 case Intrinsic::x86_avx2_vperm2i128:
10257 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10258 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10260 case Intrinsic::x86_avx2_permd:
10261 case Intrinsic::x86_avx2_permps:
10262 // Operands intentionally swapped. Mask is last operand to intrinsic,
10263 // but second operand for node/intruction.
10264 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10265 Op.getOperand(2), Op.getOperand(1));
10267 // ptest and testp intrinsics. The intrinsic these come from are designed to
10268 // return an integer value, not just an instruction so lower it to the ptest
10269 // or testp pattern and a setcc for the result.
10270 case Intrinsic::x86_sse41_ptestz:
10271 case Intrinsic::x86_sse41_ptestc:
10272 case Intrinsic::x86_sse41_ptestnzc:
10273 case Intrinsic::x86_avx_ptestz_256:
10274 case Intrinsic::x86_avx_ptestc_256:
10275 case Intrinsic::x86_avx_ptestnzc_256:
10276 case Intrinsic::x86_avx_vtestz_ps:
10277 case Intrinsic::x86_avx_vtestc_ps:
10278 case Intrinsic::x86_avx_vtestnzc_ps:
10279 case Intrinsic::x86_avx_vtestz_pd:
10280 case Intrinsic::x86_avx_vtestc_pd:
10281 case Intrinsic::x86_avx_vtestnzc_pd:
10282 case Intrinsic::x86_avx_vtestz_ps_256:
10283 case Intrinsic::x86_avx_vtestc_ps_256:
10284 case Intrinsic::x86_avx_vtestnzc_ps_256:
10285 case Intrinsic::x86_avx_vtestz_pd_256:
10286 case Intrinsic::x86_avx_vtestc_pd_256:
10287 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10288 bool IsTestPacked = false;
10291 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10292 case Intrinsic::x86_avx_vtestz_ps:
10293 case Intrinsic::x86_avx_vtestz_pd:
10294 case Intrinsic::x86_avx_vtestz_ps_256:
10295 case Intrinsic::x86_avx_vtestz_pd_256:
10296 IsTestPacked = true; // Fallthrough
10297 case Intrinsic::x86_sse41_ptestz:
10298 case Intrinsic::x86_avx_ptestz_256:
10300 X86CC = X86::COND_E;
10302 case Intrinsic::x86_avx_vtestc_ps:
10303 case Intrinsic::x86_avx_vtestc_pd:
10304 case Intrinsic::x86_avx_vtestc_ps_256:
10305 case Intrinsic::x86_avx_vtestc_pd_256:
10306 IsTestPacked = true; // Fallthrough
10307 case Intrinsic::x86_sse41_ptestc:
10308 case Intrinsic::x86_avx_ptestc_256:
10310 X86CC = X86::COND_B;
10312 case Intrinsic::x86_avx_vtestnzc_ps:
10313 case Intrinsic::x86_avx_vtestnzc_pd:
10314 case Intrinsic::x86_avx_vtestnzc_ps_256:
10315 case Intrinsic::x86_avx_vtestnzc_pd_256:
10316 IsTestPacked = true; // Fallthrough
10317 case Intrinsic::x86_sse41_ptestnzc:
10318 case Intrinsic::x86_avx_ptestnzc_256:
10320 X86CC = X86::COND_A;
10324 SDValue LHS = Op.getOperand(1);
10325 SDValue RHS = Op.getOperand(2);
10326 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10327 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10328 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10329 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10330 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10333 // SSE/AVX shift intrinsics
10334 case Intrinsic::x86_sse2_psll_w:
10335 case Intrinsic::x86_sse2_psll_d:
10336 case Intrinsic::x86_sse2_psll_q:
10337 case Intrinsic::x86_avx2_psll_w:
10338 case Intrinsic::x86_avx2_psll_d:
10339 case Intrinsic::x86_avx2_psll_q:
10340 case Intrinsic::x86_sse2_psrl_w:
10341 case Intrinsic::x86_sse2_psrl_d:
10342 case Intrinsic::x86_sse2_psrl_q:
10343 case Intrinsic::x86_avx2_psrl_w:
10344 case Intrinsic::x86_avx2_psrl_d:
10345 case Intrinsic::x86_avx2_psrl_q:
10346 case Intrinsic::x86_sse2_psra_w:
10347 case Intrinsic::x86_sse2_psra_d:
10348 case Intrinsic::x86_avx2_psra_w:
10349 case Intrinsic::x86_avx2_psra_d: {
10352 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10353 case Intrinsic::x86_sse2_psll_w:
10354 case Intrinsic::x86_sse2_psll_d:
10355 case Intrinsic::x86_sse2_psll_q:
10356 case Intrinsic::x86_avx2_psll_w:
10357 case Intrinsic::x86_avx2_psll_d:
10358 case Intrinsic::x86_avx2_psll_q:
10359 Opcode = X86ISD::VSHL;
10361 case Intrinsic::x86_sse2_psrl_w:
10362 case Intrinsic::x86_sse2_psrl_d:
10363 case Intrinsic::x86_sse2_psrl_q:
10364 case Intrinsic::x86_avx2_psrl_w:
10365 case Intrinsic::x86_avx2_psrl_d:
10366 case Intrinsic::x86_avx2_psrl_q:
10367 Opcode = X86ISD::VSRL;
10369 case Intrinsic::x86_sse2_psra_w:
10370 case Intrinsic::x86_sse2_psra_d:
10371 case Intrinsic::x86_avx2_psra_w:
10372 case Intrinsic::x86_avx2_psra_d:
10373 Opcode = X86ISD::VSRA;
10376 return DAG.getNode(Opcode, dl, Op.getValueType(),
10377 Op.getOperand(1), Op.getOperand(2));
10380 // SSE/AVX immediate shift intrinsics
10381 case Intrinsic::x86_sse2_pslli_w:
10382 case Intrinsic::x86_sse2_pslli_d:
10383 case Intrinsic::x86_sse2_pslli_q:
10384 case Intrinsic::x86_avx2_pslli_w:
10385 case Intrinsic::x86_avx2_pslli_d:
10386 case Intrinsic::x86_avx2_pslli_q:
10387 case Intrinsic::x86_sse2_psrli_w:
10388 case Intrinsic::x86_sse2_psrli_d:
10389 case Intrinsic::x86_sse2_psrli_q:
10390 case Intrinsic::x86_avx2_psrli_w:
10391 case Intrinsic::x86_avx2_psrli_d:
10392 case Intrinsic::x86_avx2_psrli_q:
10393 case Intrinsic::x86_sse2_psrai_w:
10394 case Intrinsic::x86_sse2_psrai_d:
10395 case Intrinsic::x86_avx2_psrai_w:
10396 case Intrinsic::x86_avx2_psrai_d: {
10399 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10400 case Intrinsic::x86_sse2_pslli_w:
10401 case Intrinsic::x86_sse2_pslli_d:
10402 case Intrinsic::x86_sse2_pslli_q:
10403 case Intrinsic::x86_avx2_pslli_w:
10404 case Intrinsic::x86_avx2_pslli_d:
10405 case Intrinsic::x86_avx2_pslli_q:
10406 Opcode = X86ISD::VSHLI;
10408 case Intrinsic::x86_sse2_psrli_w:
10409 case Intrinsic::x86_sse2_psrli_d:
10410 case Intrinsic::x86_sse2_psrli_q:
10411 case Intrinsic::x86_avx2_psrli_w:
10412 case Intrinsic::x86_avx2_psrli_d:
10413 case Intrinsic::x86_avx2_psrli_q:
10414 Opcode = X86ISD::VSRLI;
10416 case Intrinsic::x86_sse2_psrai_w:
10417 case Intrinsic::x86_sse2_psrai_d:
10418 case Intrinsic::x86_avx2_psrai_w:
10419 case Intrinsic::x86_avx2_psrai_d:
10420 Opcode = X86ISD::VSRAI;
10423 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10424 Op.getOperand(1), Op.getOperand(2), DAG);
10427 case Intrinsic::x86_sse42_pcmpistria128:
10428 case Intrinsic::x86_sse42_pcmpestria128:
10429 case Intrinsic::x86_sse42_pcmpistric128:
10430 case Intrinsic::x86_sse42_pcmpestric128:
10431 case Intrinsic::x86_sse42_pcmpistrio128:
10432 case Intrinsic::x86_sse42_pcmpestrio128:
10433 case Intrinsic::x86_sse42_pcmpistris128:
10434 case Intrinsic::x86_sse42_pcmpestris128:
10435 case Intrinsic::x86_sse42_pcmpistriz128:
10436 case Intrinsic::x86_sse42_pcmpestriz128: {
10440 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10441 case Intrinsic::x86_sse42_pcmpistria128:
10442 Opcode = X86ISD::PCMPISTRI;
10443 X86CC = X86::COND_A;
10445 case Intrinsic::x86_sse42_pcmpestria128:
10446 Opcode = X86ISD::PCMPESTRI;
10447 X86CC = X86::COND_A;
10449 case Intrinsic::x86_sse42_pcmpistric128:
10450 Opcode = X86ISD::PCMPISTRI;
10451 X86CC = X86::COND_B;
10453 case Intrinsic::x86_sse42_pcmpestric128:
10454 Opcode = X86ISD::PCMPESTRI;
10455 X86CC = X86::COND_B;
10457 case Intrinsic::x86_sse42_pcmpistrio128:
10458 Opcode = X86ISD::PCMPISTRI;
10459 X86CC = X86::COND_O;
10461 case Intrinsic::x86_sse42_pcmpestrio128:
10462 Opcode = X86ISD::PCMPESTRI;
10463 X86CC = X86::COND_O;
10465 case Intrinsic::x86_sse42_pcmpistris128:
10466 Opcode = X86ISD::PCMPISTRI;
10467 X86CC = X86::COND_S;
10469 case Intrinsic::x86_sse42_pcmpestris128:
10470 Opcode = X86ISD::PCMPESTRI;
10471 X86CC = X86::COND_S;
10473 case Intrinsic::x86_sse42_pcmpistriz128:
10474 Opcode = X86ISD::PCMPISTRI;
10475 X86CC = X86::COND_E;
10477 case Intrinsic::x86_sse42_pcmpestriz128:
10478 Opcode = X86ISD::PCMPESTRI;
10479 X86CC = X86::COND_E;
10482 SmallVector<SDValue, 5> NewOps;
10483 NewOps.append(Op->op_begin()+1, Op->op_end());
10484 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10485 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10486 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10487 DAG.getConstant(X86CC, MVT::i8),
10488 SDValue(PCMP.getNode(), 1));
10489 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10492 case Intrinsic::x86_sse42_pcmpistri128:
10493 case Intrinsic::x86_sse42_pcmpestri128: {
10495 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10496 Opcode = X86ISD::PCMPISTRI;
10498 Opcode = X86ISD::PCMPESTRI;
10500 SmallVector<SDValue, 5> NewOps;
10501 NewOps.append(Op->op_begin()+1, Op->op_end());
10502 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10503 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10505 case Intrinsic::x86_fma_vfmadd_ps:
10506 case Intrinsic::x86_fma_vfmadd_pd:
10507 case Intrinsic::x86_fma_vfmsub_ps:
10508 case Intrinsic::x86_fma_vfmsub_pd:
10509 case Intrinsic::x86_fma_vfnmadd_ps:
10510 case Intrinsic::x86_fma_vfnmadd_pd:
10511 case Intrinsic::x86_fma_vfnmsub_ps:
10512 case Intrinsic::x86_fma_vfnmsub_pd:
10513 case Intrinsic::x86_fma_vfmaddsub_ps:
10514 case Intrinsic::x86_fma_vfmaddsub_pd:
10515 case Intrinsic::x86_fma_vfmsubadd_ps:
10516 case Intrinsic::x86_fma_vfmsubadd_pd:
10517 case Intrinsic::x86_fma_vfmadd_ps_256:
10518 case Intrinsic::x86_fma_vfmadd_pd_256:
10519 case Intrinsic::x86_fma_vfmsub_ps_256:
10520 case Intrinsic::x86_fma_vfmsub_pd_256:
10521 case Intrinsic::x86_fma_vfnmadd_ps_256:
10522 case Intrinsic::x86_fma_vfnmadd_pd_256:
10523 case Intrinsic::x86_fma_vfnmsub_ps_256:
10524 case Intrinsic::x86_fma_vfnmsub_pd_256:
10525 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10526 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10527 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10528 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10531 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10532 case Intrinsic::x86_fma_vfmadd_ps:
10533 case Intrinsic::x86_fma_vfmadd_pd:
10534 case Intrinsic::x86_fma_vfmadd_ps_256:
10535 case Intrinsic::x86_fma_vfmadd_pd_256:
10536 Opc = X86ISD::FMADD;
10538 case Intrinsic::x86_fma_vfmsub_ps:
10539 case Intrinsic::x86_fma_vfmsub_pd:
10540 case Intrinsic::x86_fma_vfmsub_ps_256:
10541 case Intrinsic::x86_fma_vfmsub_pd_256:
10542 Opc = X86ISD::FMSUB;
10544 case Intrinsic::x86_fma_vfnmadd_ps:
10545 case Intrinsic::x86_fma_vfnmadd_pd:
10546 case Intrinsic::x86_fma_vfnmadd_ps_256:
10547 case Intrinsic::x86_fma_vfnmadd_pd_256:
10548 Opc = X86ISD::FNMADD;
10550 case Intrinsic::x86_fma_vfnmsub_ps:
10551 case Intrinsic::x86_fma_vfnmsub_pd:
10552 case Intrinsic::x86_fma_vfnmsub_ps_256:
10553 case Intrinsic::x86_fma_vfnmsub_pd_256:
10554 Opc = X86ISD::FNMSUB;
10556 case Intrinsic::x86_fma_vfmaddsub_ps:
10557 case Intrinsic::x86_fma_vfmaddsub_pd:
10558 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10559 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10560 Opc = X86ISD::FMADDSUB;
10562 case Intrinsic::x86_fma_vfmsubadd_ps:
10563 case Intrinsic::x86_fma_vfmsubadd_pd:
10564 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10565 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10566 Opc = X86ISD::FMSUBADD;
10570 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10571 Op.getOperand(2), Op.getOperand(3));
10576 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10577 DebugLoc dl = Op.getDebugLoc();
10578 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10580 default: return SDValue(); // Don't custom lower most intrinsics.
10582 // RDRAND intrinsics.
10583 case Intrinsic::x86_rdrand_16:
10584 case Intrinsic::x86_rdrand_32:
10585 case Intrinsic::x86_rdrand_64: {
10586 // Emit the node with the right value type.
10587 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10588 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10590 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10591 // return the value from Rand, which is always 0, casted to i32.
10592 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10593 DAG.getConstant(1, Op->getValueType(1)),
10594 DAG.getConstant(X86::COND_B, MVT::i32),
10595 SDValue(Result.getNode(), 1) };
10596 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10597 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10600 // Return { result, isValid, chain }.
10601 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10602 SDValue(Result.getNode(), 2));
10607 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10608 SelectionDAG &DAG) const {
10609 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10610 MFI->setReturnAddressIsTaken(true);
10612 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10613 DebugLoc dl = Op.getDebugLoc();
10614 EVT PtrVT = getPointerTy();
10617 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10619 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10620 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10621 DAG.getNode(ISD::ADD, dl, PtrVT,
10622 FrameAddr, Offset),
10623 MachinePointerInfo(), false, false, false, 0);
10626 // Just load the return address.
10627 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10628 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10629 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10632 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10633 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10634 MFI->setFrameAddressIsTaken(true);
10636 EVT VT = Op.getValueType();
10637 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10638 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10639 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10640 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10642 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10643 MachinePointerInfo(),
10644 false, false, false, 0);
10648 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10649 SelectionDAG &DAG) const {
10650 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10653 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10654 SDValue Chain = Op.getOperand(0);
10655 SDValue Offset = Op.getOperand(1);
10656 SDValue Handler = Op.getOperand(2);
10657 DebugLoc dl = Op.getDebugLoc();
10659 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10660 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10662 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10664 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10665 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10666 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10667 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10669 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10671 return DAG.getNode(X86ISD::EH_RETURN, dl,
10673 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10676 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10677 SelectionDAG &DAG) const {
10678 DebugLoc DL = Op.getDebugLoc();
10679 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10680 DAG.getVTList(MVT::i32, MVT::Other),
10681 Op.getOperand(0), Op.getOperand(1));
10684 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10685 SelectionDAG &DAG) const {
10686 DebugLoc DL = Op.getDebugLoc();
10687 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10688 Op.getOperand(0), Op.getOperand(1));
10691 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10692 return Op.getOperand(0);
10695 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10696 SelectionDAG &DAG) const {
10697 SDValue Root = Op.getOperand(0);
10698 SDValue Trmp = Op.getOperand(1); // trampoline
10699 SDValue FPtr = Op.getOperand(2); // nested function
10700 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10701 DebugLoc dl = Op.getDebugLoc();
10703 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10704 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10706 if (Subtarget->is64Bit()) {
10707 SDValue OutChains[6];
10709 // Large code-model.
10710 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10711 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10713 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10714 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10716 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10718 // Load the pointer to the nested function into R11.
10719 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10720 SDValue Addr = Trmp;
10721 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10722 Addr, MachinePointerInfo(TrmpAddr),
10725 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10726 DAG.getConstant(2, MVT::i64));
10727 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10728 MachinePointerInfo(TrmpAddr, 2),
10731 // Load the 'nest' parameter value into R10.
10732 // R10 is specified in X86CallingConv.td
10733 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10734 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10735 DAG.getConstant(10, MVT::i64));
10736 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10737 Addr, MachinePointerInfo(TrmpAddr, 10),
10740 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10741 DAG.getConstant(12, MVT::i64));
10742 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10743 MachinePointerInfo(TrmpAddr, 12),
10746 // Jump to the nested function.
10747 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10748 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10749 DAG.getConstant(20, MVT::i64));
10750 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10751 Addr, MachinePointerInfo(TrmpAddr, 20),
10754 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10755 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10756 DAG.getConstant(22, MVT::i64));
10757 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10758 MachinePointerInfo(TrmpAddr, 22),
10761 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10763 const Function *Func =
10764 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10765 CallingConv::ID CC = Func->getCallingConv();
10770 llvm_unreachable("Unsupported calling convention");
10771 case CallingConv::C:
10772 case CallingConv::X86_StdCall: {
10773 // Pass 'nest' parameter in ECX.
10774 // Must be kept in sync with X86CallingConv.td
10775 NestReg = X86::ECX;
10777 // Check that ECX wasn't needed by an 'inreg' parameter.
10778 FunctionType *FTy = Func->getFunctionType();
10779 const AttributeSet &Attrs = Func->getAttributes();
10781 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10782 unsigned InRegCount = 0;
10785 for (FunctionType::param_iterator I = FTy->param_begin(),
10786 E = FTy->param_end(); I != E; ++I, ++Idx)
10787 if (Attrs.getParamAttributes(Idx).hasAttribute(Attribute::InReg))
10788 // FIXME: should only count parameters that are lowered to integers.
10789 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10791 if (InRegCount > 2) {
10792 report_fatal_error("Nest register in use - reduce number of inreg"
10798 case CallingConv::X86_FastCall:
10799 case CallingConv::X86_ThisCall:
10800 case CallingConv::Fast:
10801 // Pass 'nest' parameter in EAX.
10802 // Must be kept in sync with X86CallingConv.td
10803 NestReg = X86::EAX;
10807 SDValue OutChains[4];
10808 SDValue Addr, Disp;
10810 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10811 DAG.getConstant(10, MVT::i32));
10812 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10814 // This is storing the opcode for MOV32ri.
10815 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10816 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10817 OutChains[0] = DAG.getStore(Root, dl,
10818 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10819 Trmp, MachinePointerInfo(TrmpAddr),
10822 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10823 DAG.getConstant(1, MVT::i32));
10824 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10825 MachinePointerInfo(TrmpAddr, 1),
10828 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10830 DAG.getConstant(5, MVT::i32));
10831 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10832 MachinePointerInfo(TrmpAddr, 5),
10835 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10836 DAG.getConstant(6, MVT::i32));
10837 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10838 MachinePointerInfo(TrmpAddr, 6),
10841 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10845 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10846 SelectionDAG &DAG) const {
10848 The rounding mode is in bits 11:10 of FPSR, and has the following
10850 00 Round to nearest
10855 FLT_ROUNDS, on the other hand, expects the following:
10862 To perform the conversion, we do:
10863 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10866 MachineFunction &MF = DAG.getMachineFunction();
10867 const TargetMachine &TM = MF.getTarget();
10868 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10869 unsigned StackAlignment = TFI.getStackAlignment();
10870 EVT VT = Op.getValueType();
10871 DebugLoc DL = Op.getDebugLoc();
10873 // Save FP Control Word to stack slot
10874 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10875 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10877 MachineMemOperand *MMO =
10878 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10879 MachineMemOperand::MOStore, 2, 2);
10881 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10882 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10883 DAG.getVTList(MVT::Other),
10884 Ops, 2, MVT::i16, MMO);
10886 // Load FP Control Word from stack slot
10887 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10888 MachinePointerInfo(), false, false, false, 0);
10890 // Transform as necessary
10892 DAG.getNode(ISD::SRL, DL, MVT::i16,
10893 DAG.getNode(ISD::AND, DL, MVT::i16,
10894 CWD, DAG.getConstant(0x800, MVT::i16)),
10895 DAG.getConstant(11, MVT::i8));
10897 DAG.getNode(ISD::SRL, DL, MVT::i16,
10898 DAG.getNode(ISD::AND, DL, MVT::i16,
10899 CWD, DAG.getConstant(0x400, MVT::i16)),
10900 DAG.getConstant(9, MVT::i8));
10903 DAG.getNode(ISD::AND, DL, MVT::i16,
10904 DAG.getNode(ISD::ADD, DL, MVT::i16,
10905 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10906 DAG.getConstant(1, MVT::i16)),
10907 DAG.getConstant(3, MVT::i16));
10909 return DAG.getNode((VT.getSizeInBits() < 16 ?
10910 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10913 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10914 EVT VT = Op.getValueType();
10916 unsigned NumBits = VT.getSizeInBits();
10917 DebugLoc dl = Op.getDebugLoc();
10919 Op = Op.getOperand(0);
10920 if (VT == MVT::i8) {
10921 // Zero extend to i32 since there is not an i8 bsr.
10923 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10926 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10927 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10928 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10930 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10933 DAG.getConstant(NumBits+NumBits-1, OpVT),
10934 DAG.getConstant(X86::COND_E, MVT::i8),
10937 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10939 // Finally xor with NumBits-1.
10940 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10943 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10947 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10948 EVT VT = Op.getValueType();
10950 unsigned NumBits = VT.getSizeInBits();
10951 DebugLoc dl = Op.getDebugLoc();
10953 Op = Op.getOperand(0);
10954 if (VT == MVT::i8) {
10955 // Zero extend to i32 since there is not an i8 bsr.
10957 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10960 // Issue a bsr (scan bits in reverse).
10961 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10962 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10964 // And xor with NumBits-1.
10965 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10968 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10972 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10973 EVT VT = Op.getValueType();
10974 unsigned NumBits = VT.getSizeInBits();
10975 DebugLoc dl = Op.getDebugLoc();
10976 Op = Op.getOperand(0);
10978 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10979 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10980 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10982 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10985 DAG.getConstant(NumBits, VT),
10986 DAG.getConstant(X86::COND_E, MVT::i8),
10989 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10992 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10993 // ones, and then concatenate the result back.
10994 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10995 EVT VT = Op.getValueType();
10997 assert(VT.is256BitVector() && VT.isInteger() &&
10998 "Unsupported value type for operation");
11000 unsigned NumElems = VT.getVectorNumElements();
11001 DebugLoc dl = Op.getDebugLoc();
11003 // Extract the LHS vectors
11004 SDValue LHS = Op.getOperand(0);
11005 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11006 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11008 // Extract the RHS vectors
11009 SDValue RHS = Op.getOperand(1);
11010 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11011 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11013 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11014 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11016 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11017 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11018 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11021 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11022 assert(Op.getValueType().is256BitVector() &&
11023 Op.getValueType().isInteger() &&
11024 "Only handle AVX 256-bit vector integer operation");
11025 return Lower256IntArith(Op, DAG);
11028 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11029 assert(Op.getValueType().is256BitVector() &&
11030 Op.getValueType().isInteger() &&
11031 "Only handle AVX 256-bit vector integer operation");
11032 return Lower256IntArith(Op, DAG);
11035 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11036 SelectionDAG &DAG) {
11037 DebugLoc dl = Op.getDebugLoc();
11038 EVT VT = Op.getValueType();
11040 // Decompose 256-bit ops into smaller 128-bit ops.
11041 if (VT.is256BitVector() && !Subtarget->hasInt256())
11042 return Lower256IntArith(Op, DAG);
11044 SDValue A = Op.getOperand(0);
11045 SDValue B = Op.getOperand(1);
11047 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11048 if (VT == MVT::v4i32) {
11049 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11050 "Should not custom lower when pmuldq is available!");
11052 // Extract the odd parts.
11053 const int UnpackMask[] = { 1, -1, 3, -1 };
11054 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11055 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11057 // Multiply the even parts.
11058 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11059 // Now multiply odd parts.
11060 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11062 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11063 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11065 // Merge the two vectors back together with a shuffle. This expands into 2
11067 const int ShufMask[] = { 0, 4, 2, 6 };
11068 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11071 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11072 "Only know how to lower V2I64/V4I64 multiply");
11074 // Ahi = psrlqi(a, 32);
11075 // Bhi = psrlqi(b, 32);
11077 // AloBlo = pmuludq(a, b);
11078 // AloBhi = pmuludq(a, Bhi);
11079 // AhiBlo = pmuludq(Ahi, b);
11081 // AloBhi = psllqi(AloBhi, 32);
11082 // AhiBlo = psllqi(AhiBlo, 32);
11083 // return AloBlo + AloBhi + AhiBlo;
11085 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11087 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11088 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11090 // Bit cast to 32-bit vectors for MULUDQ
11091 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11092 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11093 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11094 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11095 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11097 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11098 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11099 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11101 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11102 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11104 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11105 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11108 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11110 EVT VT = Op.getValueType();
11111 DebugLoc dl = Op.getDebugLoc();
11112 SDValue R = Op.getOperand(0);
11113 SDValue Amt = Op.getOperand(1);
11114 LLVMContext *Context = DAG.getContext();
11116 if (!Subtarget->hasSSE2())
11119 // Optimize shl/srl/sra with constant shift amount.
11120 if (isSplatVector(Amt.getNode())) {
11121 SDValue SclrAmt = Amt->getOperand(0);
11122 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11123 uint64_t ShiftAmt = C->getZExtValue();
11125 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11126 (Subtarget->hasInt256() &&
11127 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11128 if (Op.getOpcode() == ISD::SHL)
11129 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11130 DAG.getConstant(ShiftAmt, MVT::i32));
11131 if (Op.getOpcode() == ISD::SRL)
11132 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11133 DAG.getConstant(ShiftAmt, MVT::i32));
11134 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11135 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11136 DAG.getConstant(ShiftAmt, MVT::i32));
11139 if (VT == MVT::v16i8) {
11140 if (Op.getOpcode() == ISD::SHL) {
11141 // Make a large shift.
11142 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11143 DAG.getConstant(ShiftAmt, MVT::i32));
11144 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11145 // Zero out the rightmost bits.
11146 SmallVector<SDValue, 16> V(16,
11147 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11149 return DAG.getNode(ISD::AND, dl, VT, SHL,
11150 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11152 if (Op.getOpcode() == ISD::SRL) {
11153 // Make a large shift.
11154 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11155 DAG.getConstant(ShiftAmt, MVT::i32));
11156 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11157 // Zero out the leftmost bits.
11158 SmallVector<SDValue, 16> V(16,
11159 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11161 return DAG.getNode(ISD::AND, dl, VT, SRL,
11162 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11164 if (Op.getOpcode() == ISD::SRA) {
11165 if (ShiftAmt == 7) {
11166 // R s>> 7 === R s< 0
11167 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11168 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11171 // R s>> a === ((R u>> a) ^ m) - m
11172 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11173 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11175 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11176 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11177 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11180 llvm_unreachable("Unknown shift opcode.");
11183 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11184 if (Op.getOpcode() == ISD::SHL) {
11185 // Make a large shift.
11186 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11187 DAG.getConstant(ShiftAmt, MVT::i32));
11188 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11189 // Zero out the rightmost bits.
11190 SmallVector<SDValue, 32> V(32,
11191 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11193 return DAG.getNode(ISD::AND, dl, VT, SHL,
11194 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11196 if (Op.getOpcode() == ISD::SRL) {
11197 // Make a large shift.
11198 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11199 DAG.getConstant(ShiftAmt, MVT::i32));
11200 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11201 // Zero out the leftmost bits.
11202 SmallVector<SDValue, 32> V(32,
11203 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11205 return DAG.getNode(ISD::AND, dl, VT, SRL,
11206 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11208 if (Op.getOpcode() == ISD::SRA) {
11209 if (ShiftAmt == 7) {
11210 // R s>> 7 === R s< 0
11211 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11212 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11215 // R s>> a === ((R u>> a) ^ m) - m
11216 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11217 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11219 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11220 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11221 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11224 llvm_unreachable("Unknown shift opcode.");
11229 // Lower SHL with variable shift amount.
11230 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11231 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11232 DAG.getConstant(23, MVT::i32));
11234 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11235 Constant *C = ConstantDataVector::get(*Context, CV);
11236 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11237 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11238 MachinePointerInfo::getConstantPool(),
11239 false, false, false, 16);
11241 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11242 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11243 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11244 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11246 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11247 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11250 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11251 DAG.getConstant(5, MVT::i32));
11252 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11254 // Turn 'a' into a mask suitable for VSELECT
11255 SDValue VSelM = DAG.getConstant(0x80, VT);
11256 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11257 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11259 SDValue CM1 = DAG.getConstant(0x0f, VT);
11260 SDValue CM2 = DAG.getConstant(0x3f, VT);
11262 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11263 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11264 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11265 DAG.getConstant(4, MVT::i32), DAG);
11266 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11267 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11270 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11271 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11272 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11274 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11275 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11276 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11277 DAG.getConstant(2, MVT::i32), DAG);
11278 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11279 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11282 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11283 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11284 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11286 // return VSELECT(r, r+r, a);
11287 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11288 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11292 // Decompose 256-bit shifts into smaller 128-bit shifts.
11293 if (VT.is256BitVector()) {
11294 unsigned NumElems = VT.getVectorNumElements();
11295 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11296 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11298 // Extract the two vectors
11299 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11300 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11302 // Recreate the shift amount vectors
11303 SDValue Amt1, Amt2;
11304 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11305 // Constant shift amount
11306 SmallVector<SDValue, 4> Amt1Csts;
11307 SmallVector<SDValue, 4> Amt2Csts;
11308 for (unsigned i = 0; i != NumElems/2; ++i)
11309 Amt1Csts.push_back(Amt->getOperand(i));
11310 for (unsigned i = NumElems/2; i != NumElems; ++i)
11311 Amt2Csts.push_back(Amt->getOperand(i));
11313 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11314 &Amt1Csts[0], NumElems/2);
11315 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11316 &Amt2Csts[0], NumElems/2);
11318 // Variable shift amount
11319 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11320 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11323 // Issue new vector shifts for the smaller types
11324 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11325 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11327 // Concatenate the result back
11328 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11334 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11335 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11336 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11337 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11338 // has only one use.
11339 SDNode *N = Op.getNode();
11340 SDValue LHS = N->getOperand(0);
11341 SDValue RHS = N->getOperand(1);
11342 unsigned BaseOp = 0;
11344 DebugLoc DL = Op.getDebugLoc();
11345 switch (Op.getOpcode()) {
11346 default: llvm_unreachable("Unknown ovf instruction!");
11348 // A subtract of one will be selected as a INC. Note that INC doesn't
11349 // set CF, so we can't do this for UADDO.
11350 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11352 BaseOp = X86ISD::INC;
11353 Cond = X86::COND_O;
11356 BaseOp = X86ISD::ADD;
11357 Cond = X86::COND_O;
11360 BaseOp = X86ISD::ADD;
11361 Cond = X86::COND_B;
11364 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11365 // set CF, so we can't do this for USUBO.
11366 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11368 BaseOp = X86ISD::DEC;
11369 Cond = X86::COND_O;
11372 BaseOp = X86ISD::SUB;
11373 Cond = X86::COND_O;
11376 BaseOp = X86ISD::SUB;
11377 Cond = X86::COND_B;
11380 BaseOp = X86ISD::SMUL;
11381 Cond = X86::COND_O;
11383 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11384 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11386 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11389 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11390 DAG.getConstant(X86::COND_O, MVT::i32),
11391 SDValue(Sum.getNode(), 2));
11393 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11397 // Also sets EFLAGS.
11398 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11399 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11402 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11403 DAG.getConstant(Cond, MVT::i32),
11404 SDValue(Sum.getNode(), 1));
11406 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11409 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11410 SelectionDAG &DAG) const {
11411 DebugLoc dl = Op.getDebugLoc();
11412 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11413 EVT VT = Op.getValueType();
11415 if (!Subtarget->hasSSE2() || !VT.isVector())
11418 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11419 ExtraVT.getScalarType().getSizeInBits();
11420 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11422 switch (VT.getSimpleVT().SimpleTy) {
11423 default: return SDValue();
11426 if (!Subtarget->hasFp256())
11428 if (!Subtarget->hasInt256()) {
11429 // needs to be split
11430 unsigned NumElems = VT.getVectorNumElements();
11432 // Extract the LHS vectors
11433 SDValue LHS = Op.getOperand(0);
11434 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11435 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11437 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11438 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11440 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11441 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11442 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11444 SDValue Extra = DAG.getValueType(ExtraVT);
11446 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11447 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11449 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11454 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11455 Op.getOperand(0), ShAmt, DAG);
11456 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11461 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11462 SelectionDAG &DAG) {
11463 DebugLoc dl = Op.getDebugLoc();
11465 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11466 // There isn't any reason to disable it if the target processor supports it.
11467 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11468 SDValue Chain = Op.getOperand(0);
11469 SDValue Zero = DAG.getConstant(0, MVT::i32);
11471 DAG.getRegister(X86::ESP, MVT::i32), // Base
11472 DAG.getTargetConstant(1, MVT::i8), // Scale
11473 DAG.getRegister(0, MVT::i32), // Index
11474 DAG.getTargetConstant(0, MVT::i32), // Disp
11475 DAG.getRegister(0, MVT::i32), // Segment.
11480 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11481 array_lengthof(Ops));
11482 return SDValue(Res, 0);
11485 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11487 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11489 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11490 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11491 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11492 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11494 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11495 if (!Op1 && !Op2 && !Op3 && Op4)
11496 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11498 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11499 if (Op1 && !Op2 && !Op3 && !Op4)
11500 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11502 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11504 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11507 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11508 SelectionDAG &DAG) {
11509 DebugLoc dl = Op.getDebugLoc();
11510 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11511 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11512 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11513 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11515 // The only fence that needs an instruction is a sequentially-consistent
11516 // cross-thread fence.
11517 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11518 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11519 // no-sse2). There isn't any reason to disable it if the target processor
11521 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11522 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11524 SDValue Chain = Op.getOperand(0);
11525 SDValue Zero = DAG.getConstant(0, MVT::i32);
11527 DAG.getRegister(X86::ESP, MVT::i32), // Base
11528 DAG.getTargetConstant(1, MVT::i8), // Scale
11529 DAG.getRegister(0, MVT::i32), // Index
11530 DAG.getTargetConstant(0, MVT::i32), // Disp
11531 DAG.getRegister(0, MVT::i32), // Segment.
11536 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11537 array_lengthof(Ops));
11538 return SDValue(Res, 0);
11541 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11542 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11545 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11546 SelectionDAG &DAG) {
11547 EVT T = Op.getValueType();
11548 DebugLoc DL = Op.getDebugLoc();
11551 switch(T.getSimpleVT().SimpleTy) {
11552 default: llvm_unreachable("Invalid value type!");
11553 case MVT::i8: Reg = X86::AL; size = 1; break;
11554 case MVT::i16: Reg = X86::AX; size = 2; break;
11555 case MVT::i32: Reg = X86::EAX; size = 4; break;
11557 assert(Subtarget->is64Bit() && "Node not type legal!");
11558 Reg = X86::RAX; size = 8;
11561 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11562 Op.getOperand(2), SDValue());
11563 SDValue Ops[] = { cpIn.getValue(0),
11566 DAG.getTargetConstant(size, MVT::i8),
11567 cpIn.getValue(1) };
11568 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11569 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11570 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11573 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11577 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11578 SelectionDAG &DAG) {
11579 assert(Subtarget->is64Bit() && "Result not type legalized?");
11580 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11581 SDValue TheChain = Op.getOperand(0);
11582 DebugLoc dl = Op.getDebugLoc();
11583 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11584 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11585 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11587 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11588 DAG.getConstant(32, MVT::i8));
11590 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11593 return DAG.getMergeValues(Ops, 2, dl);
11596 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11597 EVT SrcVT = Op.getOperand(0).getValueType();
11598 EVT DstVT = Op.getValueType();
11599 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11600 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11601 assert((DstVT == MVT::i64 ||
11602 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11603 "Unexpected custom BITCAST");
11604 // i64 <=> MMX conversions are Legal.
11605 if (SrcVT==MVT::i64 && DstVT.isVector())
11607 if (DstVT==MVT::i64 && SrcVT.isVector())
11609 // MMX <=> MMX conversions are Legal.
11610 if (SrcVT.isVector() && DstVT.isVector())
11612 // All other conversions need to be expanded.
11616 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11617 SDNode *Node = Op.getNode();
11618 DebugLoc dl = Node->getDebugLoc();
11619 EVT T = Node->getValueType(0);
11620 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11621 DAG.getConstant(0, T), Node->getOperand(2));
11622 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11623 cast<AtomicSDNode>(Node)->getMemoryVT(),
11624 Node->getOperand(0),
11625 Node->getOperand(1), negOp,
11626 cast<AtomicSDNode>(Node)->getSrcValue(),
11627 cast<AtomicSDNode>(Node)->getAlignment(),
11628 cast<AtomicSDNode>(Node)->getOrdering(),
11629 cast<AtomicSDNode>(Node)->getSynchScope());
11632 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11633 SDNode *Node = Op.getNode();
11634 DebugLoc dl = Node->getDebugLoc();
11635 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11637 // Convert seq_cst store -> xchg
11638 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11639 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11640 // (The only way to get a 16-byte store is cmpxchg16b)
11641 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11642 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11643 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11644 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11645 cast<AtomicSDNode>(Node)->getMemoryVT(),
11646 Node->getOperand(0),
11647 Node->getOperand(1), Node->getOperand(2),
11648 cast<AtomicSDNode>(Node)->getMemOperand(),
11649 cast<AtomicSDNode>(Node)->getOrdering(),
11650 cast<AtomicSDNode>(Node)->getSynchScope());
11651 return Swap.getValue(1);
11653 // Other atomic stores have a simple pattern.
11657 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11658 EVT VT = Op.getNode()->getValueType(0);
11660 // Let legalize expand this if it isn't a legal type yet.
11661 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11664 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11667 bool ExtraOp = false;
11668 switch (Op.getOpcode()) {
11669 default: llvm_unreachable("Invalid code");
11670 case ISD::ADDC: Opc = X86ISD::ADD; break;
11671 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11672 case ISD::SUBC: Opc = X86ISD::SUB; break;
11673 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11677 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11679 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11680 Op.getOperand(1), Op.getOperand(2));
11683 /// LowerOperation - Provide custom lowering hooks for some operations.
11685 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11686 switch (Op.getOpcode()) {
11687 default: llvm_unreachable("Should not custom lower this!");
11688 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11689 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11690 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11691 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11692 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11693 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11694 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11695 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11696 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11697 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11698 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11699 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11700 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11701 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11702 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11703 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11704 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11705 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11706 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11707 case ISD::SHL_PARTS:
11708 case ISD::SRA_PARTS:
11709 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11710 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11711 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11712 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11713 case ISD::ZERO_EXTEND: return lowerZERO_EXTEND(Op, DAG);
11714 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11715 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11716 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11717 case ISD::FABS: return LowerFABS(Op, DAG);
11718 case ISD::FNEG: return LowerFNEG(Op, DAG);
11719 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11720 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11721 case ISD::SETCC: return LowerSETCC(Op, DAG);
11722 case ISD::SELECT: return LowerSELECT(Op, DAG);
11723 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11724 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11725 case ISD::VASTART: return LowerVASTART(Op, DAG);
11726 case ISD::VAARG: return LowerVAARG(Op, DAG);
11727 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11728 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11729 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11730 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11731 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11732 case ISD::FRAME_TO_ARGS_OFFSET:
11733 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11734 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11735 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11736 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11737 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11738 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11739 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11740 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11741 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11742 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11743 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11744 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11747 case ISD::SHL: return LowerShift(Op, DAG);
11753 case ISD::UMULO: return LowerXALUO(Op, DAG);
11754 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11755 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11759 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11760 case ISD::ADD: return LowerADD(Op, DAG);
11761 case ISD::SUB: return LowerSUB(Op, DAG);
11765 static void ReplaceATOMIC_LOAD(SDNode *Node,
11766 SmallVectorImpl<SDValue> &Results,
11767 SelectionDAG &DAG) {
11768 DebugLoc dl = Node->getDebugLoc();
11769 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11771 // Convert wide load -> cmpxchg8b/cmpxchg16b
11772 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11773 // (The only way to get a 16-byte load is cmpxchg16b)
11774 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11775 SDValue Zero = DAG.getConstant(0, VT);
11776 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11777 Node->getOperand(0),
11778 Node->getOperand(1), Zero, Zero,
11779 cast<AtomicSDNode>(Node)->getMemOperand(),
11780 cast<AtomicSDNode>(Node)->getOrdering(),
11781 cast<AtomicSDNode>(Node)->getSynchScope());
11782 Results.push_back(Swap.getValue(0));
11783 Results.push_back(Swap.getValue(1));
11787 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11788 SelectionDAG &DAG, unsigned NewOp) {
11789 DebugLoc dl = Node->getDebugLoc();
11790 assert (Node->getValueType(0) == MVT::i64 &&
11791 "Only know how to expand i64 atomics");
11793 SDValue Chain = Node->getOperand(0);
11794 SDValue In1 = Node->getOperand(1);
11795 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11796 Node->getOperand(2), DAG.getIntPtrConstant(0));
11797 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11798 Node->getOperand(2), DAG.getIntPtrConstant(1));
11799 SDValue Ops[] = { Chain, In1, In2L, In2H };
11800 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11802 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11803 cast<MemSDNode>(Node)->getMemOperand());
11804 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11805 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11806 Results.push_back(Result.getValue(2));
11809 /// ReplaceNodeResults - Replace a node with an illegal result type
11810 /// with a new node built out of custom code.
11811 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11812 SmallVectorImpl<SDValue>&Results,
11813 SelectionDAG &DAG) const {
11814 DebugLoc dl = N->getDebugLoc();
11815 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11816 switch (N->getOpcode()) {
11818 llvm_unreachable("Do not know how to custom type legalize this operation!");
11819 case ISD::SIGN_EXTEND_INREG:
11824 // We don't want to expand or promote these.
11826 case ISD::FP_TO_SINT:
11827 case ISD::FP_TO_UINT: {
11828 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11830 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11833 std::pair<SDValue,SDValue> Vals =
11834 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11835 SDValue FIST = Vals.first, StackSlot = Vals.second;
11836 if (FIST.getNode() != 0) {
11837 EVT VT = N->getValueType(0);
11838 // Return a load from the stack slot.
11839 if (StackSlot.getNode() != 0)
11840 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11841 MachinePointerInfo(),
11842 false, false, false, 0));
11844 Results.push_back(FIST);
11848 case ISD::UINT_TO_FP: {
11849 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11850 N->getValueType(0) != MVT::v2f32)
11852 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11854 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11856 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11857 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11858 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11859 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11860 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11861 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11864 case ISD::FP_ROUND: {
11865 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
11867 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11868 Results.push_back(V);
11871 case ISD::READCYCLECOUNTER: {
11872 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11873 SDValue TheChain = N->getOperand(0);
11874 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11875 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11877 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11879 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11880 SDValue Ops[] = { eax, edx };
11881 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11882 Results.push_back(edx.getValue(1));
11885 case ISD::ATOMIC_CMP_SWAP: {
11886 EVT T = N->getValueType(0);
11887 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11888 bool Regs64bit = T == MVT::i128;
11889 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11890 SDValue cpInL, cpInH;
11891 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11892 DAG.getConstant(0, HalfT));
11893 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11894 DAG.getConstant(1, HalfT));
11895 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11896 Regs64bit ? X86::RAX : X86::EAX,
11898 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11899 Regs64bit ? X86::RDX : X86::EDX,
11900 cpInH, cpInL.getValue(1));
11901 SDValue swapInL, swapInH;
11902 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11903 DAG.getConstant(0, HalfT));
11904 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11905 DAG.getConstant(1, HalfT));
11906 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11907 Regs64bit ? X86::RBX : X86::EBX,
11908 swapInL, cpInH.getValue(1));
11909 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11910 Regs64bit ? X86::RCX : X86::ECX,
11911 swapInH, swapInL.getValue(1));
11912 SDValue Ops[] = { swapInH.getValue(0),
11914 swapInH.getValue(1) };
11915 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11916 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11917 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11918 X86ISD::LCMPXCHG8_DAG;
11919 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11921 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11922 Regs64bit ? X86::RAX : X86::EAX,
11923 HalfT, Result.getValue(1));
11924 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11925 Regs64bit ? X86::RDX : X86::EDX,
11926 HalfT, cpOutL.getValue(2));
11927 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11928 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11929 Results.push_back(cpOutH.getValue(1));
11932 case ISD::ATOMIC_LOAD_ADD:
11933 case ISD::ATOMIC_LOAD_AND:
11934 case ISD::ATOMIC_LOAD_NAND:
11935 case ISD::ATOMIC_LOAD_OR:
11936 case ISD::ATOMIC_LOAD_SUB:
11937 case ISD::ATOMIC_LOAD_XOR:
11938 case ISD::ATOMIC_LOAD_MAX:
11939 case ISD::ATOMIC_LOAD_MIN:
11940 case ISD::ATOMIC_LOAD_UMAX:
11941 case ISD::ATOMIC_LOAD_UMIN:
11942 case ISD::ATOMIC_SWAP: {
11944 switch (N->getOpcode()) {
11945 default: llvm_unreachable("Unexpected opcode");
11946 case ISD::ATOMIC_LOAD_ADD:
11947 Opc = X86ISD::ATOMADD64_DAG;
11949 case ISD::ATOMIC_LOAD_AND:
11950 Opc = X86ISD::ATOMAND64_DAG;
11952 case ISD::ATOMIC_LOAD_NAND:
11953 Opc = X86ISD::ATOMNAND64_DAG;
11955 case ISD::ATOMIC_LOAD_OR:
11956 Opc = X86ISD::ATOMOR64_DAG;
11958 case ISD::ATOMIC_LOAD_SUB:
11959 Opc = X86ISD::ATOMSUB64_DAG;
11961 case ISD::ATOMIC_LOAD_XOR:
11962 Opc = X86ISD::ATOMXOR64_DAG;
11964 case ISD::ATOMIC_LOAD_MAX:
11965 Opc = X86ISD::ATOMMAX64_DAG;
11967 case ISD::ATOMIC_LOAD_MIN:
11968 Opc = X86ISD::ATOMMIN64_DAG;
11970 case ISD::ATOMIC_LOAD_UMAX:
11971 Opc = X86ISD::ATOMUMAX64_DAG;
11973 case ISD::ATOMIC_LOAD_UMIN:
11974 Opc = X86ISD::ATOMUMIN64_DAG;
11976 case ISD::ATOMIC_SWAP:
11977 Opc = X86ISD::ATOMSWAP64_DAG;
11980 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11983 case ISD::ATOMIC_LOAD:
11984 ReplaceATOMIC_LOAD(N, Results, DAG);
11988 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11990 default: return NULL;
11991 case X86ISD::BSF: return "X86ISD::BSF";
11992 case X86ISD::BSR: return "X86ISD::BSR";
11993 case X86ISD::SHLD: return "X86ISD::SHLD";
11994 case X86ISD::SHRD: return "X86ISD::SHRD";
11995 case X86ISD::FAND: return "X86ISD::FAND";
11996 case X86ISD::FOR: return "X86ISD::FOR";
11997 case X86ISD::FXOR: return "X86ISD::FXOR";
11998 case X86ISD::FSRL: return "X86ISD::FSRL";
11999 case X86ISD::FILD: return "X86ISD::FILD";
12000 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12001 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12002 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12003 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12004 case X86ISD::FLD: return "X86ISD::FLD";
12005 case X86ISD::FST: return "X86ISD::FST";
12006 case X86ISD::CALL: return "X86ISD::CALL";
12007 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12008 case X86ISD::BT: return "X86ISD::BT";
12009 case X86ISD::CMP: return "X86ISD::CMP";
12010 case X86ISD::COMI: return "X86ISD::COMI";
12011 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12012 case X86ISD::SETCC: return "X86ISD::SETCC";
12013 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12014 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12015 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12016 case X86ISD::CMOV: return "X86ISD::CMOV";
12017 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12018 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12019 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12020 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12021 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12022 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12023 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12024 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12025 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12026 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12027 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12028 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12029 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12030 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12031 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12032 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12033 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12034 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12035 case X86ISD::HADD: return "X86ISD::HADD";
12036 case X86ISD::HSUB: return "X86ISD::HSUB";
12037 case X86ISD::FHADD: return "X86ISD::FHADD";
12038 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12039 case X86ISD::UMAX: return "X86ISD::UMAX";
12040 case X86ISD::UMIN: return "X86ISD::UMIN";
12041 case X86ISD::SMAX: return "X86ISD::SMAX";
12042 case X86ISD::SMIN: return "X86ISD::SMIN";
12043 case X86ISD::FMAX: return "X86ISD::FMAX";
12044 case X86ISD::FMIN: return "X86ISD::FMIN";
12045 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12046 case X86ISD::FMINC: return "X86ISD::FMINC";
12047 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12048 case X86ISD::FRCP: return "X86ISD::FRCP";
12049 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12050 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12051 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12052 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12053 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12054 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12055 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12056 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12057 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12058 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12059 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12060 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12061 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12062 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12063 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12064 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12065 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12066 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12067 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12068 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12069 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12070 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12071 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12072 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12073 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12074 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12075 case X86ISD::VSHL: return "X86ISD::VSHL";
12076 case X86ISD::VSRL: return "X86ISD::VSRL";
12077 case X86ISD::VSRA: return "X86ISD::VSRA";
12078 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12079 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12080 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12081 case X86ISD::CMPP: return "X86ISD::CMPP";
12082 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12083 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12084 case X86ISD::ADD: return "X86ISD::ADD";
12085 case X86ISD::SUB: return "X86ISD::SUB";
12086 case X86ISD::ADC: return "X86ISD::ADC";
12087 case X86ISD::SBB: return "X86ISD::SBB";
12088 case X86ISD::SMUL: return "X86ISD::SMUL";
12089 case X86ISD::UMUL: return "X86ISD::UMUL";
12090 case X86ISD::INC: return "X86ISD::INC";
12091 case X86ISD::DEC: return "X86ISD::DEC";
12092 case X86ISD::OR: return "X86ISD::OR";
12093 case X86ISD::XOR: return "X86ISD::XOR";
12094 case X86ISD::AND: return "X86ISD::AND";
12095 case X86ISD::BLSI: return "X86ISD::BLSI";
12096 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12097 case X86ISD::BLSR: return "X86ISD::BLSR";
12098 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12099 case X86ISD::PTEST: return "X86ISD::PTEST";
12100 case X86ISD::TESTP: return "X86ISD::TESTP";
12101 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12102 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12103 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12104 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12105 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12106 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12107 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12108 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12109 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12110 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12111 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12112 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12113 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12114 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12115 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12116 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12117 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12118 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12119 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12120 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12121 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12122 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12123 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12124 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12125 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12126 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12127 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12128 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12129 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12130 case X86ISD::SAHF: return "X86ISD::SAHF";
12131 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12132 case X86ISD::FMADD: return "X86ISD::FMADD";
12133 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12134 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12135 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12136 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12137 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12138 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12139 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12143 // isLegalAddressingMode - Return true if the addressing mode represented
12144 // by AM is legal for this target, for a load/store of the specified type.
12145 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12147 // X86 supports extremely general addressing modes.
12148 CodeModel::Model M = getTargetMachine().getCodeModel();
12149 Reloc::Model R = getTargetMachine().getRelocationModel();
12151 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12152 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12157 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12159 // If a reference to this global requires an extra load, we can't fold it.
12160 if (isGlobalStubReference(GVFlags))
12163 // If BaseGV requires a register for the PIC base, we cannot also have a
12164 // BaseReg specified.
12165 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12168 // If lower 4G is not available, then we must use rip-relative addressing.
12169 if ((M != CodeModel::Small || R != Reloc::Static) &&
12170 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12174 switch (AM.Scale) {
12180 // These scales always work.
12185 // These scales are formed with basereg+scalereg. Only accept if there is
12190 default: // Other stuff never works.
12197 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12198 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12200 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12201 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12202 if (NumBits1 <= NumBits2)
12207 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12208 return Imm == (int32_t)Imm;
12211 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12212 // Can also use sub to handle negated immediates.
12213 return Imm == (int32_t)Imm;
12216 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12217 if (!VT1.isInteger() || !VT2.isInteger())
12219 unsigned NumBits1 = VT1.getSizeInBits();
12220 unsigned NumBits2 = VT2.getSizeInBits();
12221 if (NumBits1 <= NumBits2)
12226 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12227 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12228 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12231 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12232 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12233 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12236 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12237 EVT VT1 = Val.getValueType();
12238 if (isZExtFree(VT1, VT2))
12241 if (Val.getOpcode() != ISD::LOAD)
12244 if (!VT1.isSimple() || !VT1.isInteger() ||
12245 !VT2.isSimple() || !VT2.isInteger())
12248 switch (VT1.getSimpleVT().SimpleTy) {
12253 // X86 has 8, 16, and 32-bit zero-extending loads.
12260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12261 // i16 instructions are longer (0x66 prefix) and potentially slower.
12262 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12268 /// are assumed to be legal.
12270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12272 // Very little shuffling can be done for 64-bit vectors right now.
12273 if (VT.getSizeInBits() == 64)
12276 // FIXME: pshufb, blends, shifts.
12277 return (VT.getVectorNumElements() == 2 ||
12278 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12279 isMOVLMask(M, VT) ||
12280 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12281 isPSHUFDMask(M, VT) ||
12282 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12283 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12284 isPALIGNRMask(M, VT, Subtarget) ||
12285 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12286 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12287 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12288 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12292 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12294 unsigned NumElts = VT.getVectorNumElements();
12295 // FIXME: This collection of masks seems suspect.
12298 if (NumElts == 4 && VT.is128BitVector()) {
12299 return (isMOVLMask(Mask, VT) ||
12300 isCommutedMOVLMask(Mask, VT, true) ||
12301 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12302 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12307 //===----------------------------------------------------------------------===//
12308 // X86 Scheduler Hooks
12309 //===----------------------------------------------------------------------===//
12311 /// Utility function to emit xbegin specifying the start of an RTM region.
12312 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12313 const TargetInstrInfo *TII) {
12314 DebugLoc DL = MI->getDebugLoc();
12316 const BasicBlock *BB = MBB->getBasicBlock();
12317 MachineFunction::iterator I = MBB;
12320 // For the v = xbegin(), we generate
12331 MachineBasicBlock *thisMBB = MBB;
12332 MachineFunction *MF = MBB->getParent();
12333 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12334 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12335 MF->insert(I, mainMBB);
12336 MF->insert(I, sinkMBB);
12338 // Transfer the remainder of BB and its successor edges to sinkMBB.
12339 sinkMBB->splice(sinkMBB->begin(), MBB,
12340 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12341 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12345 // # fallthrough to mainMBB
12346 // # abortion to sinkMBB
12347 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12348 thisMBB->addSuccessor(mainMBB);
12349 thisMBB->addSuccessor(sinkMBB);
12353 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12354 mainMBB->addSuccessor(sinkMBB);
12357 // EAX is live into the sinkMBB
12358 sinkMBB->addLiveIn(X86::EAX);
12359 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12360 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12363 MI->eraseFromParent();
12367 // Get CMPXCHG opcode for the specified data type.
12368 static unsigned getCmpXChgOpcode(EVT VT) {
12369 switch (VT.getSimpleVT().SimpleTy) {
12370 case MVT::i8: return X86::LCMPXCHG8;
12371 case MVT::i16: return X86::LCMPXCHG16;
12372 case MVT::i32: return X86::LCMPXCHG32;
12373 case MVT::i64: return X86::LCMPXCHG64;
12377 llvm_unreachable("Invalid operand size!");
12380 // Get LOAD opcode for the specified data type.
12381 static unsigned getLoadOpcode(EVT VT) {
12382 switch (VT.getSimpleVT().SimpleTy) {
12383 case MVT::i8: return X86::MOV8rm;
12384 case MVT::i16: return X86::MOV16rm;
12385 case MVT::i32: return X86::MOV32rm;
12386 case MVT::i64: return X86::MOV64rm;
12390 llvm_unreachable("Invalid operand size!");
12393 // Get opcode of the non-atomic one from the specified atomic instruction.
12394 static unsigned getNonAtomicOpcode(unsigned Opc) {
12396 case X86::ATOMAND8: return X86::AND8rr;
12397 case X86::ATOMAND16: return X86::AND16rr;
12398 case X86::ATOMAND32: return X86::AND32rr;
12399 case X86::ATOMAND64: return X86::AND64rr;
12400 case X86::ATOMOR8: return X86::OR8rr;
12401 case X86::ATOMOR16: return X86::OR16rr;
12402 case X86::ATOMOR32: return X86::OR32rr;
12403 case X86::ATOMOR64: return X86::OR64rr;
12404 case X86::ATOMXOR8: return X86::XOR8rr;
12405 case X86::ATOMXOR16: return X86::XOR16rr;
12406 case X86::ATOMXOR32: return X86::XOR32rr;
12407 case X86::ATOMXOR64: return X86::XOR64rr;
12409 llvm_unreachable("Unhandled atomic-load-op opcode!");
12412 // Get opcode of the non-atomic one from the specified atomic instruction with
12414 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12415 unsigned &ExtraOpc) {
12417 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12418 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12419 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12420 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12421 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12422 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12423 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12424 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12425 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12426 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12427 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12428 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12429 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12430 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12431 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12432 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12433 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12434 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12435 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12436 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12438 llvm_unreachable("Unhandled atomic-load-op opcode!");
12441 // Get opcode of the non-atomic one from the specified atomic instruction for
12442 // 64-bit data type on 32-bit target.
12443 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12445 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12446 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12447 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12448 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12449 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12450 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12451 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12452 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12453 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12454 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12456 llvm_unreachable("Unhandled atomic-load-op opcode!");
12459 // Get opcode of the non-atomic one from the specified atomic instruction for
12460 // 64-bit data type on 32-bit target with extra opcode.
12461 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12463 unsigned &ExtraOpc) {
12465 case X86::ATOMNAND6432:
12466 ExtraOpc = X86::NOT32r;
12467 HiOpc = X86::AND32rr;
12468 return X86::AND32rr;
12470 llvm_unreachable("Unhandled atomic-load-op opcode!");
12473 // Get pseudo CMOV opcode from the specified data type.
12474 static unsigned getPseudoCMOVOpc(EVT VT) {
12475 switch (VT.getSimpleVT().SimpleTy) {
12476 case MVT::i8: return X86::CMOV_GR8;
12477 case MVT::i16: return X86::CMOV_GR16;
12478 case MVT::i32: return X86::CMOV_GR32;
12482 llvm_unreachable("Unknown CMOV opcode!");
12485 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12486 // They will be translated into a spin-loop or compare-exchange loop from
12489 // dst = atomic-fetch-op MI.addr, MI.val
12495 // EAX = LOAD MI.addr
12497 // t1 = OP MI.val, EAX
12498 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12503 MachineBasicBlock *
12504 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12505 MachineBasicBlock *MBB) const {
12506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12507 DebugLoc DL = MI->getDebugLoc();
12509 MachineFunction *MF = MBB->getParent();
12510 MachineRegisterInfo &MRI = MF->getRegInfo();
12512 const BasicBlock *BB = MBB->getBasicBlock();
12513 MachineFunction::iterator I = MBB;
12516 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12517 "Unexpected number of operands");
12519 assert(MI->hasOneMemOperand() &&
12520 "Expected atomic-load-op to have one memoperand");
12522 // Memory Reference
12523 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12524 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12526 unsigned DstReg, SrcReg;
12527 unsigned MemOpndSlot;
12529 unsigned CurOp = 0;
12531 DstReg = MI->getOperand(CurOp++).getReg();
12532 MemOpndSlot = CurOp;
12533 CurOp += X86::AddrNumOperands;
12534 SrcReg = MI->getOperand(CurOp++).getReg();
12536 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12537 MVT::SimpleValueType VT = *RC->vt_begin();
12538 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12540 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12541 unsigned LOADOpc = getLoadOpcode(VT);
12543 // For the atomic load-arith operator, we generate
12546 // EAX = LOAD [MI.addr]
12548 // t1 = OP MI.val, EAX
12549 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12553 MachineBasicBlock *thisMBB = MBB;
12554 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12555 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12556 MF->insert(I, mainMBB);
12557 MF->insert(I, sinkMBB);
12559 MachineInstrBuilder MIB;
12561 // Transfer the remainder of BB and its successor edges to sinkMBB.
12562 sinkMBB->splice(sinkMBB->begin(), MBB,
12563 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12564 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12567 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12568 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12569 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12570 MIB.setMemRefs(MMOBegin, MMOEnd);
12572 thisMBB->addSuccessor(mainMBB);
12575 MachineBasicBlock *origMainMBB = mainMBB;
12576 mainMBB->addLiveIn(AccPhyReg);
12578 // Copy AccPhyReg as it is used more than once.
12579 unsigned AccReg = MRI.createVirtualRegister(RC);
12580 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12581 .addReg(AccPhyReg);
12583 unsigned t1 = MRI.createVirtualRegister(RC);
12584 unsigned Opc = MI->getOpcode();
12587 llvm_unreachable("Unhandled atomic-load-op opcode!");
12588 case X86::ATOMAND8:
12589 case X86::ATOMAND16:
12590 case X86::ATOMAND32:
12591 case X86::ATOMAND64:
12593 case X86::ATOMOR16:
12594 case X86::ATOMOR32:
12595 case X86::ATOMOR64:
12596 case X86::ATOMXOR8:
12597 case X86::ATOMXOR16:
12598 case X86::ATOMXOR32:
12599 case X86::ATOMXOR64: {
12600 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12601 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12605 case X86::ATOMNAND8:
12606 case X86::ATOMNAND16:
12607 case X86::ATOMNAND32:
12608 case X86::ATOMNAND64: {
12609 unsigned t2 = MRI.createVirtualRegister(RC);
12611 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12612 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12614 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12617 case X86::ATOMMAX8:
12618 case X86::ATOMMAX16:
12619 case X86::ATOMMAX32:
12620 case X86::ATOMMAX64:
12621 case X86::ATOMMIN8:
12622 case X86::ATOMMIN16:
12623 case X86::ATOMMIN32:
12624 case X86::ATOMMIN64:
12625 case X86::ATOMUMAX8:
12626 case X86::ATOMUMAX16:
12627 case X86::ATOMUMAX32:
12628 case X86::ATOMUMAX64:
12629 case X86::ATOMUMIN8:
12630 case X86::ATOMUMIN16:
12631 case X86::ATOMUMIN32:
12632 case X86::ATOMUMIN64: {
12634 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12636 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12640 if (Subtarget->hasCMov()) {
12641 if (VT != MVT::i8) {
12643 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12647 // Promote i8 to i32 to use CMOV32
12648 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12649 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12650 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12651 unsigned t2 = MRI.createVirtualRegister(RC32);
12653 unsigned Undef = MRI.createVirtualRegister(RC32);
12654 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12656 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12659 .addImm(X86::sub_8bit);
12660 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12663 .addImm(X86::sub_8bit);
12665 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12669 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12670 .addReg(t2, 0, X86::sub_8bit);
12673 // Use pseudo select and lower them.
12674 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12675 "Invalid atomic-load-op transformation!");
12676 unsigned SelOpc = getPseudoCMOVOpc(VT);
12677 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12678 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12679 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12680 .addReg(SrcReg).addReg(AccReg)
12682 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12688 // Copy AccPhyReg back from virtual register.
12689 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12692 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12693 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12694 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12696 MIB.setMemRefs(MMOBegin, MMOEnd);
12698 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12700 mainMBB->addSuccessor(origMainMBB);
12701 mainMBB->addSuccessor(sinkMBB);
12704 sinkMBB->addLiveIn(AccPhyReg);
12706 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12707 TII->get(TargetOpcode::COPY), DstReg)
12708 .addReg(AccPhyReg);
12710 MI->eraseFromParent();
12714 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12715 // instructions. They will be translated into a spin-loop or compare-exchange
12719 // dst = atomic-fetch-op MI.addr, MI.val
12725 // EAX = LOAD [MI.addr + 0]
12726 // EDX = LOAD [MI.addr + 4]
12728 // EBX = OP MI.val.lo, EAX
12729 // ECX = OP MI.val.hi, EDX
12730 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12735 MachineBasicBlock *
12736 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12737 MachineBasicBlock *MBB) const {
12738 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12739 DebugLoc DL = MI->getDebugLoc();
12741 MachineFunction *MF = MBB->getParent();
12742 MachineRegisterInfo &MRI = MF->getRegInfo();
12744 const BasicBlock *BB = MBB->getBasicBlock();
12745 MachineFunction::iterator I = MBB;
12748 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12749 "Unexpected number of operands");
12751 assert(MI->hasOneMemOperand() &&
12752 "Expected atomic-load-op32 to have one memoperand");
12754 // Memory Reference
12755 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12756 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12758 unsigned DstLoReg, DstHiReg;
12759 unsigned SrcLoReg, SrcHiReg;
12760 unsigned MemOpndSlot;
12762 unsigned CurOp = 0;
12764 DstLoReg = MI->getOperand(CurOp++).getReg();
12765 DstHiReg = MI->getOperand(CurOp++).getReg();
12766 MemOpndSlot = CurOp;
12767 CurOp += X86::AddrNumOperands;
12768 SrcLoReg = MI->getOperand(CurOp++).getReg();
12769 SrcHiReg = MI->getOperand(CurOp++).getReg();
12771 const TargetRegisterClass *RC = &X86::GR32RegClass;
12772 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12774 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12775 unsigned LOADOpc = X86::MOV32rm;
12777 // For the atomic load-arith operator, we generate
12780 // EAX = LOAD [MI.addr + 0]
12781 // EDX = LOAD [MI.addr + 4]
12783 // EBX = OP MI.vallo, EAX
12784 // ECX = OP MI.valhi, EDX
12785 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12789 MachineBasicBlock *thisMBB = MBB;
12790 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12791 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12792 MF->insert(I, mainMBB);
12793 MF->insert(I, sinkMBB);
12795 MachineInstrBuilder MIB;
12797 // Transfer the remainder of BB and its successor edges to sinkMBB.
12798 sinkMBB->splice(sinkMBB->begin(), MBB,
12799 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12800 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12804 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12805 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12806 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12807 MIB.setMemRefs(MMOBegin, MMOEnd);
12809 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12810 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12811 if (i == X86::AddrDisp)
12812 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12814 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12816 MIB.setMemRefs(MMOBegin, MMOEnd);
12818 thisMBB->addSuccessor(mainMBB);
12821 MachineBasicBlock *origMainMBB = mainMBB;
12822 mainMBB->addLiveIn(X86::EAX);
12823 mainMBB->addLiveIn(X86::EDX);
12825 // Copy EDX:EAX as they are used more than once.
12826 unsigned LoReg = MRI.createVirtualRegister(RC);
12827 unsigned HiReg = MRI.createVirtualRegister(RC);
12828 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12829 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12831 unsigned t1L = MRI.createVirtualRegister(RC);
12832 unsigned t1H = MRI.createVirtualRegister(RC);
12834 unsigned Opc = MI->getOpcode();
12837 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12838 case X86::ATOMAND6432:
12839 case X86::ATOMOR6432:
12840 case X86::ATOMXOR6432:
12841 case X86::ATOMADD6432:
12842 case X86::ATOMSUB6432: {
12844 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12845 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12846 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12849 case X86::ATOMNAND6432: {
12850 unsigned HiOpc, NOTOpc;
12851 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12852 unsigned t2L = MRI.createVirtualRegister(RC);
12853 unsigned t2H = MRI.createVirtualRegister(RC);
12854 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12855 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12856 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12857 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12860 case X86::ATOMMAX6432:
12861 case X86::ATOMMIN6432:
12862 case X86::ATOMUMAX6432:
12863 case X86::ATOMUMIN6432: {
12865 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12866 unsigned cL = MRI.createVirtualRegister(RC8);
12867 unsigned cH = MRI.createVirtualRegister(RC8);
12868 unsigned cL32 = MRI.createVirtualRegister(RC);
12869 unsigned cH32 = MRI.createVirtualRegister(RC);
12870 unsigned cc = MRI.createVirtualRegister(RC);
12871 // cl := cmp src_lo, lo
12872 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12873 .addReg(SrcLoReg).addReg(LoReg);
12874 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12875 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12876 // ch := cmp src_hi, hi
12877 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12878 .addReg(SrcHiReg).addReg(HiReg);
12879 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12880 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12881 // cc := if (src_hi == hi) ? cl : ch;
12882 if (Subtarget->hasCMov()) {
12883 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12884 .addReg(cH32).addReg(cL32);
12886 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12887 .addReg(cH32).addReg(cL32)
12888 .addImm(X86::COND_E);
12889 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12891 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12892 if (Subtarget->hasCMov()) {
12893 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12894 .addReg(SrcLoReg).addReg(LoReg);
12895 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12896 .addReg(SrcHiReg).addReg(HiReg);
12898 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12899 .addReg(SrcLoReg).addReg(LoReg)
12900 .addImm(X86::COND_NE);
12901 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12902 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12903 .addReg(SrcHiReg).addReg(HiReg)
12904 .addImm(X86::COND_NE);
12905 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12909 case X86::ATOMSWAP6432: {
12911 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12912 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12913 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12918 // Copy EDX:EAX back from HiReg:LoReg
12919 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12920 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12921 // Copy ECX:EBX from t1H:t1L
12922 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12923 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12925 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12926 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12927 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12928 MIB.setMemRefs(MMOBegin, MMOEnd);
12930 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12932 mainMBB->addSuccessor(origMainMBB);
12933 mainMBB->addSuccessor(sinkMBB);
12936 sinkMBB->addLiveIn(X86::EAX);
12937 sinkMBB->addLiveIn(X86::EDX);
12939 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12940 TII->get(TargetOpcode::COPY), DstLoReg)
12942 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12943 TII->get(TargetOpcode::COPY), DstHiReg)
12946 MI->eraseFromParent();
12950 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12951 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12952 // in the .td file.
12953 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12954 const TargetInstrInfo *TII) {
12956 switch (MI->getOpcode()) {
12957 default: llvm_unreachable("illegal opcode!");
12958 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
12959 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12960 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
12961 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12962 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
12963 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12964 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
12965 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12968 DebugLoc dl = MI->getDebugLoc();
12969 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12971 unsigned NumArgs = MI->getNumOperands();
12972 for (unsigned i = 1; i < NumArgs; ++i) {
12973 MachineOperand &Op = MI->getOperand(i);
12974 if (!(Op.isReg() && Op.isImplicit()))
12975 MIB.addOperand(Op);
12977 if (MI->hasOneMemOperand())
12978 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12980 BuildMI(*BB, MI, dl,
12981 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12982 .addReg(X86::XMM0);
12984 MI->eraseFromParent();
12988 // FIXME: Custom handling because TableGen doesn't support multiple implicit
12989 // defs in an instruction pattern
12990 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12991 const TargetInstrInfo *TII) {
12993 switch (MI->getOpcode()) {
12994 default: llvm_unreachable("illegal opcode!");
12995 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
12996 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12997 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
12998 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12999 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13000 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13001 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13002 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13005 DebugLoc dl = MI->getDebugLoc();
13006 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13008 unsigned NumArgs = MI->getNumOperands(); // remove the results
13009 for (unsigned i = 1; i < NumArgs; ++i) {
13010 MachineOperand &Op = MI->getOperand(i);
13011 if (!(Op.isReg() && Op.isImplicit()))
13012 MIB.addOperand(Op);
13014 if (MI->hasOneMemOperand())
13015 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13017 BuildMI(*BB, MI, dl,
13018 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13021 MI->eraseFromParent();
13025 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13026 const TargetInstrInfo *TII,
13027 const X86Subtarget* Subtarget) {
13028 DebugLoc dl = MI->getDebugLoc();
13030 // Address into RAX/EAX, other two args into ECX, EDX.
13031 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13032 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13033 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13034 for (int i = 0; i < X86::AddrNumOperands; ++i)
13035 MIB.addOperand(MI->getOperand(i));
13037 unsigned ValOps = X86::AddrNumOperands;
13038 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13039 .addReg(MI->getOperand(ValOps).getReg());
13040 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13041 .addReg(MI->getOperand(ValOps+1).getReg());
13043 // The instruction doesn't actually take any operands though.
13044 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13046 MI->eraseFromParent(); // The pseudo is gone now.
13050 MachineBasicBlock *
13051 X86TargetLowering::EmitVAARG64WithCustomInserter(
13053 MachineBasicBlock *MBB) const {
13054 // Emit va_arg instruction on X86-64.
13056 // Operands to this pseudo-instruction:
13057 // 0 ) Output : destination address (reg)
13058 // 1-5) Input : va_list address (addr, i64mem)
13059 // 6 ) ArgSize : Size (in bytes) of vararg type
13060 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13061 // 8 ) Align : Alignment of type
13062 // 9 ) EFLAGS (implicit-def)
13064 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13065 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13067 unsigned DestReg = MI->getOperand(0).getReg();
13068 MachineOperand &Base = MI->getOperand(1);
13069 MachineOperand &Scale = MI->getOperand(2);
13070 MachineOperand &Index = MI->getOperand(3);
13071 MachineOperand &Disp = MI->getOperand(4);
13072 MachineOperand &Segment = MI->getOperand(5);
13073 unsigned ArgSize = MI->getOperand(6).getImm();
13074 unsigned ArgMode = MI->getOperand(7).getImm();
13075 unsigned Align = MI->getOperand(8).getImm();
13077 // Memory Reference
13078 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13079 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13080 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13082 // Machine Information
13083 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13084 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13085 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13086 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13087 DebugLoc DL = MI->getDebugLoc();
13089 // struct va_list {
13092 // i64 overflow_area (address)
13093 // i64 reg_save_area (address)
13095 // sizeof(va_list) = 24
13096 // alignment(va_list) = 8
13098 unsigned TotalNumIntRegs = 6;
13099 unsigned TotalNumXMMRegs = 8;
13100 bool UseGPOffset = (ArgMode == 1);
13101 bool UseFPOffset = (ArgMode == 2);
13102 unsigned MaxOffset = TotalNumIntRegs * 8 +
13103 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13105 /* Align ArgSize to a multiple of 8 */
13106 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13107 bool NeedsAlign = (Align > 8);
13109 MachineBasicBlock *thisMBB = MBB;
13110 MachineBasicBlock *overflowMBB;
13111 MachineBasicBlock *offsetMBB;
13112 MachineBasicBlock *endMBB;
13114 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13115 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13116 unsigned OffsetReg = 0;
13118 if (!UseGPOffset && !UseFPOffset) {
13119 // If we only pull from the overflow region, we don't create a branch.
13120 // We don't need to alter control flow.
13121 OffsetDestReg = 0; // unused
13122 OverflowDestReg = DestReg;
13125 overflowMBB = thisMBB;
13128 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13129 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13130 // If not, pull from overflow_area. (branch to overflowMBB)
13135 // offsetMBB overflowMBB
13140 // Registers for the PHI in endMBB
13141 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13142 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13144 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13145 MachineFunction *MF = MBB->getParent();
13146 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13147 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13148 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13150 MachineFunction::iterator MBBIter = MBB;
13153 // Insert the new basic blocks
13154 MF->insert(MBBIter, offsetMBB);
13155 MF->insert(MBBIter, overflowMBB);
13156 MF->insert(MBBIter, endMBB);
13158 // Transfer the remainder of MBB and its successor edges to endMBB.
13159 endMBB->splice(endMBB->begin(), thisMBB,
13160 llvm::next(MachineBasicBlock::iterator(MI)),
13162 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13164 // Make offsetMBB and overflowMBB successors of thisMBB
13165 thisMBB->addSuccessor(offsetMBB);
13166 thisMBB->addSuccessor(overflowMBB);
13168 // endMBB is a successor of both offsetMBB and overflowMBB
13169 offsetMBB->addSuccessor(endMBB);
13170 overflowMBB->addSuccessor(endMBB);
13172 // Load the offset value into a register
13173 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13174 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13178 .addDisp(Disp, UseFPOffset ? 4 : 0)
13179 .addOperand(Segment)
13180 .setMemRefs(MMOBegin, MMOEnd);
13182 // Check if there is enough room left to pull this argument.
13183 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13185 .addImm(MaxOffset + 8 - ArgSizeA8);
13187 // Branch to "overflowMBB" if offset >= max
13188 // Fall through to "offsetMBB" otherwise
13189 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13190 .addMBB(overflowMBB);
13193 // In offsetMBB, emit code to use the reg_save_area.
13195 assert(OffsetReg != 0);
13197 // Read the reg_save_area address.
13198 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13199 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13204 .addOperand(Segment)
13205 .setMemRefs(MMOBegin, MMOEnd);
13207 // Zero-extend the offset
13208 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13209 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13212 .addImm(X86::sub_32bit);
13214 // Add the offset to the reg_save_area to get the final address.
13215 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13216 .addReg(OffsetReg64)
13217 .addReg(RegSaveReg);
13219 // Compute the offset for the next argument
13220 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13221 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13223 .addImm(UseFPOffset ? 16 : 8);
13225 // Store it back into the va_list.
13226 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13230 .addDisp(Disp, UseFPOffset ? 4 : 0)
13231 .addOperand(Segment)
13232 .addReg(NextOffsetReg)
13233 .setMemRefs(MMOBegin, MMOEnd);
13236 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13241 // Emit code to use overflow area
13244 // Load the overflow_area address into a register.
13245 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13246 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13251 .addOperand(Segment)
13252 .setMemRefs(MMOBegin, MMOEnd);
13254 // If we need to align it, do so. Otherwise, just copy the address
13255 // to OverflowDestReg.
13257 // Align the overflow address
13258 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13259 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13261 // aligned_addr = (addr + (align-1)) & ~(align-1)
13262 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13263 .addReg(OverflowAddrReg)
13266 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13268 .addImm(~(uint64_t)(Align-1));
13270 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13271 .addReg(OverflowAddrReg);
13274 // Compute the next overflow address after this argument.
13275 // (the overflow address should be kept 8-byte aligned)
13276 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13277 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13278 .addReg(OverflowDestReg)
13279 .addImm(ArgSizeA8);
13281 // Store the new overflow address.
13282 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13287 .addOperand(Segment)
13288 .addReg(NextAddrReg)
13289 .setMemRefs(MMOBegin, MMOEnd);
13291 // If we branched, emit the PHI to the front of endMBB.
13293 BuildMI(*endMBB, endMBB->begin(), DL,
13294 TII->get(X86::PHI), DestReg)
13295 .addReg(OffsetDestReg).addMBB(offsetMBB)
13296 .addReg(OverflowDestReg).addMBB(overflowMBB);
13299 // Erase the pseudo instruction
13300 MI->eraseFromParent();
13305 MachineBasicBlock *
13306 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13308 MachineBasicBlock *MBB) const {
13309 // Emit code to save XMM registers to the stack. The ABI says that the
13310 // number of registers to save is given in %al, so it's theoretically
13311 // possible to do an indirect jump trick to avoid saving all of them,
13312 // however this code takes a simpler approach and just executes all
13313 // of the stores if %al is non-zero. It's less code, and it's probably
13314 // easier on the hardware branch predictor, and stores aren't all that
13315 // expensive anyway.
13317 // Create the new basic blocks. One block contains all the XMM stores,
13318 // and one block is the final destination regardless of whether any
13319 // stores were performed.
13320 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13321 MachineFunction *F = MBB->getParent();
13322 MachineFunction::iterator MBBIter = MBB;
13324 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13325 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13326 F->insert(MBBIter, XMMSaveMBB);
13327 F->insert(MBBIter, EndMBB);
13329 // Transfer the remainder of MBB and its successor edges to EndMBB.
13330 EndMBB->splice(EndMBB->begin(), MBB,
13331 llvm::next(MachineBasicBlock::iterator(MI)),
13333 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13335 // The original block will now fall through to the XMM save block.
13336 MBB->addSuccessor(XMMSaveMBB);
13337 // The XMMSaveMBB will fall through to the end block.
13338 XMMSaveMBB->addSuccessor(EndMBB);
13340 // Now add the instructions.
13341 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13342 DebugLoc DL = MI->getDebugLoc();
13344 unsigned CountReg = MI->getOperand(0).getReg();
13345 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13346 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13348 if (!Subtarget->isTargetWin64()) {
13349 // If %al is 0, branch around the XMM save block.
13350 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13351 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13352 MBB->addSuccessor(EndMBB);
13355 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13356 // In the XMM save block, save all the XMM argument registers.
13357 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13358 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13359 MachineMemOperand *MMO =
13360 F->getMachineMemOperand(
13361 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13362 MachineMemOperand::MOStore,
13363 /*Size=*/16, /*Align=*/16);
13364 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13365 .addFrameIndex(RegSaveFrameIndex)
13366 .addImm(/*Scale=*/1)
13367 .addReg(/*IndexReg=*/0)
13368 .addImm(/*Disp=*/Offset)
13369 .addReg(/*Segment=*/0)
13370 .addReg(MI->getOperand(i).getReg())
13371 .addMemOperand(MMO);
13374 MI->eraseFromParent(); // The pseudo instruction is gone now.
13379 // The EFLAGS operand of SelectItr might be missing a kill marker
13380 // because there were multiple uses of EFLAGS, and ISel didn't know
13381 // which to mark. Figure out whether SelectItr should have had a
13382 // kill marker, and set it if it should. Returns the correct kill
13384 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13385 MachineBasicBlock* BB,
13386 const TargetRegisterInfo* TRI) {
13387 // Scan forward through BB for a use/def of EFLAGS.
13388 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13389 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13390 const MachineInstr& mi = *miI;
13391 if (mi.readsRegister(X86::EFLAGS))
13393 if (mi.definesRegister(X86::EFLAGS))
13394 break; // Should have kill-flag - update below.
13397 // If we hit the end of the block, check whether EFLAGS is live into a
13399 if (miI == BB->end()) {
13400 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13401 sEnd = BB->succ_end();
13402 sItr != sEnd; ++sItr) {
13403 MachineBasicBlock* succ = *sItr;
13404 if (succ->isLiveIn(X86::EFLAGS))
13409 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13410 // out. SelectMI should have a kill flag on EFLAGS.
13411 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13415 MachineBasicBlock *
13416 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13417 MachineBasicBlock *BB) const {
13418 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13419 DebugLoc DL = MI->getDebugLoc();
13421 // To "insert" a SELECT_CC instruction, we actually have to insert the
13422 // diamond control-flow pattern. The incoming instruction knows the
13423 // destination vreg to set, the condition code register to branch on, the
13424 // true/false values to select between, and a branch opcode to use.
13425 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13426 MachineFunction::iterator It = BB;
13432 // cmpTY ccX, r1, r2
13434 // fallthrough --> copy0MBB
13435 MachineBasicBlock *thisMBB = BB;
13436 MachineFunction *F = BB->getParent();
13437 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13438 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13439 F->insert(It, copy0MBB);
13440 F->insert(It, sinkMBB);
13442 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13443 // live into the sink and copy blocks.
13444 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13445 if (!MI->killsRegister(X86::EFLAGS) &&
13446 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13447 copy0MBB->addLiveIn(X86::EFLAGS);
13448 sinkMBB->addLiveIn(X86::EFLAGS);
13451 // Transfer the remainder of BB and its successor edges to sinkMBB.
13452 sinkMBB->splice(sinkMBB->begin(), BB,
13453 llvm::next(MachineBasicBlock::iterator(MI)),
13455 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13457 // Add the true and fallthrough blocks as its successors.
13458 BB->addSuccessor(copy0MBB);
13459 BB->addSuccessor(sinkMBB);
13461 // Create the conditional branch instruction.
13463 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13464 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13467 // %FalseValue = ...
13468 // # fallthrough to sinkMBB
13469 copy0MBB->addSuccessor(sinkMBB);
13472 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13474 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13475 TII->get(X86::PHI), MI->getOperand(0).getReg())
13476 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13477 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13479 MI->eraseFromParent(); // The pseudo instruction is gone now.
13483 MachineBasicBlock *
13484 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13485 bool Is64Bit) const {
13486 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13487 DebugLoc DL = MI->getDebugLoc();
13488 MachineFunction *MF = BB->getParent();
13489 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13491 assert(getTargetMachine().Options.EnableSegmentedStacks);
13493 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13494 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13497 // ... [Till the alloca]
13498 // If stacklet is not large enough, jump to mallocMBB
13501 // Allocate by subtracting from RSP
13502 // Jump to continueMBB
13505 // Allocate by call to runtime
13509 // [rest of original BB]
13512 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13513 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13514 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13516 MachineRegisterInfo &MRI = MF->getRegInfo();
13517 const TargetRegisterClass *AddrRegClass =
13518 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13520 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13521 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13522 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13523 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13524 sizeVReg = MI->getOperand(1).getReg(),
13525 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13527 MachineFunction::iterator MBBIter = BB;
13530 MF->insert(MBBIter, bumpMBB);
13531 MF->insert(MBBIter, mallocMBB);
13532 MF->insert(MBBIter, continueMBB);
13534 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13535 (MachineBasicBlock::iterator(MI)), BB->end());
13536 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13538 // Add code to the main basic block to check if the stack limit has been hit,
13539 // and if so, jump to mallocMBB otherwise to bumpMBB.
13540 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13541 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13542 .addReg(tmpSPVReg).addReg(sizeVReg);
13543 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13544 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13545 .addReg(SPLimitVReg);
13546 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13548 // bumpMBB simply decreases the stack pointer, since we know the current
13549 // stacklet has enough space.
13550 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13551 .addReg(SPLimitVReg);
13552 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13553 .addReg(SPLimitVReg);
13554 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13556 // Calls into a routine in libgcc to allocate more space from the heap.
13557 const uint32_t *RegMask =
13558 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13560 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13562 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13563 .addExternalSymbol("__morestack_allocate_stack_space")
13564 .addRegMask(RegMask)
13565 .addReg(X86::RDI, RegState::Implicit)
13566 .addReg(X86::RAX, RegState::ImplicitDefine);
13568 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13570 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13571 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13572 .addExternalSymbol("__morestack_allocate_stack_space")
13573 .addRegMask(RegMask)
13574 .addReg(X86::EAX, RegState::ImplicitDefine);
13578 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13581 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13582 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13583 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13585 // Set up the CFG correctly.
13586 BB->addSuccessor(bumpMBB);
13587 BB->addSuccessor(mallocMBB);
13588 mallocMBB->addSuccessor(continueMBB);
13589 bumpMBB->addSuccessor(continueMBB);
13591 // Take care of the PHI nodes.
13592 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13593 MI->getOperand(0).getReg())
13594 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13595 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13597 // Delete the original pseudo instruction.
13598 MI->eraseFromParent();
13601 return continueMBB;
13604 MachineBasicBlock *
13605 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13606 MachineBasicBlock *BB) const {
13607 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13608 DebugLoc DL = MI->getDebugLoc();
13610 assert(!Subtarget->isTargetEnvMacho());
13612 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13613 // non-trivial part is impdef of ESP.
13615 if (Subtarget->isTargetWin64()) {
13616 if (Subtarget->isTargetCygMing()) {
13617 // ___chkstk(Mingw64):
13618 // Clobbers R10, R11, RAX and EFLAGS.
13620 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13621 .addExternalSymbol("___chkstk")
13622 .addReg(X86::RAX, RegState::Implicit)
13623 .addReg(X86::RSP, RegState::Implicit)
13624 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13625 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13626 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13628 // __chkstk(MSVCRT): does not update stack pointer.
13629 // Clobbers R10, R11 and EFLAGS.
13630 // FIXME: RAX(allocated size) might be reused and not killed.
13631 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13632 .addExternalSymbol("__chkstk")
13633 .addReg(X86::RAX, RegState::Implicit)
13634 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13635 // RAX has the offset to subtracted from RSP.
13636 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13641 const char *StackProbeSymbol =
13642 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13644 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13645 .addExternalSymbol(StackProbeSymbol)
13646 .addReg(X86::EAX, RegState::Implicit)
13647 .addReg(X86::ESP, RegState::Implicit)
13648 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13649 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13650 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13653 MI->eraseFromParent(); // The pseudo instruction is gone now.
13657 MachineBasicBlock *
13658 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13659 MachineBasicBlock *BB) const {
13660 // This is pretty easy. We're taking the value that we received from
13661 // our load from the relocation, sticking it in either RDI (x86-64)
13662 // or EAX and doing an indirect call. The return value will then
13663 // be in the normal return register.
13664 const X86InstrInfo *TII
13665 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13666 DebugLoc DL = MI->getDebugLoc();
13667 MachineFunction *F = BB->getParent();
13669 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13670 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13672 // Get a register mask for the lowered call.
13673 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13674 // proper register mask.
13675 const uint32_t *RegMask =
13676 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13677 if (Subtarget->is64Bit()) {
13678 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13679 TII->get(X86::MOV64rm), X86::RDI)
13681 .addImm(0).addReg(0)
13682 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13683 MI->getOperand(3).getTargetFlags())
13685 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13686 addDirectMem(MIB, X86::RDI);
13687 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13688 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13689 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13690 TII->get(X86::MOV32rm), X86::EAX)
13692 .addImm(0).addReg(0)
13693 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13694 MI->getOperand(3).getTargetFlags())
13696 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13697 addDirectMem(MIB, X86::EAX);
13698 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13700 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13701 TII->get(X86::MOV32rm), X86::EAX)
13702 .addReg(TII->getGlobalBaseReg(F))
13703 .addImm(0).addReg(0)
13704 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13705 MI->getOperand(3).getTargetFlags())
13707 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13708 addDirectMem(MIB, X86::EAX);
13709 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13712 MI->eraseFromParent(); // The pseudo instruction is gone now.
13716 MachineBasicBlock *
13717 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13718 MachineBasicBlock *MBB) const {
13719 DebugLoc DL = MI->getDebugLoc();
13720 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13722 MachineFunction *MF = MBB->getParent();
13723 MachineRegisterInfo &MRI = MF->getRegInfo();
13725 const BasicBlock *BB = MBB->getBasicBlock();
13726 MachineFunction::iterator I = MBB;
13729 // Memory Reference
13730 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13731 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13734 unsigned MemOpndSlot = 0;
13736 unsigned CurOp = 0;
13738 DstReg = MI->getOperand(CurOp++).getReg();
13739 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13740 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13741 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13742 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13744 MemOpndSlot = CurOp;
13746 MVT PVT = getPointerTy();
13747 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13748 "Invalid Pointer Size!");
13750 // For v = setjmp(buf), we generate
13753 // buf[LabelOffset] = restoreMBB
13754 // SjLjSetup restoreMBB
13760 // v = phi(main, restore)
13765 MachineBasicBlock *thisMBB = MBB;
13766 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13767 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13768 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13769 MF->insert(I, mainMBB);
13770 MF->insert(I, sinkMBB);
13771 MF->push_back(restoreMBB);
13773 MachineInstrBuilder MIB;
13775 // Transfer the remainder of BB and its successor edges to sinkMBB.
13776 sinkMBB->splice(sinkMBB->begin(), MBB,
13777 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13778 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13781 unsigned PtrStoreOpc = 0;
13782 unsigned LabelReg = 0;
13783 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13784 Reloc::Model RM = getTargetMachine().getRelocationModel();
13785 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13786 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13788 // Prepare IP either in reg or imm.
13789 if (!UseImmLabel) {
13790 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13791 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13792 LabelReg = MRI.createVirtualRegister(PtrRC);
13793 if (Subtarget->is64Bit()) {
13794 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13798 .addMBB(restoreMBB)
13801 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13802 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13803 .addReg(XII->getGlobalBaseReg(MF))
13806 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13810 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13812 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13813 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13814 if (i == X86::AddrDisp)
13815 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13817 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13820 MIB.addReg(LabelReg);
13822 MIB.addMBB(restoreMBB);
13823 MIB.setMemRefs(MMOBegin, MMOEnd);
13825 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13826 .addMBB(restoreMBB);
13827 MIB.addRegMask(RegInfo->getNoPreservedMask());
13828 thisMBB->addSuccessor(mainMBB);
13829 thisMBB->addSuccessor(restoreMBB);
13833 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13834 mainMBB->addSuccessor(sinkMBB);
13837 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13838 TII->get(X86::PHI), DstReg)
13839 .addReg(mainDstReg).addMBB(mainMBB)
13840 .addReg(restoreDstReg).addMBB(restoreMBB);
13843 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13844 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13845 restoreMBB->addSuccessor(sinkMBB);
13847 MI->eraseFromParent();
13851 MachineBasicBlock *
13852 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13853 MachineBasicBlock *MBB) const {
13854 DebugLoc DL = MI->getDebugLoc();
13855 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13857 MachineFunction *MF = MBB->getParent();
13858 MachineRegisterInfo &MRI = MF->getRegInfo();
13860 // Memory Reference
13861 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13862 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13864 MVT PVT = getPointerTy();
13865 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13866 "Invalid Pointer Size!");
13868 const TargetRegisterClass *RC =
13869 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13870 unsigned Tmp = MRI.createVirtualRegister(RC);
13871 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13872 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13873 unsigned SP = RegInfo->getStackRegister();
13875 MachineInstrBuilder MIB;
13877 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13878 const int64_t SPOffset = 2 * PVT.getStoreSize();
13880 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13881 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13884 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13885 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13886 MIB.addOperand(MI->getOperand(i));
13887 MIB.setMemRefs(MMOBegin, MMOEnd);
13889 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13890 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13891 if (i == X86::AddrDisp)
13892 MIB.addDisp(MI->getOperand(i), LabelOffset);
13894 MIB.addOperand(MI->getOperand(i));
13896 MIB.setMemRefs(MMOBegin, MMOEnd);
13898 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13899 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13900 if (i == X86::AddrDisp)
13901 MIB.addDisp(MI->getOperand(i), SPOffset);
13903 MIB.addOperand(MI->getOperand(i));
13905 MIB.setMemRefs(MMOBegin, MMOEnd);
13907 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13909 MI->eraseFromParent();
13913 MachineBasicBlock *
13914 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13915 MachineBasicBlock *BB) const {
13916 switch (MI->getOpcode()) {
13917 default: llvm_unreachable("Unexpected instr type to insert");
13918 case X86::TAILJMPd64:
13919 case X86::TAILJMPr64:
13920 case X86::TAILJMPm64:
13921 llvm_unreachable("TAILJMP64 would not be touched here.");
13922 case X86::TCRETURNdi64:
13923 case X86::TCRETURNri64:
13924 case X86::TCRETURNmi64:
13926 case X86::WIN_ALLOCA:
13927 return EmitLoweredWinAlloca(MI, BB);
13928 case X86::SEG_ALLOCA_32:
13929 return EmitLoweredSegAlloca(MI, BB, false);
13930 case X86::SEG_ALLOCA_64:
13931 return EmitLoweredSegAlloca(MI, BB, true);
13932 case X86::TLSCall_32:
13933 case X86::TLSCall_64:
13934 return EmitLoweredTLSCall(MI, BB);
13935 case X86::CMOV_GR8:
13936 case X86::CMOV_FR32:
13937 case X86::CMOV_FR64:
13938 case X86::CMOV_V4F32:
13939 case X86::CMOV_V2F64:
13940 case X86::CMOV_V2I64:
13941 case X86::CMOV_V8F32:
13942 case X86::CMOV_V4F64:
13943 case X86::CMOV_V4I64:
13944 case X86::CMOV_GR16:
13945 case X86::CMOV_GR32:
13946 case X86::CMOV_RFP32:
13947 case X86::CMOV_RFP64:
13948 case X86::CMOV_RFP80:
13949 return EmitLoweredSelect(MI, BB);
13951 case X86::FP32_TO_INT16_IN_MEM:
13952 case X86::FP32_TO_INT32_IN_MEM:
13953 case X86::FP32_TO_INT64_IN_MEM:
13954 case X86::FP64_TO_INT16_IN_MEM:
13955 case X86::FP64_TO_INT32_IN_MEM:
13956 case X86::FP64_TO_INT64_IN_MEM:
13957 case X86::FP80_TO_INT16_IN_MEM:
13958 case X86::FP80_TO_INT32_IN_MEM:
13959 case X86::FP80_TO_INT64_IN_MEM: {
13960 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13961 DebugLoc DL = MI->getDebugLoc();
13963 // Change the floating point control register to use "round towards zero"
13964 // mode when truncating to an integer value.
13965 MachineFunction *F = BB->getParent();
13966 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13967 addFrameReference(BuildMI(*BB, MI, DL,
13968 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13970 // Load the old value of the high byte of the control word...
13972 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13973 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13976 // Set the high part to be round to zero...
13977 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13980 // Reload the modified control word now...
13981 addFrameReference(BuildMI(*BB, MI, DL,
13982 TII->get(X86::FLDCW16m)), CWFrameIdx);
13984 // Restore the memory image of control word to original value
13985 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13988 // Get the X86 opcode to use.
13990 switch (MI->getOpcode()) {
13991 default: llvm_unreachable("illegal opcode!");
13992 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13993 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13994 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13995 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13996 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13997 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13998 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13999 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14000 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14004 MachineOperand &Op = MI->getOperand(0);
14006 AM.BaseType = X86AddressMode::RegBase;
14007 AM.Base.Reg = Op.getReg();
14009 AM.BaseType = X86AddressMode::FrameIndexBase;
14010 AM.Base.FrameIndex = Op.getIndex();
14012 Op = MI->getOperand(1);
14014 AM.Scale = Op.getImm();
14015 Op = MI->getOperand(2);
14017 AM.IndexReg = Op.getImm();
14018 Op = MI->getOperand(3);
14019 if (Op.isGlobal()) {
14020 AM.GV = Op.getGlobal();
14022 AM.Disp = Op.getImm();
14024 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14025 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14027 // Reload the original control word now.
14028 addFrameReference(BuildMI(*BB, MI, DL,
14029 TII->get(X86::FLDCW16m)), CWFrameIdx);
14031 MI->eraseFromParent(); // The pseudo instruction is gone now.
14034 // String/text processing lowering.
14035 case X86::PCMPISTRM128REG:
14036 case X86::VPCMPISTRM128REG:
14037 case X86::PCMPISTRM128MEM:
14038 case X86::VPCMPISTRM128MEM:
14039 case X86::PCMPESTRM128REG:
14040 case X86::VPCMPESTRM128REG:
14041 case X86::PCMPESTRM128MEM:
14042 case X86::VPCMPESTRM128MEM:
14043 assert(Subtarget->hasSSE42() &&
14044 "Target must have SSE4.2 or AVX features enabled");
14045 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14047 // String/text processing lowering.
14048 case X86::PCMPISTRIREG:
14049 case X86::VPCMPISTRIREG:
14050 case X86::PCMPISTRIMEM:
14051 case X86::VPCMPISTRIMEM:
14052 case X86::PCMPESTRIREG:
14053 case X86::VPCMPESTRIREG:
14054 case X86::PCMPESTRIMEM:
14055 case X86::VPCMPESTRIMEM:
14056 assert(Subtarget->hasSSE42() &&
14057 "Target must have SSE4.2 or AVX features enabled");
14058 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14060 // Thread synchronization.
14062 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14066 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14068 // Atomic Lowering.
14069 case X86::ATOMAND8:
14070 case X86::ATOMAND16:
14071 case X86::ATOMAND32:
14072 case X86::ATOMAND64:
14075 case X86::ATOMOR16:
14076 case X86::ATOMOR32:
14077 case X86::ATOMOR64:
14079 case X86::ATOMXOR16:
14080 case X86::ATOMXOR8:
14081 case X86::ATOMXOR32:
14082 case X86::ATOMXOR64:
14084 case X86::ATOMNAND8:
14085 case X86::ATOMNAND16:
14086 case X86::ATOMNAND32:
14087 case X86::ATOMNAND64:
14089 case X86::ATOMMAX8:
14090 case X86::ATOMMAX16:
14091 case X86::ATOMMAX32:
14092 case X86::ATOMMAX64:
14094 case X86::ATOMMIN8:
14095 case X86::ATOMMIN16:
14096 case X86::ATOMMIN32:
14097 case X86::ATOMMIN64:
14099 case X86::ATOMUMAX8:
14100 case X86::ATOMUMAX16:
14101 case X86::ATOMUMAX32:
14102 case X86::ATOMUMAX64:
14104 case X86::ATOMUMIN8:
14105 case X86::ATOMUMIN16:
14106 case X86::ATOMUMIN32:
14107 case X86::ATOMUMIN64:
14108 return EmitAtomicLoadArith(MI, BB);
14110 // This group does 64-bit operations on a 32-bit host.
14111 case X86::ATOMAND6432:
14112 case X86::ATOMOR6432:
14113 case X86::ATOMXOR6432:
14114 case X86::ATOMNAND6432:
14115 case X86::ATOMADD6432:
14116 case X86::ATOMSUB6432:
14117 case X86::ATOMMAX6432:
14118 case X86::ATOMMIN6432:
14119 case X86::ATOMUMAX6432:
14120 case X86::ATOMUMIN6432:
14121 case X86::ATOMSWAP6432:
14122 return EmitAtomicLoadArith6432(MI, BB);
14124 case X86::VASTART_SAVE_XMM_REGS:
14125 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14127 case X86::VAARG_64:
14128 return EmitVAARG64WithCustomInserter(MI, BB);
14130 case X86::EH_SjLj_SetJmp32:
14131 case X86::EH_SjLj_SetJmp64:
14132 return emitEHSjLjSetJmp(MI, BB);
14134 case X86::EH_SjLj_LongJmp32:
14135 case X86::EH_SjLj_LongJmp64:
14136 return emitEHSjLjLongJmp(MI, BB);
14140 //===----------------------------------------------------------------------===//
14141 // X86 Optimization Hooks
14142 //===----------------------------------------------------------------------===//
14144 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14147 const SelectionDAG &DAG,
14148 unsigned Depth) const {
14149 unsigned BitWidth = KnownZero.getBitWidth();
14150 unsigned Opc = Op.getOpcode();
14151 assert((Opc >= ISD::BUILTIN_OP_END ||
14152 Opc == ISD::INTRINSIC_WO_CHAIN ||
14153 Opc == ISD::INTRINSIC_W_CHAIN ||
14154 Opc == ISD::INTRINSIC_VOID) &&
14155 "Should use MaskedValueIsZero if you don't know whether Op"
14156 " is a target node!");
14158 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14172 // These nodes' second result is a boolean.
14173 if (Op.getResNo() == 0)
14176 case X86ISD::SETCC:
14177 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14179 case ISD::INTRINSIC_WO_CHAIN: {
14180 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14181 unsigned NumLoBits = 0;
14184 case Intrinsic::x86_sse_movmsk_ps:
14185 case Intrinsic::x86_avx_movmsk_ps_256:
14186 case Intrinsic::x86_sse2_movmsk_pd:
14187 case Intrinsic::x86_avx_movmsk_pd_256:
14188 case Intrinsic::x86_mmx_pmovmskb:
14189 case Intrinsic::x86_sse2_pmovmskb_128:
14190 case Intrinsic::x86_avx2_pmovmskb: {
14191 // High bits of movmskp{s|d}, pmovmskb are known zero.
14193 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14194 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14195 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14196 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14197 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14198 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14199 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14200 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14202 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14211 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14212 unsigned Depth) const {
14213 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14214 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14215 return Op.getValueType().getScalarType().getSizeInBits();
14221 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14222 /// node is a GlobalAddress + offset.
14223 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14224 const GlobalValue* &GA,
14225 int64_t &Offset) const {
14226 if (N->getOpcode() == X86ISD::Wrapper) {
14227 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14228 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14229 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14233 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14236 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14237 /// same as extracting the high 128-bit part of 256-bit vector and then
14238 /// inserting the result into the low part of a new 256-bit vector
14239 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14240 EVT VT = SVOp->getValueType(0);
14241 unsigned NumElems = VT.getVectorNumElements();
14243 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14244 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14245 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14246 SVOp->getMaskElt(j) >= 0)
14252 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14253 /// same as extracting the low 128-bit part of 256-bit vector and then
14254 /// inserting the result into the high part of a new 256-bit vector
14255 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14256 EVT VT = SVOp->getValueType(0);
14257 unsigned NumElems = VT.getVectorNumElements();
14259 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14260 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14261 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14262 SVOp->getMaskElt(j) >= 0)
14268 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14269 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14270 TargetLowering::DAGCombinerInfo &DCI,
14271 const X86Subtarget* Subtarget) {
14272 DebugLoc dl = N->getDebugLoc();
14273 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14274 SDValue V1 = SVOp->getOperand(0);
14275 SDValue V2 = SVOp->getOperand(1);
14276 EVT VT = SVOp->getValueType(0);
14277 unsigned NumElems = VT.getVectorNumElements();
14279 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14280 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14284 // V UNDEF BUILD_VECTOR UNDEF
14286 // CONCAT_VECTOR CONCAT_VECTOR
14289 // RESULT: V + zero extended
14291 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14292 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14293 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14296 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14299 // To match the shuffle mask, the first half of the mask should
14300 // be exactly the first vector, and all the rest a splat with the
14301 // first element of the second one.
14302 for (unsigned i = 0; i != NumElems/2; ++i)
14303 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14304 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14307 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14308 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14309 if (Ld->hasNUsesOfValue(1, 0)) {
14310 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14311 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14313 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14315 Ld->getPointerInfo(),
14316 Ld->getAlignment(),
14317 false/*isVolatile*/, true/*ReadMem*/,
14318 false/*WriteMem*/);
14320 // Make sure the newly-created LOAD is in the same position as Ld in
14321 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14322 // and update uses of Ld's output chain to use the TokenFactor.
14323 if (Ld->hasAnyUseOfValue(1)) {
14324 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14325 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14326 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14327 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14328 SDValue(ResNode.getNode(), 1));
14331 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14335 // Emit a zeroed vector and insert the desired subvector on its
14337 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14338 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14339 return DCI.CombineTo(N, InsV);
14342 //===--------------------------------------------------------------------===//
14343 // Combine some shuffles into subvector extracts and inserts:
14346 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14347 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14348 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14349 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14350 return DCI.CombineTo(N, InsV);
14353 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14354 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14355 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14356 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14357 return DCI.CombineTo(N, InsV);
14363 /// PerformShuffleCombine - Performs several different shuffle combines.
14364 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14365 TargetLowering::DAGCombinerInfo &DCI,
14366 const X86Subtarget *Subtarget) {
14367 DebugLoc dl = N->getDebugLoc();
14368 EVT VT = N->getValueType(0);
14370 // Don't create instructions with illegal types after legalize types has run.
14371 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14372 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14375 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14376 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14377 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14378 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14380 // Only handle 128 wide vector from here on.
14381 if (!VT.is128BitVector())
14384 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14385 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14386 // consecutive, non-overlapping, and in the right order.
14387 SmallVector<SDValue, 16> Elts;
14388 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14389 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14391 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14394 /// PerformTruncateCombine - Converts truncate operation to
14395 /// a sequence of vector shuffle operations.
14396 /// It is possible when we truncate 256-bit vector to 128-bit vector
14397 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14398 TargetLowering::DAGCombinerInfo &DCI,
14399 const X86Subtarget *Subtarget) {
14400 if (!DCI.isBeforeLegalizeOps())
14403 if (!Subtarget->hasFp256())
14406 EVT VT = N->getValueType(0);
14407 SDValue Op = N->getOperand(0);
14408 EVT OpVT = Op.getValueType();
14409 DebugLoc dl = N->getDebugLoc();
14411 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14413 if (Subtarget->hasInt256()) {
14414 // AVX2: v4i64 -> v4i32
14417 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14419 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14420 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14423 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14424 DAG.getIntPtrConstant(0));
14427 // AVX: v4i64 -> v4i32
14428 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14429 DAG.getIntPtrConstant(0));
14431 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14432 DAG.getIntPtrConstant(2));
14434 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14435 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14438 static const int ShufMask1[] = {0, 2, 0, 0};
14440 SDValue Undef = DAG.getUNDEF(VT);
14441 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14442 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14445 static const int ShufMask2[] = {0, 1, 4, 5};
14447 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14450 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14452 if (Subtarget->hasInt256()) {
14453 // AVX2: v8i32 -> v8i16
14455 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14458 SmallVector<SDValue,32> pshufbMask;
14459 for (unsigned i = 0; i < 2; ++i) {
14460 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14461 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14462 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14463 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14464 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14465 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14466 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14467 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14468 for (unsigned j = 0; j < 8; ++j)
14469 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14471 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14472 &pshufbMask[0], 32);
14473 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14475 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14477 static const int ShufMask[] = {0, 2, -1, -1};
14478 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14481 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14482 DAG.getIntPtrConstant(0));
14484 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14487 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14488 DAG.getIntPtrConstant(0));
14490 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14491 DAG.getIntPtrConstant(4));
14493 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14494 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14497 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14498 -1, -1, -1, -1, -1, -1, -1, -1};
14500 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14501 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14502 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14504 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14505 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14508 static const int ShufMask2[] = {0, 1, 4, 5};
14510 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14511 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14517 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14518 /// specific shuffle of a load can be folded into a single element load.
14519 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14520 /// shuffles have been customed lowered so we need to handle those here.
14521 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14522 TargetLowering::DAGCombinerInfo &DCI) {
14523 if (DCI.isBeforeLegalizeOps())
14526 SDValue InVec = N->getOperand(0);
14527 SDValue EltNo = N->getOperand(1);
14529 if (!isa<ConstantSDNode>(EltNo))
14532 EVT VT = InVec.getValueType();
14534 bool HasShuffleIntoBitcast = false;
14535 if (InVec.getOpcode() == ISD::BITCAST) {
14536 // Don't duplicate a load with other uses.
14537 if (!InVec.hasOneUse())
14539 EVT BCVT = InVec.getOperand(0).getValueType();
14540 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14542 InVec = InVec.getOperand(0);
14543 HasShuffleIntoBitcast = true;
14546 if (!isTargetShuffle(InVec.getOpcode()))
14549 // Don't duplicate a load with other uses.
14550 if (!InVec.hasOneUse())
14553 SmallVector<int, 16> ShuffleMask;
14555 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14559 // Select the input vector, guarding against out of range extract vector.
14560 unsigned NumElems = VT.getVectorNumElements();
14561 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14562 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14563 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14564 : InVec.getOperand(1);
14566 // If inputs to shuffle are the same for both ops, then allow 2 uses
14567 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14569 if (LdNode.getOpcode() == ISD::BITCAST) {
14570 // Don't duplicate a load with other uses.
14571 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14574 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14575 LdNode = LdNode.getOperand(0);
14578 if (!ISD::isNormalLoad(LdNode.getNode()))
14581 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14583 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14586 if (HasShuffleIntoBitcast) {
14587 // If there's a bitcast before the shuffle, check if the load type and
14588 // alignment is valid.
14589 unsigned Align = LN0->getAlignment();
14590 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14591 unsigned NewAlign = TLI.getDataLayout()->
14592 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14594 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14598 // All checks match so transform back to vector_shuffle so that DAG combiner
14599 // can finish the job
14600 DebugLoc dl = N->getDebugLoc();
14602 // Create shuffle node taking into account the case that its a unary shuffle
14603 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14604 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14605 InVec.getOperand(0), Shuffle,
14607 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14608 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14612 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14613 /// generation and convert it from being a bunch of shuffles and extracts
14614 /// to a simple store and scalar loads to extract the elements.
14615 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14616 TargetLowering::DAGCombinerInfo &DCI) {
14617 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14618 if (NewOp.getNode())
14621 SDValue InputVector = N->getOperand(0);
14622 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14623 // from mmx to v2i32 has a single usage.
14624 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14625 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14626 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14627 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14628 N->getValueType(0),
14629 InputVector.getNode()->getOperand(0));
14631 // Only operate on vectors of 4 elements, where the alternative shuffling
14632 // gets to be more expensive.
14633 if (InputVector.getValueType() != MVT::v4i32)
14636 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14637 // single use which is a sign-extend or zero-extend, and all elements are
14639 SmallVector<SDNode *, 4> Uses;
14640 unsigned ExtractedElements = 0;
14641 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14642 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14643 if (UI.getUse().getResNo() != InputVector.getResNo())
14646 SDNode *Extract = *UI;
14647 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14650 if (Extract->getValueType(0) != MVT::i32)
14652 if (!Extract->hasOneUse())
14654 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14655 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14657 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14660 // Record which element was extracted.
14661 ExtractedElements |=
14662 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14664 Uses.push_back(Extract);
14667 // If not all the elements were used, this may not be worthwhile.
14668 if (ExtractedElements != 15)
14671 // Ok, we've now decided to do the transformation.
14672 DebugLoc dl = InputVector.getDebugLoc();
14674 // Store the value to a temporary stack slot.
14675 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14676 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14677 MachinePointerInfo(), false, false, 0);
14679 // Replace each use (extract) with a load of the appropriate element.
14680 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14681 UE = Uses.end(); UI != UE; ++UI) {
14682 SDNode *Extract = *UI;
14684 // cOMpute the element's address.
14685 SDValue Idx = Extract->getOperand(1);
14687 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14688 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14689 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14690 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14692 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14693 StackPtr, OffsetVal);
14695 // Load the scalar.
14696 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14697 ScalarAddr, MachinePointerInfo(),
14698 false, false, false, 0);
14700 // Replace the exact with the load.
14701 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14704 // The replacement was made in place; don't return anything.
14708 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14709 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14710 SDValue RHS, SelectionDAG &DAG,
14711 const X86Subtarget *Subtarget) {
14712 if (!VT.isVector())
14715 switch (VT.getSimpleVT().SimpleTy) {
14720 if (!Subtarget->hasAVX2())
14725 if (!Subtarget->hasSSE2())
14729 // SSE2 has only a small subset of the operations.
14730 bool hasUnsigned = Subtarget->hasSSE41() ||
14731 (Subtarget->hasSSE2() && VT == MVT::v16i8);
14732 bool hasSigned = Subtarget->hasSSE41() ||
14733 (Subtarget->hasSSE2() && VT == MVT::v8i16);
14735 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14737 // Check for x CC y ? x : y.
14738 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14739 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14744 return hasUnsigned ? X86ISD::UMIN : 0;
14747 return hasUnsigned ? X86ISD::UMAX : 0;
14750 return hasSigned ? X86ISD::SMIN : 0;
14753 return hasSigned ? X86ISD::SMAX : 0;
14755 // Check for x CC y ? y : x -- a min/max with reversed arms.
14756 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14757 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14762 return hasUnsigned ? X86ISD::UMAX : 0;
14765 return hasUnsigned ? X86ISD::UMIN : 0;
14768 return hasSigned ? X86ISD::SMAX : 0;
14771 return hasSigned ? X86ISD::SMIN : 0;
14778 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14780 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14781 TargetLowering::DAGCombinerInfo &DCI,
14782 const X86Subtarget *Subtarget) {
14783 DebugLoc DL = N->getDebugLoc();
14784 SDValue Cond = N->getOperand(0);
14785 // Get the LHS/RHS of the select.
14786 SDValue LHS = N->getOperand(1);
14787 SDValue RHS = N->getOperand(2);
14788 EVT VT = LHS.getValueType();
14790 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14791 // instructions match the semantics of the common C idiom x<y?x:y but not
14792 // x<=y?x:y, because of how they handle negative zero (which can be
14793 // ignored in unsafe-math mode).
14794 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14795 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14796 (Subtarget->hasSSE2() ||
14797 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14798 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14800 unsigned Opcode = 0;
14801 // Check for x CC y ? x : y.
14802 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14803 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14807 // Converting this to a min would handle NaNs incorrectly, and swapping
14808 // the operands would cause it to handle comparisons between positive
14809 // and negative zero incorrectly.
14810 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14811 if (!DAG.getTarget().Options.UnsafeFPMath &&
14812 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14814 std::swap(LHS, RHS);
14816 Opcode = X86ISD::FMIN;
14819 // Converting this to a min would handle comparisons between positive
14820 // and negative zero incorrectly.
14821 if (!DAG.getTarget().Options.UnsafeFPMath &&
14822 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14824 Opcode = X86ISD::FMIN;
14827 // Converting this to a min would handle both negative zeros and NaNs
14828 // incorrectly, but we can swap the operands to fix both.
14829 std::swap(LHS, RHS);
14833 Opcode = X86ISD::FMIN;
14837 // Converting this to a max would handle comparisons between positive
14838 // and negative zero incorrectly.
14839 if (!DAG.getTarget().Options.UnsafeFPMath &&
14840 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14842 Opcode = X86ISD::FMAX;
14845 // Converting this to a max would handle NaNs incorrectly, and swapping
14846 // the operands would cause it to handle comparisons between positive
14847 // and negative zero incorrectly.
14848 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14849 if (!DAG.getTarget().Options.UnsafeFPMath &&
14850 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14852 std::swap(LHS, RHS);
14854 Opcode = X86ISD::FMAX;
14857 // Converting this to a max would handle both negative zeros and NaNs
14858 // incorrectly, but we can swap the operands to fix both.
14859 std::swap(LHS, RHS);
14863 Opcode = X86ISD::FMAX;
14866 // Check for x CC y ? y : x -- a min/max with reversed arms.
14867 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14868 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14872 // Converting this to a min would handle comparisons between positive
14873 // and negative zero incorrectly, and swapping the operands would
14874 // cause it to handle NaNs incorrectly.
14875 if (!DAG.getTarget().Options.UnsafeFPMath &&
14876 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14877 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14879 std::swap(LHS, RHS);
14881 Opcode = X86ISD::FMIN;
14884 // Converting this to a min would handle NaNs incorrectly.
14885 if (!DAG.getTarget().Options.UnsafeFPMath &&
14886 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14888 Opcode = X86ISD::FMIN;
14891 // Converting this to a min would handle both negative zeros and NaNs
14892 // incorrectly, but we can swap the operands to fix both.
14893 std::swap(LHS, RHS);
14897 Opcode = X86ISD::FMIN;
14901 // Converting this to a max would handle NaNs incorrectly.
14902 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14904 Opcode = X86ISD::FMAX;
14907 // Converting this to a max would handle comparisons between positive
14908 // and negative zero incorrectly, and swapping the operands would
14909 // cause it to handle NaNs incorrectly.
14910 if (!DAG.getTarget().Options.UnsafeFPMath &&
14911 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14912 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14914 std::swap(LHS, RHS);
14916 Opcode = X86ISD::FMAX;
14919 // Converting this to a max would handle both negative zeros and NaNs
14920 // incorrectly, but we can swap the operands to fix both.
14921 std::swap(LHS, RHS);
14925 Opcode = X86ISD::FMAX;
14931 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14934 // If this is a select between two integer constants, try to do some
14936 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14937 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14938 // Don't do this for crazy integer types.
14939 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14940 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14941 // so that TrueC (the true value) is larger than FalseC.
14942 bool NeedsCondInvert = false;
14944 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14945 // Efficiently invertible.
14946 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14947 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14948 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14949 NeedsCondInvert = true;
14950 std::swap(TrueC, FalseC);
14953 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14954 if (FalseC->getAPIntValue() == 0 &&
14955 TrueC->getAPIntValue().isPowerOf2()) {
14956 if (NeedsCondInvert) // Invert the condition if needed.
14957 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14958 DAG.getConstant(1, Cond.getValueType()));
14960 // Zero extend the condition if needed.
14961 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14963 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14964 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14965 DAG.getConstant(ShAmt, MVT::i8));
14968 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14969 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14970 if (NeedsCondInvert) // Invert the condition if needed.
14971 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14972 DAG.getConstant(1, Cond.getValueType()));
14974 // Zero extend the condition if needed.
14975 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14976 FalseC->getValueType(0), Cond);
14977 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14978 SDValue(FalseC, 0));
14981 // Optimize cases that will turn into an LEA instruction. This requires
14982 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14983 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14984 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14985 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14987 bool isFastMultiplier = false;
14989 switch ((unsigned char)Diff) {
14991 case 1: // result = add base, cond
14992 case 2: // result = lea base( , cond*2)
14993 case 3: // result = lea base(cond, cond*2)
14994 case 4: // result = lea base( , cond*4)
14995 case 5: // result = lea base(cond, cond*4)
14996 case 8: // result = lea base( , cond*8)
14997 case 9: // result = lea base(cond, cond*8)
14998 isFastMultiplier = true;
15003 if (isFastMultiplier) {
15004 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15005 if (NeedsCondInvert) // Invert the condition if needed.
15006 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15007 DAG.getConstant(1, Cond.getValueType()));
15009 // Zero extend the condition if needed.
15010 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15012 // Scale the condition by the difference.
15014 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15015 DAG.getConstant(Diff, Cond.getValueType()));
15017 // Add the base if non-zero.
15018 if (FalseC->getAPIntValue() != 0)
15019 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15020 SDValue(FalseC, 0));
15027 // Canonicalize max and min:
15028 // (x > y) ? x : y -> (x >= y) ? x : y
15029 // (x < y) ? x : y -> (x <= y) ? x : y
15030 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15031 // the need for an extra compare
15032 // against zero. e.g.
15033 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15035 // testl %edi, %edi
15037 // cmovgl %edi, %eax
15041 // cmovsl %eax, %edi
15042 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15043 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15044 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15045 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15050 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15051 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15052 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15053 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15058 // Match VSELECTs into subs with unsigned saturation.
15059 if (!DCI.isBeforeLegalize() &&
15060 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15061 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15062 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15063 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15064 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15066 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15067 // left side invert the predicate to simplify logic below.
15069 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15071 CC = ISD::getSetCCInverse(CC, true);
15072 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15076 if (Other.getNode() && Other->getNumOperands() == 2 &&
15077 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15078 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15079 SDValue CondRHS = Cond->getOperand(1);
15081 // Look for a general sub with unsigned saturation first.
15082 // x >= y ? x-y : 0 --> subus x, y
15083 // x > y ? x-y : 0 --> subus x, y
15084 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15085 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15086 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15088 // If the RHS is a constant we have to reverse the const canonicalization.
15089 // x > C-1 ? x+-C : 0 --> subus x, C
15090 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15091 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15092 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15093 if (CondRHS.getConstantOperandVal(0) == -A-1) {
15094 SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15095 DAG.getConstant(-A, VT.getScalarType()));
15096 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15097 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15098 V.data(), V.size()));
15102 // Another special case: If C was a sign bit, the sub has been
15103 // canonicalized into a xor.
15104 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15105 // it's safe to decanonicalize the xor?
15106 // x s< 0 ? x^C : 0 --> subus x, C
15107 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15108 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15109 isSplatVector(OpRHS.getNode())) {
15110 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15112 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15117 // Try to match a min/max vector operation.
15118 if (!DCI.isBeforeLegalize() &&
15119 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15120 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15121 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15123 // If we know that this node is legal then we know that it is going to be
15124 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15125 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15126 // to simplify previous instructions.
15127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15128 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15129 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15130 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15132 // Don't optimize vector selects that map to mask-registers.
15136 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15137 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15139 APInt KnownZero, KnownOne;
15140 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15141 DCI.isBeforeLegalizeOps());
15142 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15143 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15144 DCI.CommitTargetLoweringOpt(TLO);
15150 // Check whether a boolean test is testing a boolean value generated by
15151 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15154 // Simplify the following patterns:
15155 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15156 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15157 // to (Op EFLAGS Cond)
15159 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15160 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15161 // to (Op EFLAGS !Cond)
15163 // where Op could be BRCOND or CMOV.
15165 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15166 // Quit if not CMP and SUB with its value result used.
15167 if (Cmp.getOpcode() != X86ISD::CMP &&
15168 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15171 // Quit if not used as a boolean value.
15172 if (CC != X86::COND_E && CC != X86::COND_NE)
15175 // Check CMP operands. One of them should be 0 or 1 and the other should be
15176 // an SetCC or extended from it.
15177 SDValue Op1 = Cmp.getOperand(0);
15178 SDValue Op2 = Cmp.getOperand(1);
15181 const ConstantSDNode* C = 0;
15182 bool needOppositeCond = (CC == X86::COND_E);
15184 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15186 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15188 else // Quit if all operands are not constants.
15191 if (C->getZExtValue() == 1)
15192 needOppositeCond = !needOppositeCond;
15193 else if (C->getZExtValue() != 0)
15194 // Quit if the constant is neither 0 or 1.
15197 // Skip 'zext' node.
15198 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15199 SetCC = SetCC.getOperand(0);
15201 switch (SetCC.getOpcode()) {
15202 case X86ISD::SETCC:
15203 // Set the condition code or opposite one if necessary.
15204 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15205 if (needOppositeCond)
15206 CC = X86::GetOppositeBranchCondition(CC);
15207 return SetCC.getOperand(1);
15208 case X86ISD::CMOV: {
15209 // Check whether false/true value has canonical one, i.e. 0 or 1.
15210 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15211 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15212 // Quit if true value is not a constant.
15215 // Quit if false value is not a constant.
15217 // A special case for rdrand, where 0 is set if false cond is found.
15218 SDValue Op = SetCC.getOperand(0);
15219 if (Op.getOpcode() != X86ISD::RDRAND)
15222 // Quit if false value is not the constant 0 or 1.
15223 bool FValIsFalse = true;
15224 if (FVal && FVal->getZExtValue() != 0) {
15225 if (FVal->getZExtValue() != 1)
15227 // If FVal is 1, opposite cond is needed.
15228 needOppositeCond = !needOppositeCond;
15229 FValIsFalse = false;
15231 // Quit if TVal is not the constant opposite of FVal.
15232 if (FValIsFalse && TVal->getZExtValue() != 1)
15234 if (!FValIsFalse && TVal->getZExtValue() != 0)
15236 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15237 if (needOppositeCond)
15238 CC = X86::GetOppositeBranchCondition(CC);
15239 return SetCC.getOperand(3);
15246 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15247 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15248 TargetLowering::DAGCombinerInfo &DCI,
15249 const X86Subtarget *Subtarget) {
15250 DebugLoc DL = N->getDebugLoc();
15252 // If the flag operand isn't dead, don't touch this CMOV.
15253 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15256 SDValue FalseOp = N->getOperand(0);
15257 SDValue TrueOp = N->getOperand(1);
15258 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15259 SDValue Cond = N->getOperand(3);
15261 if (CC == X86::COND_E || CC == X86::COND_NE) {
15262 switch (Cond.getOpcode()) {
15266 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15267 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15268 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15274 Flags = checkBoolTestSetCCCombine(Cond, CC);
15275 if (Flags.getNode() &&
15276 // Extra check as FCMOV only supports a subset of X86 cond.
15277 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15278 SDValue Ops[] = { FalseOp, TrueOp,
15279 DAG.getConstant(CC, MVT::i8), Flags };
15280 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15281 Ops, array_lengthof(Ops));
15284 // If this is a select between two integer constants, try to do some
15285 // optimizations. Note that the operands are ordered the opposite of SELECT
15287 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15288 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15289 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15290 // larger than FalseC (the false value).
15291 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15292 CC = X86::GetOppositeBranchCondition(CC);
15293 std::swap(TrueC, FalseC);
15294 std::swap(TrueOp, FalseOp);
15297 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15298 // This is efficient for any integer data type (including i8/i16) and
15300 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15301 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15302 DAG.getConstant(CC, MVT::i8), Cond);
15304 // Zero extend the condition if needed.
15305 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15307 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15308 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15309 DAG.getConstant(ShAmt, MVT::i8));
15310 if (N->getNumValues() == 2) // Dead flag value?
15311 return DCI.CombineTo(N, Cond, SDValue());
15315 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15316 // for any integer data type, including i8/i16.
15317 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15318 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15319 DAG.getConstant(CC, MVT::i8), Cond);
15321 // Zero extend the condition if needed.
15322 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15323 FalseC->getValueType(0), Cond);
15324 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15325 SDValue(FalseC, 0));
15327 if (N->getNumValues() == 2) // Dead flag value?
15328 return DCI.CombineTo(N, Cond, SDValue());
15332 // Optimize cases that will turn into an LEA instruction. This requires
15333 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15334 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15335 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15336 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15338 bool isFastMultiplier = false;
15340 switch ((unsigned char)Diff) {
15342 case 1: // result = add base, cond
15343 case 2: // result = lea base( , cond*2)
15344 case 3: // result = lea base(cond, cond*2)
15345 case 4: // result = lea base( , cond*4)
15346 case 5: // result = lea base(cond, cond*4)
15347 case 8: // result = lea base( , cond*8)
15348 case 9: // result = lea base(cond, cond*8)
15349 isFastMultiplier = true;
15354 if (isFastMultiplier) {
15355 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15356 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15357 DAG.getConstant(CC, MVT::i8), Cond);
15358 // Zero extend the condition if needed.
15359 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15361 // Scale the condition by the difference.
15363 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15364 DAG.getConstant(Diff, Cond.getValueType()));
15366 // Add the base if non-zero.
15367 if (FalseC->getAPIntValue() != 0)
15368 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15369 SDValue(FalseC, 0));
15370 if (N->getNumValues() == 2) // Dead flag value?
15371 return DCI.CombineTo(N, Cond, SDValue());
15378 // Handle these cases:
15379 // (select (x != c), e, c) -> select (x != c), e, x),
15380 // (select (x == c), c, e) -> select (x == c), x, e)
15381 // where the c is an integer constant, and the "select" is the combination
15382 // of CMOV and CMP.
15384 // The rationale for this change is that the conditional-move from a constant
15385 // needs two instructions, however, conditional-move from a register needs
15386 // only one instruction.
15388 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15389 // some instruction-combining opportunities. This opt needs to be
15390 // postponed as late as possible.
15392 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15393 // the DCI.xxxx conditions are provided to postpone the optimization as
15394 // late as possible.
15396 ConstantSDNode *CmpAgainst = 0;
15397 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15398 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15399 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15401 if (CC == X86::COND_NE &&
15402 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15403 CC = X86::GetOppositeBranchCondition(CC);
15404 std::swap(TrueOp, FalseOp);
15407 if (CC == X86::COND_E &&
15408 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15409 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15410 DAG.getConstant(CC, MVT::i8), Cond };
15411 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15412 array_lengthof(Ops));
15420 /// PerformMulCombine - Optimize a single multiply with constant into two
15421 /// in order to implement it with two cheaper instructions, e.g.
15422 /// LEA + SHL, LEA + LEA.
15423 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15424 TargetLowering::DAGCombinerInfo &DCI) {
15425 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15428 EVT VT = N->getValueType(0);
15429 if (VT != MVT::i64)
15432 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15435 uint64_t MulAmt = C->getZExtValue();
15436 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15439 uint64_t MulAmt1 = 0;
15440 uint64_t MulAmt2 = 0;
15441 if ((MulAmt % 9) == 0) {
15443 MulAmt2 = MulAmt / 9;
15444 } else if ((MulAmt % 5) == 0) {
15446 MulAmt2 = MulAmt / 5;
15447 } else if ((MulAmt % 3) == 0) {
15449 MulAmt2 = MulAmt / 3;
15452 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15453 DebugLoc DL = N->getDebugLoc();
15455 if (isPowerOf2_64(MulAmt2) &&
15456 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15457 // If second multiplifer is pow2, issue it first. We want the multiply by
15458 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15460 std::swap(MulAmt1, MulAmt2);
15463 if (isPowerOf2_64(MulAmt1))
15464 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15465 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15467 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15468 DAG.getConstant(MulAmt1, VT));
15470 if (isPowerOf2_64(MulAmt2))
15471 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15472 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15474 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15475 DAG.getConstant(MulAmt2, VT));
15477 // Do not add new nodes to DAG combiner worklist.
15478 DCI.CombineTo(N, NewMul, false);
15483 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15484 SDValue N0 = N->getOperand(0);
15485 SDValue N1 = N->getOperand(1);
15486 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15487 EVT VT = N0.getValueType();
15489 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15490 // since the result of setcc_c is all zero's or all ones.
15491 if (VT.isInteger() && !VT.isVector() &&
15492 N1C && N0.getOpcode() == ISD::AND &&
15493 N0.getOperand(1).getOpcode() == ISD::Constant) {
15494 SDValue N00 = N0.getOperand(0);
15495 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15496 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15497 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15498 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15499 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15500 APInt ShAmt = N1C->getAPIntValue();
15501 Mask = Mask.shl(ShAmt);
15503 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15504 N00, DAG.getConstant(Mask, VT));
15508 // Hardware support for vector shifts is sparse which makes us scalarize the
15509 // vector operations in many cases. Also, on sandybridge ADD is faster than
15511 // (shl V, 1) -> add V,V
15512 if (isSplatVector(N1.getNode())) {
15513 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15514 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15515 // We shift all of the values by one. In many cases we do not have
15516 // hardware support for this operation. This is better expressed as an ADD
15518 if (N1C && (1 == N1C->getZExtValue())) {
15519 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15526 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15528 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15529 TargetLowering::DAGCombinerInfo &DCI,
15530 const X86Subtarget *Subtarget) {
15531 EVT VT = N->getValueType(0);
15532 if (N->getOpcode() == ISD::SHL) {
15533 SDValue V = PerformSHLCombine(N, DAG);
15534 if (V.getNode()) return V;
15537 // On X86 with SSE2 support, we can transform this to a vector shift if
15538 // all elements are shifted by the same amount. We can't do this in legalize
15539 // because the a constant vector is typically transformed to a constant pool
15540 // so we have no knowledge of the shift amount.
15541 if (!Subtarget->hasSSE2())
15544 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15545 (!Subtarget->hasInt256() ||
15546 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15549 SDValue ShAmtOp = N->getOperand(1);
15550 EVT EltVT = VT.getVectorElementType();
15551 DebugLoc DL = N->getDebugLoc();
15552 SDValue BaseShAmt = SDValue();
15553 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15554 unsigned NumElts = VT.getVectorNumElements();
15556 for (; i != NumElts; ++i) {
15557 SDValue Arg = ShAmtOp.getOperand(i);
15558 if (Arg.getOpcode() == ISD::UNDEF) continue;
15562 // Handle the case where the build_vector is all undef
15563 // FIXME: Should DAG allow this?
15567 for (; i != NumElts; ++i) {
15568 SDValue Arg = ShAmtOp.getOperand(i);
15569 if (Arg.getOpcode() == ISD::UNDEF) continue;
15570 if (Arg != BaseShAmt) {
15574 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15575 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15576 SDValue InVec = ShAmtOp.getOperand(0);
15577 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15578 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15580 for (; i != NumElts; ++i) {
15581 SDValue Arg = InVec.getOperand(i);
15582 if (Arg.getOpcode() == ISD::UNDEF) continue;
15586 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15587 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15588 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15589 if (C->getZExtValue() == SplatIdx)
15590 BaseShAmt = InVec.getOperand(1);
15593 if (BaseShAmt.getNode() == 0) {
15594 // Don't create instructions with illegal types after legalize
15596 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15597 !DCI.isBeforeLegalize())
15600 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15601 DAG.getIntPtrConstant(0));
15606 // The shift amount is an i32.
15607 if (EltVT.bitsGT(MVT::i32))
15608 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15609 else if (EltVT.bitsLT(MVT::i32))
15610 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15612 // The shift amount is identical so we can do a vector shift.
15613 SDValue ValOp = N->getOperand(0);
15614 switch (N->getOpcode()) {
15616 llvm_unreachable("Unknown shift opcode!");
15618 switch (VT.getSimpleVT().SimpleTy) {
15619 default: return SDValue();
15626 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15629 switch (VT.getSimpleVT().SimpleTy) {
15630 default: return SDValue();
15635 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15638 switch (VT.getSimpleVT().SimpleTy) {
15639 default: return SDValue();
15646 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15651 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15652 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15653 // and friends. Likewise for OR -> CMPNEQSS.
15654 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15655 TargetLowering::DAGCombinerInfo &DCI,
15656 const X86Subtarget *Subtarget) {
15659 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15660 // we're requiring SSE2 for both.
15661 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15662 SDValue N0 = N->getOperand(0);
15663 SDValue N1 = N->getOperand(1);
15664 SDValue CMP0 = N0->getOperand(1);
15665 SDValue CMP1 = N1->getOperand(1);
15666 DebugLoc DL = N->getDebugLoc();
15668 // The SETCCs should both refer to the same CMP.
15669 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15672 SDValue CMP00 = CMP0->getOperand(0);
15673 SDValue CMP01 = CMP0->getOperand(1);
15674 EVT VT = CMP00.getValueType();
15676 if (VT == MVT::f32 || VT == MVT::f64) {
15677 bool ExpectingFlags = false;
15678 // Check for any users that want flags:
15679 for (SDNode::use_iterator UI = N->use_begin(),
15681 !ExpectingFlags && UI != UE; ++UI)
15682 switch (UI->getOpcode()) {
15687 ExpectingFlags = true;
15689 case ISD::CopyToReg:
15690 case ISD::SIGN_EXTEND:
15691 case ISD::ZERO_EXTEND:
15692 case ISD::ANY_EXTEND:
15696 if (!ExpectingFlags) {
15697 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15698 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15700 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15701 X86::CondCode tmp = cc0;
15706 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15707 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15708 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15709 X86ISD::NodeType NTOperator = is64BitFP ?
15710 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15711 // FIXME: need symbolic constants for these magic numbers.
15712 // See X86ATTInstPrinter.cpp:printSSECC().
15713 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15714 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15715 DAG.getConstant(x86cc, MVT::i8));
15716 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15718 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15719 DAG.getConstant(1, MVT::i32));
15720 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15721 return OneBitOfTruth;
15729 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15730 /// so it can be folded inside ANDNP.
15731 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15732 EVT VT = N->getValueType(0);
15734 // Match direct AllOnes for 128 and 256-bit vectors
15735 if (ISD::isBuildVectorAllOnes(N))
15738 // Look through a bit convert.
15739 if (N->getOpcode() == ISD::BITCAST)
15740 N = N->getOperand(0).getNode();
15742 // Sometimes the operand may come from a insert_subvector building a 256-bit
15744 if (VT.is256BitVector() &&
15745 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15746 SDValue V1 = N->getOperand(0);
15747 SDValue V2 = N->getOperand(1);
15749 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15750 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15751 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15752 ISD::isBuildVectorAllOnes(V2.getNode()))
15759 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15760 TargetLowering::DAGCombinerInfo &DCI,
15761 const X86Subtarget *Subtarget) {
15762 if (DCI.isBeforeLegalizeOps())
15765 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15769 EVT VT = N->getValueType(0);
15771 // Create BLSI, and BLSR instructions
15772 // BLSI is X & (-X)
15773 // BLSR is X & (X-1)
15774 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15775 SDValue N0 = N->getOperand(0);
15776 SDValue N1 = N->getOperand(1);
15777 DebugLoc DL = N->getDebugLoc();
15779 // Check LHS for neg
15780 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15781 isZero(N0.getOperand(0)))
15782 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15784 // Check RHS for neg
15785 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15786 isZero(N1.getOperand(0)))
15787 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15789 // Check LHS for X-1
15790 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15791 isAllOnes(N0.getOperand(1)))
15792 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15794 // Check RHS for X-1
15795 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15796 isAllOnes(N1.getOperand(1)))
15797 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15802 // Want to form ANDNP nodes:
15803 // 1) In the hopes of then easily combining them with OR and AND nodes
15804 // to form PBLEND/PSIGN.
15805 // 2) To match ANDN packed intrinsics
15806 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15809 SDValue N0 = N->getOperand(0);
15810 SDValue N1 = N->getOperand(1);
15811 DebugLoc DL = N->getDebugLoc();
15813 // Check LHS for vnot
15814 if (N0.getOpcode() == ISD::XOR &&
15815 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15816 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15817 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15819 // Check RHS for vnot
15820 if (N1.getOpcode() == ISD::XOR &&
15821 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15822 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15823 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15828 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15829 TargetLowering::DAGCombinerInfo &DCI,
15830 const X86Subtarget *Subtarget) {
15831 if (DCI.isBeforeLegalizeOps())
15834 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15838 EVT VT = N->getValueType(0);
15840 SDValue N0 = N->getOperand(0);
15841 SDValue N1 = N->getOperand(1);
15843 // look for psign/blend
15844 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15845 if (!Subtarget->hasSSSE3() ||
15846 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
15849 // Canonicalize pandn to RHS
15850 if (N0.getOpcode() == X86ISD::ANDNP)
15852 // or (and (m, y), (pandn m, x))
15853 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15854 SDValue Mask = N1.getOperand(0);
15855 SDValue X = N1.getOperand(1);
15857 if (N0.getOperand(0) == Mask)
15858 Y = N0.getOperand(1);
15859 if (N0.getOperand(1) == Mask)
15860 Y = N0.getOperand(0);
15862 // Check to see if the mask appeared in both the AND and ANDNP and
15866 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15867 // Look through mask bitcast.
15868 if (Mask.getOpcode() == ISD::BITCAST)
15869 Mask = Mask.getOperand(0);
15870 if (X.getOpcode() == ISD::BITCAST)
15871 X = X.getOperand(0);
15872 if (Y.getOpcode() == ISD::BITCAST)
15873 Y = Y.getOperand(0);
15875 EVT MaskVT = Mask.getValueType();
15877 // Validate that the Mask operand is a vector sra node.
15878 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15879 // there is no psrai.b
15880 if (Mask.getOpcode() != X86ISD::VSRAI)
15883 // Check that the SRA is all signbits.
15884 SDValue SraC = Mask.getOperand(1);
15885 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15886 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15887 if ((SraAmt + 1) != EltBits)
15890 DebugLoc DL = N->getDebugLoc();
15892 // We are going to replace the AND, OR, NAND with either BLEND
15893 // or PSIGN, which only look at the MSB. The VSRAI instruction
15894 // does not affect the highest bit, so we can get rid of it.
15895 Mask = Mask.getOperand(0);
15897 // Now we know we at least have a plendvb with the mask val. See if
15898 // we can form a psignb/w/d.
15899 // psign = x.type == y.type == mask.type && y = sub(0, x);
15900 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15901 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15902 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15903 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15904 "Unsupported VT for PSIGN");
15905 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
15906 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15908 // PBLENDVB only available on SSE 4.1
15909 if (!Subtarget->hasSSE41())
15912 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15914 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15915 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15916 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15917 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15918 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15922 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15925 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15926 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15928 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15930 if (!N0.hasOneUse() || !N1.hasOneUse())
15933 SDValue ShAmt0 = N0.getOperand(1);
15934 if (ShAmt0.getValueType() != MVT::i8)
15936 SDValue ShAmt1 = N1.getOperand(1);
15937 if (ShAmt1.getValueType() != MVT::i8)
15939 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15940 ShAmt0 = ShAmt0.getOperand(0);
15941 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15942 ShAmt1 = ShAmt1.getOperand(0);
15944 DebugLoc DL = N->getDebugLoc();
15945 unsigned Opc = X86ISD::SHLD;
15946 SDValue Op0 = N0.getOperand(0);
15947 SDValue Op1 = N1.getOperand(0);
15948 if (ShAmt0.getOpcode() == ISD::SUB) {
15949 Opc = X86ISD::SHRD;
15950 std::swap(Op0, Op1);
15951 std::swap(ShAmt0, ShAmt1);
15954 unsigned Bits = VT.getSizeInBits();
15955 if (ShAmt1.getOpcode() == ISD::SUB) {
15956 SDValue Sum = ShAmt1.getOperand(0);
15957 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15958 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15959 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15960 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15961 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15962 return DAG.getNode(Opc, DL, VT,
15964 DAG.getNode(ISD::TRUNCATE, DL,
15967 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15968 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15970 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15971 return DAG.getNode(Opc, DL, VT,
15972 N0.getOperand(0), N1.getOperand(0),
15973 DAG.getNode(ISD::TRUNCATE, DL,
15980 // Generate NEG and CMOV for integer abs.
15981 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15982 EVT VT = N->getValueType(0);
15984 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15985 // 8-bit integer abs to NEG and CMOV.
15986 if (VT.isInteger() && VT.getSizeInBits() == 8)
15989 SDValue N0 = N->getOperand(0);
15990 SDValue N1 = N->getOperand(1);
15991 DebugLoc DL = N->getDebugLoc();
15993 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15994 // and change it to SUB and CMOV.
15995 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15996 N0.getOpcode() == ISD::ADD &&
15997 N0.getOperand(1) == N1 &&
15998 N1.getOpcode() == ISD::SRA &&
15999 N1.getOperand(0) == N0.getOperand(0))
16000 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16001 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16002 // Generate SUB & CMOV.
16003 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16004 DAG.getConstant(0, VT), N0.getOperand(0));
16006 SDValue Ops[] = { N0.getOperand(0), Neg,
16007 DAG.getConstant(X86::COND_GE, MVT::i8),
16008 SDValue(Neg.getNode(), 1) };
16009 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16010 Ops, array_lengthof(Ops));
16015 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16016 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16017 TargetLowering::DAGCombinerInfo &DCI,
16018 const X86Subtarget *Subtarget) {
16019 if (DCI.isBeforeLegalizeOps())
16022 if (Subtarget->hasCMov()) {
16023 SDValue RV = performIntegerAbsCombine(N, DAG);
16028 // Try forming BMI if it is available.
16029 if (!Subtarget->hasBMI())
16032 EVT VT = N->getValueType(0);
16034 if (VT != MVT::i32 && VT != MVT::i64)
16037 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16039 // Create BLSMSK instructions by finding X ^ (X-1)
16040 SDValue N0 = N->getOperand(0);
16041 SDValue N1 = N->getOperand(1);
16042 DebugLoc DL = N->getDebugLoc();
16044 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16045 isAllOnes(N0.getOperand(1)))
16046 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16048 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16049 isAllOnes(N1.getOperand(1)))
16050 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16055 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16056 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16057 TargetLowering::DAGCombinerInfo &DCI,
16058 const X86Subtarget *Subtarget) {
16059 LoadSDNode *Ld = cast<LoadSDNode>(N);
16060 EVT RegVT = Ld->getValueType(0);
16061 EVT MemVT = Ld->getMemoryVT();
16062 DebugLoc dl = Ld->getDebugLoc();
16063 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16065 ISD::LoadExtType Ext = Ld->getExtensionType();
16067 // If this is a vector EXT Load then attempt to optimize it using a
16068 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16069 // expansion is still better than scalar code.
16070 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16071 // emit a shuffle and a arithmetic shift.
16072 // TODO: It is possible to support ZExt by zeroing the undef values
16073 // during the shuffle phase or after the shuffle.
16074 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16075 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16076 assert(MemVT != RegVT && "Cannot extend to the same type");
16077 assert(MemVT.isVector() && "Must load a vector from memory");
16079 unsigned NumElems = RegVT.getVectorNumElements();
16080 unsigned RegSz = RegVT.getSizeInBits();
16081 unsigned MemSz = MemVT.getSizeInBits();
16082 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16084 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16087 // All sizes must be a power of two.
16088 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16091 // Attempt to load the original value using scalar loads.
16092 // Find the largest scalar type that divides the total loaded size.
16093 MVT SclrLoadTy = MVT::i8;
16094 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16095 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16096 MVT Tp = (MVT::SimpleValueType)tp;
16097 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16102 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16103 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16105 SclrLoadTy = MVT::f64;
16107 // Calculate the number of scalar loads that we need to perform
16108 // in order to load our vector from memory.
16109 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16110 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16113 unsigned loadRegZize = RegSz;
16114 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16117 // Represent our vector as a sequence of elements which are the
16118 // largest scalar that we can load.
16119 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16120 loadRegZize/SclrLoadTy.getSizeInBits());
16122 // Represent the data using the same element type that is stored in
16123 // memory. In practice, we ''widen'' MemVT.
16125 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16126 loadRegZize/MemVT.getScalarType().getSizeInBits());
16128 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16129 "Invalid vector type");
16131 // We can't shuffle using an illegal type.
16132 if (!TLI.isTypeLegal(WideVecVT))
16135 SmallVector<SDValue, 8> Chains;
16136 SDValue Ptr = Ld->getBasePtr();
16137 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16138 TLI.getPointerTy());
16139 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16141 for (unsigned i = 0; i < NumLoads; ++i) {
16142 // Perform a single load.
16143 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16144 Ptr, Ld->getPointerInfo(),
16145 Ld->isVolatile(), Ld->isNonTemporal(),
16146 Ld->isInvariant(), Ld->getAlignment());
16147 Chains.push_back(ScalarLoad.getValue(1));
16148 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16149 // another round of DAGCombining.
16151 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16153 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16154 ScalarLoad, DAG.getIntPtrConstant(i));
16156 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16159 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16162 // Bitcast the loaded value to a vector of the original element type, in
16163 // the size of the target vector type.
16164 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16165 unsigned SizeRatio = RegSz/MemSz;
16167 if (Ext == ISD::SEXTLOAD) {
16168 // If we have SSE4.1 we can directly emit a VSEXT node.
16169 if (Subtarget->hasSSE41()) {
16170 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16171 return DCI.CombineTo(N, Sext, TF, true);
16174 // Otherwise we'll shuffle the small elements in the high bits of the
16175 // larger type and perform an arithmetic shift. If the shift is not legal
16176 // it's better to scalarize.
16177 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16180 // Redistribute the loaded elements into the different locations.
16181 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16182 for (unsigned i = 0; i != NumElems; ++i)
16183 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16185 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16186 DAG.getUNDEF(WideVecVT),
16189 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16191 // Build the arithmetic shift.
16192 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16193 MemVT.getVectorElementType().getSizeInBits();
16194 SmallVector<SDValue, 8> C(NumElems,
16195 DAG.getConstant(Amt, RegVT.getScalarType()));
16196 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16197 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16199 return DCI.CombineTo(N, Shuff, TF, true);
16202 // Redistribute the loaded elements into the different locations.
16203 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16204 for (unsigned i = 0; i != NumElems; ++i)
16205 ShuffleVec[i*SizeRatio] = i;
16207 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16208 DAG.getUNDEF(WideVecVT),
16211 // Bitcast to the requested type.
16212 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16213 // Replace the original load with the new sequence
16214 // and return the new chain.
16215 return DCI.CombineTo(N, Shuff, TF, true);
16221 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16222 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16223 const X86Subtarget *Subtarget) {
16224 StoreSDNode *St = cast<StoreSDNode>(N);
16225 EVT VT = St->getValue().getValueType();
16226 EVT StVT = St->getMemoryVT();
16227 DebugLoc dl = St->getDebugLoc();
16228 SDValue StoredVal = St->getOperand(1);
16229 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16231 // If we are saving a concatenation of two XMM registers, perform two stores.
16232 // On Sandy Bridge, 256-bit memory operations are executed by two
16233 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16234 // memory operation.
16235 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16236 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
16237 StoredVal.getNumOperands() == 2) {
16238 SDValue Value0 = StoredVal.getOperand(0);
16239 SDValue Value1 = StoredVal.getOperand(1);
16241 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16242 SDValue Ptr0 = St->getBasePtr();
16243 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16245 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16246 St->getPointerInfo(), St->isVolatile(),
16247 St->isNonTemporal(), St->getAlignment());
16248 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16249 St->getPointerInfo(), St->isVolatile(),
16250 St->isNonTemporal(), St->getAlignment());
16251 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16254 // Optimize trunc store (of multiple scalars) to shuffle and store.
16255 // First, pack all of the elements in one place. Next, store to memory
16256 // in fewer chunks.
16257 if (St->isTruncatingStore() && VT.isVector()) {
16258 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16259 unsigned NumElems = VT.getVectorNumElements();
16260 assert(StVT != VT && "Cannot truncate to the same type");
16261 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16262 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16264 // From, To sizes and ElemCount must be pow of two
16265 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16266 // We are going to use the original vector elt for storing.
16267 // Accumulated smaller vector elements must be a multiple of the store size.
16268 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16270 unsigned SizeRatio = FromSz / ToSz;
16272 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16274 // Create a type on which we perform the shuffle
16275 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16276 StVT.getScalarType(), NumElems*SizeRatio);
16278 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16280 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16281 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16282 for (unsigned i = 0; i != NumElems; ++i)
16283 ShuffleVec[i] = i * SizeRatio;
16285 // Can't shuffle using an illegal type.
16286 if (!TLI.isTypeLegal(WideVecVT))
16289 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16290 DAG.getUNDEF(WideVecVT),
16292 // At this point all of the data is stored at the bottom of the
16293 // register. We now need to save it to mem.
16295 // Find the largest store unit
16296 MVT StoreType = MVT::i8;
16297 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16298 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16299 MVT Tp = (MVT::SimpleValueType)tp;
16300 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16304 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16305 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16306 (64 <= NumElems * ToSz))
16307 StoreType = MVT::f64;
16309 // Bitcast the original vector into a vector of store-size units
16310 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16311 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16312 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16313 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16314 SmallVector<SDValue, 8> Chains;
16315 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16316 TLI.getPointerTy());
16317 SDValue Ptr = St->getBasePtr();
16319 // Perform one or more big stores into memory.
16320 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16321 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16322 StoreType, ShuffWide,
16323 DAG.getIntPtrConstant(i));
16324 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16325 St->getPointerInfo(), St->isVolatile(),
16326 St->isNonTemporal(), St->getAlignment());
16327 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16328 Chains.push_back(Ch);
16331 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16335 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16336 // the FP state in cases where an emms may be missing.
16337 // A preferable solution to the general problem is to figure out the right
16338 // places to insert EMMS. This qualifies as a quick hack.
16340 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16341 if (VT.getSizeInBits() != 64)
16344 const Function *F = DAG.getMachineFunction().getFunction();
16345 bool NoImplicitFloatOps = F->getFnAttributes().
16346 hasAttribute(Attribute::NoImplicitFloat);
16347 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16348 && Subtarget->hasSSE2();
16349 if ((VT.isVector() ||
16350 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16351 isa<LoadSDNode>(St->getValue()) &&
16352 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16353 St->getChain().hasOneUse() && !St->isVolatile()) {
16354 SDNode* LdVal = St->getValue().getNode();
16355 LoadSDNode *Ld = 0;
16356 int TokenFactorIndex = -1;
16357 SmallVector<SDValue, 8> Ops;
16358 SDNode* ChainVal = St->getChain().getNode();
16359 // Must be a store of a load. We currently handle two cases: the load
16360 // is a direct child, and it's under an intervening TokenFactor. It is
16361 // possible to dig deeper under nested TokenFactors.
16362 if (ChainVal == LdVal)
16363 Ld = cast<LoadSDNode>(St->getChain());
16364 else if (St->getValue().hasOneUse() &&
16365 ChainVal->getOpcode() == ISD::TokenFactor) {
16366 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16367 if (ChainVal->getOperand(i).getNode() == LdVal) {
16368 TokenFactorIndex = i;
16369 Ld = cast<LoadSDNode>(St->getValue());
16371 Ops.push_back(ChainVal->getOperand(i));
16375 if (!Ld || !ISD::isNormalLoad(Ld))
16378 // If this is not the MMX case, i.e. we are just turning i64 load/store
16379 // into f64 load/store, avoid the transformation if there are multiple
16380 // uses of the loaded value.
16381 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16384 DebugLoc LdDL = Ld->getDebugLoc();
16385 DebugLoc StDL = N->getDebugLoc();
16386 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16387 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16389 if (Subtarget->is64Bit() || F64IsLegal) {
16390 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16391 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16392 Ld->getPointerInfo(), Ld->isVolatile(),
16393 Ld->isNonTemporal(), Ld->isInvariant(),
16394 Ld->getAlignment());
16395 SDValue NewChain = NewLd.getValue(1);
16396 if (TokenFactorIndex != -1) {
16397 Ops.push_back(NewChain);
16398 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16401 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16402 St->getPointerInfo(),
16403 St->isVolatile(), St->isNonTemporal(),
16404 St->getAlignment());
16407 // Otherwise, lower to two pairs of 32-bit loads / stores.
16408 SDValue LoAddr = Ld->getBasePtr();
16409 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16410 DAG.getConstant(4, MVT::i32));
16412 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16413 Ld->getPointerInfo(),
16414 Ld->isVolatile(), Ld->isNonTemporal(),
16415 Ld->isInvariant(), Ld->getAlignment());
16416 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16417 Ld->getPointerInfo().getWithOffset(4),
16418 Ld->isVolatile(), Ld->isNonTemporal(),
16420 MinAlign(Ld->getAlignment(), 4));
16422 SDValue NewChain = LoLd.getValue(1);
16423 if (TokenFactorIndex != -1) {
16424 Ops.push_back(LoLd);
16425 Ops.push_back(HiLd);
16426 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16430 LoAddr = St->getBasePtr();
16431 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16432 DAG.getConstant(4, MVT::i32));
16434 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16435 St->getPointerInfo(),
16436 St->isVolatile(), St->isNonTemporal(),
16437 St->getAlignment());
16438 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16439 St->getPointerInfo().getWithOffset(4),
16441 St->isNonTemporal(),
16442 MinAlign(St->getAlignment(), 4));
16443 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16448 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16449 /// and return the operands for the horizontal operation in LHS and RHS. A
16450 /// horizontal operation performs the binary operation on successive elements
16451 /// of its first operand, then on successive elements of its second operand,
16452 /// returning the resulting values in a vector. For example, if
16453 /// A = < float a0, float a1, float a2, float a3 >
16455 /// B = < float b0, float b1, float b2, float b3 >
16456 /// then the result of doing a horizontal operation on A and B is
16457 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16458 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16459 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16460 /// set to A, RHS to B, and the routine returns 'true'.
16461 /// Note that the binary operation should have the property that if one of the
16462 /// operands is UNDEF then the result is UNDEF.
16463 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16464 // Look for the following pattern: if
16465 // A = < float a0, float a1, float a2, float a3 >
16466 // B = < float b0, float b1, float b2, float b3 >
16468 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16469 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16470 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16471 // which is A horizontal-op B.
16473 // At least one of the operands should be a vector shuffle.
16474 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16475 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16478 EVT VT = LHS.getValueType();
16480 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16481 "Unsupported vector type for horizontal add/sub");
16483 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16484 // operate independently on 128-bit lanes.
16485 unsigned NumElts = VT.getVectorNumElements();
16486 unsigned NumLanes = VT.getSizeInBits()/128;
16487 unsigned NumLaneElts = NumElts / NumLanes;
16488 assert((NumLaneElts % 2 == 0) &&
16489 "Vector type should have an even number of elements in each lane");
16490 unsigned HalfLaneElts = NumLaneElts/2;
16492 // View LHS in the form
16493 // LHS = VECTOR_SHUFFLE A, B, LMask
16494 // If LHS is not a shuffle then pretend it is the shuffle
16495 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16496 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16499 SmallVector<int, 16> LMask(NumElts);
16500 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16501 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16502 A = LHS.getOperand(0);
16503 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16504 B = LHS.getOperand(1);
16505 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16506 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16508 if (LHS.getOpcode() != ISD::UNDEF)
16510 for (unsigned i = 0; i != NumElts; ++i)
16514 // Likewise, view RHS in the form
16515 // RHS = VECTOR_SHUFFLE C, D, RMask
16517 SmallVector<int, 16> RMask(NumElts);
16518 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16519 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16520 C = RHS.getOperand(0);
16521 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16522 D = RHS.getOperand(1);
16523 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16524 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16526 if (RHS.getOpcode() != ISD::UNDEF)
16528 for (unsigned i = 0; i != NumElts; ++i)
16532 // Check that the shuffles are both shuffling the same vectors.
16533 if (!(A == C && B == D) && !(A == D && B == C))
16536 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16537 if (!A.getNode() && !B.getNode())
16540 // If A and B occur in reverse order in RHS, then "swap" them (which means
16541 // rewriting the mask).
16543 CommuteVectorShuffleMask(RMask, NumElts);
16545 // At this point LHS and RHS are equivalent to
16546 // LHS = VECTOR_SHUFFLE A, B, LMask
16547 // RHS = VECTOR_SHUFFLE A, B, RMask
16548 // Check that the masks correspond to performing a horizontal operation.
16549 for (unsigned i = 0; i != NumElts; ++i) {
16550 int LIdx = LMask[i], RIdx = RMask[i];
16552 // Ignore any UNDEF components.
16553 if (LIdx < 0 || RIdx < 0 ||
16554 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16555 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16558 // Check that successive elements are being operated on. If not, this is
16559 // not a horizontal operation.
16560 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16561 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16562 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16563 if (!(LIdx == Index && RIdx == Index + 1) &&
16564 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16568 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16569 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16573 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16574 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16575 const X86Subtarget *Subtarget) {
16576 EVT VT = N->getValueType(0);
16577 SDValue LHS = N->getOperand(0);
16578 SDValue RHS = N->getOperand(1);
16580 // Try to synthesize horizontal adds from adds of shuffles.
16581 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16582 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16583 isHorizontalBinOp(LHS, RHS, true))
16584 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16588 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16589 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16590 const X86Subtarget *Subtarget) {
16591 EVT VT = N->getValueType(0);
16592 SDValue LHS = N->getOperand(0);
16593 SDValue RHS = N->getOperand(1);
16595 // Try to synthesize horizontal subs from subs of shuffles.
16596 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16597 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16598 isHorizontalBinOp(LHS, RHS, false))
16599 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16603 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16604 /// X86ISD::FXOR nodes.
16605 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16606 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16607 // F[X]OR(0.0, x) -> x
16608 // F[X]OR(x, 0.0) -> x
16609 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16610 if (C->getValueAPF().isPosZero())
16611 return N->getOperand(1);
16612 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16613 if (C->getValueAPF().isPosZero())
16614 return N->getOperand(0);
16618 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16619 /// X86ISD::FMAX nodes.
16620 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16621 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16623 // Only perform optimizations if UnsafeMath is used.
16624 if (!DAG.getTarget().Options.UnsafeFPMath)
16627 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16628 // into FMINC and FMAXC, which are Commutative operations.
16629 unsigned NewOp = 0;
16630 switch (N->getOpcode()) {
16631 default: llvm_unreachable("unknown opcode");
16632 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16633 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16636 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16637 N->getOperand(0), N->getOperand(1));
16640 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16641 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16642 // FAND(0.0, x) -> 0.0
16643 // FAND(x, 0.0) -> 0.0
16644 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16645 if (C->getValueAPF().isPosZero())
16646 return N->getOperand(0);
16647 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16648 if (C->getValueAPF().isPosZero())
16649 return N->getOperand(1);
16653 static SDValue PerformBTCombine(SDNode *N,
16655 TargetLowering::DAGCombinerInfo &DCI) {
16656 // BT ignores high bits in the bit index operand.
16657 SDValue Op1 = N->getOperand(1);
16658 if (Op1.hasOneUse()) {
16659 unsigned BitWidth = Op1.getValueSizeInBits();
16660 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16661 APInt KnownZero, KnownOne;
16662 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16663 !DCI.isBeforeLegalizeOps());
16664 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16665 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16666 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16667 DCI.CommitTargetLoweringOpt(TLO);
16672 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16673 SDValue Op = N->getOperand(0);
16674 if (Op.getOpcode() == ISD::BITCAST)
16675 Op = Op.getOperand(0);
16676 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16677 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16678 VT.getVectorElementType().getSizeInBits() ==
16679 OpVT.getVectorElementType().getSizeInBits()) {
16680 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16685 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16686 TargetLowering::DAGCombinerInfo &DCI,
16687 const X86Subtarget *Subtarget) {
16688 if (!DCI.isBeforeLegalizeOps())
16691 if (!Subtarget->hasFp256())
16694 EVT VT = N->getValueType(0);
16695 SDValue Op = N->getOperand(0);
16696 EVT OpVT = Op.getValueType();
16697 DebugLoc dl = N->getDebugLoc();
16699 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16700 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16702 if (Subtarget->hasInt256())
16703 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16705 // Optimize vectors in AVX mode
16706 // Sign extend v8i16 to v8i32 and
16709 // Divide input vector into two parts
16710 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16711 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16712 // concat the vectors to original VT
16714 unsigned NumElems = OpVT.getVectorNumElements();
16715 SDValue Undef = DAG.getUNDEF(OpVT);
16717 SmallVector<int,8> ShufMask1(NumElems, -1);
16718 for (unsigned i = 0; i != NumElems/2; ++i)
16721 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16723 SmallVector<int,8> ShufMask2(NumElems, -1);
16724 for (unsigned i = 0; i != NumElems/2; ++i)
16725 ShufMask2[i] = i + NumElems/2;
16727 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16729 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16730 VT.getVectorNumElements()/2);
16732 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16733 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16735 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16740 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16741 const X86Subtarget* Subtarget) {
16742 DebugLoc dl = N->getDebugLoc();
16743 EVT VT = N->getValueType(0);
16745 // Let legalize expand this if it isn't a legal type yet.
16746 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16749 EVT ScalarVT = VT.getScalarType();
16750 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16751 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16754 SDValue A = N->getOperand(0);
16755 SDValue B = N->getOperand(1);
16756 SDValue C = N->getOperand(2);
16758 bool NegA = (A.getOpcode() == ISD::FNEG);
16759 bool NegB = (B.getOpcode() == ISD::FNEG);
16760 bool NegC = (C.getOpcode() == ISD::FNEG);
16762 // Negative multiplication when NegA xor NegB
16763 bool NegMul = (NegA != NegB);
16765 A = A.getOperand(0);
16767 B = B.getOperand(0);
16769 C = C.getOperand(0);
16773 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16775 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16777 return DAG.getNode(Opcode, dl, VT, A, B, C);
16780 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16781 TargetLowering::DAGCombinerInfo &DCI,
16782 const X86Subtarget *Subtarget) {
16783 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16784 // (and (i32 x86isd::setcc_carry), 1)
16785 // This eliminates the zext. This transformation is necessary because
16786 // ISD::SETCC is always legalized to i8.
16787 DebugLoc dl = N->getDebugLoc();
16788 SDValue N0 = N->getOperand(0);
16789 EVT VT = N->getValueType(0);
16790 EVT OpVT = N0.getValueType();
16792 if (N0.getOpcode() == ISD::AND &&
16794 N0.getOperand(0).hasOneUse()) {
16795 SDValue N00 = N0.getOperand(0);
16796 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16798 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16799 if (!C || C->getZExtValue() != 1)
16801 return DAG.getNode(ISD::AND, dl, VT,
16802 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16803 N00.getOperand(0), N00.getOperand(1)),
16804 DAG.getConstant(1, VT));
16807 // Optimize vectors in AVX mode:
16810 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16811 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16812 // Concat upper and lower parts.
16815 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16816 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16817 // Concat upper and lower parts.
16819 if (!DCI.isBeforeLegalizeOps())
16822 if (!Subtarget->hasFp256())
16825 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16826 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16828 if (Subtarget->hasInt256())
16829 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16831 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16832 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16833 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16835 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16836 VT.getVectorNumElements()/2);
16838 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16839 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16841 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16847 // Optimize x == -y --> x+y == 0
16848 // x != -y --> x+y != 0
16849 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16850 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16851 SDValue LHS = N->getOperand(0);
16852 SDValue RHS = N->getOperand(1);
16854 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16855 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16856 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16857 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16858 LHS.getValueType(), RHS, LHS.getOperand(1));
16859 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16860 addV, DAG.getConstant(0, addV.getValueType()), CC);
16862 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16863 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16864 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16865 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16866 RHS.getValueType(), LHS, RHS.getOperand(1));
16867 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16868 addV, DAG.getConstant(0, addV.getValueType()), CC);
16873 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
16874 // as "sbb reg,reg", since it can be extended without zext and produces
16875 // an all-ones bit which is more useful than 0/1 in some cases.
16876 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16877 return DAG.getNode(ISD::AND, DL, MVT::i8,
16878 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16879 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16880 DAG.getConstant(1, MVT::i8));
16883 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16884 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16885 TargetLowering::DAGCombinerInfo &DCI,
16886 const X86Subtarget *Subtarget) {
16887 DebugLoc DL = N->getDebugLoc();
16888 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16889 SDValue EFLAGS = N->getOperand(1);
16891 if (CC == X86::COND_A) {
16892 // Try to convert COND_A into COND_B in an attempt to facilitate
16893 // materializing "setb reg".
16895 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16896 // cannot take an immediate as its first operand.
16898 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
16899 EFLAGS.getValueType().isInteger() &&
16900 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16901 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16902 EFLAGS.getNode()->getVTList(),
16903 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16904 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16905 return MaterializeSETB(DL, NewEFLAGS, DAG);
16909 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16910 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16912 if (CC == X86::COND_B)
16913 return MaterializeSETB(DL, EFLAGS, DAG);
16917 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16918 if (Flags.getNode()) {
16919 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16920 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16926 // Optimize branch condition evaluation.
16928 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16929 TargetLowering::DAGCombinerInfo &DCI,
16930 const X86Subtarget *Subtarget) {
16931 DebugLoc DL = N->getDebugLoc();
16932 SDValue Chain = N->getOperand(0);
16933 SDValue Dest = N->getOperand(1);
16934 SDValue EFLAGS = N->getOperand(3);
16935 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16939 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16940 if (Flags.getNode()) {
16941 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16942 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16949 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16950 const X86TargetLowering *XTLI) {
16951 SDValue Op0 = N->getOperand(0);
16952 EVT InVT = Op0->getValueType(0);
16954 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16955 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16956 DebugLoc dl = N->getDebugLoc();
16957 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16958 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16959 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16962 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16963 // a 32-bit target where SSE doesn't support i64->FP operations.
16964 if (Op0.getOpcode() == ISD::LOAD) {
16965 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16966 EVT VT = Ld->getValueType(0);
16967 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16968 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16969 !XTLI->getSubtarget()->is64Bit() &&
16970 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16971 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16972 Ld->getChain(), Op0, DAG);
16973 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16980 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16981 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16982 X86TargetLowering::DAGCombinerInfo &DCI) {
16983 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16984 // the result is either zero or one (depending on the input carry bit).
16985 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16986 if (X86::isZeroNode(N->getOperand(0)) &&
16987 X86::isZeroNode(N->getOperand(1)) &&
16988 // We don't have a good way to replace an EFLAGS use, so only do this when
16990 SDValue(N, 1).use_empty()) {
16991 DebugLoc DL = N->getDebugLoc();
16992 EVT VT = N->getValueType(0);
16993 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16994 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16995 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16996 DAG.getConstant(X86::COND_B,MVT::i8),
16998 DAG.getConstant(1, VT));
16999 return DCI.CombineTo(N, Res1, CarryOut);
17005 // fold (add Y, (sete X, 0)) -> adc 0, Y
17006 // (add Y, (setne X, 0)) -> sbb -1, Y
17007 // (sub (sete X, 0), Y) -> sbb 0, Y
17008 // (sub (setne X, 0), Y) -> adc -1, Y
17009 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17010 DebugLoc DL = N->getDebugLoc();
17012 // Look through ZExts.
17013 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17014 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17017 SDValue SetCC = Ext.getOperand(0);
17018 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17021 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17022 if (CC != X86::COND_E && CC != X86::COND_NE)
17025 SDValue Cmp = SetCC.getOperand(1);
17026 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17027 !X86::isZeroNode(Cmp.getOperand(1)) ||
17028 !Cmp.getOperand(0).getValueType().isInteger())
17031 SDValue CmpOp0 = Cmp.getOperand(0);
17032 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17033 DAG.getConstant(1, CmpOp0.getValueType()));
17035 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17036 if (CC == X86::COND_NE)
17037 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17038 DL, OtherVal.getValueType(), OtherVal,
17039 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17040 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17041 DL, OtherVal.getValueType(), OtherVal,
17042 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17045 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17046 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17047 const X86Subtarget *Subtarget) {
17048 EVT VT = N->getValueType(0);
17049 SDValue Op0 = N->getOperand(0);
17050 SDValue Op1 = N->getOperand(1);
17052 // Try to synthesize horizontal adds from adds of shuffles.
17053 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17054 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17055 isHorizontalBinOp(Op0, Op1, true))
17056 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17058 return OptimizeConditionalInDecrement(N, DAG);
17061 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17062 const X86Subtarget *Subtarget) {
17063 SDValue Op0 = N->getOperand(0);
17064 SDValue Op1 = N->getOperand(1);
17066 // X86 can't encode an immediate LHS of a sub. See if we can push the
17067 // negation into a preceding instruction.
17068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17069 // If the RHS of the sub is a XOR with one use and a constant, invert the
17070 // immediate. Then add one to the LHS of the sub so we can turn
17071 // X-Y -> X+~Y+1, saving one register.
17072 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17073 isa<ConstantSDNode>(Op1.getOperand(1))) {
17074 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17075 EVT VT = Op0.getValueType();
17076 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17078 DAG.getConstant(~XorC, VT));
17079 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17080 DAG.getConstant(C->getAPIntValue()+1, VT));
17084 // Try to synthesize horizontal adds from adds of shuffles.
17085 EVT VT = N->getValueType(0);
17086 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17087 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17088 isHorizontalBinOp(Op0, Op1, true))
17089 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17091 return OptimizeConditionalInDecrement(N, DAG);
17094 /// performVZEXTCombine - Performs build vector combines
17095 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17096 TargetLowering::DAGCombinerInfo &DCI,
17097 const X86Subtarget *Subtarget) {
17098 // (vzext (bitcast (vzext (x)) -> (vzext x)
17099 SDValue In = N->getOperand(0);
17100 while (In.getOpcode() == ISD::BITCAST)
17101 In = In.getOperand(0);
17103 if (In.getOpcode() != X86ISD::VZEXT)
17106 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17109 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17110 DAGCombinerInfo &DCI) const {
17111 SelectionDAG &DAG = DCI.DAG;
17112 switch (N->getOpcode()) {
17114 case ISD::EXTRACT_VECTOR_ELT:
17115 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17117 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17118 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17119 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17120 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17121 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17122 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17125 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17126 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17127 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17128 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17129 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17130 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17131 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17132 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17133 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17135 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17137 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17138 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17139 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17140 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17141 case ISD::ANY_EXTEND:
17142 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17143 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17144 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17145 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17146 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17147 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17148 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17149 case X86ISD::SHUFP: // Handle all target specific shuffles
17150 case X86ISD::PALIGN:
17151 case X86ISD::UNPCKH:
17152 case X86ISD::UNPCKL:
17153 case X86ISD::MOVHLPS:
17154 case X86ISD::MOVLHPS:
17155 case X86ISD::PSHUFD:
17156 case X86ISD::PSHUFHW:
17157 case X86ISD::PSHUFLW:
17158 case X86ISD::MOVSS:
17159 case X86ISD::MOVSD:
17160 case X86ISD::VPERMILP:
17161 case X86ISD::VPERM2X128:
17162 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17163 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17169 /// isTypeDesirableForOp - Return true if the target has native support for
17170 /// the specified value type and it is 'desirable' to use the type for the
17171 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17172 /// instruction encodings are longer and some i16 instructions are slow.
17173 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17174 if (!isTypeLegal(VT))
17176 if (VT != MVT::i16)
17183 case ISD::SIGN_EXTEND:
17184 case ISD::ZERO_EXTEND:
17185 case ISD::ANY_EXTEND:
17198 /// IsDesirableToPromoteOp - This method query the target whether it is
17199 /// beneficial for dag combiner to promote the specified node. If true, it
17200 /// should return the desired promotion type by reference.
17201 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17202 EVT VT = Op.getValueType();
17203 if (VT != MVT::i16)
17206 bool Promote = false;
17207 bool Commute = false;
17208 switch (Op.getOpcode()) {
17211 LoadSDNode *LD = cast<LoadSDNode>(Op);
17212 // If the non-extending load has a single use and it's not live out, then it
17213 // might be folded.
17214 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17215 Op.hasOneUse()*/) {
17216 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17217 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17218 // The only case where we'd want to promote LOAD (rather then it being
17219 // promoted as an operand is when it's only use is liveout.
17220 if (UI->getOpcode() != ISD::CopyToReg)
17227 case ISD::SIGN_EXTEND:
17228 case ISD::ZERO_EXTEND:
17229 case ISD::ANY_EXTEND:
17234 SDValue N0 = Op.getOperand(0);
17235 // Look out for (store (shl (load), x)).
17236 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17249 SDValue N0 = Op.getOperand(0);
17250 SDValue N1 = Op.getOperand(1);
17251 if (!Commute && MayFoldLoad(N1))
17253 // Avoid disabling potential load folding opportunities.
17254 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17256 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17266 //===----------------------------------------------------------------------===//
17267 // X86 Inline Assembly Support
17268 //===----------------------------------------------------------------------===//
17271 // Helper to match a string separated by whitespace.
17272 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17273 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17275 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17276 StringRef piece(*args[i]);
17277 if (!s.startswith(piece)) // Check if the piece matches.
17280 s = s.substr(piece.size());
17281 StringRef::size_type pos = s.find_first_not_of(" \t");
17282 if (pos == 0) // We matched a prefix.
17290 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17293 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17294 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17296 std::string AsmStr = IA->getAsmString();
17298 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17299 if (!Ty || Ty->getBitWidth() % 16 != 0)
17302 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17303 SmallVector<StringRef, 4> AsmPieces;
17304 SplitString(AsmStr, AsmPieces, ";\n");
17306 switch (AsmPieces.size()) {
17307 default: return false;
17309 // FIXME: this should verify that we are targeting a 486 or better. If not,
17310 // we will turn this bswap into something that will be lowered to logical
17311 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17312 // lower so don't worry about this.
17314 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17315 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17316 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17317 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17318 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17319 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17320 // No need to check constraints, nothing other than the equivalent of
17321 // "=r,0" would be valid here.
17322 return IntrinsicLowering::LowerToByteSwap(CI);
17325 // rorw $$8, ${0:w} --> llvm.bswap.i16
17326 if (CI->getType()->isIntegerTy(16) &&
17327 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17328 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17329 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17331 const std::string &ConstraintsStr = IA->getConstraintString();
17332 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17333 std::sort(AsmPieces.begin(), AsmPieces.end());
17334 if (AsmPieces.size() == 4 &&
17335 AsmPieces[0] == "~{cc}" &&
17336 AsmPieces[1] == "~{dirflag}" &&
17337 AsmPieces[2] == "~{flags}" &&
17338 AsmPieces[3] == "~{fpsr}")
17339 return IntrinsicLowering::LowerToByteSwap(CI);
17343 if (CI->getType()->isIntegerTy(32) &&
17344 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17345 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17346 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17347 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17349 const std::string &ConstraintsStr = IA->getConstraintString();
17350 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17351 std::sort(AsmPieces.begin(), AsmPieces.end());
17352 if (AsmPieces.size() == 4 &&
17353 AsmPieces[0] == "~{cc}" &&
17354 AsmPieces[1] == "~{dirflag}" &&
17355 AsmPieces[2] == "~{flags}" &&
17356 AsmPieces[3] == "~{fpsr}")
17357 return IntrinsicLowering::LowerToByteSwap(CI);
17360 if (CI->getType()->isIntegerTy(64)) {
17361 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17362 if (Constraints.size() >= 2 &&
17363 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17364 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17365 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17366 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17367 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17368 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17369 return IntrinsicLowering::LowerToByteSwap(CI);
17377 /// getConstraintType - Given a constraint letter, return the type of
17378 /// constraint it is for this target.
17379 X86TargetLowering::ConstraintType
17380 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17381 if (Constraint.size() == 1) {
17382 switch (Constraint[0]) {
17393 return C_RegisterClass;
17417 return TargetLowering::getConstraintType(Constraint);
17420 /// Examine constraint type and operand type and determine a weight value.
17421 /// This object must already have been set up with the operand type
17422 /// and the current alternative constraint selected.
17423 TargetLowering::ConstraintWeight
17424 X86TargetLowering::getSingleConstraintMatchWeight(
17425 AsmOperandInfo &info, const char *constraint) const {
17426 ConstraintWeight weight = CW_Invalid;
17427 Value *CallOperandVal = info.CallOperandVal;
17428 // If we don't have a value, we can't do a match,
17429 // but allow it at the lowest weight.
17430 if (CallOperandVal == NULL)
17432 Type *type = CallOperandVal->getType();
17433 // Look at the constraint type.
17434 switch (*constraint) {
17436 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17447 if (CallOperandVal->getType()->isIntegerTy())
17448 weight = CW_SpecificReg;
17453 if (type->isFloatingPointTy())
17454 weight = CW_SpecificReg;
17457 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17458 weight = CW_SpecificReg;
17462 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17463 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17464 weight = CW_Register;
17467 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17468 if (C->getZExtValue() <= 31)
17469 weight = CW_Constant;
17473 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17474 if (C->getZExtValue() <= 63)
17475 weight = CW_Constant;
17479 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17480 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17481 weight = CW_Constant;
17485 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17486 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17487 weight = CW_Constant;
17491 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17492 if (C->getZExtValue() <= 3)
17493 weight = CW_Constant;
17497 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17498 if (C->getZExtValue() <= 0xff)
17499 weight = CW_Constant;
17504 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17505 weight = CW_Constant;
17509 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17510 if ((C->getSExtValue() >= -0x80000000LL) &&
17511 (C->getSExtValue() <= 0x7fffffffLL))
17512 weight = CW_Constant;
17516 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17517 if (C->getZExtValue() <= 0xffffffff)
17518 weight = CW_Constant;
17525 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17526 /// with another that has more specific requirements based on the type of the
17527 /// corresponding operand.
17528 const char *X86TargetLowering::
17529 LowerXConstraint(EVT ConstraintVT) const {
17530 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17531 // 'f' like normal targets.
17532 if (ConstraintVT.isFloatingPoint()) {
17533 if (Subtarget->hasSSE2())
17535 if (Subtarget->hasSSE1())
17539 return TargetLowering::LowerXConstraint(ConstraintVT);
17542 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17543 /// vector. If it is invalid, don't add anything to Ops.
17544 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17545 std::string &Constraint,
17546 std::vector<SDValue>&Ops,
17547 SelectionDAG &DAG) const {
17548 SDValue Result(0, 0);
17550 // Only support length 1 constraints for now.
17551 if (Constraint.length() > 1) return;
17553 char ConstraintLetter = Constraint[0];
17554 switch (ConstraintLetter) {
17557 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17558 if (C->getZExtValue() <= 31) {
17559 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17566 if (C->getZExtValue() <= 63) {
17567 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17574 if (isInt<8>(C->getSExtValue())) {
17575 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17581 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17582 if (C->getZExtValue() <= 255) {
17583 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17589 // 32-bit signed value
17590 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17591 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17592 C->getSExtValue())) {
17593 // Widen to 64 bits here to get it sign extended.
17594 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17597 // FIXME gcc accepts some relocatable values here too, but only in certain
17598 // memory models; it's complicated.
17603 // 32-bit unsigned value
17604 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17605 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17606 C->getZExtValue())) {
17607 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17611 // FIXME gcc accepts some relocatable values here too, but only in certain
17612 // memory models; it's complicated.
17616 // Literal immediates are always ok.
17617 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17618 // Widen to 64 bits here to get it sign extended.
17619 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17623 // In any sort of PIC mode addresses need to be computed at runtime by
17624 // adding in a register or some sort of table lookup. These can't
17625 // be used as immediates.
17626 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17629 // If we are in non-pic codegen mode, we allow the address of a global (with
17630 // an optional displacement) to be used with 'i'.
17631 GlobalAddressSDNode *GA = 0;
17632 int64_t Offset = 0;
17634 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17636 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17637 Offset += GA->getOffset();
17639 } else if (Op.getOpcode() == ISD::ADD) {
17640 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17641 Offset += C->getZExtValue();
17642 Op = Op.getOperand(0);
17645 } else if (Op.getOpcode() == ISD::SUB) {
17646 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17647 Offset += -C->getZExtValue();
17648 Op = Op.getOperand(0);
17653 // Otherwise, this isn't something we can handle, reject it.
17657 const GlobalValue *GV = GA->getGlobal();
17658 // If we require an extra load to get this address, as in PIC mode, we
17659 // can't accept it.
17660 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17661 getTargetMachine())))
17664 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17665 GA->getValueType(0), Offset);
17670 if (Result.getNode()) {
17671 Ops.push_back(Result);
17674 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17677 std::pair<unsigned, const TargetRegisterClass*>
17678 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17680 // First, see if this is a constraint that directly corresponds to an LLVM
17682 if (Constraint.size() == 1) {
17683 // GCC Constraint Letters
17684 switch (Constraint[0]) {
17686 // TODO: Slight differences here in allocation order and leaving
17687 // RIP in the class. Do they matter any more here than they do
17688 // in the normal allocation?
17689 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17690 if (Subtarget->is64Bit()) {
17691 if (VT == MVT::i32 || VT == MVT::f32)
17692 return std::make_pair(0U, &X86::GR32RegClass);
17693 if (VT == MVT::i16)
17694 return std::make_pair(0U, &X86::GR16RegClass);
17695 if (VT == MVT::i8 || VT == MVT::i1)
17696 return std::make_pair(0U, &X86::GR8RegClass);
17697 if (VT == MVT::i64 || VT == MVT::f64)
17698 return std::make_pair(0U, &X86::GR64RegClass);
17701 // 32-bit fallthrough
17702 case 'Q': // Q_REGS
17703 if (VT == MVT::i32 || VT == MVT::f32)
17704 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17705 if (VT == MVT::i16)
17706 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17707 if (VT == MVT::i8 || VT == MVT::i1)
17708 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17709 if (VT == MVT::i64)
17710 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17712 case 'r': // GENERAL_REGS
17713 case 'l': // INDEX_REGS
17714 if (VT == MVT::i8 || VT == MVT::i1)
17715 return std::make_pair(0U, &X86::GR8RegClass);
17716 if (VT == MVT::i16)
17717 return std::make_pair(0U, &X86::GR16RegClass);
17718 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17719 return std::make_pair(0U, &X86::GR32RegClass);
17720 return std::make_pair(0U, &X86::GR64RegClass);
17721 case 'R': // LEGACY_REGS
17722 if (VT == MVT::i8 || VT == MVT::i1)
17723 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17724 if (VT == MVT::i16)
17725 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17726 if (VT == MVT::i32 || !Subtarget->is64Bit())
17727 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17728 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17729 case 'f': // FP Stack registers.
17730 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17731 // value to the correct fpstack register class.
17732 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17733 return std::make_pair(0U, &X86::RFP32RegClass);
17734 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17735 return std::make_pair(0U, &X86::RFP64RegClass);
17736 return std::make_pair(0U, &X86::RFP80RegClass);
17737 case 'y': // MMX_REGS if MMX allowed.
17738 if (!Subtarget->hasMMX()) break;
17739 return std::make_pair(0U, &X86::VR64RegClass);
17740 case 'Y': // SSE_REGS if SSE2 allowed
17741 if (!Subtarget->hasSSE2()) break;
17743 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17744 if (!Subtarget->hasSSE1()) break;
17746 switch (VT.getSimpleVT().SimpleTy) {
17748 // Scalar SSE types.
17751 return std::make_pair(0U, &X86::FR32RegClass);
17754 return std::make_pair(0U, &X86::FR64RegClass);
17762 return std::make_pair(0U, &X86::VR128RegClass);
17770 return std::make_pair(0U, &X86::VR256RegClass);
17776 // Use the default implementation in TargetLowering to convert the register
17777 // constraint into a member of a register class.
17778 std::pair<unsigned, const TargetRegisterClass*> Res;
17779 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17781 // Not found as a standard register?
17782 if (Res.second == 0) {
17783 // Map st(0) -> st(7) -> ST0
17784 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17785 tolower(Constraint[1]) == 's' &&
17786 tolower(Constraint[2]) == 't' &&
17787 Constraint[3] == '(' &&
17788 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17789 Constraint[5] == ')' &&
17790 Constraint[6] == '}') {
17792 Res.first = X86::ST0+Constraint[4]-'0';
17793 Res.second = &X86::RFP80RegClass;
17797 // GCC allows "st(0)" to be called just plain "st".
17798 if (StringRef("{st}").equals_lower(Constraint)) {
17799 Res.first = X86::ST0;
17800 Res.second = &X86::RFP80RegClass;
17805 if (StringRef("{flags}").equals_lower(Constraint)) {
17806 Res.first = X86::EFLAGS;
17807 Res.second = &X86::CCRRegClass;
17811 // 'A' means EAX + EDX.
17812 if (Constraint == "A") {
17813 Res.first = X86::EAX;
17814 Res.second = &X86::GR32_ADRegClass;
17820 // Otherwise, check to see if this is a register class of the wrong value
17821 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17822 // turn into {ax},{dx}.
17823 if (Res.second->hasType(VT))
17824 return Res; // Correct type already, nothing to do.
17826 // All of the single-register GCC register classes map their values onto
17827 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17828 // really want an 8-bit or 32-bit register, map to the appropriate register
17829 // class and return the appropriate register.
17830 if (Res.second == &X86::GR16RegClass) {
17831 if (VT == MVT::i8) {
17832 unsigned DestReg = 0;
17833 switch (Res.first) {
17835 case X86::AX: DestReg = X86::AL; break;
17836 case X86::DX: DestReg = X86::DL; break;
17837 case X86::CX: DestReg = X86::CL; break;
17838 case X86::BX: DestReg = X86::BL; break;
17841 Res.first = DestReg;
17842 Res.second = &X86::GR8RegClass;
17844 } else if (VT == MVT::i32) {
17845 unsigned DestReg = 0;
17846 switch (Res.first) {
17848 case X86::AX: DestReg = X86::EAX; break;
17849 case X86::DX: DestReg = X86::EDX; break;
17850 case X86::CX: DestReg = X86::ECX; break;
17851 case X86::BX: DestReg = X86::EBX; break;
17852 case X86::SI: DestReg = X86::ESI; break;
17853 case X86::DI: DestReg = X86::EDI; break;
17854 case X86::BP: DestReg = X86::EBP; break;
17855 case X86::SP: DestReg = X86::ESP; break;
17858 Res.first = DestReg;
17859 Res.second = &X86::GR32RegClass;
17861 } else if (VT == MVT::i64) {
17862 unsigned DestReg = 0;
17863 switch (Res.first) {
17865 case X86::AX: DestReg = X86::RAX; break;
17866 case X86::DX: DestReg = X86::RDX; break;
17867 case X86::CX: DestReg = X86::RCX; break;
17868 case X86::BX: DestReg = X86::RBX; break;
17869 case X86::SI: DestReg = X86::RSI; break;
17870 case X86::DI: DestReg = X86::RDI; break;
17871 case X86::BP: DestReg = X86::RBP; break;
17872 case X86::SP: DestReg = X86::RSP; break;
17875 Res.first = DestReg;
17876 Res.second = &X86::GR64RegClass;
17879 } else if (Res.second == &X86::FR32RegClass ||
17880 Res.second == &X86::FR64RegClass ||
17881 Res.second == &X86::VR128RegClass) {
17882 // Handle references to XMM physical registers that got mapped into the
17883 // wrong class. This can happen with constraints like {xmm0} where the
17884 // target independent register mapper will just pick the first match it can
17885 // find, ignoring the required type.
17887 if (VT == MVT::f32 || VT == MVT::i32)
17888 Res.second = &X86::FR32RegClass;
17889 else if (VT == MVT::f64 || VT == MVT::i64)
17890 Res.second = &X86::FR64RegClass;
17891 else if (X86::VR128RegClass.hasType(VT))
17892 Res.second = &X86::VR128RegClass;
17893 else if (X86::VR256RegClass.hasType(VT))
17894 Res.second = &X86::VR256RegClass;
17900 //===----------------------------------------------------------------------===//
17904 //===----------------------------------------------------------------------===//
17906 struct X86CostTblEntry {
17913 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17914 for (unsigned int i = 0; i < len; ++i)
17915 if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17918 // Could not find an entry.
17922 struct X86TypeConversionCostTblEntry {
17930 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17931 int ISD, MVT Dst, MVT Src) {
17932 for (unsigned int i = 0; i < len; ++i)
17933 if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17936 // Could not find an entry.
17940 ScalarTargetTransformInfo::PopcntHwSupport
17941 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
17942 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
17943 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17945 // TODO: Currently the __builtin_popcount() implementation using SSE3
17946 // instructions is inefficient. Once the problem is fixed, we should
17947 // call ST.hasSSE3() instead of ST.hasSSE4().
17948 return ST.hasSSE41() ? Fast : None;
17952 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17954 // Legalize the type.
17955 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17957 int ISD = InstructionOpcodeToISD(Opcode);
17958 assert(ISD && "Invalid opcode");
17960 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17962 static const X86CostTblEntry AVX1CostTable[] = {
17963 // We don't have to scalarize unsupported ops. We can issue two half-sized
17964 // operations and we only need to extract the upper YMM half.
17965 // Two ops + 1 extract + 1 insert = 4.
17966 { ISD::MUL, MVT::v8i32, 4 },
17967 { ISD::SUB, MVT::v8i32, 4 },
17968 { ISD::ADD, MVT::v8i32, 4 },
17969 { ISD::MUL, MVT::v4i64, 4 },
17970 { ISD::SUB, MVT::v4i64, 4 },
17971 { ISD::ADD, MVT::v4i64, 4 },
17974 // Look for AVX1 lowering tricks.
17976 int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17979 return LT.first * AVX1CostTable[Idx].Cost;
17981 // Fallback to the default implementation.
17982 return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17986 X86VectorTargetTransformInfo::getMemoryOpCost(unsigned Opcode, Type *Src,
17987 unsigned Alignment,
17988 unsigned AddressSpace) const {
17989 // Legalize the type.
17990 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Src);
17991 assert((Opcode == Instruction::Load || Opcode == Instruction::Store) &&
17994 const X86Subtarget &ST =
17995 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17997 // Each load/store unit costs 1.
17998 unsigned Cost = LT.first * 1;
18000 // On Sandybridge 256bit load/stores are double pumped
18001 // (but not on Haswell).
18002 if (LT.second.getSizeInBits() > 128 && !ST.hasAVX2())
18009 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
18010 unsigned Index) const {
18011 assert(Val->isVectorTy() && "This must be a vector type");
18013 if (Index != -1U) {
18014 // Legalize the type.
18015 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
18017 // This type is legalized to a scalar type.
18018 if (!LT.second.isVector())
18021 // The type may be split. Normalize the index to the new type.
18022 unsigned Width = LT.second.getVectorNumElements();
18023 Index = Index % Width;
18025 // Floating point scalars are already located in index #0.
18026 if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
18030 return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
18033 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
18035 Type *CondTy) const {
18036 // Legalize the type.
18037 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
18039 MVT MTy = LT.second;
18041 int ISD = InstructionOpcodeToISD(Opcode);
18042 assert(ISD && "Invalid opcode");
18044 const X86Subtarget &ST =
18045 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18047 static const X86CostTblEntry SSE42CostTbl[] = {
18048 { ISD::SETCC, MVT::v2f64, 1 },
18049 { ISD::SETCC, MVT::v4f32, 1 },
18050 { ISD::SETCC, MVT::v2i64, 1 },
18051 { ISD::SETCC, MVT::v4i32, 1 },
18052 { ISD::SETCC, MVT::v8i16, 1 },
18053 { ISD::SETCC, MVT::v16i8, 1 },
18056 static const X86CostTblEntry AVX1CostTbl[] = {
18057 { ISD::SETCC, MVT::v4f64, 1 },
18058 { ISD::SETCC, MVT::v8f32, 1 },
18059 // AVX1 does not support 8-wide integer compare.
18060 { ISD::SETCC, MVT::v4i64, 4 },
18061 { ISD::SETCC, MVT::v8i32, 4 },
18062 { ISD::SETCC, MVT::v16i16, 4 },
18063 { ISD::SETCC, MVT::v32i8, 4 },
18066 static const X86CostTblEntry AVX2CostTbl[] = {
18067 { ISD::SETCC, MVT::v4i64, 1 },
18068 { ISD::SETCC, MVT::v8i32, 1 },
18069 { ISD::SETCC, MVT::v16i16, 1 },
18070 { ISD::SETCC, MVT::v32i8, 1 },
18073 if (ST.hasAVX2()) {
18074 int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
18076 return LT.first * AVX2CostTbl[Idx].Cost;
18080 int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
18082 return LT.first * AVX1CostTbl[Idx].Cost;
18085 if (ST.hasSSE42()) {
18086 int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
18088 return LT.first * SSE42CostTbl[Idx].Cost;
18091 return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
18094 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
18097 int ISD = InstructionOpcodeToISD(Opcode);
18098 assert(ISD && "Invalid opcode");
18100 EVT SrcTy = TLI->getValueType(Src);
18101 EVT DstTy = TLI->getValueType(Dst);
18103 if (!SrcTy.isSimple() || !DstTy.isSimple())
18104 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
18106 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
18108 static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
18109 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18110 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
18111 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18112 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
18113 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1 },
18114 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1 },
18115 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18116 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18117 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
18118 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
18119 { ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 1 },
18120 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
18121 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 6 },
18122 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 9 },
18123 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 3 },
18127 int Idx = FindInConvertTable(AVXConversionTbl,
18128 array_lengthof(AVXConversionTbl),
18129 ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
18131 return AVXConversionTbl[Idx].Cost;
18134 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);