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/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/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 expensive divides on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
186 addBypassSlowDiv(32, 8);
187 if (Subtarget->is64Bit())
188 addBypassSlowDiv(64, 16);
191 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
192 // Setup Windows compiler runtime calls.
193 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
194 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
195 setLibcallName(RTLIB::SREM_I64, "_allrem");
196 setLibcallName(RTLIB::UREM_I64, "_aullrem");
197 setLibcallName(RTLIB::MUL_I64, "_allmul");
198 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
201 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
202 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
204 // The _ftol2 runtime function has an unusual calling conv, which
205 // is modeled by a special pseudo-instruction.
206 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
208 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
209 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
212 if (Subtarget->isTargetDarwin()) {
213 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214 setUseUnderscoreSetJmp(false);
215 setUseUnderscoreLongJmp(false);
216 } else if (Subtarget->isTargetMingw()) {
217 // MS runtime is weird: it exports _setjmp, but longjmp!
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(false);
221 setUseUnderscoreSetJmp(true);
222 setUseUnderscoreLongJmp(true);
225 // Set up the register classes.
226 addRegisterClass(MVT::i8, &X86::GR8RegClass);
227 addRegisterClass(MVT::i16, &X86::GR16RegClass);
228 addRegisterClass(MVT::i32, &X86::GR32RegClass);
229 if (Subtarget->is64Bit())
230 addRegisterClass(MVT::i64, &X86::GR64RegClass);
232 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
234 // We don't accept any truncstore of integer registers.
235 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
242 // SETOEQ and SETUNE require checking two conditions.
243 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
250 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
252 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
253 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
254 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
258 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
259 } else if (!TM.Options.UseSoftFloat) {
260 // We have an algorithm for SSE2->double, and we turn this into a
261 // 64-bit FILD followed by conditional FADD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
263 // We have an algorithm for SSE2, and we turn this into a 64-bit
264 // FILD for other targets.
265 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
268 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
270 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
271 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
273 if (!TM.Options.UseSoftFloat) {
274 // SSE has no i16 to fp conversion, only i32
275 if (X86ScalarSSEf32) {
276 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
277 // f32 and f64 cases are Legal, f80 case is not
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
280 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
284 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
285 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
288 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
289 // are Legal, f80 is custom lowered.
290 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
291 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
293 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
295 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
296 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
298 if (X86ScalarSSEf32) {
299 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
300 // f32 and f64 cases are Legal, f80 case is not
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
303 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
304 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
307 // Handle FP_TO_UINT by promoting the destination to a larger signed
309 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
310 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
311 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
313 if (Subtarget->is64Bit()) {
314 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
315 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
316 } else if (!TM.Options.UseSoftFloat) {
317 // Since AVX is a superset of SSE3, only check for SSE here.
318 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319 // Expand FP_TO_UINT into a select.
320 // FIXME: We would like to use a Custom expander here eventually to do
321 // the optimal thing for SSE vs. the default expansion in the legalizer.
322 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
324 // With SSE3 we can use fisttpll to convert to a signed i64; without
325 // SSE, we're stuck with a fistpll.
326 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
329 if (isTargetFTOL()) {
330 // Use the _ftol2 runtime function, which has a pseudo-instruction
331 // to handle its weird calling convention.
332 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
335 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
336 if (!X86ScalarSSEf64) {
337 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
338 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
339 if (Subtarget->is64Bit()) {
340 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
341 // Without SSE, i64->f64 goes through memory.
342 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
346 // Scalar integer divide and remainder are lowered to use operations that
347 // produce two results, to match the available instructions. This exposes
348 // the two-result form to trivial CSE, which is able to combine x/y and x%y
349 // into a single instruction.
351 // Scalar integer multiply-high is also lowered to use two-result
352 // operations, to match the available instructions. However, plain multiply
353 // (low) operations are left as Legal, as there are single-result
354 // instructions for this in x86. Using the two-result multiply instructions
355 // when both high and low results are needed must be arranged by dagcombine.
356 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
358 setOperationAction(ISD::MULHS, VT, Expand);
359 setOperationAction(ISD::MULHU, VT, Expand);
360 setOperationAction(ISD::SDIV, VT, Expand);
361 setOperationAction(ISD::UDIV, VT, Expand);
362 setOperationAction(ISD::SREM, VT, Expand);
363 setOperationAction(ISD::UREM, VT, Expand);
365 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
366 setOperationAction(ISD::ADDC, VT, Custom);
367 setOperationAction(ISD::ADDE, VT, Custom);
368 setOperationAction(ISD::SUBC, VT, Custom);
369 setOperationAction(ISD::SUBE, VT, Custom);
372 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
373 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
374 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
375 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
376 if (Subtarget->is64Bit())
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
379 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
380 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
381 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
382 setOperationAction(ISD::FREM , MVT::f32 , Expand);
383 setOperationAction(ISD::FREM , MVT::f64 , Expand);
384 setOperationAction(ISD::FREM , MVT::f80 , Expand);
385 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
387 // Promote the i8 variants and force them on up to i32 which has a shorter
389 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
392 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
393 if (Subtarget->hasBMI()) {
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
396 if (Subtarget->is64Bit())
397 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
399 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
400 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
401 if (Subtarget->is64Bit())
402 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
405 if (Subtarget->hasLZCNT()) {
406 // When promoting the i8 variants, force them to i32 for a shorter
408 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
411 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
414 if (Subtarget->is64Bit())
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
417 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
421 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
423 if (Subtarget->is64Bit()) {
424 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
425 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
429 if (Subtarget->hasPOPCNT()) {
430 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
432 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
433 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
434 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
435 if (Subtarget->is64Bit())
436 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
439 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
440 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
442 // These should be promoted to a larger select which is supported.
443 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
444 // X86 wants to expand cmov itself.
445 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
446 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
447 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
449 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
450 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
452 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
453 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
455 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
457 if (Subtarget->is64Bit()) {
458 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
459 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
461 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
462 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
463 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
464 // support continuation, user-level threading, and etc.. As a result, no
465 // other SjLj exception interfaces are implemented and please don't build
466 // your own exception handling based on them.
467 // LLVM/Clang supports zero-cost DWARF exception handling.
468 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
469 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
472 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
473 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
474 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
475 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
476 if (Subtarget->is64Bit())
477 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
478 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
479 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
480 if (Subtarget->is64Bit()) {
481 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
482 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
483 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
484 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
485 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
487 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
488 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
489 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
490 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
491 if (Subtarget->is64Bit()) {
492 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
493 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
494 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
497 if (Subtarget->hasSSE1())
498 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
500 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
501 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
503 // On X86 and X86-64, atomic operations are lowered to locked instructions.
504 // Locked instructions, in turn, have implicit fence semantics (all memory
505 // operations are flushed before issuing the locked instruction, and they
506 // are not buffered), so we can fold away the common pattern of
507 // fence-atomic-fence.
508 setShouldFoldAtomicFences(true);
510 // Expand certain atomics
511 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
513 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
514 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
515 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
518 if (!Subtarget->is64Bit()) {
519 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
528 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
529 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
530 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
533 if (Subtarget->hasCmpxchg16b()) {
534 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
537 // FIXME - use subtarget debug flags
538 if (!Subtarget->isTargetDarwin() &&
539 !Subtarget->isTargetELF() &&
540 !Subtarget->isTargetCygMing()) {
541 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
544 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
545 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
546 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
547 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
548 if (Subtarget->is64Bit()) {
549 setExceptionPointerRegister(X86::RAX);
550 setExceptionSelectorRegister(X86::RDX);
552 setExceptionPointerRegister(X86::EAX);
553 setExceptionSelectorRegister(X86::EDX);
555 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
556 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
558 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
559 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
561 setOperationAction(ISD::TRAP, MVT::Other, Legal);
562 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
564 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
565 setOperationAction(ISD::VASTART , MVT::Other, Custom);
566 setOperationAction(ISD::VAEND , MVT::Other, Expand);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::VAARG , MVT::Other, Custom);
569 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
571 setOperationAction(ISD::VAARG , MVT::Other, Expand);
572 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
575 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
576 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
578 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
581 else if (TM.Options.EnableSegmentedStacks)
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Custom);
585 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
586 MVT::i64 : MVT::i32, Expand);
588 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
589 // f32 and f64 use SSE.
590 // Set up the FP register classes.
591 addRegisterClass(MVT::f32, &X86::FR32RegClass);
592 addRegisterClass(MVT::f64, &X86::FR64RegClass);
594 // Use ANDPD to simulate FABS.
595 setOperationAction(ISD::FABS , MVT::f64, Custom);
596 setOperationAction(ISD::FABS , MVT::f32, Custom);
598 // Use XORP to simulate FNEG.
599 setOperationAction(ISD::FNEG , MVT::f64, Custom);
600 setOperationAction(ISD::FNEG , MVT::f32, Custom);
602 // Use ANDPD and ORPD to simulate FCOPYSIGN.
603 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
604 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
606 // Lower this to FGETSIGNx86 plus an AND.
607 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
608 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
610 // We don't support sin/cos/fmod
611 setOperationAction(ISD::FSIN , MVT::f64, Expand);
612 setOperationAction(ISD::FCOS , MVT::f64, Expand);
613 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
614 setOperationAction(ISD::FSIN , MVT::f32, Expand);
615 setOperationAction(ISD::FCOS , MVT::f32, Expand);
616 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
618 // Expand FP immediates into loads from the stack, except for the special
620 addLegalFPImmediate(APFloat(+0.0)); // xorpd
621 addLegalFPImmediate(APFloat(+0.0f)); // xorps
622 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
623 // Use SSE for f32, x87 for f64.
624 // Set up the FP register classes.
625 addRegisterClass(MVT::f32, &X86::FR32RegClass);
626 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
628 // Use ANDPS to simulate FABS.
629 setOperationAction(ISD::FABS , MVT::f32, Custom);
631 // Use XORP to simulate FNEG.
632 setOperationAction(ISD::FNEG , MVT::f32, Custom);
634 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
636 // Use ANDPS and ORPS to simulate FCOPYSIGN.
637 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
638 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
640 // We don't support sin/cos/fmod
641 setOperationAction(ISD::FSIN , MVT::f32, Expand);
642 setOperationAction(ISD::FCOS , MVT::f32, Expand);
643 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
645 // Special cases we handle for FP constants.
646 addLegalFPImmediate(APFloat(+0.0f)); // xorps
647 addLegalFPImmediate(APFloat(+0.0)); // FLD0
648 addLegalFPImmediate(APFloat(+1.0)); // FLD1
649 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
650 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
652 if (!TM.Options.UnsafeFPMath) {
653 setOperationAction(ISD::FSIN , MVT::f64, Expand);
654 setOperationAction(ISD::FCOS , MVT::f64, Expand);
655 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
657 } else if (!TM.Options.UseSoftFloat) {
658 // f32 and f64 in x87.
659 // Set up the FP register classes.
660 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
661 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
663 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
664 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
665 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
666 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
668 if (!TM.Options.UnsafeFPMath) {
669 setOperationAction(ISD::FSIN , MVT::f64, Expand);
670 setOperationAction(ISD::FSIN , MVT::f32, Expand);
671 setOperationAction(ISD::FCOS , MVT::f64, Expand);
672 setOperationAction(ISD::FCOS , MVT::f32, Expand);
673 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
676 addLegalFPImmediate(APFloat(+0.0)); // FLD0
677 addLegalFPImmediate(APFloat(+1.0)); // FLD1
678 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
679 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
680 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
681 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
682 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
683 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
686 // We don't support FMA.
687 setOperationAction(ISD::FMA, MVT::f64, Expand);
688 setOperationAction(ISD::FMA, MVT::f32, Expand);
690 // Long double always uses X87.
691 if (!TM.Options.UseSoftFloat) {
692 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
693 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
694 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
696 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
697 addLegalFPImmediate(TmpFlt); // FLD0
699 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
702 APFloat TmpFlt2(+1.0);
703 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
705 addLegalFPImmediate(TmpFlt2); // FLD1
706 TmpFlt2.changeSign();
707 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
710 if (!TM.Options.UnsafeFPMath) {
711 setOperationAction(ISD::FSIN , MVT::f80, Expand);
712 setOperationAction(ISD::FCOS , MVT::f80, Expand);
713 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
716 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
717 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
718 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
719 setOperationAction(ISD::FRINT, MVT::f80, Expand);
720 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
721 setOperationAction(ISD::FMA, MVT::f80, Expand);
724 // Always use a library call for pow.
725 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
726 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
727 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
729 setOperationAction(ISD::FLOG, MVT::f80, Expand);
730 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
731 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
732 setOperationAction(ISD::FEXP, MVT::f80, Expand);
733 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
735 // First set operation action for all vector types to either promote
736 // (for widening) or expand (for scalarization). Then we will selectively
737 // turn on ones that can be effectively codegen'd.
738 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
739 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
740 MVT VT = (MVT::SimpleValueType)i;
741 setOperationAction(ISD::ADD , VT, Expand);
742 setOperationAction(ISD::SUB , VT, Expand);
743 setOperationAction(ISD::FADD, VT, Expand);
744 setOperationAction(ISD::FNEG, VT, Expand);
745 setOperationAction(ISD::FSUB, VT, Expand);
746 setOperationAction(ISD::MUL , VT, Expand);
747 setOperationAction(ISD::FMUL, VT, Expand);
748 setOperationAction(ISD::SDIV, VT, Expand);
749 setOperationAction(ISD::UDIV, VT, Expand);
750 setOperationAction(ISD::FDIV, VT, Expand);
751 setOperationAction(ISD::SREM, VT, Expand);
752 setOperationAction(ISD::UREM, VT, Expand);
753 setOperationAction(ISD::LOAD, VT, Expand);
754 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
756 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
757 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
758 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
759 setOperationAction(ISD::FABS, VT, Expand);
760 setOperationAction(ISD::FSIN, VT, Expand);
761 setOperationAction(ISD::FSINCOS, VT, Expand);
762 setOperationAction(ISD::FCOS, VT, Expand);
763 setOperationAction(ISD::FSINCOS, VT, Expand);
764 setOperationAction(ISD::FREM, VT, Expand);
765 setOperationAction(ISD::FMA, VT, Expand);
766 setOperationAction(ISD::FPOWI, VT, Expand);
767 setOperationAction(ISD::FSQRT, VT, Expand);
768 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
769 setOperationAction(ISD::FFLOOR, VT, Expand);
770 setOperationAction(ISD::FCEIL, VT, Expand);
771 setOperationAction(ISD::FTRUNC, VT, Expand);
772 setOperationAction(ISD::FRINT, VT, Expand);
773 setOperationAction(ISD::FNEARBYINT, VT, Expand);
774 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
775 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
776 setOperationAction(ISD::SDIVREM, VT, Expand);
777 setOperationAction(ISD::UDIVREM, VT, Expand);
778 setOperationAction(ISD::FPOW, VT, Expand);
779 setOperationAction(ISD::CTPOP, VT, Expand);
780 setOperationAction(ISD::CTTZ, VT, Expand);
781 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
782 setOperationAction(ISD::CTLZ, VT, Expand);
783 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
784 setOperationAction(ISD::SHL, VT, Expand);
785 setOperationAction(ISD::SRA, VT, Expand);
786 setOperationAction(ISD::SRL, VT, Expand);
787 setOperationAction(ISD::ROTL, VT, Expand);
788 setOperationAction(ISD::ROTR, VT, Expand);
789 setOperationAction(ISD::BSWAP, VT, Expand);
790 setOperationAction(ISD::SETCC, VT, Expand);
791 setOperationAction(ISD::FLOG, VT, Expand);
792 setOperationAction(ISD::FLOG2, VT, Expand);
793 setOperationAction(ISD::FLOG10, VT, Expand);
794 setOperationAction(ISD::FEXP, VT, Expand);
795 setOperationAction(ISD::FEXP2, VT, Expand);
796 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
797 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
798 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
799 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
800 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
801 setOperationAction(ISD::TRUNCATE, VT, Expand);
802 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
803 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
804 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
805 setOperationAction(ISD::VSELECT, VT, Expand);
806 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
807 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
808 setTruncStoreAction(VT,
809 (MVT::SimpleValueType)InnerVT, Expand);
810 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
811 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
812 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
815 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
816 // with -msoft-float, disable use of MMX as well.
817 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
818 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
819 // No operations on x86mmx supported, everything uses intrinsics.
822 // MMX-sized vectors (other than x86mmx) are expected to be expanded
823 // into smaller operations.
824 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
825 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
826 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
827 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
828 setOperationAction(ISD::AND, MVT::v8i8, Expand);
829 setOperationAction(ISD::AND, MVT::v4i16, Expand);
830 setOperationAction(ISD::AND, MVT::v2i32, Expand);
831 setOperationAction(ISD::AND, MVT::v1i64, Expand);
832 setOperationAction(ISD::OR, MVT::v8i8, Expand);
833 setOperationAction(ISD::OR, MVT::v4i16, Expand);
834 setOperationAction(ISD::OR, MVT::v2i32, Expand);
835 setOperationAction(ISD::OR, MVT::v1i64, Expand);
836 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
837 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
838 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
839 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
840 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
841 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
842 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
843 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
845 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
846 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
847 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
848 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
849 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
850 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
851 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
852 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
854 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
855 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
857 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
858 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
859 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
860 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
861 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
862 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
863 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
864 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
865 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
866 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
867 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
868 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
871 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
872 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
874 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
875 // registers cannot be used even for integer operations.
876 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
877 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
878 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
879 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
881 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
882 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
883 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
884 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
885 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
886 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
887 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
888 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
889 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
890 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
891 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
892 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
893 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
894 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
895 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
896 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
897 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
898 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
900 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
901 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
902 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
903 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
905 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
906 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
911 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
912 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
913 MVT VT = (MVT::SimpleValueType)i;
914 // Do not attempt to custom lower non-power-of-2 vectors
915 if (!isPowerOf2_32(VT.getVectorNumElements()))
917 // Do not attempt to custom lower non-128-bit vectors
918 if (!VT.is128BitVector())
920 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
925 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
926 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
927 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
928 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
930 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
932 if (Subtarget->is64Bit()) {
933 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
934 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
937 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
938 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
939 MVT VT = (MVT::SimpleValueType)i;
941 // Do not attempt to promote non-128-bit vectors
942 if (!VT.is128BitVector())
945 setOperationAction(ISD::AND, VT, Promote);
946 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
947 setOperationAction(ISD::OR, VT, Promote);
948 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
949 setOperationAction(ISD::XOR, VT, Promote);
950 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
951 setOperationAction(ISD::LOAD, VT, Promote);
952 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
953 setOperationAction(ISD::SELECT, VT, Promote);
954 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
957 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
959 // Custom lower v2i64 and v2f64 selects.
960 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
961 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
962 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
963 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
965 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
966 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
968 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
969 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
970 // As there is no 64-bit GPR available, we need build a special custom
971 // sequence to convert from v2i32 to v2f32.
972 if (!Subtarget->is64Bit())
973 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
975 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
976 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
978 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
981 if (Subtarget->hasSSE41()) {
982 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
983 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
984 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
985 setOperationAction(ISD::FRINT, MVT::f32, Legal);
986 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
987 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
988 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
989 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
990 setOperationAction(ISD::FRINT, MVT::f64, Legal);
991 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
993 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
994 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
995 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
996 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
997 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
998 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
999 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1000 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1001 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1002 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1004 // FIXME: Do we need to handle scalar-to-vector here?
1005 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1007 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
1008 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
1009 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1010 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
1011 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1013 // i8 and i16 vectors are custom , because the source register and source
1014 // source memory operand types are not the same width. f32 vectors are
1015 // custom since the immediate controlling the insert encodes additional
1017 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1019 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1020 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1022 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1024 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1025 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1027 // FIXME: these should be Legal but thats only for the case where
1028 // the index is constant. For now custom expand to deal with that.
1029 if (Subtarget->is64Bit()) {
1030 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1031 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1035 if (Subtarget->hasSSE2()) {
1036 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1037 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1039 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1040 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1042 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1043 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1045 if (Subtarget->hasInt256()) {
1046 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1047 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1049 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1050 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1052 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1054 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1055 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1057 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1058 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1060 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1062 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1063 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1066 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1067 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1068 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1069 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1070 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1071 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1072 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1074 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1075 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1076 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1078 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1079 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1080 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1081 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1082 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1083 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1084 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1085 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1086 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1087 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1088 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1089 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1091 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1092 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1093 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1094 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1095 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1101 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1102 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1104 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1105 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1107 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1109 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1110 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1111 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1113 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1114 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1115 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1117 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1119 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1120 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1122 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1123 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1125 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1126 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1128 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1130 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1131 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1132 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1133 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1135 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1136 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1137 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1139 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1140 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1141 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1142 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1144 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1145 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1146 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1147 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1148 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1149 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1151 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1152 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1155 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1156 setOperationAction(ISD::FMA, MVT::f32, Legal);
1157 setOperationAction(ISD::FMA, MVT::f64, Legal);
1160 if (Subtarget->hasInt256()) {
1161 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1162 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1163 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1164 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1167 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1168 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1169 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1171 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1172 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1173 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1174 // Don't lower v32i8 because there is no 128-bit byte mul
1176 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1178 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1179 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1181 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1182 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1184 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1186 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1188 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1189 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1190 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1191 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1194 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1195 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1196 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1198 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1199 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1200 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1201 // Don't lower v32i8 because there is no 128-bit byte mul
1203 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1204 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1206 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1207 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1209 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1212 // Custom lower several nodes for 256-bit types.
1213 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1214 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1215 MVT VT = (MVT::SimpleValueType)i;
1217 // Extract subvector is special because the value type
1218 // (result) is 128-bit but the source is 256-bit wide.
1219 if (VT.is128BitVector())
1220 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1222 // Do not attempt to custom lower other non-256-bit vectors
1223 if (!VT.is256BitVector())
1226 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1227 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1228 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1229 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1230 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1231 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1232 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1235 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1236 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1237 MVT VT = (MVT::SimpleValueType)i;
1239 // Do not attempt to promote non-256-bit vectors
1240 if (!VT.is256BitVector())
1243 setOperationAction(ISD::AND, VT, Promote);
1244 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1245 setOperationAction(ISD::OR, VT, Promote);
1246 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1247 setOperationAction(ISD::XOR, VT, Promote);
1248 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1249 setOperationAction(ISD::LOAD, VT, Promote);
1250 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1251 setOperationAction(ISD::SELECT, VT, Promote);
1252 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1256 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1257 // of this type with custom code.
1258 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1259 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1260 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1264 // We want to custom lower some of our intrinsics.
1265 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1266 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1268 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1269 // handle type legalization for these operations here.
1271 // FIXME: We really should do custom legalization for addition and
1272 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1273 // than generic legalization for 64-bit multiplication-with-overflow, though.
1274 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1275 // Add/Sub/Mul with overflow operations are custom lowered.
1277 setOperationAction(ISD::SADDO, VT, Custom);
1278 setOperationAction(ISD::UADDO, VT, Custom);
1279 setOperationAction(ISD::SSUBO, VT, Custom);
1280 setOperationAction(ISD::USUBO, VT, Custom);
1281 setOperationAction(ISD::SMULO, VT, Custom);
1282 setOperationAction(ISD::UMULO, VT, Custom);
1285 // There are no 8-bit 3-address imul/mul instructions
1286 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1287 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1289 if (!Subtarget->is64Bit()) {
1290 // These libcalls are not available in 32-bit.
1291 setLibcallName(RTLIB::SHL_I128, 0);
1292 setLibcallName(RTLIB::SRL_I128, 0);
1293 setLibcallName(RTLIB::SRA_I128, 0);
1296 // Combine sin / cos into one node or libcall if possible.
1297 if (Subtarget->hasSinCos()) {
1298 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1299 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1300 if (Subtarget->isTargetDarwin()) {
1301 // For MacOSX, we don't want to the normal expansion of a libcall to
1302 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1304 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1305 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1309 // We have target-specific dag combine patterns for the following nodes:
1310 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1311 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1312 setTargetDAGCombine(ISD::VSELECT);
1313 setTargetDAGCombine(ISD::SELECT);
1314 setTargetDAGCombine(ISD::SHL);
1315 setTargetDAGCombine(ISD::SRA);
1316 setTargetDAGCombine(ISD::SRL);
1317 setTargetDAGCombine(ISD::OR);
1318 setTargetDAGCombine(ISD::AND);
1319 setTargetDAGCombine(ISD::ADD);
1320 setTargetDAGCombine(ISD::FADD);
1321 setTargetDAGCombine(ISD::FSUB);
1322 setTargetDAGCombine(ISD::FMA);
1323 setTargetDAGCombine(ISD::SUB);
1324 setTargetDAGCombine(ISD::LOAD);
1325 setTargetDAGCombine(ISD::STORE);
1326 setTargetDAGCombine(ISD::ZERO_EXTEND);
1327 setTargetDAGCombine(ISD::ANY_EXTEND);
1328 setTargetDAGCombine(ISD::SIGN_EXTEND);
1329 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1330 setTargetDAGCombine(ISD::TRUNCATE);
1331 setTargetDAGCombine(ISD::SINT_TO_FP);
1332 setTargetDAGCombine(ISD::SETCC);
1333 if (Subtarget->is64Bit())
1334 setTargetDAGCombine(ISD::MUL);
1335 setTargetDAGCombine(ISD::XOR);
1337 computeRegisterProperties();
1339 // On Darwin, -Os means optimize for size without hurting performance,
1340 // do not reduce the limit.
1341 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1342 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1343 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1344 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1345 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1346 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1347 setPrefLoopAlignment(4); // 2^4 bytes.
1348 BenefitFromCodePlacementOpt = true;
1350 // Predictable cmov don't hurt on atom because it's in-order.
1351 PredictableSelectIsExpensive = !Subtarget->isAtom();
1353 setPrefFunctionAlignment(4); // 2^4 bytes.
1356 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1357 if (!VT.isVector()) return MVT::i8;
1358 return VT.changeVectorElementTypeToInteger();
1361 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1362 /// the desired ByVal argument alignment.
1363 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1366 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1367 if (VTy->getBitWidth() == 128)
1369 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1370 unsigned EltAlign = 0;
1371 getMaxByValAlign(ATy->getElementType(), EltAlign);
1372 if (EltAlign > MaxAlign)
1373 MaxAlign = EltAlign;
1374 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1375 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1376 unsigned EltAlign = 0;
1377 getMaxByValAlign(STy->getElementType(i), EltAlign);
1378 if (EltAlign > MaxAlign)
1379 MaxAlign = EltAlign;
1386 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1387 /// function arguments in the caller parameter area. For X86, aggregates
1388 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1389 /// are at 4-byte boundaries.
1390 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1391 if (Subtarget->is64Bit()) {
1392 // Max of 8 and alignment of type.
1393 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1400 if (Subtarget->hasSSE1())
1401 getMaxByValAlign(Ty, Align);
1405 /// getOptimalMemOpType - Returns the target specific optimal type for load
1406 /// and store operations as a result of memset, memcpy, and memmove
1407 /// lowering. If DstAlign is zero that means it's safe to destination
1408 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1409 /// means there isn't a need to check it against alignment requirement,
1410 /// probably because the source does not need to be loaded. If 'IsMemset' is
1411 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1412 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1413 /// source is constant so it does not need to be loaded.
1414 /// It returns EVT::Other if the type should be determined using generic
1415 /// target-independent logic.
1417 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1418 unsigned DstAlign, unsigned SrcAlign,
1419 bool IsMemset, bool ZeroMemset,
1421 MachineFunction &MF) const {
1422 const Function *F = MF.getFunction();
1423 if ((!IsMemset || ZeroMemset) &&
1424 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1425 Attribute::NoImplicitFloat)) {
1427 (Subtarget->isUnalignedMemAccessFast() ||
1428 ((DstAlign == 0 || DstAlign >= 16) &&
1429 (SrcAlign == 0 || SrcAlign >= 16)))) {
1431 if (Subtarget->hasInt256())
1433 if (Subtarget->hasFp256())
1436 if (Subtarget->hasSSE2())
1438 if (Subtarget->hasSSE1())
1440 } else if (!MemcpyStrSrc && Size >= 8 &&
1441 !Subtarget->is64Bit() &&
1442 Subtarget->hasSSE2()) {
1443 // Do not use f64 to lower memcpy if source is string constant. It's
1444 // better to use i32 to avoid the loads.
1448 if (Subtarget->is64Bit() && Size >= 8)
1453 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1455 return X86ScalarSSEf32;
1456 else if (VT == MVT::f64)
1457 return X86ScalarSSEf64;
1462 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1464 *Fast = Subtarget->isUnalignedMemAccessFast();
1468 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1469 /// current function. The returned value is a member of the
1470 /// MachineJumpTableInfo::JTEntryKind enum.
1471 unsigned X86TargetLowering::getJumpTableEncoding() const {
1472 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1474 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1475 Subtarget->isPICStyleGOT())
1476 return MachineJumpTableInfo::EK_Custom32;
1478 // Otherwise, use the normal jump table encoding heuristics.
1479 return TargetLowering::getJumpTableEncoding();
1483 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1484 const MachineBasicBlock *MBB,
1485 unsigned uid,MCContext &Ctx) const{
1486 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1487 Subtarget->isPICStyleGOT());
1488 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1490 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1491 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1494 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1496 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1497 SelectionDAG &DAG) const {
1498 if (!Subtarget->is64Bit())
1499 // This doesn't have DebugLoc associated with it, but is not really the
1500 // same as a Register.
1501 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1505 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1506 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1508 const MCExpr *X86TargetLowering::
1509 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1510 MCContext &Ctx) const {
1511 // X86-64 uses RIP relative addressing based on the jump table label.
1512 if (Subtarget->isPICStyleRIPRel())
1513 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1515 // Otherwise, the reference is relative to the PIC base.
1516 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1519 // FIXME: Why this routine is here? Move to RegInfo!
1520 std::pair<const TargetRegisterClass*, uint8_t>
1521 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1522 const TargetRegisterClass *RRC = 0;
1524 switch (VT.SimpleTy) {
1526 return TargetLowering::findRepresentativeClass(VT);
1527 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1528 RRC = Subtarget->is64Bit() ?
1529 (const TargetRegisterClass*)&X86::GR64RegClass :
1530 (const TargetRegisterClass*)&X86::GR32RegClass;
1533 RRC = &X86::VR64RegClass;
1535 case MVT::f32: case MVT::f64:
1536 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1537 case MVT::v4f32: case MVT::v2f64:
1538 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1540 RRC = &X86::VR128RegClass;
1543 return std::make_pair(RRC, Cost);
1546 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1547 unsigned &Offset) const {
1548 if (!Subtarget->isTargetLinux())
1551 if (Subtarget->is64Bit()) {
1552 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1554 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1566 //===----------------------------------------------------------------------===//
1567 // Return Value Calling Convention Implementation
1568 //===----------------------------------------------------------------------===//
1570 #include "X86GenCallingConv.inc"
1573 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1574 MachineFunction &MF, bool isVarArg,
1575 const SmallVectorImpl<ISD::OutputArg> &Outs,
1576 LLVMContext &Context) const {
1577 SmallVector<CCValAssign, 16> RVLocs;
1578 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1580 return CCInfo.CheckReturn(Outs, RetCC_X86);
1584 X86TargetLowering::LowerReturn(SDValue Chain,
1585 CallingConv::ID CallConv, bool isVarArg,
1586 const SmallVectorImpl<ISD::OutputArg> &Outs,
1587 const SmallVectorImpl<SDValue> &OutVals,
1588 DebugLoc dl, SelectionDAG &DAG) const {
1589 MachineFunction &MF = DAG.getMachineFunction();
1590 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1592 SmallVector<CCValAssign, 16> RVLocs;
1593 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1594 RVLocs, *DAG.getContext());
1595 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1598 SmallVector<SDValue, 6> RetOps;
1599 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1600 // Operand #1 = Bytes To Pop
1601 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1604 // Copy the result values into the output registers.
1605 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1606 CCValAssign &VA = RVLocs[i];
1607 assert(VA.isRegLoc() && "Can only return in registers!");
1608 SDValue ValToCopy = OutVals[i];
1609 EVT ValVT = ValToCopy.getValueType();
1611 // Promote values to the appropriate types
1612 if (VA.getLocInfo() == CCValAssign::SExt)
1613 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1614 else if (VA.getLocInfo() == CCValAssign::ZExt)
1615 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1616 else if (VA.getLocInfo() == CCValAssign::AExt)
1617 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1618 else if (VA.getLocInfo() == CCValAssign::BCvt)
1619 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1621 // If this is x86-64, and we disabled SSE, we can't return FP values,
1622 // or SSE or MMX vectors.
1623 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1624 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1625 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1626 report_fatal_error("SSE register return with SSE disabled");
1628 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1629 // llvm-gcc has never done it right and no one has noticed, so this
1630 // should be OK for now.
1631 if (ValVT == MVT::f64 &&
1632 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1633 report_fatal_error("SSE2 register return with SSE2 disabled");
1635 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1636 // the RET instruction and handled by the FP Stackifier.
1637 if (VA.getLocReg() == X86::ST0 ||
1638 VA.getLocReg() == X86::ST1) {
1639 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1640 // change the value to the FP stack register class.
1641 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1642 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1643 RetOps.push_back(ValToCopy);
1644 // Don't emit a copytoreg.
1648 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1649 // which is returned in RAX / RDX.
1650 if (Subtarget->is64Bit()) {
1651 if (ValVT == MVT::x86mmx) {
1652 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1653 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1654 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1656 // If we don't have SSE2 available, convert to v4f32 so the generated
1657 // register is legal.
1658 if (!Subtarget->hasSSE2())
1659 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1664 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1665 Flag = Chain.getValue(1);
1666 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1669 // The x86-64 ABIs require that for returning structs by value we copy
1670 // the sret argument into %rax/%eax (depending on ABI) for the return.
1671 // We saved the argument into a virtual register in the entry block,
1672 // so now we copy the value out and into %rax/%eax.
1673 if (Subtarget->is64Bit() &&
1674 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1675 MachineFunction &MF = DAG.getMachineFunction();
1676 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1677 unsigned Reg = FuncInfo->getSRetReturnReg();
1679 "SRetReturnReg should have been set in LowerFormalArguments().");
1680 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1682 unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1683 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1684 Flag = Chain.getValue(1);
1686 // RAX/EAX now acts like a return value.
1687 RetOps.push_back(DAG.getRegister(RetValReg, MVT::i64));
1690 RetOps[0] = Chain; // Update chain.
1692 // Add the flag if we have it.
1694 RetOps.push_back(Flag);
1696 return DAG.getNode(X86ISD::RET_FLAG, dl,
1697 MVT::Other, &RetOps[0], RetOps.size());
1700 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1701 if (N->getNumValues() != 1)
1703 if (!N->hasNUsesOfValue(1, 0))
1706 SDValue TCChain = Chain;
1707 SDNode *Copy = *N->use_begin();
1708 if (Copy->getOpcode() == ISD::CopyToReg) {
1709 // If the copy has a glue operand, we conservatively assume it isn't safe to
1710 // perform a tail call.
1711 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1713 TCChain = Copy->getOperand(0);
1714 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1717 bool HasRet = false;
1718 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1720 if (UI->getOpcode() != X86ISD::RET_FLAG)
1733 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1734 ISD::NodeType ExtendKind) const {
1736 // TODO: Is this also valid on 32-bit?
1737 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1738 ReturnMVT = MVT::i8;
1740 ReturnMVT = MVT::i32;
1742 MVT MinVT = getRegisterType(ReturnMVT);
1743 return VT.bitsLT(MinVT) ? MinVT : VT;
1746 /// LowerCallResult - Lower the result values of a call into the
1747 /// appropriate copies out of appropriate physical registers.
1750 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1751 CallingConv::ID CallConv, bool isVarArg,
1752 const SmallVectorImpl<ISD::InputArg> &Ins,
1753 DebugLoc dl, SelectionDAG &DAG,
1754 SmallVectorImpl<SDValue> &InVals) const {
1756 // Assign locations to each value returned by this call.
1757 SmallVector<CCValAssign, 16> RVLocs;
1758 bool Is64Bit = Subtarget->is64Bit();
1759 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1760 getTargetMachine(), RVLocs, *DAG.getContext());
1761 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1763 // Copy all of the result registers out of their specified physreg.
1764 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1765 CCValAssign &VA = RVLocs[i];
1766 EVT CopyVT = VA.getValVT();
1768 // If this is x86-64, and we disabled SSE, we can't return FP values
1769 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1770 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1771 report_fatal_error("SSE register return with SSE disabled");
1776 // If this is a call to a function that returns an fp value on the floating
1777 // point stack, we must guarantee the value is popped from the stack, so
1778 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1779 // if the return value is not used. We use the FpPOP_RETVAL instruction
1781 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1782 // If we prefer to use the value in xmm registers, copy it out as f80 and
1783 // use a truncate to move it from fp stack reg to xmm reg.
1784 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1785 SDValue Ops[] = { Chain, InFlag };
1786 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1787 MVT::Other, MVT::Glue, Ops, 2), 1);
1788 Val = Chain.getValue(0);
1790 // Round the f80 to the right size, which also moves it to the appropriate
1792 if (CopyVT != VA.getValVT())
1793 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1794 // This truncation won't change the value.
1795 DAG.getIntPtrConstant(1));
1797 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1798 CopyVT, InFlag).getValue(1);
1799 Val = Chain.getValue(0);
1801 InFlag = Chain.getValue(2);
1802 InVals.push_back(Val);
1808 //===----------------------------------------------------------------------===//
1809 // C & StdCall & Fast Calling Convention implementation
1810 //===----------------------------------------------------------------------===//
1811 // StdCall calling convention seems to be standard for many Windows' API
1812 // routines and around. It differs from C calling convention just a little:
1813 // callee should clean up the stack, not caller. Symbols should be also
1814 // decorated in some fancy way :) It doesn't support any vector arguments.
1815 // For info on fast calling convention see Fast Calling Convention (tail call)
1816 // implementation LowerX86_32FastCCCallTo.
1818 /// CallIsStructReturn - Determines whether a call uses struct return
1820 enum StructReturnType {
1825 static StructReturnType
1826 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1828 return NotStructReturn;
1830 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1831 if (!Flags.isSRet())
1832 return NotStructReturn;
1833 if (Flags.isInReg())
1834 return RegStructReturn;
1835 return StackStructReturn;
1838 /// ArgsAreStructReturn - Determines whether a function uses struct
1839 /// return semantics.
1840 static StructReturnType
1841 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1843 return NotStructReturn;
1845 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1846 if (!Flags.isSRet())
1847 return NotStructReturn;
1848 if (Flags.isInReg())
1849 return RegStructReturn;
1850 return StackStructReturn;
1853 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1854 /// by "Src" to address "Dst" with size and alignment information specified by
1855 /// the specific parameter attribute. The copy will be passed as a byval
1856 /// function parameter.
1858 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1859 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1861 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1863 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1864 /*isVolatile*/false, /*AlwaysInline=*/true,
1865 MachinePointerInfo(), MachinePointerInfo());
1868 /// IsTailCallConvention - Return true if the calling convention is one that
1869 /// supports tail call optimization.
1870 static bool IsTailCallConvention(CallingConv::ID CC) {
1871 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1872 CC == CallingConv::HiPE);
1875 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1876 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1880 CallingConv::ID CalleeCC = CS.getCallingConv();
1881 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1887 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1888 /// a tailcall target by changing its ABI.
1889 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1890 bool GuaranteedTailCallOpt) {
1891 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1895 X86TargetLowering::LowerMemArgument(SDValue Chain,
1896 CallingConv::ID CallConv,
1897 const SmallVectorImpl<ISD::InputArg> &Ins,
1898 DebugLoc dl, SelectionDAG &DAG,
1899 const CCValAssign &VA,
1900 MachineFrameInfo *MFI,
1902 // Create the nodes corresponding to a load from this parameter slot.
1903 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1904 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1905 getTargetMachine().Options.GuaranteedTailCallOpt);
1906 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1909 // If value is passed by pointer we have address passed instead of the value
1911 if (VA.getLocInfo() == CCValAssign::Indirect)
1912 ValVT = VA.getLocVT();
1914 ValVT = VA.getValVT();
1916 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1917 // changed with more analysis.
1918 // In case of tail call optimization mark all arguments mutable. Since they
1919 // could be overwritten by lowering of arguments in case of a tail call.
1920 if (Flags.isByVal()) {
1921 unsigned Bytes = Flags.getByValSize();
1922 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1923 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1924 return DAG.getFrameIndex(FI, getPointerTy());
1926 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1927 VA.getLocMemOffset(), isImmutable);
1928 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1929 return DAG.getLoad(ValVT, dl, Chain, FIN,
1930 MachinePointerInfo::getFixedStack(FI),
1931 false, false, false, 0);
1936 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1937 CallingConv::ID CallConv,
1939 const SmallVectorImpl<ISD::InputArg> &Ins,
1942 SmallVectorImpl<SDValue> &InVals)
1944 MachineFunction &MF = DAG.getMachineFunction();
1945 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947 const Function* Fn = MF.getFunction();
1948 if (Fn->hasExternalLinkage() &&
1949 Subtarget->isTargetCygMing() &&
1950 Fn->getName() == "main")
1951 FuncInfo->setForceFramePointer(true);
1953 MachineFrameInfo *MFI = MF.getFrameInfo();
1954 bool Is64Bit = Subtarget->is64Bit();
1955 bool IsWindows = Subtarget->isTargetWindows();
1956 bool IsWin64 = Subtarget->isTargetWin64();
1958 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1959 "Var args not supported with calling convention fastcc, ghc or hipe");
1961 // Assign locations to all of the incoming arguments.
1962 SmallVector<CCValAssign, 16> ArgLocs;
1963 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1964 ArgLocs, *DAG.getContext());
1966 // Allocate shadow area for Win64
1968 CCInfo.AllocateStack(32, 8);
1971 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1973 unsigned LastVal = ~0U;
1975 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1976 CCValAssign &VA = ArgLocs[i];
1977 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1979 assert(VA.getValNo() != LastVal &&
1980 "Don't support value assigned to multiple locs yet");
1982 LastVal = VA.getValNo();
1984 if (VA.isRegLoc()) {
1985 EVT RegVT = VA.getLocVT();
1986 const TargetRegisterClass *RC;
1987 if (RegVT == MVT::i32)
1988 RC = &X86::GR32RegClass;
1989 else if (Is64Bit && RegVT == MVT::i64)
1990 RC = &X86::GR64RegClass;
1991 else if (RegVT == MVT::f32)
1992 RC = &X86::FR32RegClass;
1993 else if (RegVT == MVT::f64)
1994 RC = &X86::FR64RegClass;
1995 else if (RegVT.is256BitVector())
1996 RC = &X86::VR256RegClass;
1997 else if (RegVT.is128BitVector())
1998 RC = &X86::VR128RegClass;
1999 else if (RegVT == MVT::x86mmx)
2000 RC = &X86::VR64RegClass;
2002 llvm_unreachable("Unknown argument type!");
2004 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2005 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2007 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2008 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2010 if (VA.getLocInfo() == CCValAssign::SExt)
2011 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2012 DAG.getValueType(VA.getValVT()));
2013 else if (VA.getLocInfo() == CCValAssign::ZExt)
2014 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2015 DAG.getValueType(VA.getValVT()));
2016 else if (VA.getLocInfo() == CCValAssign::BCvt)
2017 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2019 if (VA.isExtInLoc()) {
2020 // Handle MMX values passed in XMM regs.
2021 if (RegVT.isVector())
2022 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2024 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2027 assert(VA.isMemLoc());
2028 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2031 // If value is passed via pointer - do a load.
2032 if (VA.getLocInfo() == CCValAssign::Indirect)
2033 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2034 MachinePointerInfo(), false, false, false, 0);
2036 InVals.push_back(ArgValue);
2039 // The x86-64 ABIs require that for returning structs by value we copy
2040 // the sret argument into %rax/%eax (depending on ABI) for the return.
2041 // Save the argument into a virtual register so that we can access it
2042 // from the return points.
2043 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2044 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2045 unsigned Reg = FuncInfo->getSRetReturnReg();
2047 MVT PtrTy = getPointerTy();
2048 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2049 FuncInfo->setSRetReturnReg(Reg);
2051 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2052 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2055 unsigned StackSize = CCInfo.getNextStackOffset();
2056 // Align stack specially for tail calls.
2057 if (FuncIsMadeTailCallSafe(CallConv,
2058 MF.getTarget().Options.GuaranteedTailCallOpt))
2059 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2061 // If the function takes variable number of arguments, make a frame index for
2062 // the start of the first vararg value... for expansion of llvm.va_start.
2064 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2065 CallConv != CallingConv::X86_ThisCall)) {
2066 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2069 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2071 // FIXME: We should really autogenerate these arrays
2072 static const uint16_t GPR64ArgRegsWin64[] = {
2073 X86::RCX, X86::RDX, X86::R8, X86::R9
2075 static const uint16_t GPR64ArgRegs64Bit[] = {
2076 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2078 static const uint16_t XMMArgRegs64Bit[] = {
2079 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2080 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2082 const uint16_t *GPR64ArgRegs;
2083 unsigned NumXMMRegs = 0;
2086 // The XMM registers which might contain var arg parameters are shadowed
2087 // in their paired GPR. So we only need to save the GPR to their home
2089 TotalNumIntRegs = 4;
2090 GPR64ArgRegs = GPR64ArgRegsWin64;
2092 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2093 GPR64ArgRegs = GPR64ArgRegs64Bit;
2095 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2098 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2101 bool NoImplicitFloatOps = Fn->getAttributes().
2102 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2103 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2104 "SSE register cannot be used when SSE is disabled!");
2105 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2106 NoImplicitFloatOps) &&
2107 "SSE register cannot be used when SSE is disabled!");
2108 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2109 !Subtarget->hasSSE1())
2110 // Kernel mode asks for SSE to be disabled, so don't push them
2112 TotalNumXMMRegs = 0;
2115 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2116 // Get to the caller-allocated home save location. Add 8 to account
2117 // for the return address.
2118 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2119 FuncInfo->setRegSaveFrameIndex(
2120 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2121 // Fixup to set vararg frame on shadow area (4 x i64).
2123 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2125 // For X86-64, if there are vararg parameters that are passed via
2126 // registers, then we must store them to their spots on the stack so
2127 // they may be loaded by deferencing the result of va_next.
2128 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2129 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2130 FuncInfo->setRegSaveFrameIndex(
2131 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2135 // Store the integer parameter registers.
2136 SmallVector<SDValue, 8> MemOps;
2137 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2139 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2140 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2141 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2142 DAG.getIntPtrConstant(Offset));
2143 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2144 &X86::GR64RegClass);
2145 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2147 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2148 MachinePointerInfo::getFixedStack(
2149 FuncInfo->getRegSaveFrameIndex(), Offset),
2151 MemOps.push_back(Store);
2155 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2156 // Now store the XMM (fp + vector) parameter registers.
2157 SmallVector<SDValue, 11> SaveXMMOps;
2158 SaveXMMOps.push_back(Chain);
2160 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2161 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2162 SaveXMMOps.push_back(ALVal);
2164 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2165 FuncInfo->getRegSaveFrameIndex()));
2166 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2167 FuncInfo->getVarArgsFPOffset()));
2169 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2170 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2171 &X86::VR128RegClass);
2172 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2173 SaveXMMOps.push_back(Val);
2175 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2177 &SaveXMMOps[0], SaveXMMOps.size()));
2180 if (!MemOps.empty())
2181 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2182 &MemOps[0], MemOps.size());
2186 // Some CCs need callee pop.
2187 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2188 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2189 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2191 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2192 // If this is an sret function, the return should pop the hidden pointer.
2193 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2194 argsAreStructReturn(Ins) == StackStructReturn)
2195 FuncInfo->setBytesToPopOnReturn(4);
2199 // RegSaveFrameIndex is X86-64 only.
2200 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2201 if (CallConv == CallingConv::X86_FastCall ||
2202 CallConv == CallingConv::X86_ThisCall)
2203 // fastcc functions can't have varargs.
2204 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2207 FuncInfo->setArgumentStackSize(StackSize);
2213 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2214 SDValue StackPtr, SDValue Arg,
2215 DebugLoc dl, SelectionDAG &DAG,
2216 const CCValAssign &VA,
2217 ISD::ArgFlagsTy Flags) const {
2218 unsigned LocMemOffset = VA.getLocMemOffset();
2219 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2220 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2221 if (Flags.isByVal())
2222 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2224 return DAG.getStore(Chain, dl, Arg, PtrOff,
2225 MachinePointerInfo::getStack(LocMemOffset),
2229 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2230 /// optimization is performed and it is required.
2232 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2233 SDValue &OutRetAddr, SDValue Chain,
2234 bool IsTailCall, bool Is64Bit,
2235 int FPDiff, DebugLoc dl) const {
2236 // Adjust the Return address stack slot.
2237 EVT VT = getPointerTy();
2238 OutRetAddr = getReturnAddressFrameIndex(DAG);
2240 // Load the "old" Return address.
2241 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2242 false, false, false, 0);
2243 return SDValue(OutRetAddr.getNode(), 1);
2246 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2247 /// optimization is performed and it is required (FPDiff!=0).
2249 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2250 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2251 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2252 // Store the return address to the appropriate stack slot.
2253 if (!FPDiff) return Chain;
2254 // Calculate the new stack slot for the return address.
2255 int NewReturnAddrFI =
2256 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2257 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2258 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2259 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2265 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2266 SmallVectorImpl<SDValue> &InVals) const {
2267 SelectionDAG &DAG = CLI.DAG;
2268 DebugLoc &dl = CLI.DL;
2269 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2270 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2271 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2272 SDValue Chain = CLI.Chain;
2273 SDValue Callee = CLI.Callee;
2274 CallingConv::ID CallConv = CLI.CallConv;
2275 bool &isTailCall = CLI.IsTailCall;
2276 bool isVarArg = CLI.IsVarArg;
2278 MachineFunction &MF = DAG.getMachineFunction();
2279 bool Is64Bit = Subtarget->is64Bit();
2280 bool IsWin64 = Subtarget->isTargetWin64();
2281 bool IsWindows = Subtarget->isTargetWindows();
2282 StructReturnType SR = callIsStructReturn(Outs);
2283 bool IsSibcall = false;
2285 if (MF.getTarget().Options.DisableTailCalls)
2289 // Check if it's really possible to do a tail call.
2290 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2291 isVarArg, SR != NotStructReturn,
2292 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2293 Outs, OutVals, Ins, DAG);
2295 // Sibcalls are automatically detected tailcalls which do not require
2297 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2304 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2305 "Var args not supported with calling convention fastcc, ghc or hipe");
2307 // Analyze operands of the call, assigning locations to each operand.
2308 SmallVector<CCValAssign, 16> ArgLocs;
2309 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2310 ArgLocs, *DAG.getContext());
2312 // Allocate shadow area for Win64
2314 CCInfo.AllocateStack(32, 8);
2317 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2319 // Get a count of how many bytes are to be pushed on the stack.
2320 unsigned NumBytes = CCInfo.getNextStackOffset();
2322 // This is a sibcall. The memory operands are available in caller's
2323 // own caller's stack.
2325 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2326 IsTailCallConvention(CallConv))
2327 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2330 if (isTailCall && !IsSibcall) {
2331 // Lower arguments at fp - stackoffset + fpdiff.
2332 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2333 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2335 FPDiff = NumBytesCallerPushed - NumBytes;
2337 // Set the delta of movement of the returnaddr stackslot.
2338 // But only set if delta is greater than previous delta.
2339 if (FPDiff < X86Info->getTCReturnAddrDelta())
2340 X86Info->setTCReturnAddrDelta(FPDiff);
2344 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2346 SDValue RetAddrFrIdx;
2347 // Load return address for tail calls.
2348 if (isTailCall && FPDiff)
2349 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2350 Is64Bit, FPDiff, dl);
2352 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2353 SmallVector<SDValue, 8> MemOpChains;
2356 // Walk the register/memloc assignments, inserting copies/loads. In the case
2357 // of tail call optimization arguments are handle later.
2358 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2359 CCValAssign &VA = ArgLocs[i];
2360 EVT RegVT = VA.getLocVT();
2361 SDValue Arg = OutVals[i];
2362 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2363 bool isByVal = Flags.isByVal();
2365 // Promote the value if needed.
2366 switch (VA.getLocInfo()) {
2367 default: llvm_unreachable("Unknown loc info!");
2368 case CCValAssign::Full: break;
2369 case CCValAssign::SExt:
2370 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2372 case CCValAssign::ZExt:
2373 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2375 case CCValAssign::AExt:
2376 if (RegVT.is128BitVector()) {
2377 // Special case: passing MMX values in XMM registers.
2378 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2379 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2380 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2382 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2384 case CCValAssign::BCvt:
2385 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2387 case CCValAssign::Indirect: {
2388 // Store the argument.
2389 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2390 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2391 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2392 MachinePointerInfo::getFixedStack(FI),
2399 if (VA.isRegLoc()) {
2400 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2401 if (isVarArg && IsWin64) {
2402 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2403 // shadow reg if callee is a varargs function.
2404 unsigned ShadowReg = 0;
2405 switch (VA.getLocReg()) {
2406 case X86::XMM0: ShadowReg = X86::RCX; break;
2407 case X86::XMM1: ShadowReg = X86::RDX; break;
2408 case X86::XMM2: ShadowReg = X86::R8; break;
2409 case X86::XMM3: ShadowReg = X86::R9; break;
2412 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2414 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2415 assert(VA.isMemLoc());
2416 if (StackPtr.getNode() == 0)
2417 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2419 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2420 dl, DAG, VA, Flags));
2424 if (!MemOpChains.empty())
2425 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2426 &MemOpChains[0], MemOpChains.size());
2428 if (Subtarget->isPICStyleGOT()) {
2429 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2432 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2433 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2435 // If we are tail calling and generating PIC/GOT style code load the
2436 // address of the callee into ECX. The value in ecx is used as target of
2437 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2438 // for tail calls on PIC/GOT architectures. Normally we would just put the
2439 // address of GOT into ebx and then call target@PLT. But for tail calls
2440 // ebx would be restored (since ebx is callee saved) before jumping to the
2443 // Note: The actual moving to ECX is done further down.
2444 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2445 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2446 !G->getGlobal()->hasProtectedVisibility())
2447 Callee = LowerGlobalAddress(Callee, DAG);
2448 else if (isa<ExternalSymbolSDNode>(Callee))
2449 Callee = LowerExternalSymbol(Callee, DAG);
2453 if (Is64Bit && isVarArg && !IsWin64) {
2454 // From AMD64 ABI document:
2455 // For calls that may call functions that use varargs or stdargs
2456 // (prototype-less calls or calls to functions containing ellipsis (...) in
2457 // the declaration) %al is used as hidden argument to specify the number
2458 // of SSE registers used. The contents of %al do not need to match exactly
2459 // the number of registers, but must be an ubound on the number of SSE
2460 // registers used and is in the range 0 - 8 inclusive.
2462 // Count the number of XMM registers allocated.
2463 static const uint16_t XMMArgRegs[] = {
2464 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2465 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2467 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2468 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2469 && "SSE registers cannot be used when SSE is disabled");
2471 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2472 DAG.getConstant(NumXMMRegs, MVT::i8)));
2475 // For tail calls lower the arguments to the 'real' stack slot.
2477 // Force all the incoming stack arguments to be loaded from the stack
2478 // before any new outgoing arguments are stored to the stack, because the
2479 // outgoing stack slots may alias the incoming argument stack slots, and
2480 // the alias isn't otherwise explicit. This is slightly more conservative
2481 // than necessary, because it means that each store effectively depends
2482 // on every argument instead of just those arguments it would clobber.
2483 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2485 SmallVector<SDValue, 8> MemOpChains2;
2488 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2489 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2490 CCValAssign &VA = ArgLocs[i];
2493 assert(VA.isMemLoc());
2494 SDValue Arg = OutVals[i];
2495 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2496 // Create frame index.
2497 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2498 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2499 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2500 FIN = DAG.getFrameIndex(FI, getPointerTy());
2502 if (Flags.isByVal()) {
2503 // Copy relative to framepointer.
2504 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2505 if (StackPtr.getNode() == 0)
2506 StackPtr = DAG.getCopyFromReg(Chain, dl,
2507 RegInfo->getStackRegister(),
2509 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2511 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2515 // Store relative to framepointer.
2516 MemOpChains2.push_back(
2517 DAG.getStore(ArgChain, dl, Arg, FIN,
2518 MachinePointerInfo::getFixedStack(FI),
2524 if (!MemOpChains2.empty())
2525 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2526 &MemOpChains2[0], MemOpChains2.size());
2528 // Store the return address to the appropriate stack slot.
2529 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2530 getPointerTy(), RegInfo->getSlotSize(),
2534 // Build a sequence of copy-to-reg nodes chained together with token chain
2535 // and flag operands which copy the outgoing args into registers.
2537 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2538 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2539 RegsToPass[i].second, InFlag);
2540 InFlag = Chain.getValue(1);
2543 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2544 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2545 // In the 64-bit large code model, we have to make all calls
2546 // through a register, since the call instruction's 32-bit
2547 // pc-relative offset may not be large enough to hold the whole
2549 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2550 // If the callee is a GlobalAddress node (quite common, every direct call
2551 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2554 // We should use extra load for direct calls to dllimported functions in
2556 const GlobalValue *GV = G->getGlobal();
2557 if (!GV->hasDLLImportLinkage()) {
2558 unsigned char OpFlags = 0;
2559 bool ExtraLoad = false;
2560 unsigned WrapperKind = ISD::DELETED_NODE;
2562 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2563 // external symbols most go through the PLT in PIC mode. If the symbol
2564 // has hidden or protected visibility, or if it is static or local, then
2565 // we don't need to use the PLT - we can directly call it.
2566 if (Subtarget->isTargetELF() &&
2567 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2568 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2569 OpFlags = X86II::MO_PLT;
2570 } else if (Subtarget->isPICStyleStubAny() &&
2571 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2572 (!Subtarget->getTargetTriple().isMacOSX() ||
2573 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2574 // PC-relative references to external symbols should go through $stub,
2575 // unless we're building with the leopard linker or later, which
2576 // automatically synthesizes these stubs.
2577 OpFlags = X86II::MO_DARWIN_STUB;
2578 } else if (Subtarget->isPICStyleRIPRel() &&
2579 isa<Function>(GV) &&
2580 cast<Function>(GV)->getAttributes().
2581 hasAttribute(AttributeSet::FunctionIndex,
2582 Attribute::NonLazyBind)) {
2583 // If the function is marked as non-lazy, generate an indirect call
2584 // which loads from the GOT directly. This avoids runtime overhead
2585 // at the cost of eager binding (and one extra byte of encoding).
2586 OpFlags = X86II::MO_GOTPCREL;
2587 WrapperKind = X86ISD::WrapperRIP;
2591 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2592 G->getOffset(), OpFlags);
2594 // Add a wrapper if needed.
2595 if (WrapperKind != ISD::DELETED_NODE)
2596 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2597 // Add extra indirection if needed.
2599 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2600 MachinePointerInfo::getGOT(),
2601 false, false, false, 0);
2603 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2604 unsigned char OpFlags = 0;
2606 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2607 // external symbols should go through the PLT.
2608 if (Subtarget->isTargetELF() &&
2609 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2610 OpFlags = X86II::MO_PLT;
2611 } else if (Subtarget->isPICStyleStubAny() &&
2612 (!Subtarget->getTargetTriple().isMacOSX() ||
2613 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2614 // PC-relative references to external symbols should go through $stub,
2615 // unless we're building with the leopard linker or later, which
2616 // automatically synthesizes these stubs.
2617 OpFlags = X86II::MO_DARWIN_STUB;
2620 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2624 // Returns a chain & a flag for retval copy to use.
2625 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2626 SmallVector<SDValue, 8> Ops;
2628 if (!IsSibcall && isTailCall) {
2629 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2630 DAG.getIntPtrConstant(0, true), InFlag);
2631 InFlag = Chain.getValue(1);
2634 Ops.push_back(Chain);
2635 Ops.push_back(Callee);
2638 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2640 // Add argument registers to the end of the list so that they are known live
2642 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2643 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2644 RegsToPass[i].second.getValueType()));
2646 // Add a register mask operand representing the call-preserved registers.
2647 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2648 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2649 assert(Mask && "Missing call preserved mask for calling convention");
2650 Ops.push_back(DAG.getRegisterMask(Mask));
2652 if (InFlag.getNode())
2653 Ops.push_back(InFlag);
2657 //// If this is the first return lowered for this function, add the regs
2658 //// to the liveout set for the function.
2659 // This isn't right, although it's probably harmless on x86; liveouts
2660 // should be computed from returns not tail calls. Consider a void
2661 // function making a tail call to a function returning int.
2662 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2665 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2666 InFlag = Chain.getValue(1);
2668 // Create the CALLSEQ_END node.
2669 unsigned NumBytesForCalleeToPush;
2670 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2671 getTargetMachine().Options.GuaranteedTailCallOpt))
2672 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2673 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2674 SR == StackStructReturn)
2675 // If this is a call to a struct-return function, the callee
2676 // pops the hidden struct pointer, so we have to push it back.
2677 // This is common for Darwin/X86, Linux & Mingw32 targets.
2678 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2679 NumBytesForCalleeToPush = 4;
2681 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2683 // Returns a flag for retval copy to use.
2685 Chain = DAG.getCALLSEQ_END(Chain,
2686 DAG.getIntPtrConstant(NumBytes, true),
2687 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2690 InFlag = Chain.getValue(1);
2693 // Handle result values, copying them out of physregs into vregs that we
2695 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2696 Ins, dl, DAG, InVals);
2699 //===----------------------------------------------------------------------===//
2700 // Fast Calling Convention (tail call) implementation
2701 //===----------------------------------------------------------------------===//
2703 // Like std call, callee cleans arguments, convention except that ECX is
2704 // reserved for storing the tail called function address. Only 2 registers are
2705 // free for argument passing (inreg). Tail call optimization is performed
2707 // * tailcallopt is enabled
2708 // * caller/callee are fastcc
2709 // On X86_64 architecture with GOT-style position independent code only local
2710 // (within module) calls are supported at the moment.
2711 // To keep the stack aligned according to platform abi the function
2712 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2713 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2714 // If a tail called function callee has more arguments than the caller the
2715 // caller needs to make sure that there is room to move the RETADDR to. This is
2716 // achieved by reserving an area the size of the argument delta right after the
2717 // original REtADDR, but before the saved framepointer or the spilled registers
2718 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2730 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2731 /// for a 16 byte align requirement.
2733 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2734 SelectionDAG& DAG) const {
2735 MachineFunction &MF = DAG.getMachineFunction();
2736 const TargetMachine &TM = MF.getTarget();
2737 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2738 unsigned StackAlignment = TFI.getStackAlignment();
2739 uint64_t AlignMask = StackAlignment - 1;
2740 int64_t Offset = StackSize;
2741 unsigned SlotSize = RegInfo->getSlotSize();
2742 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2743 // Number smaller than 12 so just add the difference.
2744 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2746 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2747 Offset = ((~AlignMask) & Offset) + StackAlignment +
2748 (StackAlignment-SlotSize);
2753 /// MatchingStackOffset - Return true if the given stack call argument is
2754 /// already available in the same position (relatively) of the caller's
2755 /// incoming argument stack.
2757 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2758 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2759 const X86InstrInfo *TII) {
2760 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2762 if (Arg.getOpcode() == ISD::CopyFromReg) {
2763 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2764 if (!TargetRegisterInfo::isVirtualRegister(VR))
2766 MachineInstr *Def = MRI->getVRegDef(VR);
2769 if (!Flags.isByVal()) {
2770 if (!TII->isLoadFromStackSlot(Def, FI))
2773 unsigned Opcode = Def->getOpcode();
2774 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2775 Def->getOperand(1).isFI()) {
2776 FI = Def->getOperand(1).getIndex();
2777 Bytes = Flags.getByValSize();
2781 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2782 if (Flags.isByVal())
2783 // ByVal argument is passed in as a pointer but it's now being
2784 // dereferenced. e.g.
2785 // define @foo(%struct.X* %A) {
2786 // tail call @bar(%struct.X* byval %A)
2789 SDValue Ptr = Ld->getBasePtr();
2790 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2793 FI = FINode->getIndex();
2794 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2795 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2796 FI = FINode->getIndex();
2797 Bytes = Flags.getByValSize();
2801 assert(FI != INT_MAX);
2802 if (!MFI->isFixedObjectIndex(FI))
2804 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2807 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2808 /// for tail call optimization. Targets which want to do tail call
2809 /// optimization should implement this function.
2811 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2812 CallingConv::ID CalleeCC,
2814 bool isCalleeStructRet,
2815 bool isCallerStructRet,
2817 const SmallVectorImpl<ISD::OutputArg> &Outs,
2818 const SmallVectorImpl<SDValue> &OutVals,
2819 const SmallVectorImpl<ISD::InputArg> &Ins,
2820 SelectionDAG &DAG) const {
2821 if (!IsTailCallConvention(CalleeCC) &&
2822 CalleeCC != CallingConv::C)
2825 // If -tailcallopt is specified, make fastcc functions tail-callable.
2826 const MachineFunction &MF = DAG.getMachineFunction();
2827 const Function *CallerF = DAG.getMachineFunction().getFunction();
2829 // If the function return type is x86_fp80 and the callee return type is not,
2830 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2831 // perform a tailcall optimization here.
2832 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2835 CallingConv::ID CallerCC = CallerF->getCallingConv();
2836 bool CCMatch = CallerCC == CalleeCC;
2838 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2839 if (IsTailCallConvention(CalleeCC) && CCMatch)
2844 // Look for obvious safe cases to perform tail call optimization that do not
2845 // require ABI changes. This is what gcc calls sibcall.
2847 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2848 // emit a special epilogue.
2849 if (RegInfo->needsStackRealignment(MF))
2852 // Also avoid sibcall optimization if either caller or callee uses struct
2853 // return semantics.
2854 if (isCalleeStructRet || isCallerStructRet)
2857 // An stdcall caller is expected to clean up its arguments; the callee
2858 // isn't going to do that.
2859 if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2862 // Do not sibcall optimize vararg calls unless all arguments are passed via
2864 if (isVarArg && !Outs.empty()) {
2866 // Optimizing for varargs on Win64 is unlikely to be safe without
2867 // additional testing.
2868 if (Subtarget->isTargetWin64())
2871 SmallVector<CCValAssign, 16> ArgLocs;
2872 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2873 getTargetMachine(), ArgLocs, *DAG.getContext());
2875 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2876 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2877 if (!ArgLocs[i].isRegLoc())
2881 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2882 // stack. Therefore, if it's not used by the call it is not safe to optimize
2883 // this into a sibcall.
2884 bool Unused = false;
2885 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2892 SmallVector<CCValAssign, 16> RVLocs;
2893 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2894 getTargetMachine(), RVLocs, *DAG.getContext());
2895 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2896 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2897 CCValAssign &VA = RVLocs[i];
2898 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2903 // If the calling conventions do not match, then we'd better make sure the
2904 // results are returned in the same way as what the caller expects.
2906 SmallVector<CCValAssign, 16> RVLocs1;
2907 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2908 getTargetMachine(), RVLocs1, *DAG.getContext());
2909 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2911 SmallVector<CCValAssign, 16> RVLocs2;
2912 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2913 getTargetMachine(), RVLocs2, *DAG.getContext());
2914 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2916 if (RVLocs1.size() != RVLocs2.size())
2918 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2919 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2921 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2923 if (RVLocs1[i].isRegLoc()) {
2924 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2927 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2933 // If the callee takes no arguments then go on to check the results of the
2935 if (!Outs.empty()) {
2936 // Check if stack adjustment is needed. For now, do not do this if any
2937 // argument is passed on the stack.
2938 SmallVector<CCValAssign, 16> ArgLocs;
2939 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2940 getTargetMachine(), ArgLocs, *DAG.getContext());
2942 // Allocate shadow area for Win64
2943 if (Subtarget->isTargetWin64()) {
2944 CCInfo.AllocateStack(32, 8);
2947 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2948 if (CCInfo.getNextStackOffset()) {
2949 MachineFunction &MF = DAG.getMachineFunction();
2950 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2953 // Check if the arguments are already laid out in the right way as
2954 // the caller's fixed stack objects.
2955 MachineFrameInfo *MFI = MF.getFrameInfo();
2956 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2957 const X86InstrInfo *TII =
2958 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2959 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2960 CCValAssign &VA = ArgLocs[i];
2961 SDValue Arg = OutVals[i];
2962 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2963 if (VA.getLocInfo() == CCValAssign::Indirect)
2965 if (!VA.isRegLoc()) {
2966 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2973 // If the tailcall address may be in a register, then make sure it's
2974 // possible to register allocate for it. In 32-bit, the call address can
2975 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2976 // callee-saved registers are restored. These happen to be the same
2977 // registers used to pass 'inreg' arguments so watch out for those.
2978 if (!Subtarget->is64Bit() &&
2979 ((!isa<GlobalAddressSDNode>(Callee) &&
2980 !isa<ExternalSymbolSDNode>(Callee)) ||
2981 getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2982 unsigned NumInRegs = 0;
2983 // In PIC we need an extra register to formulate the address computation
2985 unsigned MaxInRegs =
2986 (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
2988 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989 CCValAssign &VA = ArgLocs[i];
2992 unsigned Reg = VA.getLocReg();
2995 case X86::EAX: case X86::EDX: case X86::ECX:
2996 if (++NumInRegs == MaxInRegs)
3008 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3009 const TargetLibraryInfo *libInfo) const {
3010 return X86::createFastISel(funcInfo, libInfo);
3013 //===----------------------------------------------------------------------===//
3014 // Other Lowering Hooks
3015 //===----------------------------------------------------------------------===//
3017 static bool MayFoldLoad(SDValue Op) {
3018 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3021 static bool MayFoldIntoStore(SDValue Op) {
3022 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3025 static bool isTargetShuffle(unsigned Opcode) {
3027 default: return false;
3028 case X86ISD::PSHUFD:
3029 case X86ISD::PSHUFHW:
3030 case X86ISD::PSHUFLW:
3032 case X86ISD::PALIGNR:
3033 case X86ISD::MOVLHPS:
3034 case X86ISD::MOVLHPD:
3035 case X86ISD::MOVHLPS:
3036 case X86ISD::MOVLPS:
3037 case X86ISD::MOVLPD:
3038 case X86ISD::MOVSHDUP:
3039 case X86ISD::MOVSLDUP:
3040 case X86ISD::MOVDDUP:
3043 case X86ISD::UNPCKL:
3044 case X86ISD::UNPCKH:
3045 case X86ISD::VPERMILP:
3046 case X86ISD::VPERM2X128:
3047 case X86ISD::VPERMI:
3052 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3053 SDValue V1, SelectionDAG &DAG) {
3055 default: llvm_unreachable("Unknown x86 shuffle node");
3056 case X86ISD::MOVSHDUP:
3057 case X86ISD::MOVSLDUP:
3058 case X86ISD::MOVDDUP:
3059 return DAG.getNode(Opc, dl, VT, V1);
3063 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3064 SDValue V1, unsigned TargetMask,
3065 SelectionDAG &DAG) {
3067 default: llvm_unreachable("Unknown x86 shuffle node");
3068 case X86ISD::PSHUFD:
3069 case X86ISD::PSHUFHW:
3070 case X86ISD::PSHUFLW:
3071 case X86ISD::VPERMILP:
3072 case X86ISD::VPERMI:
3073 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3077 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3078 SDValue V1, SDValue V2, unsigned TargetMask,
3079 SelectionDAG &DAG) {
3081 default: llvm_unreachable("Unknown x86 shuffle node");
3082 case X86ISD::PALIGNR:
3084 case X86ISD::VPERM2X128:
3085 return DAG.getNode(Opc, dl, VT, V1, V2,
3086 DAG.getConstant(TargetMask, MVT::i8));
3090 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3091 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3093 default: llvm_unreachable("Unknown x86 shuffle node");
3094 case X86ISD::MOVLHPS:
3095 case X86ISD::MOVLHPD:
3096 case X86ISD::MOVHLPS:
3097 case X86ISD::MOVLPS:
3098 case X86ISD::MOVLPD:
3101 case X86ISD::UNPCKL:
3102 case X86ISD::UNPCKH:
3103 return DAG.getNode(Opc, dl, VT, V1, V2);
3107 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3108 MachineFunction &MF = DAG.getMachineFunction();
3109 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3110 int ReturnAddrIndex = FuncInfo->getRAIndex();
3112 if (ReturnAddrIndex == 0) {
3113 // Set up a frame object for the return address.
3114 unsigned SlotSize = RegInfo->getSlotSize();
3115 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3117 FuncInfo->setRAIndex(ReturnAddrIndex);
3120 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3123 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3124 bool hasSymbolicDisplacement) {
3125 // Offset should fit into 32 bit immediate field.
3126 if (!isInt<32>(Offset))
3129 // If we don't have a symbolic displacement - we don't have any extra
3131 if (!hasSymbolicDisplacement)
3134 // FIXME: Some tweaks might be needed for medium code model.
3135 if (M != CodeModel::Small && M != CodeModel::Kernel)
3138 // For small code model we assume that latest object is 16MB before end of 31
3139 // bits boundary. We may also accept pretty large negative constants knowing
3140 // that all objects are in the positive half of address space.
3141 if (M == CodeModel::Small && Offset < 16*1024*1024)
3144 // For kernel code model we know that all object resist in the negative half
3145 // of 32bits address space. We may not accept negative offsets, since they may
3146 // be just off and we may accept pretty large positive ones.
3147 if (M == CodeModel::Kernel && Offset > 0)
3153 /// isCalleePop - Determines whether the callee is required to pop its
3154 /// own arguments. Callee pop is necessary to support tail calls.
3155 bool X86::isCalleePop(CallingConv::ID CallingConv,
3156 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3160 switch (CallingConv) {
3163 case CallingConv::X86_StdCall:
3165 case CallingConv::X86_FastCall:
3167 case CallingConv::X86_ThisCall:
3169 case CallingConv::Fast:
3171 case CallingConv::GHC:
3173 case CallingConv::HiPE:
3178 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3179 /// specific condition code, returning the condition code and the LHS/RHS of the
3180 /// comparison to make.
3181 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3182 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3184 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3185 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3186 // X > -1 -> X == 0, jump !sign.
3187 RHS = DAG.getConstant(0, RHS.getValueType());
3188 return X86::COND_NS;
3190 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3191 // X < 0 -> X == 0, jump on sign.
3194 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3196 RHS = DAG.getConstant(0, RHS.getValueType());
3197 return X86::COND_LE;
3201 switch (SetCCOpcode) {
3202 default: llvm_unreachable("Invalid integer condition!");
3203 case ISD::SETEQ: return X86::COND_E;
3204 case ISD::SETGT: return X86::COND_G;
3205 case ISD::SETGE: return X86::COND_GE;
3206 case ISD::SETLT: return X86::COND_L;
3207 case ISD::SETLE: return X86::COND_LE;
3208 case ISD::SETNE: return X86::COND_NE;
3209 case ISD::SETULT: return X86::COND_B;
3210 case ISD::SETUGT: return X86::COND_A;
3211 case ISD::SETULE: return X86::COND_BE;
3212 case ISD::SETUGE: return X86::COND_AE;
3216 // First determine if it is required or is profitable to flip the operands.
3218 // If LHS is a foldable load, but RHS is not, flip the condition.
3219 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3220 !ISD::isNON_EXTLoad(RHS.getNode())) {
3221 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3222 std::swap(LHS, RHS);
3225 switch (SetCCOpcode) {
3231 std::swap(LHS, RHS);
3235 // On a floating point condition, the flags are set as follows:
3237 // 0 | 0 | 0 | X > Y
3238 // 0 | 0 | 1 | X < Y
3239 // 1 | 0 | 0 | X == Y
3240 // 1 | 1 | 1 | unordered
3241 switch (SetCCOpcode) {
3242 default: llvm_unreachable("Condcode should be pre-legalized away");
3244 case ISD::SETEQ: return X86::COND_E;
3245 case ISD::SETOLT: // flipped
3247 case ISD::SETGT: return X86::COND_A;
3248 case ISD::SETOLE: // flipped
3250 case ISD::SETGE: return X86::COND_AE;
3251 case ISD::SETUGT: // flipped
3253 case ISD::SETLT: return X86::COND_B;
3254 case ISD::SETUGE: // flipped
3256 case ISD::SETLE: return X86::COND_BE;
3258 case ISD::SETNE: return X86::COND_NE;
3259 case ISD::SETUO: return X86::COND_P;
3260 case ISD::SETO: return X86::COND_NP;
3262 case ISD::SETUNE: return X86::COND_INVALID;
3266 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3267 /// code. Current x86 isa includes the following FP cmov instructions:
3268 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3269 static bool hasFPCMov(unsigned X86CC) {
3285 /// isFPImmLegal - Returns true if the target can instruction select the
3286 /// specified FP immediate natively. If false, the legalizer will
3287 /// materialize the FP immediate as a load from a constant pool.
3288 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3289 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3290 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3296 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3297 /// the specified range (L, H].
3298 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3299 return (Val < 0) || (Val >= Low && Val < Hi);
3302 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3303 /// specified value.
3304 static bool isUndefOrEqual(int Val, int CmpVal) {
3305 return (Val < 0 || Val == CmpVal);
3308 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3309 /// from position Pos and ending in Pos+Size, falls within the specified
3310 /// sequential range (L, L+Pos]. or is undef.
3311 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3312 unsigned Pos, unsigned Size, int Low) {
3313 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3314 if (!isUndefOrEqual(Mask[i], Low))
3319 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3320 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3321 /// the second operand.
3322 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3323 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3324 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3325 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3326 return (Mask[0] < 2 && Mask[1] < 2);
3330 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3331 /// is suitable for input to PSHUFHW.
3332 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3333 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3336 // Lower quadword copied in order or undef.
3337 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3340 // Upper quadword shuffled.
3341 for (unsigned i = 4; i != 8; ++i)
3342 if (!isUndefOrInRange(Mask[i], 4, 8))
3345 if (VT == MVT::v16i16) {
3346 // Lower quadword copied in order or undef.
3347 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3350 // Upper quadword shuffled.
3351 for (unsigned i = 12; i != 16; ++i)
3352 if (!isUndefOrInRange(Mask[i], 12, 16))
3359 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3360 /// is suitable for input to PSHUFLW.
3361 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3362 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3365 // Upper quadword copied in order.
3366 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3369 // Lower quadword shuffled.
3370 for (unsigned i = 0; i != 4; ++i)
3371 if (!isUndefOrInRange(Mask[i], 0, 4))
3374 if (VT == MVT::v16i16) {
3375 // Upper quadword copied in order.
3376 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3379 // Lower quadword shuffled.
3380 for (unsigned i = 8; i != 12; ++i)
3381 if (!isUndefOrInRange(Mask[i], 8, 12))
3388 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3389 /// is suitable for input to PALIGNR.
3390 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3391 const X86Subtarget *Subtarget) {
3392 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3393 (VT.is256BitVector() && !Subtarget->hasInt256()))
3396 unsigned NumElts = VT.getVectorNumElements();
3397 unsigned NumLanes = VT.getSizeInBits()/128;
3398 unsigned NumLaneElts = NumElts/NumLanes;
3400 // Do not handle 64-bit element shuffles with palignr.
3401 if (NumLaneElts == 2)
3404 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3406 for (i = 0; i != NumLaneElts; ++i) {
3411 // Lane is all undef, go to next lane
3412 if (i == NumLaneElts)
3415 int Start = Mask[i+l];
3417 // Make sure its in this lane in one of the sources
3418 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3419 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3422 // If not lane 0, then we must match lane 0
3423 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3426 // Correct second source to be contiguous with first source
3427 if (Start >= (int)NumElts)
3428 Start -= NumElts - NumLaneElts;
3430 // Make sure we're shifting in the right direction.
3431 if (Start <= (int)(i+l))
3436 // Check the rest of the elements to see if they are consecutive.
3437 for (++i; i != NumLaneElts; ++i) {
3438 int Idx = Mask[i+l];
3440 // Make sure its in this lane
3441 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3442 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3445 // If not lane 0, then we must match lane 0
3446 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3449 if (Idx >= (int)NumElts)
3450 Idx -= NumElts - NumLaneElts;
3452 if (!isUndefOrEqual(Idx, Start+i))
3461 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3462 /// the two vector operands have swapped position.
3463 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3464 unsigned NumElems) {
3465 for (unsigned i = 0; i != NumElems; ++i) {
3469 else if (idx < (int)NumElems)
3470 Mask[i] = idx + NumElems;
3472 Mask[i] = idx - NumElems;
3476 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3477 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3478 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3479 /// reverse of what x86 shuffles want.
3480 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3481 bool Commuted = false) {
3482 if (!HasFp256 && VT.is256BitVector())
3485 unsigned NumElems = VT.getVectorNumElements();
3486 unsigned NumLanes = VT.getSizeInBits()/128;
3487 unsigned NumLaneElems = NumElems/NumLanes;
3489 if (NumLaneElems != 2 && NumLaneElems != 4)
3492 // VSHUFPSY divides the resulting vector into 4 chunks.
3493 // The sources are also splitted into 4 chunks, and each destination
3494 // chunk must come from a different source chunk.
3496 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3497 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3499 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3500 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3502 // VSHUFPDY divides the resulting vector into 4 chunks.
3503 // The sources are also splitted into 4 chunks, and each destination
3504 // chunk must come from a different source chunk.
3506 // SRC1 => X3 X2 X1 X0
3507 // SRC2 => Y3 Y2 Y1 Y0
3509 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3511 unsigned HalfLaneElems = NumLaneElems/2;
3512 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3513 for (unsigned i = 0; i != NumLaneElems; ++i) {
3514 int Idx = Mask[i+l];
3515 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3516 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3518 // For VSHUFPSY, the mask of the second half must be the same as the
3519 // first but with the appropriate offsets. This works in the same way as
3520 // VPERMILPS works with masks.
3521 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3523 if (!isUndefOrEqual(Idx, Mask[i]+l))
3531 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3532 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3533 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3534 if (!VT.is128BitVector())
3537 unsigned NumElems = VT.getVectorNumElements();
3542 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3543 return isUndefOrEqual(Mask[0], 6) &&
3544 isUndefOrEqual(Mask[1], 7) &&
3545 isUndefOrEqual(Mask[2], 2) &&
3546 isUndefOrEqual(Mask[3], 3);
3549 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3550 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3552 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3553 if (!VT.is128BitVector())
3556 unsigned NumElems = VT.getVectorNumElements();
3561 return isUndefOrEqual(Mask[0], 2) &&
3562 isUndefOrEqual(Mask[1], 3) &&
3563 isUndefOrEqual(Mask[2], 2) &&
3564 isUndefOrEqual(Mask[3], 3);
3567 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3568 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3569 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3570 if (!VT.is128BitVector())
3573 unsigned NumElems = VT.getVectorNumElements();
3575 if (NumElems != 2 && NumElems != 4)
3578 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3579 if (!isUndefOrEqual(Mask[i], i + NumElems))
3582 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3583 if (!isUndefOrEqual(Mask[i], i))
3589 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3590 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3591 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3592 if (!VT.is128BitVector())
3595 unsigned NumElems = VT.getVectorNumElements();
3597 if (NumElems != 2 && NumElems != 4)
3600 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3601 if (!isUndefOrEqual(Mask[i], i))
3604 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3605 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3612 // Some special combinations that can be optimized.
3615 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3616 SelectionDAG &DAG) {
3617 MVT VT = SVOp->getValueType(0).getSimpleVT();
3618 DebugLoc dl = SVOp->getDebugLoc();
3620 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3623 ArrayRef<int> Mask = SVOp->getMask();
3625 // These are the special masks that may be optimized.
3626 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3627 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3628 bool MatchEvenMask = true;
3629 bool MatchOddMask = true;
3630 for (int i=0; i<8; ++i) {
3631 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3632 MatchEvenMask = false;
3633 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3634 MatchOddMask = false;
3637 if (!MatchEvenMask && !MatchOddMask)
3640 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3642 SDValue Op0 = SVOp->getOperand(0);
3643 SDValue Op1 = SVOp->getOperand(1);
3645 if (MatchEvenMask) {
3646 // Shift the second operand right to 32 bits.
3647 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3648 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3650 // Shift the first operand left to 32 bits.
3651 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3652 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3654 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3655 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3658 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3659 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3660 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3661 bool HasInt256, bool V2IsSplat = false) {
3662 unsigned NumElts = VT.getVectorNumElements();
3664 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3665 "Unsupported vector type for unpckh");
3667 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3668 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3671 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3672 // independently on 128-bit lanes.
3673 unsigned NumLanes = VT.getSizeInBits()/128;
3674 unsigned NumLaneElts = NumElts/NumLanes;
3676 for (unsigned l = 0; l != NumLanes; ++l) {
3677 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3678 i != (l+1)*NumLaneElts;
3681 int BitI1 = Mask[i+1];
3682 if (!isUndefOrEqual(BitI, j))
3685 if (!isUndefOrEqual(BitI1, NumElts))
3688 if (!isUndefOrEqual(BitI1, j + NumElts))
3697 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3698 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3699 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3700 bool HasInt256, bool V2IsSplat = false) {
3701 unsigned NumElts = VT.getVectorNumElements();
3703 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3704 "Unsupported vector type for unpckh");
3706 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3707 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3710 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3711 // independently on 128-bit lanes.
3712 unsigned NumLanes = VT.getSizeInBits()/128;
3713 unsigned NumLaneElts = NumElts/NumLanes;
3715 for (unsigned l = 0; l != NumLanes; ++l) {
3716 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3717 i != (l+1)*NumLaneElts; i += 2, ++j) {
3719 int BitI1 = Mask[i+1];
3720 if (!isUndefOrEqual(BitI, j))
3723 if (isUndefOrEqual(BitI1, NumElts))
3726 if (!isUndefOrEqual(BitI1, j+NumElts))
3734 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3735 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3737 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3738 unsigned NumElts = VT.getVectorNumElements();
3739 bool Is256BitVec = VT.is256BitVector();
3741 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3742 "Unsupported vector type for unpckh");
3744 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3745 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3748 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3749 // FIXME: Need a better way to get rid of this, there's no latency difference
3750 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3751 // the former later. We should also remove the "_undef" special mask.
3752 if (NumElts == 4 && Is256BitVec)
3755 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3756 // independently on 128-bit lanes.
3757 unsigned NumLanes = VT.getSizeInBits()/128;
3758 unsigned NumLaneElts = NumElts/NumLanes;
3760 for (unsigned l = 0; l != NumLanes; ++l) {
3761 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3762 i != (l+1)*NumLaneElts;
3765 int BitI1 = Mask[i+1];
3767 if (!isUndefOrEqual(BitI, j))
3769 if (!isUndefOrEqual(BitI1, j))
3777 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3778 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3780 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3781 unsigned NumElts = VT.getVectorNumElements();
3783 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3784 "Unsupported vector type for unpckh");
3786 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3787 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3790 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3791 // independently on 128-bit lanes.
3792 unsigned NumLanes = VT.getSizeInBits()/128;
3793 unsigned NumLaneElts = NumElts/NumLanes;
3795 for (unsigned l = 0; l != NumLanes; ++l) {
3796 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3797 i != (l+1)*NumLaneElts; i += 2, ++j) {
3799 int BitI1 = Mask[i+1];
3800 if (!isUndefOrEqual(BitI, j))
3802 if (!isUndefOrEqual(BitI1, j))
3809 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3810 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3811 /// MOVSD, and MOVD, i.e. setting the lowest element.
3812 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3813 if (VT.getVectorElementType().getSizeInBits() < 32)
3815 if (!VT.is128BitVector())
3818 unsigned NumElts = VT.getVectorNumElements();
3820 if (!isUndefOrEqual(Mask[0], NumElts))
3823 for (unsigned i = 1; i != NumElts; ++i)
3824 if (!isUndefOrEqual(Mask[i], i))
3830 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3831 /// as permutations between 128-bit chunks or halves. As an example: this
3833 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3834 /// The first half comes from the second half of V1 and the second half from the
3835 /// the second half of V2.
3836 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3837 if (!HasFp256 || !VT.is256BitVector())
3840 // The shuffle result is divided into half A and half B. In total the two
3841 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3842 // B must come from C, D, E or F.
3843 unsigned HalfSize = VT.getVectorNumElements()/2;
3844 bool MatchA = false, MatchB = false;
3846 // Check if A comes from one of C, D, E, F.
3847 for (unsigned Half = 0; Half != 4; ++Half) {
3848 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3854 // Check if B comes from one of C, D, E, F.
3855 for (unsigned Half = 0; Half != 4; ++Half) {
3856 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3862 return MatchA && MatchB;
3865 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3866 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3867 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3868 MVT VT = SVOp->getValueType(0).getSimpleVT();
3870 unsigned HalfSize = VT.getVectorNumElements()/2;
3872 unsigned FstHalf = 0, SndHalf = 0;
3873 for (unsigned i = 0; i < HalfSize; ++i) {
3874 if (SVOp->getMaskElt(i) > 0) {
3875 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3879 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3880 if (SVOp->getMaskElt(i) > 0) {
3881 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3886 return (FstHalf | (SndHalf << 4));
3889 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3890 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3891 /// Note that VPERMIL mask matching is different depending whether theunderlying
3892 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3893 /// to the same elements of the low, but to the higher half of the source.
3894 /// In VPERMILPD the two lanes could be shuffled independently of each other
3895 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3896 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3900 unsigned NumElts = VT.getVectorNumElements();
3901 // Only match 256-bit with 32/64-bit types
3902 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3905 unsigned NumLanes = VT.getSizeInBits()/128;
3906 unsigned LaneSize = NumElts/NumLanes;
3907 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3908 for (unsigned i = 0; i != LaneSize; ++i) {
3909 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3911 if (NumElts != 8 || l == 0)
3913 // VPERMILPS handling
3916 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3924 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3925 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3926 /// element of vector 2 and the other elements to come from vector 1 in order.
3927 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3928 bool V2IsSplat = false, bool V2IsUndef = false) {
3929 if (!VT.is128BitVector())
3932 unsigned NumOps = VT.getVectorNumElements();
3933 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3936 if (!isUndefOrEqual(Mask[0], 0))
3939 for (unsigned i = 1; i != NumOps; ++i)
3940 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3941 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3942 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3948 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3949 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3950 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3951 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3952 const X86Subtarget *Subtarget) {
3953 if (!Subtarget->hasSSE3())
3956 unsigned NumElems = VT.getVectorNumElements();
3958 if ((VT.is128BitVector() && NumElems != 4) ||
3959 (VT.is256BitVector() && NumElems != 8))
3962 // "i+1" is the value the indexed mask element must have
3963 for (unsigned i = 0; i != NumElems; i += 2)
3964 if (!isUndefOrEqual(Mask[i], i+1) ||
3965 !isUndefOrEqual(Mask[i+1], i+1))
3971 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3973 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3974 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3975 const X86Subtarget *Subtarget) {
3976 if (!Subtarget->hasSSE3())
3979 unsigned NumElems = VT.getVectorNumElements();
3981 if ((VT.is128BitVector() && NumElems != 4) ||
3982 (VT.is256BitVector() && NumElems != 8))
3985 // "i" is the value the indexed mask element must have
3986 for (unsigned i = 0; i != NumElems; i += 2)
3987 if (!isUndefOrEqual(Mask[i], i) ||
3988 !isUndefOrEqual(Mask[i+1], i))
3994 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3995 /// specifies a shuffle of elements that is suitable for input to 256-bit
3996 /// version of MOVDDUP.
3997 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3998 if (!HasFp256 || !VT.is256BitVector())
4001 unsigned NumElts = VT.getVectorNumElements();
4005 for (unsigned i = 0; i != NumElts/2; ++i)
4006 if (!isUndefOrEqual(Mask[i], 0))
4008 for (unsigned i = NumElts/2; i != NumElts; ++i)
4009 if (!isUndefOrEqual(Mask[i], NumElts/2))
4014 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4015 /// specifies a shuffle of elements that is suitable for input to 128-bit
4016 /// version of MOVDDUP.
4017 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4018 if (!VT.is128BitVector())
4021 unsigned e = VT.getVectorNumElements() / 2;
4022 for (unsigned i = 0; i != e; ++i)
4023 if (!isUndefOrEqual(Mask[i], i))
4025 for (unsigned i = 0; i != e; ++i)
4026 if (!isUndefOrEqual(Mask[e+i], i))
4031 /// isVEXTRACTF128Index - Return true if the specified
4032 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4033 /// suitable for input to VEXTRACTF128.
4034 bool X86::isVEXTRACTF128Index(SDNode *N) {
4035 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4038 // The index should be aligned on a 128-bit boundary.
4040 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4042 MVT VT = N->getValueType(0).getSimpleVT();
4043 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4044 bool Result = (Index * ElSize) % 128 == 0;
4049 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4050 /// operand specifies a subvector insert that is suitable for input to
4052 bool X86::isVINSERTF128Index(SDNode *N) {
4053 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4056 // The index should be aligned on a 128-bit boundary.
4058 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4060 MVT VT = N->getValueType(0).getSimpleVT();
4061 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4062 bool Result = (Index * ElSize) % 128 == 0;
4067 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4068 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4069 /// Handles 128-bit and 256-bit.
4070 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4071 MVT VT = N->getValueType(0).getSimpleVT();
4073 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4074 "Unsupported vector type for PSHUF/SHUFP");
4076 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4077 // independently on 128-bit lanes.
4078 unsigned NumElts = VT.getVectorNumElements();
4079 unsigned NumLanes = VT.getSizeInBits()/128;
4080 unsigned NumLaneElts = NumElts/NumLanes;
4082 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4083 "Only supports 2 or 4 elements per lane");
4085 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4087 for (unsigned i = 0; i != NumElts; ++i) {
4088 int Elt = N->getMaskElt(i);
4089 if (Elt < 0) continue;
4090 Elt &= NumLaneElts - 1;
4091 unsigned ShAmt = (i << Shift) % 8;
4092 Mask |= Elt << ShAmt;
4098 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4099 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4100 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4101 MVT VT = N->getValueType(0).getSimpleVT();
4103 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4104 "Unsupported vector type for PSHUFHW");
4106 unsigned NumElts = VT.getVectorNumElements();
4109 for (unsigned l = 0; l != NumElts; l += 8) {
4110 // 8 nodes per lane, but we only care about the last 4.
4111 for (unsigned i = 0; i < 4; ++i) {
4112 int Elt = N->getMaskElt(l+i+4);
4113 if (Elt < 0) continue;
4114 Elt &= 0x3; // only 2-bits.
4115 Mask |= Elt << (i * 2);
4122 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4123 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4124 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4125 MVT VT = N->getValueType(0).getSimpleVT();
4127 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4128 "Unsupported vector type for PSHUFHW");
4130 unsigned NumElts = VT.getVectorNumElements();
4133 for (unsigned l = 0; l != NumElts; l += 8) {
4134 // 8 nodes per lane, but we only care about the first 4.
4135 for (unsigned i = 0; i < 4; ++i) {
4136 int Elt = N->getMaskElt(l+i);
4137 if (Elt < 0) continue;
4138 Elt &= 0x3; // only 2-bits
4139 Mask |= Elt << (i * 2);
4146 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4147 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4148 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4149 MVT VT = SVOp->getValueType(0).getSimpleVT();
4150 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4152 unsigned NumElts = VT.getVectorNumElements();
4153 unsigned NumLanes = VT.getSizeInBits()/128;
4154 unsigned NumLaneElts = NumElts/NumLanes;
4158 for (i = 0; i != NumElts; ++i) {
4159 Val = SVOp->getMaskElt(i);
4163 if (Val >= (int)NumElts)
4164 Val -= NumElts - NumLaneElts;
4166 assert(Val - i > 0 && "PALIGNR imm should be positive");
4167 return (Val - i) * EltSize;
4170 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4171 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4173 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4174 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4175 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4178 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4180 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4181 MVT ElVT = VecVT.getVectorElementType();
4183 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4184 return Index / NumElemsPerChunk;
4187 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4188 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4190 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4191 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4192 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4195 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4197 MVT VecVT = N->getValueType(0).getSimpleVT();
4198 MVT ElVT = VecVT.getVectorElementType();
4200 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4201 return Index / NumElemsPerChunk;
4204 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4205 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4206 /// Handles 256-bit.
4207 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4208 MVT VT = N->getValueType(0).getSimpleVT();
4210 unsigned NumElts = VT.getVectorNumElements();
4212 assert((VT.is256BitVector() && NumElts == 4) &&
4213 "Unsupported vector type for VPERMQ/VPERMPD");
4216 for (unsigned i = 0; i != NumElts; ++i) {
4217 int Elt = N->getMaskElt(i);
4220 Mask |= Elt << (i*2);
4225 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4227 bool X86::isZeroNode(SDValue Elt) {
4228 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4229 return CN->isNullValue();
4230 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4231 return CFP->getValueAPF().isPosZero();
4235 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4236 /// their permute mask.
4237 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4238 SelectionDAG &DAG) {
4239 MVT VT = SVOp->getValueType(0).getSimpleVT();
4240 unsigned NumElems = VT.getVectorNumElements();
4241 SmallVector<int, 8> MaskVec;
4243 for (unsigned i = 0; i != NumElems; ++i) {
4244 int Idx = SVOp->getMaskElt(i);
4246 if (Idx < (int)NumElems)
4251 MaskVec.push_back(Idx);
4253 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4254 SVOp->getOperand(0), &MaskVec[0]);
4257 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4258 /// match movhlps. The lower half elements should come from upper half of
4259 /// V1 (and in order), and the upper half elements should come from the upper
4260 /// half of V2 (and in order).
4261 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4262 if (!VT.is128BitVector())
4264 if (VT.getVectorNumElements() != 4)
4266 for (unsigned i = 0, e = 2; i != e; ++i)
4267 if (!isUndefOrEqual(Mask[i], i+2))
4269 for (unsigned i = 2; i != 4; ++i)
4270 if (!isUndefOrEqual(Mask[i], i+4))
4275 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4276 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4278 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4279 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4281 N = N->getOperand(0).getNode();
4282 if (!ISD::isNON_EXTLoad(N))
4285 *LD = cast<LoadSDNode>(N);
4289 // Test whether the given value is a vector value which will be legalized
4291 static bool WillBeConstantPoolLoad(SDNode *N) {
4292 if (N->getOpcode() != ISD::BUILD_VECTOR)
4295 // Check for any non-constant elements.
4296 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4297 switch (N->getOperand(i).getNode()->getOpcode()) {
4299 case ISD::ConstantFP:
4306 // Vectors of all-zeros and all-ones are materialized with special
4307 // instructions rather than being loaded.
4308 return !ISD::isBuildVectorAllZeros(N) &&
4309 !ISD::isBuildVectorAllOnes(N);
4312 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4313 /// match movlp{s|d}. The lower half elements should come from lower half of
4314 /// V1 (and in order), and the upper half elements should come from the upper
4315 /// half of V2 (and in order). And since V1 will become the source of the
4316 /// MOVLP, it must be either a vector load or a scalar load to vector.
4317 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4318 ArrayRef<int> Mask, EVT VT) {
4319 if (!VT.is128BitVector())
4322 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4324 // Is V2 is a vector load, don't do this transformation. We will try to use
4325 // load folding shufps op.
4326 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4329 unsigned NumElems = VT.getVectorNumElements();
4331 if (NumElems != 2 && NumElems != 4)
4333 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4334 if (!isUndefOrEqual(Mask[i], i))
4336 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4337 if (!isUndefOrEqual(Mask[i], i+NumElems))
4342 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4344 static bool isSplatVector(SDNode *N) {
4345 if (N->getOpcode() != ISD::BUILD_VECTOR)
4348 SDValue SplatValue = N->getOperand(0);
4349 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4350 if (N->getOperand(i) != SplatValue)
4355 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4356 /// to an zero vector.
4357 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4358 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4359 SDValue V1 = N->getOperand(0);
4360 SDValue V2 = N->getOperand(1);
4361 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4362 for (unsigned i = 0; i != NumElems; ++i) {
4363 int Idx = N->getMaskElt(i);
4364 if (Idx >= (int)NumElems) {
4365 unsigned Opc = V2.getOpcode();
4366 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4368 if (Opc != ISD::BUILD_VECTOR ||
4369 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4371 } else if (Idx >= 0) {
4372 unsigned Opc = V1.getOpcode();
4373 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4375 if (Opc != ISD::BUILD_VECTOR ||
4376 !X86::isZeroNode(V1.getOperand(Idx)))
4383 /// getZeroVector - Returns a vector of specified type with all zero elements.
4385 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4386 SelectionDAG &DAG, DebugLoc dl) {
4387 assert(VT.isVector() && "Expected a vector type");
4389 // Always build SSE zero vectors as <4 x i32> bitcasted
4390 // to their dest type. This ensures they get CSE'd.
4392 if (VT.is128BitVector()) { // SSE
4393 if (Subtarget->hasSSE2()) { // SSE2
4394 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4395 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4397 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4398 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4400 } else if (VT.is256BitVector()) { // AVX
4401 if (Subtarget->hasInt256()) { // AVX2
4402 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4403 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4404 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4406 // 256-bit logic and arithmetic instructions in AVX are all
4407 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4408 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4409 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4410 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4413 llvm_unreachable("Unexpected vector type");
4415 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4418 /// getOnesVector - Returns a vector of specified type with all bits set.
4419 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4420 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4421 /// Then bitcast to their original type, ensuring they get CSE'd.
4422 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4424 assert(VT.isVector() && "Expected a vector type");
4426 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4428 if (VT.is256BitVector()) {
4429 if (HasInt256) { // AVX2
4430 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4431 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4433 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4434 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4436 } else if (VT.is128BitVector()) {
4437 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4439 llvm_unreachable("Unexpected vector type");
4441 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4444 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4445 /// that point to V2 points to its first element.
4446 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4447 for (unsigned i = 0; i != NumElems; ++i) {
4448 if (Mask[i] > (int)NumElems) {
4454 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4455 /// operation of specified width.
4456 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4458 unsigned NumElems = VT.getVectorNumElements();
4459 SmallVector<int, 8> Mask;
4460 Mask.push_back(NumElems);
4461 for (unsigned i = 1; i != NumElems; ++i)
4463 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4466 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4467 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4469 unsigned NumElems = VT.getVectorNumElements();
4470 SmallVector<int, 8> Mask;
4471 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4473 Mask.push_back(i + NumElems);
4475 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4478 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4479 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4481 unsigned NumElems = VT.getVectorNumElements();
4482 SmallVector<int, 8> Mask;
4483 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4484 Mask.push_back(i + Half);
4485 Mask.push_back(i + NumElems + Half);
4487 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4490 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4491 // a generic shuffle instruction because the target has no such instructions.
4492 // Generate shuffles which repeat i16 and i8 several times until they can be
4493 // represented by v4f32 and then be manipulated by target suported shuffles.
4494 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4495 EVT VT = V.getValueType();
4496 int NumElems = VT.getVectorNumElements();
4497 DebugLoc dl = V.getDebugLoc();
4499 while (NumElems > 4) {
4500 if (EltNo < NumElems/2) {
4501 V = getUnpackl(DAG, dl, VT, V, V);
4503 V = getUnpackh(DAG, dl, VT, V, V);
4504 EltNo -= NumElems/2;
4511 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4512 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4513 EVT VT = V.getValueType();
4514 DebugLoc dl = V.getDebugLoc();
4516 if (VT.is128BitVector()) {
4517 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4518 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4519 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4521 } else if (VT.is256BitVector()) {
4522 // To use VPERMILPS to splat scalars, the second half of indicies must
4523 // refer to the higher part, which is a duplication of the lower one,
4524 // because VPERMILPS can only handle in-lane permutations.
4525 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4526 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4528 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4529 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4532 llvm_unreachable("Vector size not supported");
4534 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4537 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4538 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4539 EVT SrcVT = SV->getValueType(0);
4540 SDValue V1 = SV->getOperand(0);
4541 DebugLoc dl = SV->getDebugLoc();
4543 int EltNo = SV->getSplatIndex();
4544 int NumElems = SrcVT.getVectorNumElements();
4545 bool Is256BitVec = SrcVT.is256BitVector();
4547 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4548 "Unknown how to promote splat for type");
4550 // Extract the 128-bit part containing the splat element and update
4551 // the splat element index when it refers to the higher register.
4553 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4554 if (EltNo >= NumElems/2)
4555 EltNo -= NumElems/2;
4558 // All i16 and i8 vector types can't be used directly by a generic shuffle
4559 // instruction because the target has no such instruction. Generate shuffles
4560 // which repeat i16 and i8 several times until they fit in i32, and then can
4561 // be manipulated by target suported shuffles.
4562 EVT EltVT = SrcVT.getVectorElementType();
4563 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4564 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4566 // Recreate the 256-bit vector and place the same 128-bit vector
4567 // into the low and high part. This is necessary because we want
4568 // to use VPERM* to shuffle the vectors
4570 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4573 return getLegalSplat(DAG, V1, EltNo);
4576 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4577 /// vector of zero or undef vector. This produces a shuffle where the low
4578 /// element of V2 is swizzled into the zero/undef vector, landing at element
4579 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4580 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4582 const X86Subtarget *Subtarget,
4583 SelectionDAG &DAG) {
4584 EVT VT = V2.getValueType();
4586 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4587 unsigned NumElems = VT.getVectorNumElements();
4588 SmallVector<int, 16> MaskVec;
4589 for (unsigned i = 0; i != NumElems; ++i)
4590 // If this is the insertion idx, put the low elt of V2 here.
4591 MaskVec.push_back(i == Idx ? NumElems : i);
4592 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4595 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4596 /// target specific opcode. Returns true if the Mask could be calculated.
4597 /// Sets IsUnary to true if only uses one source.
4598 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4599 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4600 unsigned NumElems = VT.getVectorNumElements();
4604 switch(N->getOpcode()) {
4606 ImmN = N->getOperand(N->getNumOperands()-1);
4607 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4609 case X86ISD::UNPCKH:
4610 DecodeUNPCKHMask(VT, Mask);
4612 case X86ISD::UNPCKL:
4613 DecodeUNPCKLMask(VT, Mask);
4615 case X86ISD::MOVHLPS:
4616 DecodeMOVHLPSMask(NumElems, Mask);
4618 case X86ISD::MOVLHPS:
4619 DecodeMOVLHPSMask(NumElems, Mask);
4621 case X86ISD::PALIGNR:
4622 ImmN = N->getOperand(N->getNumOperands()-1);
4623 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4625 case X86ISD::PSHUFD:
4626 case X86ISD::VPERMILP:
4627 ImmN = N->getOperand(N->getNumOperands()-1);
4628 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4631 case X86ISD::PSHUFHW:
4632 ImmN = N->getOperand(N->getNumOperands()-1);
4633 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4636 case X86ISD::PSHUFLW:
4637 ImmN = N->getOperand(N->getNumOperands()-1);
4638 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4641 case X86ISD::VPERMI:
4642 ImmN = N->getOperand(N->getNumOperands()-1);
4643 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4647 case X86ISD::MOVSD: {
4648 // The index 0 always comes from the first element of the second source,
4649 // this is why MOVSS and MOVSD are used in the first place. The other
4650 // elements come from the other positions of the first source vector
4651 Mask.push_back(NumElems);
4652 for (unsigned i = 1; i != NumElems; ++i) {
4657 case X86ISD::VPERM2X128:
4658 ImmN = N->getOperand(N->getNumOperands()-1);
4659 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660 if (Mask.empty()) return false;
4662 case X86ISD::MOVDDUP:
4663 case X86ISD::MOVLHPD:
4664 case X86ISD::MOVLPD:
4665 case X86ISD::MOVLPS:
4666 case X86ISD::MOVSHDUP:
4667 case X86ISD::MOVSLDUP:
4668 // Not yet implemented
4670 default: llvm_unreachable("unknown target shuffle node");
4676 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4677 /// element of the result of the vector shuffle.
4678 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4681 return SDValue(); // Limit search depth.
4683 SDValue V = SDValue(N, 0);
4684 EVT VT = V.getValueType();
4685 unsigned Opcode = V.getOpcode();
4687 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4688 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4689 int Elt = SV->getMaskElt(Index);
4692 return DAG.getUNDEF(VT.getVectorElementType());
4694 unsigned NumElems = VT.getVectorNumElements();
4695 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4696 : SV->getOperand(1);
4697 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4700 // Recurse into target specific vector shuffles to find scalars.
4701 if (isTargetShuffle(Opcode)) {
4702 MVT ShufVT = V.getValueType().getSimpleVT();
4703 unsigned NumElems = ShufVT.getVectorNumElements();
4704 SmallVector<int, 16> ShuffleMask;
4707 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4710 int Elt = ShuffleMask[Index];
4712 return DAG.getUNDEF(ShufVT.getVectorElementType());
4714 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4716 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4720 // Actual nodes that may contain scalar elements
4721 if (Opcode == ISD::BITCAST) {
4722 V = V.getOperand(0);
4723 EVT SrcVT = V.getValueType();
4724 unsigned NumElems = VT.getVectorNumElements();
4726 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4730 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4731 return (Index == 0) ? V.getOperand(0)
4732 : DAG.getUNDEF(VT.getVectorElementType());
4734 if (V.getOpcode() == ISD::BUILD_VECTOR)
4735 return V.getOperand(Index);
4740 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4741 /// shuffle operation which come from a consecutively from a zero. The
4742 /// search can start in two different directions, from left or right.
4744 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4745 bool ZerosFromLeft, SelectionDAG &DAG) {
4747 for (i = 0; i != NumElems; ++i) {
4748 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4749 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4750 if (!(Elt.getNode() &&
4751 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4758 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4759 /// correspond consecutively to elements from one of the vector operands,
4760 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4762 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4763 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4764 unsigned NumElems, unsigned &OpNum) {
4765 bool SeenV1 = false;
4766 bool SeenV2 = false;
4768 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4769 int Idx = SVOp->getMaskElt(i);
4770 // Ignore undef indicies
4774 if (Idx < (int)NumElems)
4779 // Only accept consecutive elements from the same vector
4780 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4784 OpNum = SeenV1 ? 0 : 1;
4788 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4789 /// logical left shift of a vector.
4790 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4791 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4792 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4793 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4794 false /* check zeros from right */, DAG);
4800 // Considering the elements in the mask that are not consecutive zeros,
4801 // check if they consecutively come from only one of the source vectors.
4803 // V1 = {X, A, B, C} 0
4805 // vector_shuffle V1, V2 <1, 2, 3, X>
4807 if (!isShuffleMaskConsecutive(SVOp,
4808 0, // Mask Start Index
4809 NumElems-NumZeros, // Mask End Index(exclusive)
4810 NumZeros, // Where to start looking in the src vector
4811 NumElems, // Number of elements in vector
4812 OpSrc)) // Which source operand ?
4817 ShVal = SVOp->getOperand(OpSrc);
4821 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4822 /// logical left shift of a vector.
4823 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4824 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4825 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4826 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4827 true /* check zeros from left */, DAG);
4833 // Considering the elements in the mask that are not consecutive zeros,
4834 // check if they consecutively come from only one of the source vectors.
4836 // 0 { A, B, X, X } = V2
4838 // vector_shuffle V1, V2 <X, X, 4, 5>
4840 if (!isShuffleMaskConsecutive(SVOp,
4841 NumZeros, // Mask Start Index
4842 NumElems, // Mask End Index(exclusive)
4843 0, // Where to start looking in the src vector
4844 NumElems, // Number of elements in vector
4845 OpSrc)) // Which source operand ?
4850 ShVal = SVOp->getOperand(OpSrc);
4854 /// isVectorShift - Returns true if the shuffle can be implemented as a
4855 /// logical left or right shift of a vector.
4856 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4857 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4858 // Although the logic below support any bitwidth size, there are no
4859 // shift instructions which handle more than 128-bit vectors.
4860 if (!SVOp->getValueType(0).is128BitVector())
4863 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4864 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4870 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4872 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4873 unsigned NumNonZero, unsigned NumZero,
4875 const X86Subtarget* Subtarget,
4876 const TargetLowering &TLI) {
4880 DebugLoc dl = Op.getDebugLoc();
4883 for (unsigned i = 0; i < 16; ++i) {
4884 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4885 if (ThisIsNonZero && First) {
4887 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4889 V = DAG.getUNDEF(MVT::v8i16);
4894 SDValue ThisElt(0, 0), LastElt(0, 0);
4895 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4896 if (LastIsNonZero) {
4897 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4898 MVT::i16, Op.getOperand(i-1));
4900 if (ThisIsNonZero) {
4901 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4902 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4903 ThisElt, DAG.getConstant(8, MVT::i8));
4905 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4909 if (ThisElt.getNode())
4910 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4911 DAG.getIntPtrConstant(i/2));
4915 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4918 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4920 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4921 unsigned NumNonZero, unsigned NumZero,
4923 const X86Subtarget* Subtarget,
4924 const TargetLowering &TLI) {
4928 DebugLoc dl = Op.getDebugLoc();
4931 for (unsigned i = 0; i < 8; ++i) {
4932 bool isNonZero = (NonZeros & (1 << i)) != 0;
4936 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4938 V = DAG.getUNDEF(MVT::v8i16);
4941 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4942 MVT::v8i16, V, Op.getOperand(i),
4943 DAG.getIntPtrConstant(i));
4950 /// getVShift - Return a vector logical shift node.
4952 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4953 unsigned NumBits, SelectionDAG &DAG,
4954 const TargetLowering &TLI, DebugLoc dl) {
4955 assert(VT.is128BitVector() && "Unknown type for VShift");
4956 EVT ShVT = MVT::v2i64;
4957 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4958 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4959 return DAG.getNode(ISD::BITCAST, dl, VT,
4960 DAG.getNode(Opc, dl, ShVT, SrcOp,
4961 DAG.getConstant(NumBits,
4962 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4966 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4967 SelectionDAG &DAG) const {
4969 // Check if the scalar load can be widened into a vector load. And if
4970 // the address is "base + cst" see if the cst can be "absorbed" into
4971 // the shuffle mask.
4972 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4973 SDValue Ptr = LD->getBasePtr();
4974 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4976 EVT PVT = LD->getValueType(0);
4977 if (PVT != MVT::i32 && PVT != MVT::f32)
4982 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4983 FI = FINode->getIndex();
4985 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4986 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4987 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4988 Offset = Ptr.getConstantOperandVal(1);
4989 Ptr = Ptr.getOperand(0);
4994 // FIXME: 256-bit vector instructions don't require a strict alignment,
4995 // improve this code to support it better.
4996 unsigned RequiredAlign = VT.getSizeInBits()/8;
4997 SDValue Chain = LD->getChain();
4998 // Make sure the stack object alignment is at least 16 or 32.
4999 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5000 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5001 if (MFI->isFixedObjectIndex(FI)) {
5002 // Can't change the alignment. FIXME: It's possible to compute
5003 // the exact stack offset and reference FI + adjust offset instead.
5004 // If someone *really* cares about this. That's the way to implement it.
5007 MFI->setObjectAlignment(FI, RequiredAlign);
5011 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5012 // Ptr + (Offset & ~15).
5015 if ((Offset % RequiredAlign) & 3)
5017 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5019 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5020 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5022 int EltNo = (Offset - StartOffset) >> 2;
5023 unsigned NumElems = VT.getVectorNumElements();
5025 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5026 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5027 LD->getPointerInfo().getWithOffset(StartOffset),
5028 false, false, false, 0);
5030 SmallVector<int, 8> Mask;
5031 for (unsigned i = 0; i != NumElems; ++i)
5032 Mask.push_back(EltNo);
5034 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5040 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5041 /// vector of type 'VT', see if the elements can be replaced by a single large
5042 /// load which has the same value as a build_vector whose operands are 'elts'.
5044 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5046 /// FIXME: we'd also like to handle the case where the last elements are zero
5047 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5048 /// There's even a handy isZeroNode for that purpose.
5049 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5050 DebugLoc &DL, SelectionDAG &DAG) {
5051 EVT EltVT = VT.getVectorElementType();
5052 unsigned NumElems = Elts.size();
5054 LoadSDNode *LDBase = NULL;
5055 unsigned LastLoadedElt = -1U;
5057 // For each element in the initializer, see if we've found a load or an undef.
5058 // If we don't find an initial load element, or later load elements are
5059 // non-consecutive, bail out.
5060 for (unsigned i = 0; i < NumElems; ++i) {
5061 SDValue Elt = Elts[i];
5063 if (!Elt.getNode() ||
5064 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5067 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5069 LDBase = cast<LoadSDNode>(Elt.getNode());
5073 if (Elt.getOpcode() == ISD::UNDEF)
5076 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5077 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5082 // If we have found an entire vector of loads and undefs, then return a large
5083 // load of the entire vector width starting at the base pointer. If we found
5084 // consecutive loads for the low half, generate a vzext_load node.
5085 if (LastLoadedElt == NumElems - 1) {
5086 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5087 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5088 LDBase->getPointerInfo(),
5089 LDBase->isVolatile(), LDBase->isNonTemporal(),
5090 LDBase->isInvariant(), 0);
5091 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5092 LDBase->getPointerInfo(),
5093 LDBase->isVolatile(), LDBase->isNonTemporal(),
5094 LDBase->isInvariant(), LDBase->getAlignment());
5096 if (NumElems == 4 && LastLoadedElt == 1 &&
5097 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5098 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5099 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5101 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5102 LDBase->getPointerInfo(),
5103 LDBase->getAlignment(),
5104 false/*isVolatile*/, true/*ReadMem*/,
5107 // Make sure the newly-created LOAD is in the same position as LDBase in
5108 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5109 // update uses of LDBase's output chain to use the TokenFactor.
5110 if (LDBase->hasAnyUseOfValue(1)) {
5111 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5112 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5113 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5114 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5115 SDValue(ResNode.getNode(), 1));
5118 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5123 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5124 /// to generate a splat value for the following cases:
5125 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5126 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5127 /// a scalar load, or a constant.
5128 /// The VBROADCAST node is returned when a pattern is found,
5129 /// or SDValue() otherwise.
5131 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5132 if (!Subtarget->hasFp256())
5135 MVT VT = Op.getValueType().getSimpleVT();
5136 DebugLoc dl = Op.getDebugLoc();
5138 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5139 "Unsupported vector type for broadcast.");
5144 switch (Op.getOpcode()) {
5146 // Unknown pattern found.
5149 case ISD::BUILD_VECTOR: {
5150 // The BUILD_VECTOR node must be a splat.
5151 if (!isSplatVector(Op.getNode()))
5154 Ld = Op.getOperand(0);
5155 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5156 Ld.getOpcode() == ISD::ConstantFP);
5158 // The suspected load node has several users. Make sure that all
5159 // of its users are from the BUILD_VECTOR node.
5160 // Constants may have multiple users.
5161 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5166 case ISD::VECTOR_SHUFFLE: {
5167 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5169 // Shuffles must have a splat mask where the first element is
5171 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5174 SDValue Sc = Op.getOperand(0);
5175 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5176 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5178 if (!Subtarget->hasInt256())
5181 // Use the register form of the broadcast instruction available on AVX2.
5182 if (VT.is256BitVector())
5183 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5184 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5187 Ld = Sc.getOperand(0);
5188 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5189 Ld.getOpcode() == ISD::ConstantFP);
5191 // The scalar_to_vector node and the suspected
5192 // load node must have exactly one user.
5193 // Constants may have multiple users.
5194 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5200 bool Is256 = VT.is256BitVector();
5202 // Handle the broadcasting a single constant scalar from the constant pool
5203 // into a vector. On Sandybridge it is still better to load a constant vector
5204 // from the constant pool and not to broadcast it from a scalar.
5205 if (ConstSplatVal && Subtarget->hasInt256()) {
5206 EVT CVT = Ld.getValueType();
5207 assert(!CVT.isVector() && "Must not broadcast a vector type");
5208 unsigned ScalarSize = CVT.getSizeInBits();
5210 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5211 const Constant *C = 0;
5212 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5213 C = CI->getConstantIntValue();
5214 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5215 C = CF->getConstantFPValue();
5217 assert(C && "Invalid constant type");
5219 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5220 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5221 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5222 MachinePointerInfo::getConstantPool(),
5223 false, false, false, Alignment);
5225 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5229 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5230 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5232 // Handle AVX2 in-register broadcasts.
5233 if (!IsLoad && Subtarget->hasInt256() &&
5234 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5235 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5237 // The scalar source must be a normal load.
5241 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5242 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5244 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5245 // double since there is no vbroadcastsd xmm
5246 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5247 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5248 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5251 // Unsupported broadcast.
5256 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5257 EVT VT = Op.getValueType();
5259 // Skip if insert_vec_elt is not supported.
5260 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5263 DebugLoc DL = Op.getDebugLoc();
5264 unsigned NumElems = Op.getNumOperands();
5268 SmallVector<unsigned, 4> InsertIndices;
5269 SmallVector<int, 8> Mask(NumElems, -1);
5271 for (unsigned i = 0; i != NumElems; ++i) {
5272 unsigned Opc = Op.getOperand(i).getOpcode();
5274 if (Opc == ISD::UNDEF)
5277 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5278 // Quit if more than 1 elements need inserting.
5279 if (InsertIndices.size() > 1)
5282 InsertIndices.push_back(i);
5286 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5287 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5289 // Quit if extracted from vector of different type.
5290 if (ExtractedFromVec.getValueType() != VT)
5293 // Quit if non-constant index.
5294 if (!isa<ConstantSDNode>(ExtIdx))
5297 if (VecIn1.getNode() == 0)
5298 VecIn1 = ExtractedFromVec;
5299 else if (VecIn1 != ExtractedFromVec) {
5300 if (VecIn2.getNode() == 0)
5301 VecIn2 = ExtractedFromVec;
5302 else if (VecIn2 != ExtractedFromVec)
5303 // Quit if more than 2 vectors to shuffle
5307 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5309 if (ExtractedFromVec == VecIn1)
5311 else if (ExtractedFromVec == VecIn2)
5312 Mask[i] = Idx + NumElems;
5315 if (VecIn1.getNode() == 0)
5318 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5319 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5320 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5321 unsigned Idx = InsertIndices[i];
5322 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5323 DAG.getIntPtrConstant(Idx));
5330 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5331 DebugLoc dl = Op.getDebugLoc();
5333 MVT VT = Op.getValueType().getSimpleVT();
5334 MVT ExtVT = VT.getVectorElementType();
5335 unsigned NumElems = Op.getNumOperands();
5337 // Vectors containing all zeros can be matched by pxor and xorps later
5338 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5339 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5340 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5341 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5344 return getZeroVector(VT, Subtarget, DAG, dl);
5347 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5348 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5349 // vpcmpeqd on 256-bit vectors.
5350 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5351 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5354 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5357 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5358 if (Broadcast.getNode())
5361 unsigned EVTBits = ExtVT.getSizeInBits();
5363 unsigned NumZero = 0;
5364 unsigned NumNonZero = 0;
5365 unsigned NonZeros = 0;
5366 bool IsAllConstants = true;
5367 SmallSet<SDValue, 8> Values;
5368 for (unsigned i = 0; i < NumElems; ++i) {
5369 SDValue Elt = Op.getOperand(i);
5370 if (Elt.getOpcode() == ISD::UNDEF)
5373 if (Elt.getOpcode() != ISD::Constant &&
5374 Elt.getOpcode() != ISD::ConstantFP)
5375 IsAllConstants = false;
5376 if (X86::isZeroNode(Elt))
5379 NonZeros |= (1 << i);
5384 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5385 if (NumNonZero == 0)
5386 return DAG.getUNDEF(VT);
5388 // Special case for single non-zero, non-undef, element.
5389 if (NumNonZero == 1) {
5390 unsigned Idx = CountTrailingZeros_32(NonZeros);
5391 SDValue Item = Op.getOperand(Idx);
5393 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5394 // the value are obviously zero, truncate the value to i32 and do the
5395 // insertion that way. Only do this if the value is non-constant or if the
5396 // value is a constant being inserted into element 0. It is cheaper to do
5397 // a constant pool load than it is to do a movd + shuffle.
5398 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5399 (!IsAllConstants || Idx == 0)) {
5400 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5402 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5403 EVT VecVT = MVT::v4i32;
5404 unsigned VecElts = 4;
5406 // Truncate the value (which may itself be a constant) to i32, and
5407 // convert it to a vector with movd (S2V+shuffle to zero extend).
5408 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5409 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5410 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5412 // Now we have our 32-bit value zero extended in the low element of
5413 // a vector. If Idx != 0, swizzle it into place.
5415 SmallVector<int, 4> Mask;
5416 Mask.push_back(Idx);
5417 for (unsigned i = 1; i != VecElts; ++i)
5419 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5422 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5426 // If we have a constant or non-constant insertion into the low element of
5427 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5428 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5429 // depending on what the source datatype is.
5432 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5434 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5435 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5436 if (VT.is256BitVector()) {
5437 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5438 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5439 Item, DAG.getIntPtrConstant(0));
5441 assert(VT.is128BitVector() && "Expected an SSE value type!");
5442 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5443 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5444 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5447 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5448 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5449 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5450 if (VT.is256BitVector()) {
5451 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5452 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5454 assert(VT.is128BitVector() && "Expected an SSE value type!");
5455 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5457 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5461 // Is it a vector logical left shift?
5462 if (NumElems == 2 && Idx == 1 &&
5463 X86::isZeroNode(Op.getOperand(0)) &&
5464 !X86::isZeroNode(Op.getOperand(1))) {
5465 unsigned NumBits = VT.getSizeInBits();
5466 return getVShift(true, VT,
5467 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5468 VT, Op.getOperand(1)),
5469 NumBits/2, DAG, *this, dl);
5472 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5475 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5476 // is a non-constant being inserted into an element other than the low one,
5477 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5478 // movd/movss) to move this into the low element, then shuffle it into
5480 if (EVTBits == 32) {
5481 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5483 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5484 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5485 SmallVector<int, 8> MaskVec;
5486 for (unsigned i = 0; i != NumElems; ++i)
5487 MaskVec.push_back(i == Idx ? 0 : 1);
5488 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5492 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5493 if (Values.size() == 1) {
5494 if (EVTBits == 32) {
5495 // Instead of a shuffle like this:
5496 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5497 // Check if it's possible to issue this instead.
5498 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5499 unsigned Idx = CountTrailingZeros_32(NonZeros);
5500 SDValue Item = Op.getOperand(Idx);
5501 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5502 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5507 // A vector full of immediates; various special cases are already
5508 // handled, so this is best done with a single constant-pool load.
5512 // For AVX-length vectors, build the individual 128-bit pieces and use
5513 // shuffles to put them in place.
5514 if (VT.is256BitVector()) {
5515 SmallVector<SDValue, 32> V;
5516 for (unsigned i = 0; i != NumElems; ++i)
5517 V.push_back(Op.getOperand(i));
5519 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5521 // Build both the lower and upper subvector.
5522 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5523 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5526 // Recreate the wider vector with the lower and upper part.
5527 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5530 // Let legalizer expand 2-wide build_vectors.
5531 if (EVTBits == 64) {
5532 if (NumNonZero == 1) {
5533 // One half is zero or undef.
5534 unsigned Idx = CountTrailingZeros_32(NonZeros);
5535 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5536 Op.getOperand(Idx));
5537 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5542 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5543 if (EVTBits == 8 && NumElems == 16) {
5544 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5546 if (V.getNode()) return V;
5549 if (EVTBits == 16 && NumElems == 8) {
5550 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5552 if (V.getNode()) return V;
5555 // If element VT is == 32 bits, turn it into a number of shuffles.
5556 SmallVector<SDValue, 8> V(NumElems);
5557 if (NumElems == 4 && NumZero > 0) {
5558 for (unsigned i = 0; i < 4; ++i) {
5559 bool isZero = !(NonZeros & (1 << i));
5561 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5563 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5566 for (unsigned i = 0; i < 2; ++i) {
5567 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5570 V[i] = V[i*2]; // Must be a zero vector.
5573 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5576 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5579 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5584 bool Reverse1 = (NonZeros & 0x3) == 2;
5585 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5589 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5590 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5592 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5595 if (Values.size() > 1 && VT.is128BitVector()) {
5596 // Check for a build vector of consecutive loads.
5597 for (unsigned i = 0; i < NumElems; ++i)
5598 V[i] = Op.getOperand(i);
5600 // Check for elements which are consecutive loads.
5601 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5605 // Check for a build vector from mostly shuffle plus few inserting.
5606 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5610 // For SSE 4.1, use insertps to put the high elements into the low element.
5611 if (getSubtarget()->hasSSE41()) {
5613 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5614 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5616 Result = DAG.getUNDEF(VT);
5618 for (unsigned i = 1; i < NumElems; ++i) {
5619 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5620 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5621 Op.getOperand(i), DAG.getIntPtrConstant(i));
5626 // Otherwise, expand into a number of unpckl*, start by extending each of
5627 // our (non-undef) elements to the full vector width with the element in the
5628 // bottom slot of the vector (which generates no code for SSE).
5629 for (unsigned i = 0; i < NumElems; ++i) {
5630 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5631 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5633 V[i] = DAG.getUNDEF(VT);
5636 // Next, we iteratively mix elements, e.g. for v4f32:
5637 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5638 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5639 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5640 unsigned EltStride = NumElems >> 1;
5641 while (EltStride != 0) {
5642 for (unsigned i = 0; i < EltStride; ++i) {
5643 // If V[i+EltStride] is undef and this is the first round of mixing,
5644 // then it is safe to just drop this shuffle: V[i] is already in the
5645 // right place, the one element (since it's the first round) being
5646 // inserted as undef can be dropped. This isn't safe for successive
5647 // rounds because they will permute elements within both vectors.
5648 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5649 EltStride == NumElems/2)
5652 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5661 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5662 // to create 256-bit vectors from two other 128-bit ones.
5663 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5664 DebugLoc dl = Op.getDebugLoc();
5665 MVT ResVT = Op.getValueType().getSimpleVT();
5667 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5669 SDValue V1 = Op.getOperand(0);
5670 SDValue V2 = Op.getOperand(1);
5671 unsigned NumElems = ResVT.getVectorNumElements();
5673 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5676 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5677 assert(Op.getNumOperands() == 2);
5679 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5680 // from two other 128-bit ones.
5681 return LowerAVXCONCAT_VECTORS(Op, DAG);
5684 // Try to lower a shuffle node into a simple blend instruction.
5686 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5687 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5688 SDValue V1 = SVOp->getOperand(0);
5689 SDValue V2 = SVOp->getOperand(1);
5690 DebugLoc dl = SVOp->getDebugLoc();
5691 MVT VT = SVOp->getValueType(0).getSimpleVT();
5692 MVT EltVT = VT.getVectorElementType();
5693 unsigned NumElems = VT.getVectorNumElements();
5695 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5697 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5700 // Check the mask for BLEND and build the value.
5701 unsigned MaskValue = 0;
5702 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5703 unsigned NumLanes = (NumElems-1)/8 + 1;
5704 unsigned NumElemsInLane = NumElems / NumLanes;
5706 // Blend for v16i16 should be symetric for the both lanes.
5707 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5709 int SndLaneEltIdx = (NumLanes == 2) ?
5710 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5711 int EltIdx = SVOp->getMaskElt(i);
5713 if ((EltIdx < 0 || EltIdx == (int)i) &&
5714 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5717 if (((unsigned)EltIdx == (i + NumElems)) &&
5718 (SndLaneEltIdx < 0 ||
5719 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5720 MaskValue |= (1<<i);
5725 // Convert i32 vectors to floating point if it is not AVX2.
5726 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5728 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5729 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5731 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5732 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5735 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5736 DAG.getConstant(MaskValue, MVT::i32));
5737 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5740 // v8i16 shuffles - Prefer shuffles in the following order:
5741 // 1. [all] pshuflw, pshufhw, optional move
5742 // 2. [ssse3] 1 x pshufb
5743 // 3. [ssse3] 2 x pshufb + 1 x por
5744 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5746 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5747 SelectionDAG &DAG) {
5748 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5749 SDValue V1 = SVOp->getOperand(0);
5750 SDValue V2 = SVOp->getOperand(1);
5751 DebugLoc dl = SVOp->getDebugLoc();
5752 SmallVector<int, 8> MaskVals;
5754 // Determine if more than 1 of the words in each of the low and high quadwords
5755 // of the result come from the same quadword of one of the two inputs. Undef
5756 // mask values count as coming from any quadword, for better codegen.
5757 unsigned LoQuad[] = { 0, 0, 0, 0 };
5758 unsigned HiQuad[] = { 0, 0, 0, 0 };
5759 std::bitset<4> InputQuads;
5760 for (unsigned i = 0; i < 8; ++i) {
5761 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5762 int EltIdx = SVOp->getMaskElt(i);
5763 MaskVals.push_back(EltIdx);
5772 InputQuads.set(EltIdx / 4);
5775 int BestLoQuad = -1;
5776 unsigned MaxQuad = 1;
5777 for (unsigned i = 0; i < 4; ++i) {
5778 if (LoQuad[i] > MaxQuad) {
5780 MaxQuad = LoQuad[i];
5784 int BestHiQuad = -1;
5786 for (unsigned i = 0; i < 4; ++i) {
5787 if (HiQuad[i] > MaxQuad) {
5789 MaxQuad = HiQuad[i];
5793 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5794 // of the two input vectors, shuffle them into one input vector so only a
5795 // single pshufb instruction is necessary. If There are more than 2 input
5796 // quads, disable the next transformation since it does not help SSSE3.
5797 bool V1Used = InputQuads[0] || InputQuads[1];
5798 bool V2Used = InputQuads[2] || InputQuads[3];
5799 if (Subtarget->hasSSSE3()) {
5800 if (InputQuads.count() == 2 && V1Used && V2Used) {
5801 BestLoQuad = InputQuads[0] ? 0 : 1;
5802 BestHiQuad = InputQuads[2] ? 2 : 3;
5804 if (InputQuads.count() > 2) {
5810 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5811 // the shuffle mask. If a quad is scored as -1, that means that it contains
5812 // words from all 4 input quadwords.
5814 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5816 BestLoQuad < 0 ? 0 : BestLoQuad,
5817 BestHiQuad < 0 ? 1 : BestHiQuad
5819 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5820 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5821 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5822 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5824 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5825 // source words for the shuffle, to aid later transformations.
5826 bool AllWordsInNewV = true;
5827 bool InOrder[2] = { true, true };
5828 for (unsigned i = 0; i != 8; ++i) {
5829 int idx = MaskVals[i];
5831 InOrder[i/4] = false;
5832 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5834 AllWordsInNewV = false;
5838 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5839 if (AllWordsInNewV) {
5840 for (int i = 0; i != 8; ++i) {
5841 int idx = MaskVals[i];
5844 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5845 if ((idx != i) && idx < 4)
5847 if ((idx != i) && idx > 3)
5856 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5857 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5858 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5859 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5860 unsigned TargetMask = 0;
5861 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5862 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5863 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5864 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5865 getShufflePSHUFLWImmediate(SVOp);
5866 V1 = NewV.getOperand(0);
5867 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5871 // Promote splats to a larger type which usually leads to more efficient code.
5872 // FIXME: Is this true if pshufb is available?
5873 if (SVOp->isSplat())
5874 return PromoteSplat(SVOp, DAG);
5876 // If we have SSSE3, and all words of the result are from 1 input vector,
5877 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5878 // is present, fall back to case 4.
5879 if (Subtarget->hasSSSE3()) {
5880 SmallVector<SDValue,16> pshufbMask;
5882 // If we have elements from both input vectors, set the high bit of the
5883 // shuffle mask element to zero out elements that come from V2 in the V1
5884 // mask, and elements that come from V1 in the V2 mask, so that the two
5885 // results can be OR'd together.
5886 bool TwoInputs = V1Used && V2Used;
5887 for (unsigned i = 0; i != 8; ++i) {
5888 int EltIdx = MaskVals[i] * 2;
5889 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5890 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5891 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5892 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5894 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5895 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5896 DAG.getNode(ISD::BUILD_VECTOR, dl,
5897 MVT::v16i8, &pshufbMask[0], 16));
5899 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5901 // Calculate the shuffle mask for the second input, shuffle it, and
5902 // OR it with the first shuffled input.
5904 for (unsigned i = 0; i != 8; ++i) {
5905 int EltIdx = MaskVals[i] * 2;
5906 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5907 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5908 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5909 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5911 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5912 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5913 DAG.getNode(ISD::BUILD_VECTOR, dl,
5914 MVT::v16i8, &pshufbMask[0], 16));
5915 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5916 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5919 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5920 // and update MaskVals with new element order.
5921 std::bitset<8> InOrder;
5922 if (BestLoQuad >= 0) {
5923 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5924 for (int i = 0; i != 4; ++i) {
5925 int idx = MaskVals[i];
5928 } else if ((idx / 4) == BestLoQuad) {
5933 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5936 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5937 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5938 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5940 getShufflePSHUFLWImmediate(SVOp), DAG);
5944 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5945 // and update MaskVals with the new element order.
5946 if (BestHiQuad >= 0) {
5947 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5948 for (unsigned i = 4; i != 8; ++i) {
5949 int idx = MaskVals[i];
5952 } else if ((idx / 4) == BestHiQuad) {
5953 MaskV[i] = (idx & 3) + 4;
5957 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5960 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5961 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5962 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5964 getShufflePSHUFHWImmediate(SVOp), DAG);
5968 // In case BestHi & BestLo were both -1, which means each quadword has a word
5969 // from each of the four input quadwords, calculate the InOrder bitvector now
5970 // before falling through to the insert/extract cleanup.
5971 if (BestLoQuad == -1 && BestHiQuad == -1) {
5973 for (int i = 0; i != 8; ++i)
5974 if (MaskVals[i] < 0 || MaskVals[i] == i)
5978 // The other elements are put in the right place using pextrw and pinsrw.
5979 for (unsigned i = 0; i != 8; ++i) {
5982 int EltIdx = MaskVals[i];
5985 SDValue ExtOp = (EltIdx < 8) ?
5986 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5987 DAG.getIntPtrConstant(EltIdx)) :
5988 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5989 DAG.getIntPtrConstant(EltIdx - 8));
5990 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5991 DAG.getIntPtrConstant(i));
5996 // v16i8 shuffles - Prefer shuffles in the following order:
5997 // 1. [ssse3] 1 x pshufb
5998 // 2. [ssse3] 2 x pshufb + 1 x por
5999 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
6001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6003 const X86TargetLowering &TLI) {
6004 SDValue V1 = SVOp->getOperand(0);
6005 SDValue V2 = SVOp->getOperand(1);
6006 DebugLoc dl = SVOp->getDebugLoc();
6007 ArrayRef<int> MaskVals = SVOp->getMask();
6009 // Promote splats to a larger type which usually leads to more efficient code.
6010 // FIXME: Is this true if pshufb is available?
6011 if (SVOp->isSplat())
6012 return PromoteSplat(SVOp, DAG);
6014 // If we have SSSE3, case 1 is generated when all result bytes come from
6015 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
6016 // present, fall back to case 3.
6018 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6019 if (TLI.getSubtarget()->hasSSSE3()) {
6020 SmallVector<SDValue,16> pshufbMask;
6022 // If all result elements are from one input vector, then only translate
6023 // undef mask values to 0x80 (zero out result) in the pshufb mask.
6025 // Otherwise, we have elements from both input vectors, and must zero out
6026 // elements that come from V2 in the first mask, and V1 in the second mask
6027 // so that we can OR them together.
6028 for (unsigned i = 0; i != 16; ++i) {
6029 int EltIdx = MaskVals[i];
6030 if (EltIdx < 0 || EltIdx >= 16)
6032 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6034 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6035 DAG.getNode(ISD::BUILD_VECTOR, dl,
6036 MVT::v16i8, &pshufbMask[0], 16));
6038 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6039 // the 2nd operand if it's undefined or zero.
6040 if (V2.getOpcode() == ISD::UNDEF ||
6041 ISD::isBuildVectorAllZeros(V2.getNode()))
6044 // Calculate the shuffle mask for the second input, shuffle it, and
6045 // OR it with the first shuffled input.
6047 for (unsigned i = 0; i != 16; ++i) {
6048 int EltIdx = MaskVals[i];
6049 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6050 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6052 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6053 DAG.getNode(ISD::BUILD_VECTOR, dl,
6054 MVT::v16i8, &pshufbMask[0], 16));
6055 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6058 // No SSSE3 - Calculate in place words and then fix all out of place words
6059 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6060 // the 16 different words that comprise the two doublequadword input vectors.
6061 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6062 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6064 for (int i = 0; i != 8; ++i) {
6065 int Elt0 = MaskVals[i*2];
6066 int Elt1 = MaskVals[i*2+1];
6068 // This word of the result is all undef, skip it.
6069 if (Elt0 < 0 && Elt1 < 0)
6072 // This word of the result is already in the correct place, skip it.
6073 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6076 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6077 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6080 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6081 // using a single extract together, load it and store it.
6082 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6083 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6084 DAG.getIntPtrConstant(Elt1 / 2));
6085 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6086 DAG.getIntPtrConstant(i));
6090 // If Elt1 is defined, extract it from the appropriate source. If the
6091 // source byte is not also odd, shift the extracted word left 8 bits
6092 // otherwise clear the bottom 8 bits if we need to do an or.
6094 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6095 DAG.getIntPtrConstant(Elt1 / 2));
6096 if ((Elt1 & 1) == 0)
6097 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6099 TLI.getShiftAmountTy(InsElt.getValueType())));
6101 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6102 DAG.getConstant(0xFF00, MVT::i16));
6104 // If Elt0 is defined, extract it from the appropriate source. If the
6105 // source byte is not also even, shift the extracted word right 8 bits. If
6106 // Elt1 was also defined, OR the extracted values together before
6107 // inserting them in the result.
6109 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6110 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6111 if ((Elt0 & 1) != 0)
6112 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6114 TLI.getShiftAmountTy(InsElt0.getValueType())));
6116 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6117 DAG.getConstant(0x00FF, MVT::i16));
6118 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6121 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6122 DAG.getIntPtrConstant(i));
6124 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6127 // v32i8 shuffles - Translate to VPSHUFB if possible.
6129 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6130 const X86Subtarget *Subtarget,
6131 SelectionDAG &DAG) {
6132 MVT VT = SVOp->getValueType(0).getSimpleVT();
6133 SDValue V1 = SVOp->getOperand(0);
6134 SDValue V2 = SVOp->getOperand(1);
6135 DebugLoc dl = SVOp->getDebugLoc();
6136 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6138 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6139 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6140 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6142 // VPSHUFB may be generated if
6143 // (1) one of input vector is undefined or zeroinitializer.
6144 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6145 // And (2) the mask indexes don't cross the 128-bit lane.
6146 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6147 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6150 if (V1IsAllZero && !V2IsAllZero) {
6151 CommuteVectorShuffleMask(MaskVals, 32);
6154 SmallVector<SDValue, 32> pshufbMask;
6155 for (unsigned i = 0; i != 32; i++) {
6156 int EltIdx = MaskVals[i];
6157 if (EltIdx < 0 || EltIdx >= 32)
6160 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6161 // Cross lane is not allowed.
6165 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6167 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6168 DAG.getNode(ISD::BUILD_VECTOR, dl,
6169 MVT::v32i8, &pshufbMask[0], 32));
6172 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6173 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6174 /// done when every pair / quad of shuffle mask elements point to elements in
6175 /// the right sequence. e.g.
6176 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6178 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6179 SelectionDAG &DAG) {
6180 MVT VT = SVOp->getValueType(0).getSimpleVT();
6181 DebugLoc dl = SVOp->getDebugLoc();
6182 unsigned NumElems = VT.getVectorNumElements();
6185 switch (VT.SimpleTy) {
6186 default: llvm_unreachable("Unexpected!");
6187 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6188 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6189 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6190 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6191 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6192 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6195 SmallVector<int, 8> MaskVec;
6196 for (unsigned i = 0; i != NumElems; i += Scale) {
6198 for (unsigned j = 0; j != Scale; ++j) {
6199 int EltIdx = SVOp->getMaskElt(i+j);
6203 StartIdx = (EltIdx / Scale);
6204 if (EltIdx != (int)(StartIdx*Scale + j))
6207 MaskVec.push_back(StartIdx);
6210 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6211 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6212 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6215 /// getVZextMovL - Return a zero-extending vector move low node.
6217 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6218 SDValue SrcOp, SelectionDAG &DAG,
6219 const X86Subtarget *Subtarget, DebugLoc dl) {
6220 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6221 LoadSDNode *LD = NULL;
6222 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6223 LD = dyn_cast<LoadSDNode>(SrcOp);
6225 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6227 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6228 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6229 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6230 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6231 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6233 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6234 return DAG.getNode(ISD::BITCAST, dl, VT,
6235 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6236 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6244 return DAG.getNode(ISD::BITCAST, dl, VT,
6245 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6246 DAG.getNode(ISD::BITCAST, dl,
6250 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6251 /// which could not be matched by any known target speficic shuffle
6253 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6255 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6256 if (NewOp.getNode())
6259 MVT VT = SVOp->getValueType(0).getSimpleVT();
6261 unsigned NumElems = VT.getVectorNumElements();
6262 unsigned NumLaneElems = NumElems / 2;
6264 DebugLoc dl = SVOp->getDebugLoc();
6265 MVT EltVT = VT.getVectorElementType();
6266 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6269 SmallVector<int, 16> Mask;
6270 for (unsigned l = 0; l < 2; ++l) {
6271 // Build a shuffle mask for the output, discovering on the fly which
6272 // input vectors to use as shuffle operands (recorded in InputUsed).
6273 // If building a suitable shuffle vector proves too hard, then bail
6274 // out with UseBuildVector set.
6275 bool UseBuildVector = false;
6276 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6277 unsigned LaneStart = l * NumLaneElems;
6278 for (unsigned i = 0; i != NumLaneElems; ++i) {
6279 // The mask element. This indexes into the input.
6280 int Idx = SVOp->getMaskElt(i+LaneStart);
6282 // the mask element does not index into any input vector.
6287 // The input vector this mask element indexes into.
6288 int Input = Idx / NumLaneElems;
6290 // Turn the index into an offset from the start of the input vector.
6291 Idx -= Input * NumLaneElems;
6293 // Find or create a shuffle vector operand to hold this input.
6295 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6296 if (InputUsed[OpNo] == Input)
6297 // This input vector is already an operand.
6299 if (InputUsed[OpNo] < 0) {
6300 // Create a new operand for this input vector.
6301 InputUsed[OpNo] = Input;
6306 if (OpNo >= array_lengthof(InputUsed)) {
6307 // More than two input vectors used! Give up on trying to create a
6308 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6309 UseBuildVector = true;
6313 // Add the mask index for the new shuffle vector.
6314 Mask.push_back(Idx + OpNo * NumLaneElems);
6317 if (UseBuildVector) {
6318 SmallVector<SDValue, 16> SVOps;
6319 for (unsigned i = 0; i != NumLaneElems; ++i) {
6320 // The mask element. This indexes into the input.
6321 int Idx = SVOp->getMaskElt(i+LaneStart);
6323 SVOps.push_back(DAG.getUNDEF(EltVT));
6327 // The input vector this mask element indexes into.
6328 int Input = Idx / NumElems;
6330 // Turn the index into an offset from the start of the input vector.
6331 Idx -= Input * NumElems;
6333 // Extract the vector element by hand.
6334 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6335 SVOp->getOperand(Input),
6336 DAG.getIntPtrConstant(Idx)));
6339 // Construct the output using a BUILD_VECTOR.
6340 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6342 } else if (InputUsed[0] < 0) {
6343 // No input vectors were used! The result is undefined.
6344 Output[l] = DAG.getUNDEF(NVT);
6346 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6347 (InputUsed[0] % 2) * NumLaneElems,
6349 // If only one input was used, use an undefined vector for the other.
6350 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6351 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6352 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6353 // At least one input vector was used. Create a new shuffle vector.
6354 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6360 // Concatenate the result back
6361 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6364 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6365 /// 4 elements, and match them with several different shuffle types.
6367 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6368 SDValue V1 = SVOp->getOperand(0);
6369 SDValue V2 = SVOp->getOperand(1);
6370 DebugLoc dl = SVOp->getDebugLoc();
6371 MVT VT = SVOp->getValueType(0).getSimpleVT();
6373 assert(VT.is128BitVector() && "Unsupported vector size");
6375 std::pair<int, int> Locs[4];
6376 int Mask1[] = { -1, -1, -1, -1 };
6377 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6381 for (unsigned i = 0; i != 4; ++i) {
6382 int Idx = PermMask[i];
6384 Locs[i] = std::make_pair(-1, -1);
6386 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6388 Locs[i] = std::make_pair(0, NumLo);
6392 Locs[i] = std::make_pair(1, NumHi);
6394 Mask1[2+NumHi] = Idx;
6400 if (NumLo <= 2 && NumHi <= 2) {
6401 // If no more than two elements come from either vector. This can be
6402 // implemented with two shuffles. First shuffle gather the elements.
6403 // The second shuffle, which takes the first shuffle as both of its
6404 // vector operands, put the elements into the right order.
6405 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6407 int Mask2[] = { -1, -1, -1, -1 };
6409 for (unsigned i = 0; i != 4; ++i)
6410 if (Locs[i].first != -1) {
6411 unsigned Idx = (i < 2) ? 0 : 4;
6412 Idx += Locs[i].first * 2 + Locs[i].second;
6416 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6419 if (NumLo == 3 || NumHi == 3) {
6420 // Otherwise, we must have three elements from one vector, call it X, and
6421 // one element from the other, call it Y. First, use a shufps to build an
6422 // intermediate vector with the one element from Y and the element from X
6423 // that will be in the same half in the final destination (the indexes don't
6424 // matter). Then, use a shufps to build the final vector, taking the half
6425 // containing the element from Y from the intermediate, and the other half
6428 // Normalize it so the 3 elements come from V1.
6429 CommuteVectorShuffleMask(PermMask, 4);
6433 // Find the element from V2.
6435 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6436 int Val = PermMask[HiIndex];
6443 Mask1[0] = PermMask[HiIndex];
6445 Mask1[2] = PermMask[HiIndex^1];
6447 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6450 Mask1[0] = PermMask[0];
6451 Mask1[1] = PermMask[1];
6452 Mask1[2] = HiIndex & 1 ? 6 : 4;
6453 Mask1[3] = HiIndex & 1 ? 4 : 6;
6454 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6457 Mask1[0] = HiIndex & 1 ? 2 : 0;
6458 Mask1[1] = HiIndex & 1 ? 0 : 2;
6459 Mask1[2] = PermMask[2];
6460 Mask1[3] = PermMask[3];
6465 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6468 // Break it into (shuffle shuffle_hi, shuffle_lo).
6469 int LoMask[] = { -1, -1, -1, -1 };
6470 int HiMask[] = { -1, -1, -1, -1 };
6472 int *MaskPtr = LoMask;
6473 unsigned MaskIdx = 0;
6476 for (unsigned i = 0; i != 4; ++i) {
6483 int Idx = PermMask[i];
6485 Locs[i] = std::make_pair(-1, -1);
6486 } else if (Idx < 4) {
6487 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6488 MaskPtr[LoIdx] = Idx;
6491 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6492 MaskPtr[HiIdx] = Idx;
6497 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6498 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6499 int MaskOps[] = { -1, -1, -1, -1 };
6500 for (unsigned i = 0; i != 4; ++i)
6501 if (Locs[i].first != -1)
6502 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6503 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6506 static bool MayFoldVectorLoad(SDValue V) {
6507 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6508 V = V.getOperand(0);
6510 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6511 V = V.getOperand(0);
6512 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6513 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6514 // BUILD_VECTOR (load), undef
6515 V = V.getOperand(0);
6517 return MayFoldLoad(V);
6521 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6522 EVT VT = Op.getValueType();
6524 // Canonizalize to v2f64.
6525 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6526 return DAG.getNode(ISD::BITCAST, dl, VT,
6527 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6532 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6534 SDValue V1 = Op.getOperand(0);
6535 SDValue V2 = Op.getOperand(1);
6536 EVT VT = Op.getValueType();
6538 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6540 if (HasSSE2 && VT == MVT::v2f64)
6541 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6543 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6544 return DAG.getNode(ISD::BITCAST, dl, VT,
6545 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6546 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6547 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6551 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6552 SDValue V1 = Op.getOperand(0);
6553 SDValue V2 = Op.getOperand(1);
6554 EVT VT = Op.getValueType();
6556 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6557 "unsupported shuffle type");
6559 if (V2.getOpcode() == ISD::UNDEF)
6563 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6567 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6568 SDValue V1 = Op.getOperand(0);
6569 SDValue V2 = Op.getOperand(1);
6570 EVT VT = Op.getValueType();
6571 unsigned NumElems = VT.getVectorNumElements();
6573 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6574 // operand of these instructions is only memory, so check if there's a
6575 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6577 bool CanFoldLoad = false;
6579 // Trivial case, when V2 comes from a load.
6580 if (MayFoldVectorLoad(V2))
6583 // When V1 is a load, it can be folded later into a store in isel, example:
6584 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6586 // (MOVLPSmr addr:$src1, VR128:$src2)
6587 // So, recognize this potential and also use MOVLPS or MOVLPD
6588 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6591 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6593 if (HasSSE2 && NumElems == 2)
6594 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6597 // If we don't care about the second element, proceed to use movss.
6598 if (SVOp->getMaskElt(1) != -1)
6599 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6602 // movl and movlp will both match v2i64, but v2i64 is never matched by
6603 // movl earlier because we make it strict to avoid messing with the movlp load
6604 // folding logic (see the code above getMOVLP call). Match it here then,
6605 // this is horrible, but will stay like this until we move all shuffle
6606 // matching to x86 specific nodes. Note that for the 1st condition all
6607 // types are matched with movsd.
6609 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6610 // as to remove this logic from here, as much as possible
6611 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6612 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6613 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6616 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6618 // Invert the operand order and use SHUFPS to match it.
6619 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6620 getShuffleSHUFImmediate(SVOp), DAG);
6623 // Reduce a vector shuffle to zext.
6625 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6626 // PMOVZX is only available from SSE41.
6627 if (!Subtarget->hasSSE41())
6630 EVT VT = Op.getValueType();
6632 // Only AVX2 support 256-bit vector integer extending.
6633 if (!Subtarget->hasInt256() && VT.is256BitVector())
6636 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6637 DebugLoc DL = Op.getDebugLoc();
6638 SDValue V1 = Op.getOperand(0);
6639 SDValue V2 = Op.getOperand(1);
6640 unsigned NumElems = VT.getVectorNumElements();
6642 // Extending is an unary operation and the element type of the source vector
6643 // won't be equal to or larger than i64.
6644 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6645 VT.getVectorElementType() == MVT::i64)
6648 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6649 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6650 while ((1U << Shift) < NumElems) {
6651 if (SVOp->getMaskElt(1U << Shift) == 1)
6654 // The maximal ratio is 8, i.e. from i8 to i64.
6659 // Check the shuffle mask.
6660 unsigned Mask = (1U << Shift) - 1;
6661 for (unsigned i = 0; i != NumElems; ++i) {
6662 int EltIdx = SVOp->getMaskElt(i);
6663 if ((i & Mask) != 0 && EltIdx != -1)
6665 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6669 LLVMContext *Context = DAG.getContext();
6670 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6671 EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6672 EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6674 if (!isTypeLegal(NVT))
6677 // Simplify the operand as it's prepared to be fed into shuffle.
6678 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6679 if (V1.getOpcode() == ISD::BITCAST &&
6680 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6681 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6683 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6684 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6685 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6686 ConstantSDNode *CIdx =
6687 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6688 // If it's foldable, i.e. normal load with single use, we will let code
6689 // selection to fold it. Otherwise, we will short the conversion sequence.
6690 if (CIdx && CIdx->getZExtValue() == 0 &&
6691 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6692 if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6693 // The "ext_vec_elt" node is wider than the result node.
6694 // In this case we should extract subvector from V.
6695 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6696 unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6697 EVT FullVT = V.getValueType();
6698 EVT SubVecVT = EVT::getVectorVT(*Context,
6699 FullVT.getVectorElementType(),
6700 FullVT.getVectorNumElements()/Ratio);
6701 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6702 DAG.getIntPtrConstant(0));
6704 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6708 return DAG.getNode(ISD::BITCAST, DL, VT,
6709 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6713 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6714 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6715 MVT VT = Op.getValueType().getSimpleVT();
6716 DebugLoc dl = Op.getDebugLoc();
6717 SDValue V1 = Op.getOperand(0);
6718 SDValue V2 = Op.getOperand(1);
6720 if (isZeroShuffle(SVOp))
6721 return getZeroVector(VT, Subtarget, DAG, dl);
6723 // Handle splat operations
6724 if (SVOp->isSplat()) {
6725 // Use vbroadcast whenever the splat comes from a foldable load
6726 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6727 if (Broadcast.getNode())
6731 // Check integer expanding shuffles.
6732 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6733 if (NewOp.getNode())
6736 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6738 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6739 VT == MVT::v16i16 || VT == MVT::v32i8) {
6740 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6741 if (NewOp.getNode())
6742 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6743 } else if ((VT == MVT::v4i32 ||
6744 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6745 // FIXME: Figure out a cleaner way to do this.
6746 // Try to make use of movq to zero out the top part.
6747 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6748 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6749 if (NewOp.getNode()) {
6750 MVT NewVT = NewOp.getValueType().getSimpleVT();
6751 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6752 NewVT, true, false))
6753 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6754 DAG, Subtarget, dl);
6756 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6757 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6758 if (NewOp.getNode()) {
6759 MVT NewVT = NewOp.getValueType().getSimpleVT();
6760 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6761 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6762 DAG, Subtarget, dl);
6770 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6772 SDValue V1 = Op.getOperand(0);
6773 SDValue V2 = Op.getOperand(1);
6774 MVT VT = Op.getValueType().getSimpleVT();
6775 DebugLoc dl = Op.getDebugLoc();
6776 unsigned NumElems = VT.getVectorNumElements();
6777 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6778 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6779 bool V1IsSplat = false;
6780 bool V2IsSplat = false;
6781 bool HasSSE2 = Subtarget->hasSSE2();
6782 bool HasFp256 = Subtarget->hasFp256();
6783 bool HasInt256 = Subtarget->hasInt256();
6784 MachineFunction &MF = DAG.getMachineFunction();
6785 bool OptForSize = MF.getFunction()->getAttributes().
6786 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6788 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6790 if (V1IsUndef && V2IsUndef)
6791 return DAG.getUNDEF(VT);
6793 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6795 // Vector shuffle lowering takes 3 steps:
6797 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6798 // narrowing and commutation of operands should be handled.
6799 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6801 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6802 // so the shuffle can be broken into other shuffles and the legalizer can
6803 // try the lowering again.
6805 // The general idea is that no vector_shuffle operation should be left to
6806 // be matched during isel, all of them must be converted to a target specific
6809 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6810 // narrowing and commutation of operands should be handled. The actual code
6811 // doesn't include all of those, work in progress...
6812 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6813 if (NewOp.getNode())
6816 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6818 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6819 // unpckh_undef). Only use pshufd if speed is more important than size.
6820 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6821 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6822 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6823 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6825 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6826 V2IsUndef && MayFoldVectorLoad(V1))
6827 return getMOVDDup(Op, dl, V1, DAG);
6829 if (isMOVHLPS_v_undef_Mask(M, VT))
6830 return getMOVHighToLow(Op, dl, DAG);
6832 // Use to match splats
6833 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6834 (VT == MVT::v2f64 || VT == MVT::v2i64))
6835 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6837 if (isPSHUFDMask(M, VT)) {
6838 // The actual implementation will match the mask in the if above and then
6839 // during isel it can match several different instructions, not only pshufd
6840 // as its name says, sad but true, emulate the behavior for now...
6841 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6842 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6844 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6846 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6847 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6849 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6850 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6853 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6857 // Check if this can be converted into a logical shift.
6858 bool isLeft = false;
6861 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6862 if (isShift && ShVal.hasOneUse()) {
6863 // If the shifted value has multiple uses, it may be cheaper to use
6864 // v_set0 + movlhps or movhlps, etc.
6865 MVT EltVT = VT.getVectorElementType();
6866 ShAmt *= EltVT.getSizeInBits();
6867 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6870 if (isMOVLMask(M, VT)) {
6871 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6872 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6873 if (!isMOVLPMask(M, VT)) {
6874 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6875 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6877 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6878 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6882 // FIXME: fold these into legal mask.
6883 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6884 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6886 if (isMOVHLPSMask(M, VT))
6887 return getMOVHighToLow(Op, dl, DAG);
6889 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6890 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6892 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6893 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6895 if (isMOVLPMask(M, VT))
6896 return getMOVLP(Op, dl, DAG, HasSSE2);
6898 if (ShouldXformToMOVHLPS(M, VT) ||
6899 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6900 return CommuteVectorShuffle(SVOp, DAG);
6903 // No better options. Use a vshldq / vsrldq.
6904 MVT EltVT = VT.getVectorElementType();
6905 ShAmt *= EltVT.getSizeInBits();
6906 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6909 bool Commuted = false;
6910 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6911 // 1,1,1,1 -> v8i16 though.
6912 V1IsSplat = isSplatVector(V1.getNode());
6913 V2IsSplat = isSplatVector(V2.getNode());
6915 // Canonicalize the splat or undef, if present, to be on the RHS.
6916 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6917 CommuteVectorShuffleMask(M, NumElems);
6919 std::swap(V1IsSplat, V2IsSplat);
6923 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6924 // Shuffling low element of v1 into undef, just return v1.
6927 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6928 // the instruction selector will not match, so get a canonical MOVL with
6929 // swapped operands to undo the commute.
6930 return getMOVL(DAG, dl, VT, V2, V1);
6933 if (isUNPCKLMask(M, VT, HasInt256))
6934 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6936 if (isUNPCKHMask(M, VT, HasInt256))
6937 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6940 // Normalize mask so all entries that point to V2 points to its first
6941 // element then try to match unpck{h|l} again. If match, return a
6942 // new vector_shuffle with the corrected mask.p
6943 SmallVector<int, 8> NewMask(M.begin(), M.end());
6944 NormalizeMask(NewMask, NumElems);
6945 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6946 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6947 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6948 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6952 // Commute is back and try unpck* again.
6953 // FIXME: this seems wrong.
6954 CommuteVectorShuffleMask(M, NumElems);
6956 std::swap(V1IsSplat, V2IsSplat);
6959 if (isUNPCKLMask(M, VT, HasInt256))
6960 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6962 if (isUNPCKHMask(M, VT, HasInt256))
6963 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6966 // Normalize the node to match x86 shuffle ops if needed
6967 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6968 return CommuteVectorShuffle(SVOp, DAG);
6970 // The checks below are all present in isShuffleMaskLegal, but they are
6971 // inlined here right now to enable us to directly emit target specific
6972 // nodes, and remove one by one until they don't return Op anymore.
6974 if (isPALIGNRMask(M, VT, Subtarget))
6975 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6976 getShufflePALIGNRImmediate(SVOp),
6979 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6980 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6981 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6982 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6985 if (isPSHUFHWMask(M, VT, HasInt256))
6986 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6987 getShufflePSHUFHWImmediate(SVOp),
6990 if (isPSHUFLWMask(M, VT, HasInt256))
6991 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6992 getShufflePSHUFLWImmediate(SVOp),
6995 if (isSHUFPMask(M, VT, HasFp256))
6996 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6997 getShuffleSHUFImmediate(SVOp), DAG);
6999 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7000 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7001 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7002 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7004 //===--------------------------------------------------------------------===//
7005 // Generate target specific nodes for 128 or 256-bit shuffles only
7006 // supported in the AVX instruction set.
7009 // Handle VMOVDDUPY permutations
7010 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7011 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7013 // Handle VPERMILPS/D* permutations
7014 if (isVPERMILPMask(M, VT, HasFp256)) {
7015 if (HasInt256 && VT == MVT::v8i32)
7016 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7017 getShuffleSHUFImmediate(SVOp), DAG);
7018 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7019 getShuffleSHUFImmediate(SVOp), DAG);
7022 // Handle VPERM2F128/VPERM2I128 permutations
7023 if (isVPERM2X128Mask(M, VT, HasFp256))
7024 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7025 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7027 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7028 if (BlendOp.getNode())
7031 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7032 SmallVector<SDValue, 8> permclMask;
7033 for (unsigned i = 0; i != 8; ++i) {
7034 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7036 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7038 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7039 return DAG.getNode(X86ISD::VPERMV, dl, VT,
7040 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7043 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7044 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7045 getShuffleCLImmediate(SVOp), DAG);
7047 //===--------------------------------------------------------------------===//
7048 // Since no target specific shuffle was selected for this generic one,
7049 // lower it into other known shuffles. FIXME: this isn't true yet, but
7050 // this is the plan.
7053 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7054 if (VT == MVT::v8i16) {
7055 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7056 if (NewOp.getNode())
7060 if (VT == MVT::v16i8) {
7061 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7062 if (NewOp.getNode())
7066 if (VT == MVT::v32i8) {
7067 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7068 if (NewOp.getNode())
7072 // Handle all 128-bit wide vectors with 4 elements, and match them with
7073 // several different shuffle types.
7074 if (NumElems == 4 && VT.is128BitVector())
7075 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7077 // Handle general 256-bit shuffles
7078 if (VT.is256BitVector())
7079 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7084 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7085 MVT VT = Op.getValueType().getSimpleVT();
7086 DebugLoc dl = Op.getDebugLoc();
7088 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7091 if (VT.getSizeInBits() == 8) {
7092 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7093 Op.getOperand(0), Op.getOperand(1));
7094 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7095 DAG.getValueType(VT));
7096 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7099 if (VT.getSizeInBits() == 16) {
7100 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7101 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7103 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7104 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7105 DAG.getNode(ISD::BITCAST, dl,
7109 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7110 Op.getOperand(0), Op.getOperand(1));
7111 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7112 DAG.getValueType(VT));
7113 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7116 if (VT == MVT::f32) {
7117 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7118 // the result back to FR32 register. It's only worth matching if the
7119 // result has a single use which is a store or a bitcast to i32. And in
7120 // the case of a store, it's not worth it if the index is a constant 0,
7121 // because a MOVSSmr can be used instead, which is smaller and faster.
7122 if (!Op.hasOneUse())
7124 SDNode *User = *Op.getNode()->use_begin();
7125 if ((User->getOpcode() != ISD::STORE ||
7126 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7127 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7128 (User->getOpcode() != ISD::BITCAST ||
7129 User->getValueType(0) != MVT::i32))
7131 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7132 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7135 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7138 if (VT == MVT::i32 || VT == MVT::i64) {
7139 // ExtractPS/pextrq works with constant index.
7140 if (isa<ConstantSDNode>(Op.getOperand(1)))
7147 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7148 SelectionDAG &DAG) const {
7149 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7152 SDValue Vec = Op.getOperand(0);
7153 MVT VecVT = Vec.getValueType().getSimpleVT();
7155 // If this is a 256-bit vector result, first extract the 128-bit vector and
7156 // then extract the element from the 128-bit vector.
7157 if (VecVT.is256BitVector()) {
7158 DebugLoc dl = Op.getNode()->getDebugLoc();
7159 unsigned NumElems = VecVT.getVectorNumElements();
7160 SDValue Idx = Op.getOperand(1);
7161 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7163 // Get the 128-bit vector.
7164 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7166 if (IdxVal >= NumElems/2)
7167 IdxVal -= NumElems/2;
7168 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7169 DAG.getConstant(IdxVal, MVT::i32));
7172 assert(VecVT.is128BitVector() && "Unexpected vector length");
7174 if (Subtarget->hasSSE41()) {
7175 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7180 MVT VT = Op.getValueType().getSimpleVT();
7181 DebugLoc dl = Op.getDebugLoc();
7182 // TODO: handle v16i8.
7183 if (VT.getSizeInBits() == 16) {
7184 SDValue Vec = Op.getOperand(0);
7185 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7187 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7188 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7189 DAG.getNode(ISD::BITCAST, dl,
7192 // Transform it so it match pextrw which produces a 32-bit result.
7193 MVT EltVT = MVT::i32;
7194 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7195 Op.getOperand(0), Op.getOperand(1));
7196 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7197 DAG.getValueType(VT));
7198 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7201 if (VT.getSizeInBits() == 32) {
7202 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7206 // SHUFPS the element to the lowest double word, then movss.
7207 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7208 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7209 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7210 DAG.getUNDEF(VVT), Mask);
7211 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7212 DAG.getIntPtrConstant(0));
7215 if (VT.getSizeInBits() == 64) {
7216 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7217 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7218 // to match extract_elt for f64.
7219 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7223 // UNPCKHPD the element to the lowest double word, then movsd.
7224 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7225 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7226 int Mask[2] = { 1, -1 };
7227 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7228 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7229 DAG.getUNDEF(VVT), Mask);
7230 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7231 DAG.getIntPtrConstant(0));
7237 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7238 MVT VT = Op.getValueType().getSimpleVT();
7239 MVT EltVT = VT.getVectorElementType();
7240 DebugLoc dl = Op.getDebugLoc();
7242 SDValue N0 = Op.getOperand(0);
7243 SDValue N1 = Op.getOperand(1);
7244 SDValue N2 = Op.getOperand(2);
7246 if (!VT.is128BitVector())
7249 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7250 isa<ConstantSDNode>(N2)) {
7252 if (VT == MVT::v8i16)
7253 Opc = X86ISD::PINSRW;
7254 else if (VT == MVT::v16i8)
7255 Opc = X86ISD::PINSRB;
7257 Opc = X86ISD::PINSRB;
7259 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7261 if (N1.getValueType() != MVT::i32)
7262 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7263 if (N2.getValueType() != MVT::i32)
7264 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7265 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7268 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7269 // Bits [7:6] of the constant are the source select. This will always be
7270 // zero here. The DAG Combiner may combine an extract_elt index into these
7271 // bits. For example (insert (extract, 3), 2) could be matched by putting
7272 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7273 // Bits [5:4] of the constant are the destination select. This is the
7274 // value of the incoming immediate.
7275 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7276 // combine either bitwise AND or insert of float 0.0 to set these bits.
7277 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7278 // Create this as a scalar to vector..
7279 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7280 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7283 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7284 // PINSR* works with constant index.
7291 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7292 MVT VT = Op.getValueType().getSimpleVT();
7293 MVT EltVT = VT.getVectorElementType();
7295 DebugLoc dl = Op.getDebugLoc();
7296 SDValue N0 = Op.getOperand(0);
7297 SDValue N1 = Op.getOperand(1);
7298 SDValue N2 = Op.getOperand(2);
7300 // If this is a 256-bit vector result, first extract the 128-bit vector,
7301 // insert the element into the extracted half and then place it back.
7302 if (VT.is256BitVector()) {
7303 if (!isa<ConstantSDNode>(N2))
7306 // Get the desired 128-bit vector half.
7307 unsigned NumElems = VT.getVectorNumElements();
7308 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7309 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7311 // Insert the element into the desired half.
7312 bool Upper = IdxVal >= NumElems/2;
7313 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7314 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7316 // Insert the changed part back to the 256-bit vector
7317 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7320 if (Subtarget->hasSSE41())
7321 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7323 if (EltVT == MVT::i8)
7326 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7327 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7328 // as its second argument.
7329 if (N1.getValueType() != MVT::i32)
7330 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7331 if (N2.getValueType() != MVT::i32)
7332 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7333 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7338 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7339 LLVMContext *Context = DAG.getContext();
7340 DebugLoc dl = Op.getDebugLoc();
7341 MVT OpVT = Op.getValueType().getSimpleVT();
7343 // If this is a 256-bit vector result, first insert into a 128-bit
7344 // vector and then insert into the 256-bit vector.
7345 if (!OpVT.is128BitVector()) {
7346 // Insert into a 128-bit vector.
7347 EVT VT128 = EVT::getVectorVT(*Context,
7348 OpVT.getVectorElementType(),
7349 OpVT.getVectorNumElements() / 2);
7351 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7353 // Insert the 128-bit vector.
7354 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7357 if (OpVT == MVT::v1i64 &&
7358 Op.getOperand(0).getValueType() == MVT::i64)
7359 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7361 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7362 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7363 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7364 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7367 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7368 // a simple subregister reference or explicit instructions to grab
7369 // upper bits of a vector.
7370 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7371 SelectionDAG &DAG) {
7372 if (Subtarget->hasFp256()) {
7373 DebugLoc dl = Op.getNode()->getDebugLoc();
7374 SDValue Vec = Op.getNode()->getOperand(0);
7375 SDValue Idx = Op.getNode()->getOperand(1);
7377 if (Op.getNode()->getValueType(0).is128BitVector() &&
7378 Vec.getNode()->getValueType(0).is256BitVector() &&
7379 isa<ConstantSDNode>(Idx)) {
7380 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7381 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7387 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7388 // simple superregister reference or explicit instructions to insert
7389 // the upper bits of a vector.
7390 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7391 SelectionDAG &DAG) {
7392 if (Subtarget->hasFp256()) {
7393 DebugLoc dl = Op.getNode()->getDebugLoc();
7394 SDValue Vec = Op.getNode()->getOperand(0);
7395 SDValue SubVec = Op.getNode()->getOperand(1);
7396 SDValue Idx = Op.getNode()->getOperand(2);
7398 if (Op.getNode()->getValueType(0).is256BitVector() &&
7399 SubVec.getNode()->getValueType(0).is128BitVector() &&
7400 isa<ConstantSDNode>(Idx)) {
7401 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7402 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7408 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7409 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7410 // one of the above mentioned nodes. It has to be wrapped because otherwise
7411 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7412 // be used to form addressing mode. These wrapped nodes will be selected
7415 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7416 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7418 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7420 unsigned char OpFlag = 0;
7421 unsigned WrapperKind = X86ISD::Wrapper;
7422 CodeModel::Model M = getTargetMachine().getCodeModel();
7424 if (Subtarget->isPICStyleRIPRel() &&
7425 (M == CodeModel::Small || M == CodeModel::Kernel))
7426 WrapperKind = X86ISD::WrapperRIP;
7427 else if (Subtarget->isPICStyleGOT())
7428 OpFlag = X86II::MO_GOTOFF;
7429 else if (Subtarget->isPICStyleStubPIC())
7430 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7432 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7434 CP->getOffset(), OpFlag);
7435 DebugLoc DL = CP->getDebugLoc();
7436 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7437 // With PIC, the address is actually $g + Offset.
7439 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7440 DAG.getNode(X86ISD::GlobalBaseReg,
7441 DebugLoc(), getPointerTy()),
7448 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7449 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7451 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7453 unsigned char OpFlag = 0;
7454 unsigned WrapperKind = X86ISD::Wrapper;
7455 CodeModel::Model M = getTargetMachine().getCodeModel();
7457 if (Subtarget->isPICStyleRIPRel() &&
7458 (M == CodeModel::Small || M == CodeModel::Kernel))
7459 WrapperKind = X86ISD::WrapperRIP;
7460 else if (Subtarget->isPICStyleGOT())
7461 OpFlag = X86II::MO_GOTOFF;
7462 else if (Subtarget->isPICStyleStubPIC())
7463 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7465 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7467 DebugLoc DL = JT->getDebugLoc();
7468 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7470 // With PIC, the address is actually $g + Offset.
7472 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7473 DAG.getNode(X86ISD::GlobalBaseReg,
7474 DebugLoc(), getPointerTy()),
7481 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7482 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7484 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7486 unsigned char OpFlag = 0;
7487 unsigned WrapperKind = X86ISD::Wrapper;
7488 CodeModel::Model M = getTargetMachine().getCodeModel();
7490 if (Subtarget->isPICStyleRIPRel() &&
7491 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7492 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7493 OpFlag = X86II::MO_GOTPCREL;
7494 WrapperKind = X86ISD::WrapperRIP;
7495 } else if (Subtarget->isPICStyleGOT()) {
7496 OpFlag = X86II::MO_GOT;
7497 } else if (Subtarget->isPICStyleStubPIC()) {
7498 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7499 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7500 OpFlag = X86II::MO_DARWIN_NONLAZY;
7503 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7505 DebugLoc DL = Op.getDebugLoc();
7506 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7508 // With PIC, the address is actually $g + Offset.
7509 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7510 !Subtarget->is64Bit()) {
7511 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7512 DAG.getNode(X86ISD::GlobalBaseReg,
7513 DebugLoc(), getPointerTy()),
7517 // For symbols that require a load from a stub to get the address, emit the
7519 if (isGlobalStubReference(OpFlag))
7520 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7521 MachinePointerInfo::getGOT(), false, false, false, 0);
7527 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7528 // Create the TargetBlockAddressAddress node.
7529 unsigned char OpFlags =
7530 Subtarget->ClassifyBlockAddressReference();
7531 CodeModel::Model M = getTargetMachine().getCodeModel();
7532 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7533 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7534 DebugLoc dl = Op.getDebugLoc();
7535 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7538 if (Subtarget->isPICStyleRIPRel() &&
7539 (M == CodeModel::Small || M == CodeModel::Kernel))
7540 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7542 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7544 // With PIC, the address is actually $g + Offset.
7545 if (isGlobalRelativeToPICBase(OpFlags)) {
7546 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7547 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7555 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7556 int64_t Offset, SelectionDAG &DAG) const {
7557 // Create the TargetGlobalAddress node, folding in the constant
7558 // offset if it is legal.
7559 unsigned char OpFlags =
7560 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7561 CodeModel::Model M = getTargetMachine().getCodeModel();
7563 if (OpFlags == X86II::MO_NO_FLAG &&
7564 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7565 // A direct static reference to a global.
7566 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7569 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7572 if (Subtarget->isPICStyleRIPRel() &&
7573 (M == CodeModel::Small || M == CodeModel::Kernel))
7574 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7576 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7578 // With PIC, the address is actually $g + Offset.
7579 if (isGlobalRelativeToPICBase(OpFlags)) {
7580 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7581 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7585 // For globals that require a load from a stub to get the address, emit the
7587 if (isGlobalStubReference(OpFlags))
7588 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7589 MachinePointerInfo::getGOT(), false, false, false, 0);
7591 // If there was a non-zero offset that we didn't fold, create an explicit
7594 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7595 DAG.getConstant(Offset, getPointerTy()));
7601 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7602 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7603 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7604 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7608 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7609 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7610 unsigned char OperandFlags, bool LocalDynamic = false) {
7611 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7612 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7613 DebugLoc dl = GA->getDebugLoc();
7614 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7615 GA->getValueType(0),
7619 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7623 SDValue Ops[] = { Chain, TGA, *InFlag };
7624 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7626 SDValue Ops[] = { Chain, TGA };
7627 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7630 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7631 MFI->setAdjustsStack(true);
7633 SDValue Flag = Chain.getValue(1);
7634 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7637 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7639 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7642 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7643 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7644 DAG.getNode(X86ISD::GlobalBaseReg,
7645 DebugLoc(), PtrVT), InFlag);
7646 InFlag = Chain.getValue(1);
7648 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7651 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7653 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7655 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7656 X86::RAX, X86II::MO_TLSGD);
7659 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7663 DebugLoc dl = GA->getDebugLoc();
7665 // Get the start address of the TLS block for this module.
7666 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7667 .getInfo<X86MachineFunctionInfo>();
7668 MFI->incNumLocalDynamicTLSAccesses();
7672 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7673 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7676 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7677 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7678 InFlag = Chain.getValue(1);
7679 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7680 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7683 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7687 unsigned char OperandFlags = X86II::MO_DTPOFF;
7688 unsigned WrapperKind = X86ISD::Wrapper;
7689 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7690 GA->getValueType(0),
7691 GA->getOffset(), OperandFlags);
7692 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7694 // Add x@dtpoff with the base.
7695 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7698 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7699 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7700 const EVT PtrVT, TLSModel::Model model,
7701 bool is64Bit, bool isPIC) {
7702 DebugLoc dl = GA->getDebugLoc();
7704 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7705 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7706 is64Bit ? 257 : 256));
7708 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7709 DAG.getIntPtrConstant(0),
7710 MachinePointerInfo(Ptr),
7711 false, false, false, 0);
7713 unsigned char OperandFlags = 0;
7714 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7716 unsigned WrapperKind = X86ISD::Wrapper;
7717 if (model == TLSModel::LocalExec) {
7718 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7719 } else if (model == TLSModel::InitialExec) {
7721 OperandFlags = X86II::MO_GOTTPOFF;
7722 WrapperKind = X86ISD::WrapperRIP;
7724 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7727 llvm_unreachable("Unexpected model");
7730 // emit "addl x@ntpoff,%eax" (local exec)
7731 // or "addl x@indntpoff,%eax" (initial exec)
7732 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7733 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7734 GA->getValueType(0),
7735 GA->getOffset(), OperandFlags);
7736 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7738 if (model == TLSModel::InitialExec) {
7739 if (isPIC && !is64Bit) {
7740 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7741 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7745 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7746 MachinePointerInfo::getGOT(), false, false, false,
7750 // The address of the thread local variable is the add of the thread
7751 // pointer with the offset of the variable.
7752 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7756 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7758 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7759 const GlobalValue *GV = GA->getGlobal();
7761 if (Subtarget->isTargetELF()) {
7762 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7765 case TLSModel::GeneralDynamic:
7766 if (Subtarget->is64Bit())
7767 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7768 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7769 case TLSModel::LocalDynamic:
7770 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7771 Subtarget->is64Bit());
7772 case TLSModel::InitialExec:
7773 case TLSModel::LocalExec:
7774 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7775 Subtarget->is64Bit(),
7776 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7778 llvm_unreachable("Unknown TLS model.");
7781 if (Subtarget->isTargetDarwin()) {
7782 // Darwin only has one model of TLS. Lower to that.
7783 unsigned char OpFlag = 0;
7784 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7785 X86ISD::WrapperRIP : X86ISD::Wrapper;
7787 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7789 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7790 !Subtarget->is64Bit();
7792 OpFlag = X86II::MO_TLVP_PIC_BASE;
7794 OpFlag = X86II::MO_TLVP;
7795 DebugLoc DL = Op.getDebugLoc();
7796 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7797 GA->getValueType(0),
7798 GA->getOffset(), OpFlag);
7799 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7801 // With PIC32, the address is actually $g + Offset.
7803 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7804 DAG.getNode(X86ISD::GlobalBaseReg,
7805 DebugLoc(), getPointerTy()),
7808 // Lowering the machine isd will make sure everything is in the right
7810 SDValue Chain = DAG.getEntryNode();
7811 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7812 SDValue Args[] = { Chain, Offset };
7813 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7815 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7816 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7817 MFI->setAdjustsStack(true);
7819 // And our return value (tls address) is in the standard call return value
7821 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7822 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7826 if (Subtarget->isTargetWindows()) {
7827 // Just use the implicit TLS architecture
7828 // Need to generate someting similar to:
7829 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7831 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7832 // mov rcx, qword [rdx+rcx*8]
7833 // mov eax, .tls$:tlsvar
7834 // [rax+rcx] contains the address
7835 // Windows 64bit: gs:0x58
7836 // Windows 32bit: fs:__tls_array
7838 // If GV is an alias then use the aliasee for determining
7839 // thread-localness.
7840 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7841 GV = GA->resolveAliasedGlobal(false);
7842 DebugLoc dl = GA->getDebugLoc();
7843 SDValue Chain = DAG.getEntryNode();
7845 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7846 // %gs:0x58 (64-bit).
7847 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7848 ? Type::getInt8PtrTy(*DAG.getContext(),
7850 : Type::getInt32PtrTy(*DAG.getContext(),
7853 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7854 Subtarget->is64Bit()
7855 ? DAG.getIntPtrConstant(0x58)
7856 : DAG.getExternalSymbol("_tls_array",
7858 MachinePointerInfo(Ptr),
7859 false, false, false, 0);
7861 // Load the _tls_index variable
7862 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7863 if (Subtarget->is64Bit())
7864 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7865 IDX, MachinePointerInfo(), MVT::i32,
7868 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7869 false, false, false, 0);
7871 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7873 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7875 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7876 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7877 false, false, false, 0);
7879 // Get the offset of start of .tls section
7880 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7881 GA->getValueType(0),
7882 GA->getOffset(), X86II::MO_SECREL);
7883 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7885 // The address of the thread local variable is the add of the thread
7886 // pointer with the offset of the variable.
7887 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7890 llvm_unreachable("TLS not implemented for this target.");
7893 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7894 /// and take a 2 x i32 value to shift plus a shift amount.
7895 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7896 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7897 EVT VT = Op.getValueType();
7898 unsigned VTBits = VT.getSizeInBits();
7899 DebugLoc dl = Op.getDebugLoc();
7900 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7901 SDValue ShOpLo = Op.getOperand(0);
7902 SDValue ShOpHi = Op.getOperand(1);
7903 SDValue ShAmt = Op.getOperand(2);
7904 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7905 DAG.getConstant(VTBits - 1, MVT::i8))
7906 : DAG.getConstant(0, VT);
7909 if (Op.getOpcode() == ISD::SHL_PARTS) {
7910 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7911 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7913 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7914 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7917 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7918 DAG.getConstant(VTBits, MVT::i8));
7919 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7920 AndNode, DAG.getConstant(0, MVT::i8));
7923 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7924 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7925 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7927 if (Op.getOpcode() == ISD::SHL_PARTS) {
7928 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7929 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7931 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7932 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7935 SDValue Ops[2] = { Lo, Hi };
7936 return DAG.getMergeValues(Ops, 2, dl);
7939 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7940 SelectionDAG &DAG) const {
7941 EVT SrcVT = Op.getOperand(0).getValueType();
7943 if (SrcVT.isVector())
7946 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7947 "Unknown SINT_TO_FP to lower!");
7949 // These are really Legal; return the operand so the caller accepts it as
7951 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7953 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7954 Subtarget->is64Bit()) {
7958 DebugLoc dl = Op.getDebugLoc();
7959 unsigned Size = SrcVT.getSizeInBits()/8;
7960 MachineFunction &MF = DAG.getMachineFunction();
7961 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7962 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7963 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7965 MachinePointerInfo::getFixedStack(SSFI),
7967 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7970 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7972 SelectionDAG &DAG) const {
7974 DebugLoc DL = Op.getDebugLoc();
7976 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7978 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7980 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7982 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7984 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7985 MachineMemOperand *MMO;
7987 int SSFI = FI->getIndex();
7989 DAG.getMachineFunction()
7990 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7991 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7993 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7994 StackSlot = StackSlot.getOperand(1);
7996 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7997 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7999 Tys, Ops, array_lengthof(Ops),
8003 Chain = Result.getValue(1);
8004 SDValue InFlag = Result.getValue(2);
8006 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8007 // shouldn't be necessary except that RFP cannot be live across
8008 // multiple blocks. When stackifier is fixed, they can be uncoupled.
8009 MachineFunction &MF = DAG.getMachineFunction();
8010 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8011 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8013 Tys = DAG.getVTList(MVT::Other);
8015 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8017 MachineMemOperand *MMO =
8018 DAG.getMachineFunction()
8019 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8020 MachineMemOperand::MOStore, SSFISize, SSFISize);
8022 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8023 Ops, array_lengthof(Ops),
8024 Op.getValueType(), MMO);
8025 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8026 MachinePointerInfo::getFixedStack(SSFI),
8027 false, false, false, 0);
8033 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8034 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8035 SelectionDAG &DAG) const {
8036 // This algorithm is not obvious. Here it is what we're trying to output:
8039 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8040 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8044 pshufd $0x4e, %xmm0, %xmm1
8049 DebugLoc dl = Op.getDebugLoc();
8050 LLVMContext *Context = DAG.getContext();
8052 // Build some magic constants.
8053 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8054 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8055 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8057 SmallVector<Constant*,2> CV1;
8059 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8060 APInt(64, 0x4330000000000000ULL))));
8062 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8063 APInt(64, 0x4530000000000000ULL))));
8064 Constant *C1 = ConstantVector::get(CV1);
8065 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8067 // Load the 64-bit value into an XMM register.
8068 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8070 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8071 MachinePointerInfo::getConstantPool(),
8072 false, false, false, 16);
8073 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8074 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8077 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8078 MachinePointerInfo::getConstantPool(),
8079 false, false, false, 16);
8080 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8081 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8084 if (Subtarget->hasSSE3()) {
8085 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8086 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8088 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8089 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8091 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8092 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8096 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8097 DAG.getIntPtrConstant(0));
8100 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8101 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8102 SelectionDAG &DAG) const {
8103 DebugLoc dl = Op.getDebugLoc();
8104 // FP constant to bias correct the final result.
8105 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8108 // Load the 32-bit value into an XMM register.
8109 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8112 // Zero out the upper parts of the register.
8113 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8115 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8116 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8117 DAG.getIntPtrConstant(0));
8119 // Or the load with the bias.
8120 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8121 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8122 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8124 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8125 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8126 MVT::v2f64, Bias)));
8127 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8128 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8129 DAG.getIntPtrConstant(0));
8131 // Subtract the bias.
8132 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8134 // Handle final rounding.
8135 EVT DestVT = Op.getValueType();
8137 if (DestVT.bitsLT(MVT::f64))
8138 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8139 DAG.getIntPtrConstant(0));
8140 if (DestVT.bitsGT(MVT::f64))
8141 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8143 // Handle final rounding.
8147 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8148 SelectionDAG &DAG) const {
8149 SDValue N0 = Op.getOperand(0);
8150 EVT SVT = N0.getValueType();
8151 DebugLoc dl = Op.getDebugLoc();
8153 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8154 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8155 "Custom UINT_TO_FP is not supported!");
8157 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8158 SVT.getVectorNumElements());
8159 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8160 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8163 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8164 SelectionDAG &DAG) const {
8165 SDValue N0 = Op.getOperand(0);
8166 DebugLoc dl = Op.getDebugLoc();
8168 if (Op.getValueType().isVector())
8169 return lowerUINT_TO_FP_vec(Op, DAG);
8171 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8172 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8173 // the optimization here.
8174 if (DAG.SignBitIsZero(N0))
8175 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8177 EVT SrcVT = N0.getValueType();
8178 EVT DstVT = Op.getValueType();
8179 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8180 return LowerUINT_TO_FP_i64(Op, DAG);
8181 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8182 return LowerUINT_TO_FP_i32(Op, DAG);
8183 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8186 // Make a 64-bit buffer, and use it to build an FILD.
8187 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8188 if (SrcVT == MVT::i32) {
8189 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8190 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8191 getPointerTy(), StackSlot, WordOff);
8192 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8193 StackSlot, MachinePointerInfo(),
8195 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8196 OffsetSlot, MachinePointerInfo(),
8198 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8202 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8203 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8204 StackSlot, MachinePointerInfo(),
8206 // For i64 source, we need to add the appropriate power of 2 if the input
8207 // was negative. This is the same as the optimization in
8208 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8209 // we must be careful to do the computation in x87 extended precision, not
8210 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8211 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8212 MachineMemOperand *MMO =
8213 DAG.getMachineFunction()
8214 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8215 MachineMemOperand::MOLoad, 8, 8);
8217 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8218 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8219 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8222 APInt FF(32, 0x5F800000ULL);
8224 // Check whether the sign bit is set.
8225 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8226 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8229 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8230 SDValue FudgePtr = DAG.getConstantPool(
8231 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8234 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8235 SDValue Zero = DAG.getIntPtrConstant(0);
8236 SDValue Four = DAG.getIntPtrConstant(4);
8237 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8239 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8241 // Load the value out, extending it from f32 to f80.
8242 // FIXME: Avoid the extend by constructing the right constant pool?
8243 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8244 FudgePtr, MachinePointerInfo::getConstantPool(),
8245 MVT::f32, false, false, 4);
8246 // Extend everything to 80 bits to force it to be done on x87.
8247 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8248 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8251 std::pair<SDValue,SDValue>
8252 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8253 bool IsSigned, bool IsReplace) const {
8254 DebugLoc DL = Op.getDebugLoc();
8256 EVT DstTy = Op.getValueType();
8258 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8259 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8263 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8264 DstTy.getSimpleVT() >= MVT::i16 &&
8265 "Unknown FP_TO_INT to lower!");
8267 // These are really Legal.
8268 if (DstTy == MVT::i32 &&
8269 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8270 return std::make_pair(SDValue(), SDValue());
8271 if (Subtarget->is64Bit() &&
8272 DstTy == MVT::i64 &&
8273 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8274 return std::make_pair(SDValue(), SDValue());
8276 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8277 // stack slot, or into the FTOL runtime function.
8278 MachineFunction &MF = DAG.getMachineFunction();
8279 unsigned MemSize = DstTy.getSizeInBits()/8;
8280 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8281 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8284 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8285 Opc = X86ISD::WIN_FTOL;
8287 switch (DstTy.getSimpleVT().SimpleTy) {
8288 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8289 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8290 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8291 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8294 SDValue Chain = DAG.getEntryNode();
8295 SDValue Value = Op.getOperand(0);
8296 EVT TheVT = Op.getOperand(0).getValueType();
8297 // FIXME This causes a redundant load/store if the SSE-class value is already
8298 // in memory, such as if it is on the callstack.
8299 if (isScalarFPTypeInSSEReg(TheVT)) {
8300 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8301 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8302 MachinePointerInfo::getFixedStack(SSFI),
8304 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8306 Chain, StackSlot, DAG.getValueType(TheVT)
8309 MachineMemOperand *MMO =
8310 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8311 MachineMemOperand::MOLoad, MemSize, MemSize);
8312 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8314 Chain = Value.getValue(1);
8315 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8316 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8319 MachineMemOperand *MMO =
8320 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8321 MachineMemOperand::MOStore, MemSize, MemSize);
8323 if (Opc != X86ISD::WIN_FTOL) {
8324 // Build the FP_TO_INT*_IN_MEM
8325 SDValue Ops[] = { Chain, Value, StackSlot };
8326 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8327 Ops, 3, DstTy, MMO);
8328 return std::make_pair(FIST, StackSlot);
8330 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8331 DAG.getVTList(MVT::Other, MVT::Glue),
8333 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8334 MVT::i32, ftol.getValue(1));
8335 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8336 MVT::i32, eax.getValue(2));
8337 SDValue Ops[] = { eax, edx };
8338 SDValue pair = IsReplace
8339 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8340 : DAG.getMergeValues(Ops, 2, DL);
8341 return std::make_pair(pair, SDValue());
8345 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8346 const X86Subtarget *Subtarget) {
8347 MVT VT = Op->getValueType(0).getSimpleVT();
8348 SDValue In = Op->getOperand(0);
8349 MVT InVT = In.getValueType().getSimpleVT();
8350 DebugLoc dl = Op->getDebugLoc();
8352 // Optimize vectors in AVX mode:
8355 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8356 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8357 // Concat upper and lower parts.
8360 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8361 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8362 // Concat upper and lower parts.
8365 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8366 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8369 if (Subtarget->hasInt256())
8370 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8372 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8373 SDValue Undef = DAG.getUNDEF(InVT);
8374 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8375 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8376 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8378 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8379 VT.getVectorNumElements()/2);
8381 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8382 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8384 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8387 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8388 SelectionDAG &DAG) const {
8389 if (Subtarget->hasFp256()) {
8390 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8397 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8398 SelectionDAG &DAG) const {
8399 DebugLoc DL = Op.getDebugLoc();
8400 MVT VT = Op.getValueType().getSimpleVT();
8401 SDValue In = Op.getOperand(0);
8402 MVT SVT = In.getValueType().getSimpleVT();
8404 if (Subtarget->hasFp256()) {
8405 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8410 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8411 VT.getVectorNumElements() != SVT.getVectorNumElements())
8414 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8416 // AVX2 has better support of integer extending.
8417 if (Subtarget->hasInt256())
8418 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8420 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8421 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8422 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8423 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8424 DAG.getUNDEF(MVT::v8i16),
8427 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8430 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8431 DebugLoc DL = Op.getDebugLoc();
8432 MVT VT = Op.getValueType().getSimpleVT();
8433 SDValue In = Op.getOperand(0);
8434 MVT SVT = In.getValueType().getSimpleVT();
8436 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8437 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8438 if (Subtarget->hasInt256()) {
8439 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8440 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8441 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8443 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8444 DAG.getIntPtrConstant(0));
8447 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8448 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8449 DAG.getIntPtrConstant(0));
8450 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8451 DAG.getIntPtrConstant(2));
8453 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8454 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8457 static const int ShufMask1[] = {0, 2, 0, 0};
8458 SDValue Undef = DAG.getUNDEF(VT);
8459 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8460 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8462 // The MOVLHPS mask:
8463 static const int ShufMask2[] = {0, 1, 4, 5};
8464 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8467 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8468 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8469 if (Subtarget->hasInt256()) {
8470 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8472 SmallVector<SDValue,32> pshufbMask;
8473 for (unsigned i = 0; i < 2; ++i) {
8474 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8475 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8476 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8477 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8478 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8479 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8480 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8481 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8482 for (unsigned j = 0; j < 8; ++j)
8483 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8485 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8486 &pshufbMask[0], 32);
8487 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8488 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8490 static const int ShufMask[] = {0, 2, -1, -1};
8491 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8493 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8494 DAG.getIntPtrConstant(0));
8495 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8498 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8499 DAG.getIntPtrConstant(0));
8501 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8502 DAG.getIntPtrConstant(4));
8504 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8505 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8508 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8509 -1, -1, -1, -1, -1, -1, -1, -1};
8511 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8512 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8513 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8515 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8516 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8518 // The MOVLHPS Mask:
8519 static const int ShufMask2[] = {0, 1, 4, 5};
8520 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8521 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8524 // Handle truncation of V256 to V128 using shuffles.
8525 if (!VT.is128BitVector() || !SVT.is256BitVector())
8528 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8530 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8532 unsigned NumElems = VT.getVectorNumElements();
8533 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8536 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8537 // Prepare truncation shuffle mask
8538 for (unsigned i = 0; i != NumElems; ++i)
8540 SDValue V = DAG.getVectorShuffle(NVT, DL,
8541 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8542 DAG.getUNDEF(NVT), &MaskVec[0]);
8543 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8544 DAG.getIntPtrConstant(0));
8547 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8548 SelectionDAG &DAG) const {
8549 MVT VT = Op.getValueType().getSimpleVT();
8550 if (VT.isVector()) {
8551 if (VT == MVT::v8i16)
8552 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8553 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8554 MVT::v8i32, Op.getOperand(0)));
8558 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8559 /*IsSigned=*/ true, /*IsReplace=*/ false);
8560 SDValue FIST = Vals.first, StackSlot = Vals.second;
8561 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8562 if (FIST.getNode() == 0) return Op;
8564 if (StackSlot.getNode())
8566 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8567 FIST, StackSlot, MachinePointerInfo(),
8568 false, false, false, 0);
8570 // The node is the result.
8574 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8575 SelectionDAG &DAG) const {
8576 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8577 /*IsSigned=*/ false, /*IsReplace=*/ false);
8578 SDValue FIST = Vals.first, StackSlot = Vals.second;
8579 assert(FIST.getNode() && "Unexpected failure");
8581 if (StackSlot.getNode())
8583 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8584 FIST, StackSlot, MachinePointerInfo(),
8585 false, false, false, 0);
8587 // The node is the result.
8591 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8592 DebugLoc DL = Op.getDebugLoc();
8593 MVT VT = Op.getValueType().getSimpleVT();
8594 SDValue In = Op.getOperand(0);
8595 MVT SVT = In.getValueType().getSimpleVT();
8597 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8599 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8600 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8601 In, DAG.getUNDEF(SVT)));
8604 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8605 LLVMContext *Context = DAG.getContext();
8606 DebugLoc dl = Op.getDebugLoc();
8607 MVT VT = Op.getValueType().getSimpleVT();
8609 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8610 if (VT.isVector()) {
8611 EltVT = VT.getVectorElementType();
8612 NumElts = VT.getVectorNumElements();
8615 if (EltVT == MVT::f64)
8616 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8617 APInt(64, ~(1ULL << 63))));
8619 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8620 APInt(32, ~(1U << 31))));
8621 C = ConstantVector::getSplat(NumElts, C);
8622 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8623 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8624 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8625 MachinePointerInfo::getConstantPool(),
8626 false, false, false, Alignment);
8627 if (VT.isVector()) {
8628 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8629 return DAG.getNode(ISD::BITCAST, dl, VT,
8630 DAG.getNode(ISD::AND, dl, ANDVT,
8631 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8633 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8635 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8638 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8639 LLVMContext *Context = DAG.getContext();
8640 DebugLoc dl = Op.getDebugLoc();
8641 MVT VT = Op.getValueType().getSimpleVT();
8643 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8644 if (VT.isVector()) {
8645 EltVT = VT.getVectorElementType();
8646 NumElts = VT.getVectorNumElements();
8649 if (EltVT == MVT::f64)
8650 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8651 APInt(64, 1ULL << 63)));
8653 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8654 APInt(32, 1U << 31)));
8655 C = ConstantVector::getSplat(NumElts, C);
8656 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8657 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8658 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8659 MachinePointerInfo::getConstantPool(),
8660 false, false, false, Alignment);
8661 if (VT.isVector()) {
8662 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8663 return DAG.getNode(ISD::BITCAST, dl, VT,
8664 DAG.getNode(ISD::XOR, dl, XORVT,
8665 DAG.getNode(ISD::BITCAST, dl, XORVT,
8667 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8670 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8673 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8674 LLVMContext *Context = DAG.getContext();
8675 SDValue Op0 = Op.getOperand(0);
8676 SDValue Op1 = Op.getOperand(1);
8677 DebugLoc dl = Op.getDebugLoc();
8678 MVT VT = Op.getValueType().getSimpleVT();
8679 MVT SrcVT = Op1.getValueType().getSimpleVT();
8681 // If second operand is smaller, extend it first.
8682 if (SrcVT.bitsLT(VT)) {
8683 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8686 // And if it is bigger, shrink it first.
8687 if (SrcVT.bitsGT(VT)) {
8688 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8692 // At this point the operands and the result should have the same
8693 // type, and that won't be f80 since that is not custom lowered.
8695 // First get the sign bit of second operand.
8696 SmallVector<Constant*,4> CV;
8697 if (SrcVT == MVT::f64) {
8698 const fltSemantics &Sem = APFloat::IEEEdouble;
8699 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8700 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8702 const fltSemantics &Sem = APFloat::IEEEsingle;
8703 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8704 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8705 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8706 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8708 Constant *C = ConstantVector::get(CV);
8709 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8710 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8711 MachinePointerInfo::getConstantPool(),
8712 false, false, false, 16);
8713 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8715 // Shift sign bit right or left if the two operands have different types.
8716 if (SrcVT.bitsGT(VT)) {
8717 // Op0 is MVT::f32, Op1 is MVT::f64.
8718 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8719 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8720 DAG.getConstant(32, MVT::i32));
8721 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8722 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8723 DAG.getIntPtrConstant(0));
8726 // Clear first operand sign bit.
8728 if (VT == MVT::f64) {
8729 const fltSemantics &Sem = APFloat::IEEEdouble;
8730 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8731 APInt(64, ~(1ULL << 63)))));
8732 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8734 const fltSemantics &Sem = APFloat::IEEEsingle;
8735 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8736 APInt(32, ~(1U << 31)))));
8737 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8738 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8739 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8741 C = ConstantVector::get(CV);
8742 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8743 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8744 MachinePointerInfo::getConstantPool(),
8745 false, false, false, 16);
8746 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8748 // Or the value with the sign bit.
8749 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8752 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8753 SDValue N0 = Op.getOperand(0);
8754 DebugLoc dl = Op.getDebugLoc();
8755 MVT VT = Op.getValueType().getSimpleVT();
8757 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8758 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8759 DAG.getConstant(1, VT));
8760 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8763 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8765 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8766 SelectionDAG &DAG) const {
8767 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8769 if (!Subtarget->hasSSE41())
8772 if (!Op->hasOneUse())
8775 SDNode *N = Op.getNode();
8776 DebugLoc DL = N->getDebugLoc();
8778 SmallVector<SDValue, 8> Opnds;
8779 DenseMap<SDValue, unsigned> VecInMap;
8780 EVT VT = MVT::Other;
8782 // Recognize a special case where a vector is casted into wide integer to
8784 Opnds.push_back(N->getOperand(0));
8785 Opnds.push_back(N->getOperand(1));
8787 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8788 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8789 // BFS traverse all OR'd operands.
8790 if (I->getOpcode() == ISD::OR) {
8791 Opnds.push_back(I->getOperand(0));
8792 Opnds.push_back(I->getOperand(1));
8793 // Re-evaluate the number of nodes to be traversed.
8794 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8798 // Quit if a non-EXTRACT_VECTOR_ELT
8799 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8802 // Quit if without a constant index.
8803 SDValue Idx = I->getOperand(1);
8804 if (!isa<ConstantSDNode>(Idx))
8807 SDValue ExtractedFromVec = I->getOperand(0);
8808 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8809 if (M == VecInMap.end()) {
8810 VT = ExtractedFromVec.getValueType();
8811 // Quit if not 128/256-bit vector.
8812 if (!VT.is128BitVector() && !VT.is256BitVector())
8814 // Quit if not the same type.
8815 if (VecInMap.begin() != VecInMap.end() &&
8816 VT != VecInMap.begin()->first.getValueType())
8818 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8820 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8823 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8824 "Not extracted from 128-/256-bit vector.");
8826 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8827 SmallVector<SDValue, 8> VecIns;
8829 for (DenseMap<SDValue, unsigned>::const_iterator
8830 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8831 // Quit if not all elements are used.
8832 if (I->second != FullMask)
8834 VecIns.push_back(I->first);
8837 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8839 // Cast all vectors into TestVT for PTEST.
8840 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8841 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8843 // If more than one full vectors are evaluated, OR them first before PTEST.
8844 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8845 // Each iteration will OR 2 nodes and append the result until there is only
8846 // 1 node left, i.e. the final OR'd value of all vectors.
8847 SDValue LHS = VecIns[Slot];
8848 SDValue RHS = VecIns[Slot + 1];
8849 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8852 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8853 VecIns.back(), VecIns.back());
8856 /// Emit nodes that will be selected as "test Op0,Op0", or something
8858 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8859 SelectionDAG &DAG) const {
8860 DebugLoc dl = Op.getDebugLoc();
8862 // CF and OF aren't always set the way we want. Determine which
8863 // of these we need.
8864 bool NeedCF = false;
8865 bool NeedOF = false;
8868 case X86::COND_A: case X86::COND_AE:
8869 case X86::COND_B: case X86::COND_BE:
8872 case X86::COND_G: case X86::COND_GE:
8873 case X86::COND_L: case X86::COND_LE:
8874 case X86::COND_O: case X86::COND_NO:
8879 // See if we can use the EFLAGS value from the operand instead of
8880 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8881 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8882 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8883 // Emit a CMP with 0, which is the TEST pattern.
8884 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8885 DAG.getConstant(0, Op.getValueType()));
8887 unsigned Opcode = 0;
8888 unsigned NumOperands = 0;
8890 // Truncate operations may prevent the merge of the SETCC instruction
8891 // and the arithmetic intruction before it. Attempt to truncate the operands
8892 // of the arithmetic instruction and use a reduced bit-width instruction.
8893 bool NeedTruncation = false;
8894 SDValue ArithOp = Op;
8895 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8896 SDValue Arith = Op->getOperand(0);
8897 // Both the trunc and the arithmetic op need to have one user each.
8898 if (Arith->hasOneUse())
8899 switch (Arith.getOpcode()) {
8906 NeedTruncation = true;
8912 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8913 // which may be the result of a CAST. We use the variable 'Op', which is the
8914 // non-casted variable when we check for possible users.
8915 switch (ArithOp.getOpcode()) {
8917 // Due to an isel shortcoming, be conservative if this add is likely to be
8918 // selected as part of a load-modify-store instruction. When the root node
8919 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8920 // uses of other nodes in the match, such as the ADD in this case. This
8921 // leads to the ADD being left around and reselected, with the result being
8922 // two adds in the output. Alas, even if none our users are stores, that
8923 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8924 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8925 // climbing the DAG back to the root, and it doesn't seem to be worth the
8927 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8928 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8929 if (UI->getOpcode() != ISD::CopyToReg &&
8930 UI->getOpcode() != ISD::SETCC &&
8931 UI->getOpcode() != ISD::STORE)
8934 if (ConstantSDNode *C =
8935 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8936 // An add of one will be selected as an INC.
8937 if (C->getAPIntValue() == 1) {
8938 Opcode = X86ISD::INC;
8943 // An add of negative one (subtract of one) will be selected as a DEC.
8944 if (C->getAPIntValue().isAllOnesValue()) {
8945 Opcode = X86ISD::DEC;
8951 // Otherwise use a regular EFLAGS-setting add.
8952 Opcode = X86ISD::ADD;
8956 // If the primary and result isn't used, don't bother using X86ISD::AND,
8957 // because a TEST instruction will be better.
8958 bool NonFlagUse = false;
8959 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8960 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8962 unsigned UOpNo = UI.getOperandNo();
8963 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8964 // Look pass truncate.
8965 UOpNo = User->use_begin().getOperandNo();
8966 User = *User->use_begin();
8969 if (User->getOpcode() != ISD::BRCOND &&
8970 User->getOpcode() != ISD::SETCC &&
8971 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8984 // Due to the ISEL shortcoming noted above, be conservative if this op is
8985 // likely to be selected as part of a load-modify-store instruction.
8986 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8987 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8988 if (UI->getOpcode() == ISD::STORE)
8991 // Otherwise use a regular EFLAGS-setting instruction.
8992 switch (ArithOp.getOpcode()) {
8993 default: llvm_unreachable("unexpected operator!");
8994 case ISD::SUB: Opcode = X86ISD::SUB; break;
8995 case ISD::XOR: Opcode = X86ISD::XOR; break;
8996 case ISD::AND: Opcode = X86ISD::AND; break;
8998 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8999 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9000 if (EFLAGS.getNode())
9003 Opcode = X86ISD::OR;
9017 return SDValue(Op.getNode(), 1);
9023 // If we found that truncation is beneficial, perform the truncation and
9025 if (NeedTruncation) {
9026 EVT VT = Op.getValueType();
9027 SDValue WideVal = Op->getOperand(0);
9028 EVT WideVT = WideVal.getValueType();
9029 unsigned ConvertedOp = 0;
9030 // Use a target machine opcode to prevent further DAGCombine
9031 // optimizations that may separate the arithmetic operations
9032 // from the setcc node.
9033 switch (WideVal.getOpcode()) {
9035 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9036 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9037 case ISD::AND: ConvertedOp = X86ISD::AND; break;
9038 case ISD::OR: ConvertedOp = X86ISD::OR; break;
9039 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9043 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9044 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9045 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9046 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9047 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9053 // Emit a CMP with 0, which is the TEST pattern.
9054 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9055 DAG.getConstant(0, Op.getValueType()));
9057 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9058 SmallVector<SDValue, 4> Ops;
9059 for (unsigned i = 0; i != NumOperands; ++i)
9060 Ops.push_back(Op.getOperand(i));
9062 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9063 DAG.ReplaceAllUsesWith(Op, New);
9064 return SDValue(New.getNode(), 1);
9067 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9069 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9070 SelectionDAG &DAG) const {
9071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9072 if (C->getAPIntValue() == 0)
9073 return EmitTest(Op0, X86CC, DAG);
9075 DebugLoc dl = Op0.getDebugLoc();
9076 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9077 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9078 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9079 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9080 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9082 return SDValue(Sub.getNode(), 1);
9084 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9087 /// Convert a comparison if required by the subtarget.
9088 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9089 SelectionDAG &DAG) const {
9090 // If the subtarget does not support the FUCOMI instruction, floating-point
9091 // comparisons have to be converted.
9092 if (Subtarget->hasCMov() ||
9093 Cmp.getOpcode() != X86ISD::CMP ||
9094 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9095 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9098 // The instruction selector will select an FUCOM instruction instead of
9099 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9100 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9101 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9102 DebugLoc dl = Cmp.getDebugLoc();
9103 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9104 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9105 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9106 DAG.getConstant(8, MVT::i8));
9107 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9108 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9111 static bool isAllOnes(SDValue V) {
9112 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9113 return C && C->isAllOnesValue();
9116 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9117 /// if it's possible.
9118 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9119 DebugLoc dl, SelectionDAG &DAG) const {
9120 SDValue Op0 = And.getOperand(0);
9121 SDValue Op1 = And.getOperand(1);
9122 if (Op0.getOpcode() == ISD::TRUNCATE)
9123 Op0 = Op0.getOperand(0);
9124 if (Op1.getOpcode() == ISD::TRUNCATE)
9125 Op1 = Op1.getOperand(0);
9128 if (Op1.getOpcode() == ISD::SHL)
9129 std::swap(Op0, Op1);
9130 if (Op0.getOpcode() == ISD::SHL) {
9131 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9132 if (And00C->getZExtValue() == 1) {
9133 // If we looked past a truncate, check that it's only truncating away
9135 unsigned BitWidth = Op0.getValueSizeInBits();
9136 unsigned AndBitWidth = And.getValueSizeInBits();
9137 if (BitWidth > AndBitWidth) {
9139 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9140 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9144 RHS = Op0.getOperand(1);
9146 } else if (Op1.getOpcode() == ISD::Constant) {
9147 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9148 uint64_t AndRHSVal = AndRHS->getZExtValue();
9149 SDValue AndLHS = Op0;
9151 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9152 LHS = AndLHS.getOperand(0);
9153 RHS = AndLHS.getOperand(1);
9156 // Use BT if the immediate can't be encoded in a TEST instruction.
9157 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9159 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9163 if (LHS.getNode()) {
9164 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9165 // the condition code later.
9166 bool Invert = false;
9167 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9169 LHS = LHS.getOperand(0);
9172 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9173 // instruction. Since the shift amount is in-range-or-undefined, we know
9174 // that doing a bittest on the i32 value is ok. We extend to i32 because
9175 // the encoding for the i16 version is larger than the i32 version.
9176 // Also promote i16 to i32 for performance / code size reason.
9177 if (LHS.getValueType() == MVT::i8 ||
9178 LHS.getValueType() == MVT::i16)
9179 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9181 // If the operand types disagree, extend the shift amount to match. Since
9182 // BT ignores high bits (like shifts) we can use anyextend.
9183 if (LHS.getValueType() != RHS.getValueType())
9184 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9186 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9187 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9188 // Flip the condition if the LHS was a not instruction
9190 Cond = X86::GetOppositeBranchCondition(Cond);
9191 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9192 DAG.getConstant(Cond, MVT::i8), BT);
9198 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9199 // ones, and then concatenate the result back.
9200 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9201 MVT VT = Op.getValueType().getSimpleVT();
9203 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9204 "Unsupported value type for operation");
9206 unsigned NumElems = VT.getVectorNumElements();
9207 DebugLoc dl = Op.getDebugLoc();
9208 SDValue CC = Op.getOperand(2);
9210 // Extract the LHS vectors
9211 SDValue LHS = Op.getOperand(0);
9212 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9213 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9215 // Extract the RHS vectors
9216 SDValue RHS = Op.getOperand(1);
9217 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9218 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9220 // Issue the operation on the smaller types and concatenate the result back
9221 MVT EltVT = VT.getVectorElementType();
9222 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9223 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9224 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9225 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9228 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9229 SelectionDAG &DAG) {
9231 SDValue Op0 = Op.getOperand(0);
9232 SDValue Op1 = Op.getOperand(1);
9233 SDValue CC = Op.getOperand(2);
9234 MVT VT = Op.getValueType().getSimpleVT();
9235 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9236 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9237 DebugLoc dl = Op.getDebugLoc();
9241 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9242 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9248 // SSE Condition code mapping:
9257 switch (SetCCOpcode) {
9258 default: llvm_unreachable("Unexpected SETCC condition");
9260 case ISD::SETEQ: SSECC = 0; break;
9262 case ISD::SETGT: Swap = true; // Fallthrough
9264 case ISD::SETOLT: SSECC = 1; break;
9266 case ISD::SETGE: Swap = true; // Fallthrough
9268 case ISD::SETOLE: SSECC = 2; break;
9269 case ISD::SETUO: SSECC = 3; break;
9271 case ISD::SETNE: SSECC = 4; break;
9272 case ISD::SETULE: Swap = true; // Fallthrough
9273 case ISD::SETUGE: SSECC = 5; break;
9274 case ISD::SETULT: Swap = true; // Fallthrough
9275 case ISD::SETUGT: SSECC = 6; break;
9276 case ISD::SETO: SSECC = 7; break;
9278 case ISD::SETONE: SSECC = 8; break;
9281 std::swap(Op0, Op1);
9283 // In the two special cases we can't handle, emit two comparisons.
9286 unsigned CombineOpc;
9287 if (SetCCOpcode == ISD::SETUEQ) {
9288 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9290 assert(SetCCOpcode == ISD::SETONE);
9291 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9294 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9295 DAG.getConstant(CC0, MVT::i8));
9296 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9297 DAG.getConstant(CC1, MVT::i8));
9298 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9300 // Handle all other FP comparisons here.
9301 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9302 DAG.getConstant(SSECC, MVT::i8));
9305 // Break 256-bit integer vector compare into smaller ones.
9306 if (VT.is256BitVector() && !Subtarget->hasInt256())
9307 return Lower256IntVSETCC(Op, DAG);
9309 // We are handling one of the integer comparisons here. Since SSE only has
9310 // GT and EQ comparisons for integer, swapping operands and multiple
9311 // operations may be required for some comparisons.
9313 bool Swap = false, Invert = false, FlipSigns = false;
9315 switch (SetCCOpcode) {
9316 default: llvm_unreachable("Unexpected SETCC condition");
9317 case ISD::SETNE: Invert = true;
9318 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9319 case ISD::SETLT: Swap = true;
9320 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9321 case ISD::SETGE: Swap = true;
9322 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9323 case ISD::SETULT: Swap = true;
9324 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9325 case ISD::SETUGE: Swap = true;
9326 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9329 std::swap(Op0, Op1);
9331 // Check that the operation in question is available (most are plain SSE2,
9332 // but PCMPGTQ and PCMPEQQ have different requirements).
9333 if (VT == MVT::v2i64) {
9334 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9336 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9337 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9338 // pcmpeqd + pshufd + pand.
9339 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9341 // First cast everything to the right type,
9342 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9343 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9346 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9348 // Make sure the lower and upper halves are both all-ones.
9349 const int Mask[] = { 1, 0, 3, 2 };
9350 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9351 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9354 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9356 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9360 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9361 // bits of the inputs before performing those operations.
9363 EVT EltVT = VT.getVectorElementType();
9364 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9366 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9367 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9369 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9370 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9373 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9375 // If the logical-not of the result is required, perform that now.
9377 Result = DAG.getNOT(dl, Result, VT);
9382 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9384 MVT VT = Op.getValueType().getSimpleVT();
9386 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9388 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9389 SDValue Op0 = Op.getOperand(0);
9390 SDValue Op1 = Op.getOperand(1);
9391 DebugLoc dl = Op.getDebugLoc();
9392 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9394 // Optimize to BT if possible.
9395 // Lower (X & (1 << N)) == 0 to BT(X, N).
9396 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9397 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9398 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9399 Op1.getOpcode() == ISD::Constant &&
9400 cast<ConstantSDNode>(Op1)->isNullValue() &&
9401 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9402 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9403 if (NewSetCC.getNode())
9407 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9409 if (Op1.getOpcode() == ISD::Constant &&
9410 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9411 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9412 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9414 // If the input is a setcc, then reuse the input setcc or use a new one with
9415 // the inverted condition.
9416 if (Op0.getOpcode() == X86ISD::SETCC) {
9417 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9418 bool Invert = (CC == ISD::SETNE) ^
9419 cast<ConstantSDNode>(Op1)->isNullValue();
9420 if (!Invert) return Op0;
9422 CCode = X86::GetOppositeBranchCondition(CCode);
9423 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9424 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9428 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9429 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9430 if (X86CC == X86::COND_INVALID)
9433 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9434 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9435 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9436 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9439 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9440 static bool isX86LogicalCmp(SDValue Op) {
9441 unsigned Opc = Op.getNode()->getOpcode();
9442 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9443 Opc == X86ISD::SAHF)
9445 if (Op.getResNo() == 1 &&
9446 (Opc == X86ISD::ADD ||
9447 Opc == X86ISD::SUB ||
9448 Opc == X86ISD::ADC ||
9449 Opc == X86ISD::SBB ||
9450 Opc == X86ISD::SMUL ||
9451 Opc == X86ISD::UMUL ||
9452 Opc == X86ISD::INC ||
9453 Opc == X86ISD::DEC ||
9454 Opc == X86ISD::OR ||
9455 Opc == X86ISD::XOR ||
9456 Opc == X86ISD::AND))
9459 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9465 static bool isZero(SDValue V) {
9466 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9467 return C && C->isNullValue();
9470 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9471 if (V.getOpcode() != ISD::TRUNCATE)
9474 SDValue VOp0 = V.getOperand(0);
9475 unsigned InBits = VOp0.getValueSizeInBits();
9476 unsigned Bits = V.getValueSizeInBits();
9477 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9480 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9481 bool addTest = true;
9482 SDValue Cond = Op.getOperand(0);
9483 SDValue Op1 = Op.getOperand(1);
9484 SDValue Op2 = Op.getOperand(2);
9485 DebugLoc DL = Op.getDebugLoc();
9488 if (Cond.getOpcode() == ISD::SETCC) {
9489 SDValue NewCond = LowerSETCC(Cond, DAG);
9490 if (NewCond.getNode())
9494 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9495 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9496 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9497 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9498 if (Cond.getOpcode() == X86ISD::SETCC &&
9499 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9500 isZero(Cond.getOperand(1).getOperand(1))) {
9501 SDValue Cmp = Cond.getOperand(1);
9503 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9505 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9506 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9507 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9509 SDValue CmpOp0 = Cmp.getOperand(0);
9510 // Apply further optimizations for special cases
9511 // (select (x != 0), -1, 0) -> neg & sbb
9512 // (select (x == 0), 0, -1) -> neg & sbb
9513 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9514 if (YC->isNullValue() &&
9515 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9516 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9517 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9518 DAG.getConstant(0, CmpOp0.getValueType()),
9520 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9521 DAG.getConstant(X86::COND_B, MVT::i8),
9522 SDValue(Neg.getNode(), 1));
9526 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9527 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9528 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9530 SDValue Res = // Res = 0 or -1.
9531 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9532 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9534 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9535 Res = DAG.getNOT(DL, Res, Res.getValueType());
9537 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9538 if (N2C == 0 || !N2C->isNullValue())
9539 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9544 // Look past (and (setcc_carry (cmp ...)), 1).
9545 if (Cond.getOpcode() == ISD::AND &&
9546 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9547 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9548 if (C && C->getAPIntValue() == 1)
9549 Cond = Cond.getOperand(0);
9552 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9553 // setting operand in place of the X86ISD::SETCC.
9554 unsigned CondOpcode = Cond.getOpcode();
9555 if (CondOpcode == X86ISD::SETCC ||
9556 CondOpcode == X86ISD::SETCC_CARRY) {
9557 CC = Cond.getOperand(0);
9559 SDValue Cmp = Cond.getOperand(1);
9560 unsigned Opc = Cmp.getOpcode();
9561 MVT VT = Op.getValueType().getSimpleVT();
9563 bool IllegalFPCMov = false;
9564 if (VT.isFloatingPoint() && !VT.isVector() &&
9565 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9566 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9568 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9569 Opc == X86ISD::BT) { // FIXME
9573 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9574 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9575 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9576 Cond.getOperand(0).getValueType() != MVT::i8)) {
9577 SDValue LHS = Cond.getOperand(0);
9578 SDValue RHS = Cond.getOperand(1);
9582 switch (CondOpcode) {
9583 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9584 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9585 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9586 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9587 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9588 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9589 default: llvm_unreachable("unexpected overflowing operator");
9591 if (CondOpcode == ISD::UMULO)
9592 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9595 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9597 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9599 if (CondOpcode == ISD::UMULO)
9600 Cond = X86Op.getValue(2);
9602 Cond = X86Op.getValue(1);
9604 CC = DAG.getConstant(X86Cond, MVT::i8);
9609 // Look pass the truncate if the high bits are known zero.
9610 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9611 Cond = Cond.getOperand(0);
9613 // We know the result of AND is compared against zero. Try to match
9615 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9616 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9617 if (NewSetCC.getNode()) {
9618 CC = NewSetCC.getOperand(0);
9619 Cond = NewSetCC.getOperand(1);
9626 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9627 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9630 // a < b ? -1 : 0 -> RES = ~setcc_carry
9631 // a < b ? 0 : -1 -> RES = setcc_carry
9632 // a >= b ? -1 : 0 -> RES = setcc_carry
9633 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9634 if (Cond.getOpcode() == X86ISD::SUB) {
9635 Cond = ConvertCmpIfNecessary(Cond, DAG);
9636 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9638 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9639 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9640 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9641 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9642 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9643 return DAG.getNOT(DL, Res, Res.getValueType());
9648 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9649 // widen the cmov and push the truncate through. This avoids introducing a new
9650 // branch during isel and doesn't add any extensions.
9651 if (Op.getValueType() == MVT::i8 &&
9652 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9653 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9654 if (T1.getValueType() == T2.getValueType() &&
9655 // Blacklist CopyFromReg to avoid partial register stalls.
9656 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9657 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9658 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9659 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9663 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9664 // condition is true.
9665 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9666 SDValue Ops[] = { Op2, Op1, CC, Cond };
9667 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9670 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9671 SelectionDAG &DAG) const {
9672 MVT VT = Op->getValueType(0).getSimpleVT();
9673 SDValue In = Op->getOperand(0);
9674 MVT InVT = In.getValueType().getSimpleVT();
9675 DebugLoc dl = Op->getDebugLoc();
9677 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9678 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9681 if (Subtarget->hasInt256())
9682 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9684 // Optimize vectors in AVX mode
9685 // Sign extend v8i16 to v8i32 and
9688 // Divide input vector into two parts
9689 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9690 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9691 // concat the vectors to original VT
9693 unsigned NumElems = InVT.getVectorNumElements();
9694 SDValue Undef = DAG.getUNDEF(InVT);
9696 SmallVector<int,8> ShufMask1(NumElems, -1);
9697 for (unsigned i = 0; i != NumElems/2; ++i)
9700 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9702 SmallVector<int,8> ShufMask2(NumElems, -1);
9703 for (unsigned i = 0; i != NumElems/2; ++i)
9704 ShufMask2[i] = i + NumElems/2;
9706 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9708 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9709 VT.getVectorNumElements()/2);
9711 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9712 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9714 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9717 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9718 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9719 // from the AND / OR.
9720 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9721 Opc = Op.getOpcode();
9722 if (Opc != ISD::OR && Opc != ISD::AND)
9724 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9725 Op.getOperand(0).hasOneUse() &&
9726 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9727 Op.getOperand(1).hasOneUse());
9730 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9731 // 1 and that the SETCC node has a single use.
9732 static bool isXor1OfSetCC(SDValue Op) {
9733 if (Op.getOpcode() != ISD::XOR)
9735 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9736 if (N1C && N1C->getAPIntValue() == 1) {
9737 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9738 Op.getOperand(0).hasOneUse();
9743 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9744 bool addTest = true;
9745 SDValue Chain = Op.getOperand(0);
9746 SDValue Cond = Op.getOperand(1);
9747 SDValue Dest = Op.getOperand(2);
9748 DebugLoc dl = Op.getDebugLoc();
9750 bool Inverted = false;
9752 if (Cond.getOpcode() == ISD::SETCC) {
9753 // Check for setcc([su]{add,sub,mul}o == 0).
9754 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9755 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9756 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9757 Cond.getOperand(0).getResNo() == 1 &&
9758 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9759 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9760 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9761 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9762 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9763 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9765 Cond = Cond.getOperand(0);
9767 SDValue NewCond = LowerSETCC(Cond, DAG);
9768 if (NewCond.getNode())
9773 // FIXME: LowerXALUO doesn't handle these!!
9774 else if (Cond.getOpcode() == X86ISD::ADD ||
9775 Cond.getOpcode() == X86ISD::SUB ||
9776 Cond.getOpcode() == X86ISD::SMUL ||
9777 Cond.getOpcode() == X86ISD::UMUL)
9778 Cond = LowerXALUO(Cond, DAG);
9781 // Look pass (and (setcc_carry (cmp ...)), 1).
9782 if (Cond.getOpcode() == ISD::AND &&
9783 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9784 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9785 if (C && C->getAPIntValue() == 1)
9786 Cond = Cond.getOperand(0);
9789 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9790 // setting operand in place of the X86ISD::SETCC.
9791 unsigned CondOpcode = Cond.getOpcode();
9792 if (CondOpcode == X86ISD::SETCC ||
9793 CondOpcode == X86ISD::SETCC_CARRY) {
9794 CC = Cond.getOperand(0);
9796 SDValue Cmp = Cond.getOperand(1);
9797 unsigned Opc = Cmp.getOpcode();
9798 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9799 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9803 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9807 // These can only come from an arithmetic instruction with overflow,
9808 // e.g. SADDO, UADDO.
9809 Cond = Cond.getNode()->getOperand(1);
9815 CondOpcode = Cond.getOpcode();
9816 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9817 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9818 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9819 Cond.getOperand(0).getValueType() != MVT::i8)) {
9820 SDValue LHS = Cond.getOperand(0);
9821 SDValue RHS = Cond.getOperand(1);
9825 switch (CondOpcode) {
9826 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9827 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9828 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9829 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9830 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9831 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9832 default: llvm_unreachable("unexpected overflowing operator");
9835 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9836 if (CondOpcode == ISD::UMULO)
9837 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9840 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9842 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9844 if (CondOpcode == ISD::UMULO)
9845 Cond = X86Op.getValue(2);
9847 Cond = X86Op.getValue(1);
9849 CC = DAG.getConstant(X86Cond, MVT::i8);
9853 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9854 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9855 if (CondOpc == ISD::OR) {
9856 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9857 // two branches instead of an explicit OR instruction with a
9859 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9860 isX86LogicalCmp(Cmp)) {
9861 CC = Cond.getOperand(0).getOperand(0);
9862 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9863 Chain, Dest, CC, Cmp);
9864 CC = Cond.getOperand(1).getOperand(0);
9868 } else { // ISD::AND
9869 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9870 // two branches instead of an explicit AND instruction with a
9871 // separate test. However, we only do this if this block doesn't
9872 // have a fall-through edge, because this requires an explicit
9873 // jmp when the condition is false.
9874 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9875 isX86LogicalCmp(Cmp) &&
9876 Op.getNode()->hasOneUse()) {
9877 X86::CondCode CCode =
9878 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9879 CCode = X86::GetOppositeBranchCondition(CCode);
9880 CC = DAG.getConstant(CCode, MVT::i8);
9881 SDNode *User = *Op.getNode()->use_begin();
9882 // Look for an unconditional branch following this conditional branch.
9883 // We need this because we need to reverse the successors in order
9884 // to implement FCMP_OEQ.
9885 if (User->getOpcode() == ISD::BR) {
9886 SDValue FalseBB = User->getOperand(1);
9888 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9889 assert(NewBR == User);
9893 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9894 Chain, Dest, CC, Cmp);
9895 X86::CondCode CCode =
9896 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9897 CCode = X86::GetOppositeBranchCondition(CCode);
9898 CC = DAG.getConstant(CCode, MVT::i8);
9904 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9905 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9906 // It should be transformed during dag combiner except when the condition
9907 // is set by a arithmetics with overflow node.
9908 X86::CondCode CCode =
9909 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9910 CCode = X86::GetOppositeBranchCondition(CCode);
9911 CC = DAG.getConstant(CCode, MVT::i8);
9912 Cond = Cond.getOperand(0).getOperand(1);
9914 } else if (Cond.getOpcode() == ISD::SETCC &&
9915 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9916 // For FCMP_OEQ, we can emit
9917 // two branches instead of an explicit AND instruction with a
9918 // separate test. However, we only do this if this block doesn't
9919 // have a fall-through edge, because this requires an explicit
9920 // jmp when the condition is false.
9921 if (Op.getNode()->hasOneUse()) {
9922 SDNode *User = *Op.getNode()->use_begin();
9923 // Look for an unconditional branch following this conditional branch.
9924 // We need this because we need to reverse the successors in order
9925 // to implement FCMP_OEQ.
9926 if (User->getOpcode() == ISD::BR) {
9927 SDValue FalseBB = User->getOperand(1);
9929 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9930 assert(NewBR == User);
9934 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9935 Cond.getOperand(0), Cond.getOperand(1));
9936 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9937 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9938 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9939 Chain, Dest, CC, Cmp);
9940 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9945 } else if (Cond.getOpcode() == ISD::SETCC &&
9946 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9947 // For FCMP_UNE, we can emit
9948 // two branches instead of an explicit AND instruction with a
9949 // separate test. However, we only do this if this block doesn't
9950 // have a fall-through edge, because this requires an explicit
9951 // jmp when the condition is false.
9952 if (Op.getNode()->hasOneUse()) {
9953 SDNode *User = *Op.getNode()->use_begin();
9954 // Look for an unconditional branch following this conditional branch.
9955 // We need this because we need to reverse the successors in order
9956 // to implement FCMP_UNE.
9957 if (User->getOpcode() == ISD::BR) {
9958 SDValue FalseBB = User->getOperand(1);
9960 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9961 assert(NewBR == User);
9964 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9965 Cond.getOperand(0), Cond.getOperand(1));
9966 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9967 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9968 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9969 Chain, Dest, CC, Cmp);
9970 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9980 // Look pass the truncate if the high bits are known zero.
9981 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9982 Cond = Cond.getOperand(0);
9984 // We know the result of AND is compared against zero. Try to match
9986 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9987 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9988 if (NewSetCC.getNode()) {
9989 CC = NewSetCC.getOperand(0);
9990 Cond = NewSetCC.getOperand(1);
9997 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9998 Cond = EmitTest(Cond, X86::COND_NE, DAG);
10000 Cond = ConvertCmpIfNecessary(Cond, DAG);
10001 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10002 Chain, Dest, CC, Cond);
10005 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10006 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10007 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10008 // that the guard pages used by the OS virtual memory manager are allocated in
10009 // correct sequence.
10011 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10012 SelectionDAG &DAG) const {
10013 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10014 getTargetMachine().Options.EnableSegmentedStacks) &&
10015 "This should be used only on Windows targets or when segmented stacks "
10017 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10018 DebugLoc dl = Op.getDebugLoc();
10021 SDValue Chain = Op.getOperand(0);
10022 SDValue Size = Op.getOperand(1);
10023 // FIXME: Ensure alignment here
10025 bool Is64Bit = Subtarget->is64Bit();
10026 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10028 if (getTargetMachine().Options.EnableSegmentedStacks) {
10029 MachineFunction &MF = DAG.getMachineFunction();
10030 MachineRegisterInfo &MRI = MF.getRegInfo();
10033 // The 64 bit implementation of segmented stacks needs to clobber both r10
10034 // r11. This makes it impossible to use it along with nested parameters.
10035 const Function *F = MF.getFunction();
10037 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10039 if (I->hasNestAttr())
10040 report_fatal_error("Cannot use segmented stacks with functions that "
10041 "have nested arguments.");
10044 const TargetRegisterClass *AddrRegClass =
10045 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10046 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10047 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10048 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10049 DAG.getRegister(Vreg, SPTy));
10050 SDValue Ops1[2] = { Value, Chain };
10051 return DAG.getMergeValues(Ops1, 2, dl);
10054 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10056 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10057 Flag = Chain.getValue(1);
10058 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10060 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10061 Flag = Chain.getValue(1);
10063 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10066 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10067 return DAG.getMergeValues(Ops1, 2, dl);
10071 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10072 MachineFunction &MF = DAG.getMachineFunction();
10073 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10075 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10076 DebugLoc DL = Op.getDebugLoc();
10078 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10079 // vastart just stores the address of the VarArgsFrameIndex slot into the
10080 // memory location argument.
10081 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10083 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10084 MachinePointerInfo(SV), false, false, 0);
10088 // gp_offset (0 - 6 * 8)
10089 // fp_offset (48 - 48 + 8 * 16)
10090 // overflow_arg_area (point to parameters coming in memory).
10092 SmallVector<SDValue, 8> MemOps;
10093 SDValue FIN = Op.getOperand(1);
10095 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10096 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10098 FIN, MachinePointerInfo(SV), false, false, 0);
10099 MemOps.push_back(Store);
10102 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10103 FIN, DAG.getIntPtrConstant(4));
10104 Store = DAG.getStore(Op.getOperand(0), DL,
10105 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10107 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10108 MemOps.push_back(Store);
10110 // Store ptr to overflow_arg_area
10111 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10112 FIN, DAG.getIntPtrConstant(4));
10113 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10115 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10116 MachinePointerInfo(SV, 8),
10118 MemOps.push_back(Store);
10120 // Store ptr to reg_save_area.
10121 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10122 FIN, DAG.getIntPtrConstant(8));
10123 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10125 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10126 MachinePointerInfo(SV, 16), false, false, 0);
10127 MemOps.push_back(Store);
10128 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10129 &MemOps[0], MemOps.size());
10132 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10133 assert(Subtarget->is64Bit() &&
10134 "LowerVAARG only handles 64-bit va_arg!");
10135 assert((Subtarget->isTargetLinux() ||
10136 Subtarget->isTargetDarwin()) &&
10137 "Unhandled target in LowerVAARG");
10138 assert(Op.getNode()->getNumOperands() == 4);
10139 SDValue Chain = Op.getOperand(0);
10140 SDValue SrcPtr = Op.getOperand(1);
10141 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10142 unsigned Align = Op.getConstantOperandVal(3);
10143 DebugLoc dl = Op.getDebugLoc();
10145 EVT ArgVT = Op.getNode()->getValueType(0);
10146 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10147 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10150 // Decide which area this value should be read from.
10151 // TODO: Implement the AMD64 ABI in its entirety. This simple
10152 // selection mechanism works only for the basic types.
10153 if (ArgVT == MVT::f80) {
10154 llvm_unreachable("va_arg for f80 not yet implemented");
10155 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10156 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10157 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10158 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10160 llvm_unreachable("Unhandled argument type in LowerVAARG");
10163 if (ArgMode == 2) {
10164 // Sanity Check: Make sure using fp_offset makes sense.
10165 assert(!getTargetMachine().Options.UseSoftFloat &&
10166 !(DAG.getMachineFunction()
10167 .getFunction()->getAttributes()
10168 .hasAttribute(AttributeSet::FunctionIndex,
10169 Attribute::NoImplicitFloat)) &&
10170 Subtarget->hasSSE1());
10173 // Insert VAARG_64 node into the DAG
10174 // VAARG_64 returns two values: Variable Argument Address, Chain
10175 SmallVector<SDValue, 11> InstOps;
10176 InstOps.push_back(Chain);
10177 InstOps.push_back(SrcPtr);
10178 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10179 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10180 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10181 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10182 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10183 VTs, &InstOps[0], InstOps.size(),
10185 MachinePointerInfo(SV),
10187 /*Volatile=*/false,
10189 /*WriteMem=*/true);
10190 Chain = VAARG.getValue(1);
10192 // Load the next argument and return it
10193 return DAG.getLoad(ArgVT, dl,
10196 MachinePointerInfo(),
10197 false, false, false, 0);
10200 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10201 SelectionDAG &DAG) {
10202 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10203 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10204 SDValue Chain = Op.getOperand(0);
10205 SDValue DstPtr = Op.getOperand(1);
10206 SDValue SrcPtr = Op.getOperand(2);
10207 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10208 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10209 DebugLoc DL = Op.getDebugLoc();
10211 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10212 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10214 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10217 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10218 // may or may not be a constant. Takes immediate version of shift as input.
10219 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10220 SDValue SrcOp, SDValue ShAmt,
10221 SelectionDAG &DAG) {
10222 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10224 if (isa<ConstantSDNode>(ShAmt)) {
10225 // Constant may be a TargetConstant. Use a regular constant.
10226 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10228 default: llvm_unreachable("Unknown target vector shift node");
10229 case X86ISD::VSHLI:
10230 case X86ISD::VSRLI:
10231 case X86ISD::VSRAI:
10232 return DAG.getNode(Opc, dl, VT, SrcOp,
10233 DAG.getConstant(ShiftAmt, MVT::i32));
10237 // Change opcode to non-immediate version
10239 default: llvm_unreachable("Unknown target vector shift node");
10240 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10241 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10242 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10245 // Need to build a vector containing shift amount
10246 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10249 ShOps[1] = DAG.getConstant(0, MVT::i32);
10250 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10251 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10253 // The return type has to be a 128-bit type with the same element
10254 // type as the input type.
10255 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10256 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10258 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10259 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10262 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10263 DebugLoc dl = Op.getDebugLoc();
10264 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10266 default: return SDValue(); // Don't custom lower most intrinsics.
10267 // Comparison intrinsics.
10268 case Intrinsic::x86_sse_comieq_ss:
10269 case Intrinsic::x86_sse_comilt_ss:
10270 case Intrinsic::x86_sse_comile_ss:
10271 case Intrinsic::x86_sse_comigt_ss:
10272 case Intrinsic::x86_sse_comige_ss:
10273 case Intrinsic::x86_sse_comineq_ss:
10274 case Intrinsic::x86_sse_ucomieq_ss:
10275 case Intrinsic::x86_sse_ucomilt_ss:
10276 case Intrinsic::x86_sse_ucomile_ss:
10277 case Intrinsic::x86_sse_ucomigt_ss:
10278 case Intrinsic::x86_sse_ucomige_ss:
10279 case Intrinsic::x86_sse_ucomineq_ss:
10280 case Intrinsic::x86_sse2_comieq_sd:
10281 case Intrinsic::x86_sse2_comilt_sd:
10282 case Intrinsic::x86_sse2_comile_sd:
10283 case Intrinsic::x86_sse2_comigt_sd:
10284 case Intrinsic::x86_sse2_comige_sd:
10285 case Intrinsic::x86_sse2_comineq_sd:
10286 case Intrinsic::x86_sse2_ucomieq_sd:
10287 case Intrinsic::x86_sse2_ucomilt_sd:
10288 case Intrinsic::x86_sse2_ucomile_sd:
10289 case Intrinsic::x86_sse2_ucomigt_sd:
10290 case Intrinsic::x86_sse2_ucomige_sd:
10291 case Intrinsic::x86_sse2_ucomineq_sd: {
10295 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10296 case Intrinsic::x86_sse_comieq_ss:
10297 case Intrinsic::x86_sse2_comieq_sd:
10298 Opc = X86ISD::COMI;
10301 case Intrinsic::x86_sse_comilt_ss:
10302 case Intrinsic::x86_sse2_comilt_sd:
10303 Opc = X86ISD::COMI;
10306 case Intrinsic::x86_sse_comile_ss:
10307 case Intrinsic::x86_sse2_comile_sd:
10308 Opc = X86ISD::COMI;
10311 case Intrinsic::x86_sse_comigt_ss:
10312 case Intrinsic::x86_sse2_comigt_sd:
10313 Opc = X86ISD::COMI;
10316 case Intrinsic::x86_sse_comige_ss:
10317 case Intrinsic::x86_sse2_comige_sd:
10318 Opc = X86ISD::COMI;
10321 case Intrinsic::x86_sse_comineq_ss:
10322 case Intrinsic::x86_sse2_comineq_sd:
10323 Opc = X86ISD::COMI;
10326 case Intrinsic::x86_sse_ucomieq_ss:
10327 case Intrinsic::x86_sse2_ucomieq_sd:
10328 Opc = X86ISD::UCOMI;
10331 case Intrinsic::x86_sse_ucomilt_ss:
10332 case Intrinsic::x86_sse2_ucomilt_sd:
10333 Opc = X86ISD::UCOMI;
10336 case Intrinsic::x86_sse_ucomile_ss:
10337 case Intrinsic::x86_sse2_ucomile_sd:
10338 Opc = X86ISD::UCOMI;
10341 case Intrinsic::x86_sse_ucomigt_ss:
10342 case Intrinsic::x86_sse2_ucomigt_sd:
10343 Opc = X86ISD::UCOMI;
10346 case Intrinsic::x86_sse_ucomige_ss:
10347 case Intrinsic::x86_sse2_ucomige_sd:
10348 Opc = X86ISD::UCOMI;
10351 case Intrinsic::x86_sse_ucomineq_ss:
10352 case Intrinsic::x86_sse2_ucomineq_sd:
10353 Opc = X86ISD::UCOMI;
10358 SDValue LHS = Op.getOperand(1);
10359 SDValue RHS = Op.getOperand(2);
10360 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10361 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10362 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10363 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10364 DAG.getConstant(X86CC, MVT::i8), Cond);
10365 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10368 // Arithmetic intrinsics.
10369 case Intrinsic::x86_sse2_pmulu_dq:
10370 case Intrinsic::x86_avx2_pmulu_dq:
10371 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10372 Op.getOperand(1), Op.getOperand(2));
10374 // SSE2/AVX2 sub with unsigned saturation intrinsics
10375 case Intrinsic::x86_sse2_psubus_b:
10376 case Intrinsic::x86_sse2_psubus_w:
10377 case Intrinsic::x86_avx2_psubus_b:
10378 case Intrinsic::x86_avx2_psubus_w:
10379 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10380 Op.getOperand(1), Op.getOperand(2));
10382 // SSE3/AVX horizontal add/sub intrinsics
10383 case Intrinsic::x86_sse3_hadd_ps:
10384 case Intrinsic::x86_sse3_hadd_pd:
10385 case Intrinsic::x86_avx_hadd_ps_256:
10386 case Intrinsic::x86_avx_hadd_pd_256:
10387 case Intrinsic::x86_sse3_hsub_ps:
10388 case Intrinsic::x86_sse3_hsub_pd:
10389 case Intrinsic::x86_avx_hsub_ps_256:
10390 case Intrinsic::x86_avx_hsub_pd_256:
10391 case Intrinsic::x86_ssse3_phadd_w_128:
10392 case Intrinsic::x86_ssse3_phadd_d_128:
10393 case Intrinsic::x86_avx2_phadd_w:
10394 case Intrinsic::x86_avx2_phadd_d:
10395 case Intrinsic::x86_ssse3_phsub_w_128:
10396 case Intrinsic::x86_ssse3_phsub_d_128:
10397 case Intrinsic::x86_avx2_phsub_w:
10398 case Intrinsic::x86_avx2_phsub_d: {
10401 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10402 case Intrinsic::x86_sse3_hadd_ps:
10403 case Intrinsic::x86_sse3_hadd_pd:
10404 case Intrinsic::x86_avx_hadd_ps_256:
10405 case Intrinsic::x86_avx_hadd_pd_256:
10406 Opcode = X86ISD::FHADD;
10408 case Intrinsic::x86_sse3_hsub_ps:
10409 case Intrinsic::x86_sse3_hsub_pd:
10410 case Intrinsic::x86_avx_hsub_ps_256:
10411 case Intrinsic::x86_avx_hsub_pd_256:
10412 Opcode = X86ISD::FHSUB;
10414 case Intrinsic::x86_ssse3_phadd_w_128:
10415 case Intrinsic::x86_ssse3_phadd_d_128:
10416 case Intrinsic::x86_avx2_phadd_w:
10417 case Intrinsic::x86_avx2_phadd_d:
10418 Opcode = X86ISD::HADD;
10420 case Intrinsic::x86_ssse3_phsub_w_128:
10421 case Intrinsic::x86_ssse3_phsub_d_128:
10422 case Intrinsic::x86_avx2_phsub_w:
10423 case Intrinsic::x86_avx2_phsub_d:
10424 Opcode = X86ISD::HSUB;
10427 return DAG.getNode(Opcode, dl, Op.getValueType(),
10428 Op.getOperand(1), Op.getOperand(2));
10431 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10432 case Intrinsic::x86_sse2_pmaxu_b:
10433 case Intrinsic::x86_sse41_pmaxuw:
10434 case Intrinsic::x86_sse41_pmaxud:
10435 case Intrinsic::x86_avx2_pmaxu_b:
10436 case Intrinsic::x86_avx2_pmaxu_w:
10437 case Intrinsic::x86_avx2_pmaxu_d:
10438 case Intrinsic::x86_sse2_pminu_b:
10439 case Intrinsic::x86_sse41_pminuw:
10440 case Intrinsic::x86_sse41_pminud:
10441 case Intrinsic::x86_avx2_pminu_b:
10442 case Intrinsic::x86_avx2_pminu_w:
10443 case Intrinsic::x86_avx2_pminu_d:
10444 case Intrinsic::x86_sse41_pmaxsb:
10445 case Intrinsic::x86_sse2_pmaxs_w:
10446 case Intrinsic::x86_sse41_pmaxsd:
10447 case Intrinsic::x86_avx2_pmaxs_b:
10448 case Intrinsic::x86_avx2_pmaxs_w:
10449 case Intrinsic::x86_avx2_pmaxs_d:
10450 case Intrinsic::x86_sse41_pminsb:
10451 case Intrinsic::x86_sse2_pmins_w:
10452 case Intrinsic::x86_sse41_pminsd:
10453 case Intrinsic::x86_avx2_pmins_b:
10454 case Intrinsic::x86_avx2_pmins_w:
10455 case Intrinsic::x86_avx2_pmins_d: {
10458 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10459 case Intrinsic::x86_sse2_pmaxu_b:
10460 case Intrinsic::x86_sse41_pmaxuw:
10461 case Intrinsic::x86_sse41_pmaxud:
10462 case Intrinsic::x86_avx2_pmaxu_b:
10463 case Intrinsic::x86_avx2_pmaxu_w:
10464 case Intrinsic::x86_avx2_pmaxu_d:
10465 Opcode = X86ISD::UMAX;
10467 case Intrinsic::x86_sse2_pminu_b:
10468 case Intrinsic::x86_sse41_pminuw:
10469 case Intrinsic::x86_sse41_pminud:
10470 case Intrinsic::x86_avx2_pminu_b:
10471 case Intrinsic::x86_avx2_pminu_w:
10472 case Intrinsic::x86_avx2_pminu_d:
10473 Opcode = X86ISD::UMIN;
10475 case Intrinsic::x86_sse41_pmaxsb:
10476 case Intrinsic::x86_sse2_pmaxs_w:
10477 case Intrinsic::x86_sse41_pmaxsd:
10478 case Intrinsic::x86_avx2_pmaxs_b:
10479 case Intrinsic::x86_avx2_pmaxs_w:
10480 case Intrinsic::x86_avx2_pmaxs_d:
10481 Opcode = X86ISD::SMAX;
10483 case Intrinsic::x86_sse41_pminsb:
10484 case Intrinsic::x86_sse2_pmins_w:
10485 case Intrinsic::x86_sse41_pminsd:
10486 case Intrinsic::x86_avx2_pmins_b:
10487 case Intrinsic::x86_avx2_pmins_w:
10488 case Intrinsic::x86_avx2_pmins_d:
10489 Opcode = X86ISD::SMIN;
10492 return DAG.getNode(Opcode, dl, Op.getValueType(),
10493 Op.getOperand(1), Op.getOperand(2));
10496 // SSE/SSE2/AVX floating point max/min intrinsics.
10497 case Intrinsic::x86_sse_max_ps:
10498 case Intrinsic::x86_sse2_max_pd:
10499 case Intrinsic::x86_avx_max_ps_256:
10500 case Intrinsic::x86_avx_max_pd_256:
10501 case Intrinsic::x86_sse_min_ps:
10502 case Intrinsic::x86_sse2_min_pd:
10503 case Intrinsic::x86_avx_min_ps_256:
10504 case Intrinsic::x86_avx_min_pd_256: {
10507 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10508 case Intrinsic::x86_sse_max_ps:
10509 case Intrinsic::x86_sse2_max_pd:
10510 case Intrinsic::x86_avx_max_ps_256:
10511 case Intrinsic::x86_avx_max_pd_256:
10512 Opcode = X86ISD::FMAX;
10514 case Intrinsic::x86_sse_min_ps:
10515 case Intrinsic::x86_sse2_min_pd:
10516 case Intrinsic::x86_avx_min_ps_256:
10517 case Intrinsic::x86_avx_min_pd_256:
10518 Opcode = X86ISD::FMIN;
10521 return DAG.getNode(Opcode, dl, Op.getValueType(),
10522 Op.getOperand(1), Op.getOperand(2));
10525 // AVX2 variable shift intrinsics
10526 case Intrinsic::x86_avx2_psllv_d:
10527 case Intrinsic::x86_avx2_psllv_q:
10528 case Intrinsic::x86_avx2_psllv_d_256:
10529 case Intrinsic::x86_avx2_psllv_q_256:
10530 case Intrinsic::x86_avx2_psrlv_d:
10531 case Intrinsic::x86_avx2_psrlv_q:
10532 case Intrinsic::x86_avx2_psrlv_d_256:
10533 case Intrinsic::x86_avx2_psrlv_q_256:
10534 case Intrinsic::x86_avx2_psrav_d:
10535 case Intrinsic::x86_avx2_psrav_d_256: {
10538 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10539 case Intrinsic::x86_avx2_psllv_d:
10540 case Intrinsic::x86_avx2_psllv_q:
10541 case Intrinsic::x86_avx2_psllv_d_256:
10542 case Intrinsic::x86_avx2_psllv_q_256:
10545 case Intrinsic::x86_avx2_psrlv_d:
10546 case Intrinsic::x86_avx2_psrlv_q:
10547 case Intrinsic::x86_avx2_psrlv_d_256:
10548 case Intrinsic::x86_avx2_psrlv_q_256:
10551 case Intrinsic::x86_avx2_psrav_d:
10552 case Intrinsic::x86_avx2_psrav_d_256:
10556 return DAG.getNode(Opcode, dl, Op.getValueType(),
10557 Op.getOperand(1), Op.getOperand(2));
10560 case Intrinsic::x86_ssse3_pshuf_b_128:
10561 case Intrinsic::x86_avx2_pshuf_b:
10562 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10563 Op.getOperand(1), Op.getOperand(2));
10565 case Intrinsic::x86_ssse3_psign_b_128:
10566 case Intrinsic::x86_ssse3_psign_w_128:
10567 case Intrinsic::x86_ssse3_psign_d_128:
10568 case Intrinsic::x86_avx2_psign_b:
10569 case Intrinsic::x86_avx2_psign_w:
10570 case Intrinsic::x86_avx2_psign_d:
10571 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10572 Op.getOperand(1), Op.getOperand(2));
10574 case Intrinsic::x86_sse41_insertps:
10575 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10578 case Intrinsic::x86_avx_vperm2f128_ps_256:
10579 case Intrinsic::x86_avx_vperm2f128_pd_256:
10580 case Intrinsic::x86_avx_vperm2f128_si_256:
10581 case Intrinsic::x86_avx2_vperm2i128:
10582 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10583 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10585 case Intrinsic::x86_avx2_permd:
10586 case Intrinsic::x86_avx2_permps:
10587 // Operands intentionally swapped. Mask is last operand to intrinsic,
10588 // but second operand for node/intruction.
10589 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10590 Op.getOperand(2), Op.getOperand(1));
10592 case Intrinsic::x86_sse_sqrt_ps:
10593 case Intrinsic::x86_sse2_sqrt_pd:
10594 case Intrinsic::x86_avx_sqrt_ps_256:
10595 case Intrinsic::x86_avx_sqrt_pd_256:
10596 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10598 // ptest and testp intrinsics. The intrinsic these come from are designed to
10599 // return an integer value, not just an instruction so lower it to the ptest
10600 // or testp pattern and a setcc for the result.
10601 case Intrinsic::x86_sse41_ptestz:
10602 case Intrinsic::x86_sse41_ptestc:
10603 case Intrinsic::x86_sse41_ptestnzc:
10604 case Intrinsic::x86_avx_ptestz_256:
10605 case Intrinsic::x86_avx_ptestc_256:
10606 case Intrinsic::x86_avx_ptestnzc_256:
10607 case Intrinsic::x86_avx_vtestz_ps:
10608 case Intrinsic::x86_avx_vtestc_ps:
10609 case Intrinsic::x86_avx_vtestnzc_ps:
10610 case Intrinsic::x86_avx_vtestz_pd:
10611 case Intrinsic::x86_avx_vtestc_pd:
10612 case Intrinsic::x86_avx_vtestnzc_pd:
10613 case Intrinsic::x86_avx_vtestz_ps_256:
10614 case Intrinsic::x86_avx_vtestc_ps_256:
10615 case Intrinsic::x86_avx_vtestnzc_ps_256:
10616 case Intrinsic::x86_avx_vtestz_pd_256:
10617 case Intrinsic::x86_avx_vtestc_pd_256:
10618 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10619 bool IsTestPacked = false;
10622 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10623 case Intrinsic::x86_avx_vtestz_ps:
10624 case Intrinsic::x86_avx_vtestz_pd:
10625 case Intrinsic::x86_avx_vtestz_ps_256:
10626 case Intrinsic::x86_avx_vtestz_pd_256:
10627 IsTestPacked = true; // Fallthrough
10628 case Intrinsic::x86_sse41_ptestz:
10629 case Intrinsic::x86_avx_ptestz_256:
10631 X86CC = X86::COND_E;
10633 case Intrinsic::x86_avx_vtestc_ps:
10634 case Intrinsic::x86_avx_vtestc_pd:
10635 case Intrinsic::x86_avx_vtestc_ps_256:
10636 case Intrinsic::x86_avx_vtestc_pd_256:
10637 IsTestPacked = true; // Fallthrough
10638 case Intrinsic::x86_sse41_ptestc:
10639 case Intrinsic::x86_avx_ptestc_256:
10641 X86CC = X86::COND_B;
10643 case Intrinsic::x86_avx_vtestnzc_ps:
10644 case Intrinsic::x86_avx_vtestnzc_pd:
10645 case Intrinsic::x86_avx_vtestnzc_ps_256:
10646 case Intrinsic::x86_avx_vtestnzc_pd_256:
10647 IsTestPacked = true; // Fallthrough
10648 case Intrinsic::x86_sse41_ptestnzc:
10649 case Intrinsic::x86_avx_ptestnzc_256:
10651 X86CC = X86::COND_A;
10655 SDValue LHS = Op.getOperand(1);
10656 SDValue RHS = Op.getOperand(2);
10657 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10658 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10659 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10660 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10661 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10664 // SSE/AVX shift intrinsics
10665 case Intrinsic::x86_sse2_psll_w:
10666 case Intrinsic::x86_sse2_psll_d:
10667 case Intrinsic::x86_sse2_psll_q:
10668 case Intrinsic::x86_avx2_psll_w:
10669 case Intrinsic::x86_avx2_psll_d:
10670 case Intrinsic::x86_avx2_psll_q:
10671 case Intrinsic::x86_sse2_psrl_w:
10672 case Intrinsic::x86_sse2_psrl_d:
10673 case Intrinsic::x86_sse2_psrl_q:
10674 case Intrinsic::x86_avx2_psrl_w:
10675 case Intrinsic::x86_avx2_psrl_d:
10676 case Intrinsic::x86_avx2_psrl_q:
10677 case Intrinsic::x86_sse2_psra_w:
10678 case Intrinsic::x86_sse2_psra_d:
10679 case Intrinsic::x86_avx2_psra_w:
10680 case Intrinsic::x86_avx2_psra_d: {
10683 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10684 case Intrinsic::x86_sse2_psll_w:
10685 case Intrinsic::x86_sse2_psll_d:
10686 case Intrinsic::x86_sse2_psll_q:
10687 case Intrinsic::x86_avx2_psll_w:
10688 case Intrinsic::x86_avx2_psll_d:
10689 case Intrinsic::x86_avx2_psll_q:
10690 Opcode = X86ISD::VSHL;
10692 case Intrinsic::x86_sse2_psrl_w:
10693 case Intrinsic::x86_sse2_psrl_d:
10694 case Intrinsic::x86_sse2_psrl_q:
10695 case Intrinsic::x86_avx2_psrl_w:
10696 case Intrinsic::x86_avx2_psrl_d:
10697 case Intrinsic::x86_avx2_psrl_q:
10698 Opcode = X86ISD::VSRL;
10700 case Intrinsic::x86_sse2_psra_w:
10701 case Intrinsic::x86_sse2_psra_d:
10702 case Intrinsic::x86_avx2_psra_w:
10703 case Intrinsic::x86_avx2_psra_d:
10704 Opcode = X86ISD::VSRA;
10707 return DAG.getNode(Opcode, dl, Op.getValueType(),
10708 Op.getOperand(1), Op.getOperand(2));
10711 // SSE/AVX immediate shift intrinsics
10712 case Intrinsic::x86_sse2_pslli_w:
10713 case Intrinsic::x86_sse2_pslli_d:
10714 case Intrinsic::x86_sse2_pslli_q:
10715 case Intrinsic::x86_avx2_pslli_w:
10716 case Intrinsic::x86_avx2_pslli_d:
10717 case Intrinsic::x86_avx2_pslli_q:
10718 case Intrinsic::x86_sse2_psrli_w:
10719 case Intrinsic::x86_sse2_psrli_d:
10720 case Intrinsic::x86_sse2_psrli_q:
10721 case Intrinsic::x86_avx2_psrli_w:
10722 case Intrinsic::x86_avx2_psrli_d:
10723 case Intrinsic::x86_avx2_psrli_q:
10724 case Intrinsic::x86_sse2_psrai_w:
10725 case Intrinsic::x86_sse2_psrai_d:
10726 case Intrinsic::x86_avx2_psrai_w:
10727 case Intrinsic::x86_avx2_psrai_d: {
10730 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10731 case Intrinsic::x86_sse2_pslli_w:
10732 case Intrinsic::x86_sse2_pslli_d:
10733 case Intrinsic::x86_sse2_pslli_q:
10734 case Intrinsic::x86_avx2_pslli_w:
10735 case Intrinsic::x86_avx2_pslli_d:
10736 case Intrinsic::x86_avx2_pslli_q:
10737 Opcode = X86ISD::VSHLI;
10739 case Intrinsic::x86_sse2_psrli_w:
10740 case Intrinsic::x86_sse2_psrli_d:
10741 case Intrinsic::x86_sse2_psrli_q:
10742 case Intrinsic::x86_avx2_psrli_w:
10743 case Intrinsic::x86_avx2_psrli_d:
10744 case Intrinsic::x86_avx2_psrli_q:
10745 Opcode = X86ISD::VSRLI;
10747 case Intrinsic::x86_sse2_psrai_w:
10748 case Intrinsic::x86_sse2_psrai_d:
10749 case Intrinsic::x86_avx2_psrai_w:
10750 case Intrinsic::x86_avx2_psrai_d:
10751 Opcode = X86ISD::VSRAI;
10754 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10755 Op.getOperand(1), Op.getOperand(2), DAG);
10758 case Intrinsic::x86_sse42_pcmpistria128:
10759 case Intrinsic::x86_sse42_pcmpestria128:
10760 case Intrinsic::x86_sse42_pcmpistric128:
10761 case Intrinsic::x86_sse42_pcmpestric128:
10762 case Intrinsic::x86_sse42_pcmpistrio128:
10763 case Intrinsic::x86_sse42_pcmpestrio128:
10764 case Intrinsic::x86_sse42_pcmpistris128:
10765 case Intrinsic::x86_sse42_pcmpestris128:
10766 case Intrinsic::x86_sse42_pcmpistriz128:
10767 case Intrinsic::x86_sse42_pcmpestriz128: {
10771 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10772 case Intrinsic::x86_sse42_pcmpistria128:
10773 Opcode = X86ISD::PCMPISTRI;
10774 X86CC = X86::COND_A;
10776 case Intrinsic::x86_sse42_pcmpestria128:
10777 Opcode = X86ISD::PCMPESTRI;
10778 X86CC = X86::COND_A;
10780 case Intrinsic::x86_sse42_pcmpistric128:
10781 Opcode = X86ISD::PCMPISTRI;
10782 X86CC = X86::COND_B;
10784 case Intrinsic::x86_sse42_pcmpestric128:
10785 Opcode = X86ISD::PCMPESTRI;
10786 X86CC = X86::COND_B;
10788 case Intrinsic::x86_sse42_pcmpistrio128:
10789 Opcode = X86ISD::PCMPISTRI;
10790 X86CC = X86::COND_O;
10792 case Intrinsic::x86_sse42_pcmpestrio128:
10793 Opcode = X86ISD::PCMPESTRI;
10794 X86CC = X86::COND_O;
10796 case Intrinsic::x86_sse42_pcmpistris128:
10797 Opcode = X86ISD::PCMPISTRI;
10798 X86CC = X86::COND_S;
10800 case Intrinsic::x86_sse42_pcmpestris128:
10801 Opcode = X86ISD::PCMPESTRI;
10802 X86CC = X86::COND_S;
10804 case Intrinsic::x86_sse42_pcmpistriz128:
10805 Opcode = X86ISD::PCMPISTRI;
10806 X86CC = X86::COND_E;
10808 case Intrinsic::x86_sse42_pcmpestriz128:
10809 Opcode = X86ISD::PCMPESTRI;
10810 X86CC = X86::COND_E;
10813 SmallVector<SDValue, 5> NewOps;
10814 NewOps.append(Op->op_begin()+1, Op->op_end());
10815 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10816 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10817 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10818 DAG.getConstant(X86CC, MVT::i8),
10819 SDValue(PCMP.getNode(), 1));
10820 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10823 case Intrinsic::x86_sse42_pcmpistri128:
10824 case Intrinsic::x86_sse42_pcmpestri128: {
10826 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10827 Opcode = X86ISD::PCMPISTRI;
10829 Opcode = X86ISD::PCMPESTRI;
10831 SmallVector<SDValue, 5> NewOps;
10832 NewOps.append(Op->op_begin()+1, Op->op_end());
10833 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10834 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10836 case Intrinsic::x86_fma_vfmadd_ps:
10837 case Intrinsic::x86_fma_vfmadd_pd:
10838 case Intrinsic::x86_fma_vfmsub_ps:
10839 case Intrinsic::x86_fma_vfmsub_pd:
10840 case Intrinsic::x86_fma_vfnmadd_ps:
10841 case Intrinsic::x86_fma_vfnmadd_pd:
10842 case Intrinsic::x86_fma_vfnmsub_ps:
10843 case Intrinsic::x86_fma_vfnmsub_pd:
10844 case Intrinsic::x86_fma_vfmaddsub_ps:
10845 case Intrinsic::x86_fma_vfmaddsub_pd:
10846 case Intrinsic::x86_fma_vfmsubadd_ps:
10847 case Intrinsic::x86_fma_vfmsubadd_pd:
10848 case Intrinsic::x86_fma_vfmadd_ps_256:
10849 case Intrinsic::x86_fma_vfmadd_pd_256:
10850 case Intrinsic::x86_fma_vfmsub_ps_256:
10851 case Intrinsic::x86_fma_vfmsub_pd_256:
10852 case Intrinsic::x86_fma_vfnmadd_ps_256:
10853 case Intrinsic::x86_fma_vfnmadd_pd_256:
10854 case Intrinsic::x86_fma_vfnmsub_ps_256:
10855 case Intrinsic::x86_fma_vfnmsub_pd_256:
10856 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10857 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10858 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10859 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10862 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10863 case Intrinsic::x86_fma_vfmadd_ps:
10864 case Intrinsic::x86_fma_vfmadd_pd:
10865 case Intrinsic::x86_fma_vfmadd_ps_256:
10866 case Intrinsic::x86_fma_vfmadd_pd_256:
10867 Opc = X86ISD::FMADD;
10869 case Intrinsic::x86_fma_vfmsub_ps:
10870 case Intrinsic::x86_fma_vfmsub_pd:
10871 case Intrinsic::x86_fma_vfmsub_ps_256:
10872 case Intrinsic::x86_fma_vfmsub_pd_256:
10873 Opc = X86ISD::FMSUB;
10875 case Intrinsic::x86_fma_vfnmadd_ps:
10876 case Intrinsic::x86_fma_vfnmadd_pd:
10877 case Intrinsic::x86_fma_vfnmadd_ps_256:
10878 case Intrinsic::x86_fma_vfnmadd_pd_256:
10879 Opc = X86ISD::FNMADD;
10881 case Intrinsic::x86_fma_vfnmsub_ps:
10882 case Intrinsic::x86_fma_vfnmsub_pd:
10883 case Intrinsic::x86_fma_vfnmsub_ps_256:
10884 case Intrinsic::x86_fma_vfnmsub_pd_256:
10885 Opc = X86ISD::FNMSUB;
10887 case Intrinsic::x86_fma_vfmaddsub_ps:
10888 case Intrinsic::x86_fma_vfmaddsub_pd:
10889 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10890 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10891 Opc = X86ISD::FMADDSUB;
10893 case Intrinsic::x86_fma_vfmsubadd_ps:
10894 case Intrinsic::x86_fma_vfmsubadd_pd:
10895 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10896 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10897 Opc = X86ISD::FMSUBADD;
10901 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10902 Op.getOperand(2), Op.getOperand(3));
10907 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10908 DebugLoc dl = Op.getDebugLoc();
10909 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10911 default: return SDValue(); // Don't custom lower most intrinsics.
10913 // RDRAND intrinsics.
10914 case Intrinsic::x86_rdrand_16:
10915 case Intrinsic::x86_rdrand_32:
10916 case Intrinsic::x86_rdrand_64: {
10917 // Emit the node with the right value type.
10918 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10919 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10921 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10922 // return the value from Rand, which is always 0, casted to i32.
10923 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10924 DAG.getConstant(1, Op->getValueType(1)),
10925 DAG.getConstant(X86::COND_B, MVT::i32),
10926 SDValue(Result.getNode(), 1) };
10927 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10928 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10931 // Return { result, isValid, chain }.
10932 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10933 SDValue(Result.getNode(), 2));
10938 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10939 SelectionDAG &DAG) const {
10940 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10941 MFI->setReturnAddressIsTaken(true);
10943 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10944 DebugLoc dl = Op.getDebugLoc();
10945 EVT PtrVT = getPointerTy();
10948 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10950 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10951 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10952 DAG.getNode(ISD::ADD, dl, PtrVT,
10953 FrameAddr, Offset),
10954 MachinePointerInfo(), false, false, false, 0);
10957 // Just load the return address.
10958 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10959 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10960 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10963 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10964 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10965 MFI->setFrameAddressIsTaken(true);
10967 EVT VT = Op.getValueType();
10968 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10969 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10970 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10971 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10973 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10974 MachinePointerInfo(),
10975 false, false, false, 0);
10979 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10980 SelectionDAG &DAG) const {
10981 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10984 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10985 SDValue Chain = Op.getOperand(0);
10986 SDValue Offset = Op.getOperand(1);
10987 SDValue Handler = Op.getOperand(2);
10988 DebugLoc dl = Op.getDebugLoc();
10990 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10991 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10993 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10995 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10996 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10997 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10998 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11000 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11002 return DAG.getNode(X86ISD::EH_RETURN, dl,
11004 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11007 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11008 SelectionDAG &DAG) const {
11009 DebugLoc DL = Op.getDebugLoc();
11010 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11011 DAG.getVTList(MVT::i32, MVT::Other),
11012 Op.getOperand(0), Op.getOperand(1));
11015 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11016 SelectionDAG &DAG) const {
11017 DebugLoc DL = Op.getDebugLoc();
11018 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11019 Op.getOperand(0), Op.getOperand(1));
11022 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11023 return Op.getOperand(0);
11026 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11027 SelectionDAG &DAG) const {
11028 SDValue Root = Op.getOperand(0);
11029 SDValue Trmp = Op.getOperand(1); // trampoline
11030 SDValue FPtr = Op.getOperand(2); // nested function
11031 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11032 DebugLoc dl = Op.getDebugLoc();
11034 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11035 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11037 if (Subtarget->is64Bit()) {
11038 SDValue OutChains[6];
11040 // Large code-model.
11041 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
11042 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11044 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11045 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11047 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11049 // Load the pointer to the nested function into R11.
11050 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11051 SDValue Addr = Trmp;
11052 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11053 Addr, MachinePointerInfo(TrmpAddr),
11056 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11057 DAG.getConstant(2, MVT::i64));
11058 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11059 MachinePointerInfo(TrmpAddr, 2),
11062 // Load the 'nest' parameter value into R10.
11063 // R10 is specified in X86CallingConv.td
11064 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11065 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11066 DAG.getConstant(10, MVT::i64));
11067 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11068 Addr, MachinePointerInfo(TrmpAddr, 10),
11071 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11072 DAG.getConstant(12, MVT::i64));
11073 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11074 MachinePointerInfo(TrmpAddr, 12),
11077 // Jump to the nested function.
11078 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11079 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11080 DAG.getConstant(20, MVT::i64));
11081 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11082 Addr, MachinePointerInfo(TrmpAddr, 20),
11085 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11086 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11087 DAG.getConstant(22, MVT::i64));
11088 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11089 MachinePointerInfo(TrmpAddr, 22),
11092 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11094 const Function *Func =
11095 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11096 CallingConv::ID CC = Func->getCallingConv();
11101 llvm_unreachable("Unsupported calling convention");
11102 case CallingConv::C:
11103 case CallingConv::X86_StdCall: {
11104 // Pass 'nest' parameter in ECX.
11105 // Must be kept in sync with X86CallingConv.td
11106 NestReg = X86::ECX;
11108 // Check that ECX wasn't needed by an 'inreg' parameter.
11109 FunctionType *FTy = Func->getFunctionType();
11110 const AttributeSet &Attrs = Func->getAttributes();
11112 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11113 unsigned InRegCount = 0;
11116 for (FunctionType::param_iterator I = FTy->param_begin(),
11117 E = FTy->param_end(); I != E; ++I, ++Idx)
11118 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11119 // FIXME: should only count parameters that are lowered to integers.
11120 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11122 if (InRegCount > 2) {
11123 report_fatal_error("Nest register in use - reduce number of inreg"
11129 case CallingConv::X86_FastCall:
11130 case CallingConv::X86_ThisCall:
11131 case CallingConv::Fast:
11132 // Pass 'nest' parameter in EAX.
11133 // Must be kept in sync with X86CallingConv.td
11134 NestReg = X86::EAX;
11138 SDValue OutChains[4];
11139 SDValue Addr, Disp;
11141 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11142 DAG.getConstant(10, MVT::i32));
11143 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11145 // This is storing the opcode for MOV32ri.
11146 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11147 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11148 OutChains[0] = DAG.getStore(Root, dl,
11149 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11150 Trmp, MachinePointerInfo(TrmpAddr),
11153 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11154 DAG.getConstant(1, MVT::i32));
11155 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11156 MachinePointerInfo(TrmpAddr, 1),
11159 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11160 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11161 DAG.getConstant(5, MVT::i32));
11162 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11163 MachinePointerInfo(TrmpAddr, 5),
11166 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11167 DAG.getConstant(6, MVT::i32));
11168 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11169 MachinePointerInfo(TrmpAddr, 6),
11172 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11176 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11177 SelectionDAG &DAG) const {
11179 The rounding mode is in bits 11:10 of FPSR, and has the following
11181 00 Round to nearest
11186 FLT_ROUNDS, on the other hand, expects the following:
11193 To perform the conversion, we do:
11194 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11197 MachineFunction &MF = DAG.getMachineFunction();
11198 const TargetMachine &TM = MF.getTarget();
11199 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11200 unsigned StackAlignment = TFI.getStackAlignment();
11201 EVT VT = Op.getValueType();
11202 DebugLoc DL = Op.getDebugLoc();
11204 // Save FP Control Word to stack slot
11205 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11206 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11208 MachineMemOperand *MMO =
11209 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11210 MachineMemOperand::MOStore, 2, 2);
11212 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11213 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11214 DAG.getVTList(MVT::Other),
11215 Ops, 2, MVT::i16, MMO);
11217 // Load FP Control Word from stack slot
11218 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11219 MachinePointerInfo(), false, false, false, 0);
11221 // Transform as necessary
11223 DAG.getNode(ISD::SRL, DL, MVT::i16,
11224 DAG.getNode(ISD::AND, DL, MVT::i16,
11225 CWD, DAG.getConstant(0x800, MVT::i16)),
11226 DAG.getConstant(11, MVT::i8));
11228 DAG.getNode(ISD::SRL, DL, MVT::i16,
11229 DAG.getNode(ISD::AND, DL, MVT::i16,
11230 CWD, DAG.getConstant(0x400, MVT::i16)),
11231 DAG.getConstant(9, MVT::i8));
11234 DAG.getNode(ISD::AND, DL, MVT::i16,
11235 DAG.getNode(ISD::ADD, DL, MVT::i16,
11236 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11237 DAG.getConstant(1, MVT::i16)),
11238 DAG.getConstant(3, MVT::i16));
11240 return DAG.getNode((VT.getSizeInBits() < 16 ?
11241 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11244 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11245 EVT VT = Op.getValueType();
11247 unsigned NumBits = VT.getSizeInBits();
11248 DebugLoc dl = Op.getDebugLoc();
11250 Op = Op.getOperand(0);
11251 if (VT == MVT::i8) {
11252 // Zero extend to i32 since there is not an i8 bsr.
11254 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11257 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11258 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11259 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11261 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11264 DAG.getConstant(NumBits+NumBits-1, OpVT),
11265 DAG.getConstant(X86::COND_E, MVT::i8),
11268 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11270 // Finally xor with NumBits-1.
11271 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11274 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11278 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11279 EVT VT = Op.getValueType();
11281 unsigned NumBits = VT.getSizeInBits();
11282 DebugLoc dl = Op.getDebugLoc();
11284 Op = Op.getOperand(0);
11285 if (VT == MVT::i8) {
11286 // Zero extend to i32 since there is not an i8 bsr.
11288 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11291 // Issue a bsr (scan bits in reverse).
11292 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11293 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11295 // And xor with NumBits-1.
11296 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11299 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11303 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11304 EVT VT = Op.getValueType();
11305 unsigned NumBits = VT.getSizeInBits();
11306 DebugLoc dl = Op.getDebugLoc();
11307 Op = Op.getOperand(0);
11309 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11310 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11311 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11313 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11316 DAG.getConstant(NumBits, VT),
11317 DAG.getConstant(X86::COND_E, MVT::i8),
11320 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11323 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11324 // ones, and then concatenate the result back.
11325 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11326 EVT VT = Op.getValueType();
11328 assert(VT.is256BitVector() && VT.isInteger() &&
11329 "Unsupported value type for operation");
11331 unsigned NumElems = VT.getVectorNumElements();
11332 DebugLoc dl = Op.getDebugLoc();
11334 // Extract the LHS vectors
11335 SDValue LHS = Op.getOperand(0);
11336 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11337 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11339 // Extract the RHS vectors
11340 SDValue RHS = Op.getOperand(1);
11341 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11342 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11344 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11345 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11347 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11348 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11349 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11352 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11353 assert(Op.getValueType().is256BitVector() &&
11354 Op.getValueType().isInteger() &&
11355 "Only handle AVX 256-bit vector integer operation");
11356 return Lower256IntArith(Op, DAG);
11359 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11360 assert(Op.getValueType().is256BitVector() &&
11361 Op.getValueType().isInteger() &&
11362 "Only handle AVX 256-bit vector integer operation");
11363 return Lower256IntArith(Op, DAG);
11366 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11367 SelectionDAG &DAG) {
11368 DebugLoc dl = Op.getDebugLoc();
11369 EVT VT = Op.getValueType();
11371 // Decompose 256-bit ops into smaller 128-bit ops.
11372 if (VT.is256BitVector() && !Subtarget->hasInt256())
11373 return Lower256IntArith(Op, DAG);
11375 SDValue A = Op.getOperand(0);
11376 SDValue B = Op.getOperand(1);
11378 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11379 if (VT == MVT::v4i32) {
11380 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11381 "Should not custom lower when pmuldq is available!");
11383 // Extract the odd parts.
11384 const int UnpackMask[] = { 1, -1, 3, -1 };
11385 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11386 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11388 // Multiply the even parts.
11389 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11390 // Now multiply odd parts.
11391 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11393 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11394 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11396 // Merge the two vectors back together with a shuffle. This expands into 2
11398 const int ShufMask[] = { 0, 4, 2, 6 };
11399 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11402 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11403 "Only know how to lower V2I64/V4I64 multiply");
11405 // Ahi = psrlqi(a, 32);
11406 // Bhi = psrlqi(b, 32);
11408 // AloBlo = pmuludq(a, b);
11409 // AloBhi = pmuludq(a, Bhi);
11410 // AhiBlo = pmuludq(Ahi, b);
11412 // AloBhi = psllqi(AloBhi, 32);
11413 // AhiBlo = psllqi(AhiBlo, 32);
11414 // return AloBlo + AloBhi + AhiBlo;
11416 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11418 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11419 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11421 // Bit cast to 32-bit vectors for MULUDQ
11422 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11423 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11424 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11425 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11426 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11428 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11429 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11430 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11432 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11433 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11435 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11436 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11439 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11440 EVT VT = Op.getValueType();
11441 EVT EltTy = VT.getVectorElementType();
11442 unsigned NumElts = VT.getVectorNumElements();
11443 SDValue N0 = Op.getOperand(0);
11444 DebugLoc dl = Op.getDebugLoc();
11446 // Lower sdiv X, pow2-const.
11447 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11451 APInt SplatValue, SplatUndef;
11452 unsigned MinSplatBits;
11454 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11457 if ((SplatValue != 0) &&
11458 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11459 unsigned lg2 = SplatValue.countTrailingZeros();
11460 // Splat the sign bit.
11461 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11462 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11463 // Add (N0 < 0) ? abs2 - 1 : 0;
11464 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11465 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11466 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11467 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11468 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11470 // If we're dividing by a positive value, we're done. Otherwise, we must
11471 // negate the result.
11472 if (SplatValue.isNonNegative())
11475 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11476 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11477 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11482 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11484 EVT VT = Op.getValueType();
11485 DebugLoc dl = Op.getDebugLoc();
11486 SDValue R = Op.getOperand(0);
11487 SDValue Amt = Op.getOperand(1);
11489 if (!Subtarget->hasSSE2())
11492 // Optimize shl/srl/sra with constant shift amount.
11493 if (isSplatVector(Amt.getNode())) {
11494 SDValue SclrAmt = Amt->getOperand(0);
11495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11496 uint64_t ShiftAmt = C->getZExtValue();
11498 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11499 (Subtarget->hasInt256() &&
11500 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11501 if (Op.getOpcode() == ISD::SHL)
11502 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11503 DAG.getConstant(ShiftAmt, MVT::i32));
11504 if (Op.getOpcode() == ISD::SRL)
11505 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11506 DAG.getConstant(ShiftAmt, MVT::i32));
11507 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11508 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11509 DAG.getConstant(ShiftAmt, MVT::i32));
11512 if (VT == MVT::v16i8) {
11513 if (Op.getOpcode() == ISD::SHL) {
11514 // Make a large shift.
11515 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11516 DAG.getConstant(ShiftAmt, MVT::i32));
11517 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11518 // Zero out the rightmost bits.
11519 SmallVector<SDValue, 16> V(16,
11520 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11522 return DAG.getNode(ISD::AND, dl, VT, SHL,
11523 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11525 if (Op.getOpcode() == ISD::SRL) {
11526 // Make a large shift.
11527 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11528 DAG.getConstant(ShiftAmt, MVT::i32));
11529 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11530 // Zero out the leftmost bits.
11531 SmallVector<SDValue, 16> V(16,
11532 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11534 return DAG.getNode(ISD::AND, dl, VT, SRL,
11535 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11537 if (Op.getOpcode() == ISD::SRA) {
11538 if (ShiftAmt == 7) {
11539 // R s>> 7 === R s< 0
11540 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11541 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11544 // R s>> a === ((R u>> a) ^ m) - m
11545 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11546 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11548 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11549 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11550 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11553 llvm_unreachable("Unknown shift opcode.");
11556 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11557 if (Op.getOpcode() == ISD::SHL) {
11558 // Make a large shift.
11559 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11560 DAG.getConstant(ShiftAmt, MVT::i32));
11561 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11562 // Zero out the rightmost bits.
11563 SmallVector<SDValue, 32> V(32,
11564 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11566 return DAG.getNode(ISD::AND, dl, VT, SHL,
11567 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11569 if (Op.getOpcode() == ISD::SRL) {
11570 // Make a large shift.
11571 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11572 DAG.getConstant(ShiftAmt, MVT::i32));
11573 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11574 // Zero out the leftmost bits.
11575 SmallVector<SDValue, 32> V(32,
11576 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11578 return DAG.getNode(ISD::AND, dl, VT, SRL,
11579 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11581 if (Op.getOpcode() == ISD::SRA) {
11582 if (ShiftAmt == 7) {
11583 // R s>> 7 === R s< 0
11584 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11585 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11588 // R s>> a === ((R u>> a) ^ m) - m
11589 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11590 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11592 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11593 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11594 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11597 llvm_unreachable("Unknown shift opcode.");
11602 // Lower SHL with variable shift amount.
11603 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11604 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11606 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11607 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11608 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11609 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11611 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11612 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11615 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11616 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11618 // Turn 'a' into a mask suitable for VSELECT
11619 SDValue VSelM = DAG.getConstant(0x80, VT);
11620 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11621 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11623 SDValue CM1 = DAG.getConstant(0x0f, VT);
11624 SDValue CM2 = DAG.getConstant(0x3f, VT);
11626 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11627 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11628 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11629 DAG.getConstant(4, MVT::i32), DAG);
11630 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11631 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11634 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11635 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11636 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11638 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11639 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11640 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11641 DAG.getConstant(2, MVT::i32), DAG);
11642 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11643 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11646 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11647 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11648 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11650 // return VSELECT(r, r+r, a);
11651 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11652 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11656 // Decompose 256-bit shifts into smaller 128-bit shifts.
11657 if (VT.is256BitVector()) {
11658 unsigned NumElems = VT.getVectorNumElements();
11659 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11660 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11662 // Extract the two vectors
11663 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11664 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11666 // Recreate the shift amount vectors
11667 SDValue Amt1, Amt2;
11668 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11669 // Constant shift amount
11670 SmallVector<SDValue, 4> Amt1Csts;
11671 SmallVector<SDValue, 4> Amt2Csts;
11672 for (unsigned i = 0; i != NumElems/2; ++i)
11673 Amt1Csts.push_back(Amt->getOperand(i));
11674 for (unsigned i = NumElems/2; i != NumElems; ++i)
11675 Amt2Csts.push_back(Amt->getOperand(i));
11677 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11678 &Amt1Csts[0], NumElems/2);
11679 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11680 &Amt2Csts[0], NumElems/2);
11682 // Variable shift amount
11683 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11684 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11687 // Issue new vector shifts for the smaller types
11688 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11689 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11691 // Concatenate the result back
11692 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11698 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11699 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11700 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11701 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11702 // has only one use.
11703 SDNode *N = Op.getNode();
11704 SDValue LHS = N->getOperand(0);
11705 SDValue RHS = N->getOperand(1);
11706 unsigned BaseOp = 0;
11708 DebugLoc DL = Op.getDebugLoc();
11709 switch (Op.getOpcode()) {
11710 default: llvm_unreachable("Unknown ovf instruction!");
11712 // A subtract of one will be selected as a INC. Note that INC doesn't
11713 // set CF, so we can't do this for UADDO.
11714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11716 BaseOp = X86ISD::INC;
11717 Cond = X86::COND_O;
11720 BaseOp = X86ISD::ADD;
11721 Cond = X86::COND_O;
11724 BaseOp = X86ISD::ADD;
11725 Cond = X86::COND_B;
11728 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11729 // set CF, so we can't do this for USUBO.
11730 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11732 BaseOp = X86ISD::DEC;
11733 Cond = X86::COND_O;
11736 BaseOp = X86ISD::SUB;
11737 Cond = X86::COND_O;
11740 BaseOp = X86ISD::SUB;
11741 Cond = X86::COND_B;
11744 BaseOp = X86ISD::SMUL;
11745 Cond = X86::COND_O;
11747 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11748 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11750 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11753 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11754 DAG.getConstant(X86::COND_O, MVT::i32),
11755 SDValue(Sum.getNode(), 2));
11757 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11761 // Also sets EFLAGS.
11762 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11763 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11766 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11767 DAG.getConstant(Cond, MVT::i32),
11768 SDValue(Sum.getNode(), 1));
11770 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11773 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11774 SelectionDAG &DAG) const {
11775 DebugLoc dl = Op.getDebugLoc();
11776 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11777 EVT VT = Op.getValueType();
11779 if (!Subtarget->hasSSE2() || !VT.isVector())
11782 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11783 ExtraVT.getScalarType().getSizeInBits();
11784 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11786 switch (VT.getSimpleVT().SimpleTy) {
11787 default: return SDValue();
11790 if (!Subtarget->hasFp256())
11792 if (!Subtarget->hasInt256()) {
11793 // needs to be split
11794 unsigned NumElems = VT.getVectorNumElements();
11796 // Extract the LHS vectors
11797 SDValue LHS = Op.getOperand(0);
11798 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11799 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11801 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11802 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11804 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11805 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11806 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11808 SDValue Extra = DAG.getValueType(ExtraVT);
11810 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11811 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11813 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11818 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11819 Op.getOperand(0), ShAmt, DAG);
11820 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11825 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11826 SelectionDAG &DAG) {
11827 DebugLoc dl = Op.getDebugLoc();
11829 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11830 // There isn't any reason to disable it if the target processor supports it.
11831 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11832 SDValue Chain = Op.getOperand(0);
11833 SDValue Zero = DAG.getConstant(0, MVT::i32);
11835 DAG.getRegister(X86::ESP, MVT::i32), // Base
11836 DAG.getTargetConstant(1, MVT::i8), // Scale
11837 DAG.getRegister(0, MVT::i32), // Index
11838 DAG.getTargetConstant(0, MVT::i32), // Disp
11839 DAG.getRegister(0, MVT::i32), // Segment.
11844 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11845 array_lengthof(Ops));
11846 return SDValue(Res, 0);
11849 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11851 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11853 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11854 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11855 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11856 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11858 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11859 if (!Op1 && !Op2 && !Op3 && Op4)
11860 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11862 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11863 if (Op1 && !Op2 && !Op3 && !Op4)
11864 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11866 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11868 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11871 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11872 SelectionDAG &DAG) {
11873 DebugLoc dl = Op.getDebugLoc();
11874 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11875 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11876 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11877 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11879 // The only fence that needs an instruction is a sequentially-consistent
11880 // cross-thread fence.
11881 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11882 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11883 // no-sse2). There isn't any reason to disable it if the target processor
11885 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11886 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11888 SDValue Chain = Op.getOperand(0);
11889 SDValue Zero = DAG.getConstant(0, MVT::i32);
11891 DAG.getRegister(X86::ESP, MVT::i32), // Base
11892 DAG.getTargetConstant(1, MVT::i8), // Scale
11893 DAG.getRegister(0, MVT::i32), // Index
11894 DAG.getTargetConstant(0, MVT::i32), // Disp
11895 DAG.getRegister(0, MVT::i32), // Segment.
11900 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11901 array_lengthof(Ops));
11902 return SDValue(Res, 0);
11905 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11906 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11909 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11910 SelectionDAG &DAG) {
11911 EVT T = Op.getValueType();
11912 DebugLoc DL = Op.getDebugLoc();
11915 switch(T.getSimpleVT().SimpleTy) {
11916 default: llvm_unreachable("Invalid value type!");
11917 case MVT::i8: Reg = X86::AL; size = 1; break;
11918 case MVT::i16: Reg = X86::AX; size = 2; break;
11919 case MVT::i32: Reg = X86::EAX; size = 4; break;
11921 assert(Subtarget->is64Bit() && "Node not type legal!");
11922 Reg = X86::RAX; size = 8;
11925 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11926 Op.getOperand(2), SDValue());
11927 SDValue Ops[] = { cpIn.getValue(0),
11930 DAG.getTargetConstant(size, MVT::i8),
11931 cpIn.getValue(1) };
11932 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11933 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11934 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11937 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11941 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11942 SelectionDAG &DAG) {
11943 assert(Subtarget->is64Bit() && "Result not type legalized?");
11944 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11945 SDValue TheChain = Op.getOperand(0);
11946 DebugLoc dl = Op.getDebugLoc();
11947 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11948 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11949 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11951 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11952 DAG.getConstant(32, MVT::i8));
11954 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11957 return DAG.getMergeValues(Ops, 2, dl);
11960 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11961 EVT SrcVT = Op.getOperand(0).getValueType();
11962 EVT DstVT = Op.getValueType();
11963 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11964 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11965 assert((DstVT == MVT::i64 ||
11966 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11967 "Unexpected custom BITCAST");
11968 // i64 <=> MMX conversions are Legal.
11969 if (SrcVT==MVT::i64 && DstVT.isVector())
11971 if (DstVT==MVT::i64 && SrcVT.isVector())
11973 // MMX <=> MMX conversions are Legal.
11974 if (SrcVT.isVector() && DstVT.isVector())
11976 // All other conversions need to be expanded.
11980 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11981 SDNode *Node = Op.getNode();
11982 DebugLoc dl = Node->getDebugLoc();
11983 EVT T = Node->getValueType(0);
11984 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11985 DAG.getConstant(0, T), Node->getOperand(2));
11986 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11987 cast<AtomicSDNode>(Node)->getMemoryVT(),
11988 Node->getOperand(0),
11989 Node->getOperand(1), negOp,
11990 cast<AtomicSDNode>(Node)->getSrcValue(),
11991 cast<AtomicSDNode>(Node)->getAlignment(),
11992 cast<AtomicSDNode>(Node)->getOrdering(),
11993 cast<AtomicSDNode>(Node)->getSynchScope());
11996 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11997 SDNode *Node = Op.getNode();
11998 DebugLoc dl = Node->getDebugLoc();
11999 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12001 // Convert seq_cst store -> xchg
12002 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12003 // FIXME: On 32-bit, store -> fist or movq would be more efficient
12004 // (The only way to get a 16-byte store is cmpxchg16b)
12005 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12006 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12007 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12008 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12009 cast<AtomicSDNode>(Node)->getMemoryVT(),
12010 Node->getOperand(0),
12011 Node->getOperand(1), Node->getOperand(2),
12012 cast<AtomicSDNode>(Node)->getMemOperand(),
12013 cast<AtomicSDNode>(Node)->getOrdering(),
12014 cast<AtomicSDNode>(Node)->getSynchScope());
12015 return Swap.getValue(1);
12017 // Other atomic stores have a simple pattern.
12021 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12022 EVT VT = Op.getNode()->getValueType(0);
12024 // Let legalize expand this if it isn't a legal type yet.
12025 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12028 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12031 bool ExtraOp = false;
12032 switch (Op.getOpcode()) {
12033 default: llvm_unreachable("Invalid code");
12034 case ISD::ADDC: Opc = X86ISD::ADD; break;
12035 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12036 case ISD::SUBC: Opc = X86ISD::SUB; break;
12037 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12041 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12043 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12044 Op.getOperand(1), Op.getOperand(2));
12047 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12048 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12050 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12051 // which returns the values in two XMM registers.
12052 DebugLoc dl = Op.getDebugLoc();
12053 SDValue Arg = Op.getOperand(0);
12054 EVT ArgVT = Arg.getValueType();
12055 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12058 ArgListEntry Entry;
12062 Entry.isSExt = false;
12063 Entry.isZExt = false;
12064 Args.push_back(Entry);
12066 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12067 // the small struct {f32, f32} is returned in (eax, edx). For f64,
12068 // the results are returned via SRet in memory.
12069 const char *LibcallName = (ArgVT == MVT::f64)
12070 ? "__sincos_stret" : "__sincosf_stret";
12071 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12073 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12075 CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12076 false, false, false, false, 0,
12077 CallingConv::C, /*isTaillCall=*/false,
12078 /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12079 Callee, Args, DAG, dl);
12080 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12081 return CallResult.first;
12084 /// LowerOperation - Provide custom lowering hooks for some operations.
12086 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12087 switch (Op.getOpcode()) {
12088 default: llvm_unreachable("Should not custom lower this!");
12089 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12090 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
12091 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12092 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12093 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12094 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12095 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12096 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12097 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12098 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12099 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12100 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12101 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12102 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12103 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12104 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12105 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12106 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12107 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12108 case ISD::SHL_PARTS:
12109 case ISD::SRA_PARTS:
12110 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12111 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12112 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12113 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12114 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12115 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12116 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12117 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12118 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12119 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12120 case ISD::FABS: return LowerFABS(Op, DAG);
12121 case ISD::FNEG: return LowerFNEG(Op, DAG);
12122 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12123 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12124 case ISD::SETCC: return LowerSETCC(Op, DAG);
12125 case ISD::SELECT: return LowerSELECT(Op, DAG);
12126 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12127 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12128 case ISD::VASTART: return LowerVASTART(Op, DAG);
12129 case ISD::VAARG: return LowerVAARG(Op, DAG);
12130 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12131 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12132 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12133 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12134 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12135 case ISD::FRAME_TO_ARGS_OFFSET:
12136 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12137 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12138 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12139 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12140 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12141 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12142 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12143 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12144 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12145 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12146 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12147 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12150 case ISD::SHL: return LowerShift(Op, DAG);
12156 case ISD::UMULO: return LowerXALUO(Op, DAG);
12157 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12158 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12162 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12163 case ISD::ADD: return LowerADD(Op, DAG);
12164 case ISD::SUB: return LowerSUB(Op, DAG);
12165 case ISD::SDIV: return LowerSDIV(Op, DAG);
12166 case ISD::FSINCOS: return LowerFSINCOS(Op, DAG);
12170 static void ReplaceATOMIC_LOAD(SDNode *Node,
12171 SmallVectorImpl<SDValue> &Results,
12172 SelectionDAG &DAG) {
12173 DebugLoc dl = Node->getDebugLoc();
12174 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12176 // Convert wide load -> cmpxchg8b/cmpxchg16b
12177 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12178 // (The only way to get a 16-byte load is cmpxchg16b)
12179 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12180 SDValue Zero = DAG.getConstant(0, VT);
12181 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12182 Node->getOperand(0),
12183 Node->getOperand(1), Zero, Zero,
12184 cast<AtomicSDNode>(Node)->getMemOperand(),
12185 cast<AtomicSDNode>(Node)->getOrdering(),
12186 cast<AtomicSDNode>(Node)->getSynchScope());
12187 Results.push_back(Swap.getValue(0));
12188 Results.push_back(Swap.getValue(1));
12192 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12193 SelectionDAG &DAG, unsigned NewOp) {
12194 DebugLoc dl = Node->getDebugLoc();
12195 assert (Node->getValueType(0) == MVT::i64 &&
12196 "Only know how to expand i64 atomics");
12198 SDValue Chain = Node->getOperand(0);
12199 SDValue In1 = Node->getOperand(1);
12200 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12201 Node->getOperand(2), DAG.getIntPtrConstant(0));
12202 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12203 Node->getOperand(2), DAG.getIntPtrConstant(1));
12204 SDValue Ops[] = { Chain, In1, In2L, In2H };
12205 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12207 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12208 cast<MemSDNode>(Node)->getMemOperand());
12209 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12210 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12211 Results.push_back(Result.getValue(2));
12214 /// ReplaceNodeResults - Replace a node with an illegal result type
12215 /// with a new node built out of custom code.
12216 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12217 SmallVectorImpl<SDValue>&Results,
12218 SelectionDAG &DAG) const {
12219 DebugLoc dl = N->getDebugLoc();
12220 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12221 switch (N->getOpcode()) {
12223 llvm_unreachable("Do not know how to custom type legalize this operation!");
12224 case ISD::SIGN_EXTEND_INREG:
12229 // We don't want to expand or promote these.
12231 case ISD::FP_TO_SINT:
12232 case ISD::FP_TO_UINT: {
12233 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12235 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12238 std::pair<SDValue,SDValue> Vals =
12239 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12240 SDValue FIST = Vals.first, StackSlot = Vals.second;
12241 if (FIST.getNode() != 0) {
12242 EVT VT = N->getValueType(0);
12243 // Return a load from the stack slot.
12244 if (StackSlot.getNode() != 0)
12245 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12246 MachinePointerInfo(),
12247 false, false, false, 0));
12249 Results.push_back(FIST);
12253 case ISD::UINT_TO_FP: {
12254 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12255 N->getValueType(0) != MVT::v2f32)
12257 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12259 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12261 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12262 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12263 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12264 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12265 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12266 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12269 case ISD::FP_ROUND: {
12270 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12272 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12273 Results.push_back(V);
12276 case ISD::READCYCLECOUNTER: {
12277 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12278 SDValue TheChain = N->getOperand(0);
12279 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12280 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12282 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12284 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12285 SDValue Ops[] = { eax, edx };
12286 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12287 Results.push_back(edx.getValue(1));
12290 case ISD::ATOMIC_CMP_SWAP: {
12291 EVT T = N->getValueType(0);
12292 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12293 bool Regs64bit = T == MVT::i128;
12294 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12295 SDValue cpInL, cpInH;
12296 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12297 DAG.getConstant(0, HalfT));
12298 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12299 DAG.getConstant(1, HalfT));
12300 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12301 Regs64bit ? X86::RAX : X86::EAX,
12303 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12304 Regs64bit ? X86::RDX : X86::EDX,
12305 cpInH, cpInL.getValue(1));
12306 SDValue swapInL, swapInH;
12307 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12308 DAG.getConstant(0, HalfT));
12309 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12310 DAG.getConstant(1, HalfT));
12311 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12312 Regs64bit ? X86::RBX : X86::EBX,
12313 swapInL, cpInH.getValue(1));
12314 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12315 Regs64bit ? X86::RCX : X86::ECX,
12316 swapInH, swapInL.getValue(1));
12317 SDValue Ops[] = { swapInH.getValue(0),
12319 swapInH.getValue(1) };
12320 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12321 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12322 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12323 X86ISD::LCMPXCHG8_DAG;
12324 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12326 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12327 Regs64bit ? X86::RAX : X86::EAX,
12328 HalfT, Result.getValue(1));
12329 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12330 Regs64bit ? X86::RDX : X86::EDX,
12331 HalfT, cpOutL.getValue(2));
12332 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12333 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12334 Results.push_back(cpOutH.getValue(1));
12337 case ISD::ATOMIC_LOAD_ADD:
12338 case ISD::ATOMIC_LOAD_AND:
12339 case ISD::ATOMIC_LOAD_NAND:
12340 case ISD::ATOMIC_LOAD_OR:
12341 case ISD::ATOMIC_LOAD_SUB:
12342 case ISD::ATOMIC_LOAD_XOR:
12343 case ISD::ATOMIC_LOAD_MAX:
12344 case ISD::ATOMIC_LOAD_MIN:
12345 case ISD::ATOMIC_LOAD_UMAX:
12346 case ISD::ATOMIC_LOAD_UMIN:
12347 case ISD::ATOMIC_SWAP: {
12349 switch (N->getOpcode()) {
12350 default: llvm_unreachable("Unexpected opcode");
12351 case ISD::ATOMIC_LOAD_ADD:
12352 Opc = X86ISD::ATOMADD64_DAG;
12354 case ISD::ATOMIC_LOAD_AND:
12355 Opc = X86ISD::ATOMAND64_DAG;
12357 case ISD::ATOMIC_LOAD_NAND:
12358 Opc = X86ISD::ATOMNAND64_DAG;
12360 case ISD::ATOMIC_LOAD_OR:
12361 Opc = X86ISD::ATOMOR64_DAG;
12363 case ISD::ATOMIC_LOAD_SUB:
12364 Opc = X86ISD::ATOMSUB64_DAG;
12366 case ISD::ATOMIC_LOAD_XOR:
12367 Opc = X86ISD::ATOMXOR64_DAG;
12369 case ISD::ATOMIC_LOAD_MAX:
12370 Opc = X86ISD::ATOMMAX64_DAG;
12372 case ISD::ATOMIC_LOAD_MIN:
12373 Opc = X86ISD::ATOMMIN64_DAG;
12375 case ISD::ATOMIC_LOAD_UMAX:
12376 Opc = X86ISD::ATOMUMAX64_DAG;
12378 case ISD::ATOMIC_LOAD_UMIN:
12379 Opc = X86ISD::ATOMUMIN64_DAG;
12381 case ISD::ATOMIC_SWAP:
12382 Opc = X86ISD::ATOMSWAP64_DAG;
12385 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12388 case ISD::ATOMIC_LOAD:
12389 ReplaceATOMIC_LOAD(N, Results, DAG);
12393 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12395 default: return NULL;
12396 case X86ISD::BSF: return "X86ISD::BSF";
12397 case X86ISD::BSR: return "X86ISD::BSR";
12398 case X86ISD::SHLD: return "X86ISD::SHLD";
12399 case X86ISD::SHRD: return "X86ISD::SHRD";
12400 case X86ISD::FAND: return "X86ISD::FAND";
12401 case X86ISD::FOR: return "X86ISD::FOR";
12402 case X86ISD::FXOR: return "X86ISD::FXOR";
12403 case X86ISD::FSRL: return "X86ISD::FSRL";
12404 case X86ISD::FILD: return "X86ISD::FILD";
12405 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12406 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12407 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12408 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12409 case X86ISD::FLD: return "X86ISD::FLD";
12410 case X86ISD::FST: return "X86ISD::FST";
12411 case X86ISD::CALL: return "X86ISD::CALL";
12412 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12413 case X86ISD::BT: return "X86ISD::BT";
12414 case X86ISD::CMP: return "X86ISD::CMP";
12415 case X86ISD::COMI: return "X86ISD::COMI";
12416 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12417 case X86ISD::SETCC: return "X86ISD::SETCC";
12418 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12419 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12420 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12421 case X86ISD::CMOV: return "X86ISD::CMOV";
12422 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12423 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12424 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12425 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12426 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12427 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12428 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12429 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12430 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12431 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12432 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12433 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12434 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12435 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12436 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12437 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12438 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12439 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12440 case X86ISD::HADD: return "X86ISD::HADD";
12441 case X86ISD::HSUB: return "X86ISD::HSUB";
12442 case X86ISD::FHADD: return "X86ISD::FHADD";
12443 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12444 case X86ISD::UMAX: return "X86ISD::UMAX";
12445 case X86ISD::UMIN: return "X86ISD::UMIN";
12446 case X86ISD::SMAX: return "X86ISD::SMAX";
12447 case X86ISD::SMIN: return "X86ISD::SMIN";
12448 case X86ISD::FMAX: return "X86ISD::FMAX";
12449 case X86ISD::FMIN: return "X86ISD::FMIN";
12450 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12451 case X86ISD::FMINC: return "X86ISD::FMINC";
12452 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12453 case X86ISD::FRCP: return "X86ISD::FRCP";
12454 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12455 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12456 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12457 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12458 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12459 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12460 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12461 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12462 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12463 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12464 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12465 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12466 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12467 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12468 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12469 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12470 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12471 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12472 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12473 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12474 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12475 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12476 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12477 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12478 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12479 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12480 case X86ISD::VSHL: return "X86ISD::VSHL";
12481 case X86ISD::VSRL: return "X86ISD::VSRL";
12482 case X86ISD::VSRA: return "X86ISD::VSRA";
12483 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12484 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12485 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12486 case X86ISD::CMPP: return "X86ISD::CMPP";
12487 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12488 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12489 case X86ISD::ADD: return "X86ISD::ADD";
12490 case X86ISD::SUB: return "X86ISD::SUB";
12491 case X86ISD::ADC: return "X86ISD::ADC";
12492 case X86ISD::SBB: return "X86ISD::SBB";
12493 case X86ISD::SMUL: return "X86ISD::SMUL";
12494 case X86ISD::UMUL: return "X86ISD::UMUL";
12495 case X86ISD::INC: return "X86ISD::INC";
12496 case X86ISD::DEC: return "X86ISD::DEC";
12497 case X86ISD::OR: return "X86ISD::OR";
12498 case X86ISD::XOR: return "X86ISD::XOR";
12499 case X86ISD::AND: return "X86ISD::AND";
12500 case X86ISD::BLSI: return "X86ISD::BLSI";
12501 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12502 case X86ISD::BLSR: return "X86ISD::BLSR";
12503 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12504 case X86ISD::PTEST: return "X86ISD::PTEST";
12505 case X86ISD::TESTP: return "X86ISD::TESTP";
12506 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
12507 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12508 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12509 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12510 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12511 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12512 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12513 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12514 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12515 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12516 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12517 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12518 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12519 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12520 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12521 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12522 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12523 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12524 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12525 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12526 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12527 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12528 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12529 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12530 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12531 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12532 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12533 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12534 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12535 case X86ISD::SAHF: return "X86ISD::SAHF";
12536 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12537 case X86ISD::FMADD: return "X86ISD::FMADD";
12538 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12539 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12540 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12541 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12542 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12543 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12544 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12548 // isLegalAddressingMode - Return true if the addressing mode represented
12549 // by AM is legal for this target, for a load/store of the specified type.
12550 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12552 // X86 supports extremely general addressing modes.
12553 CodeModel::Model M = getTargetMachine().getCodeModel();
12554 Reloc::Model R = getTargetMachine().getRelocationModel();
12556 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12557 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12562 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12564 // If a reference to this global requires an extra load, we can't fold it.
12565 if (isGlobalStubReference(GVFlags))
12568 // If BaseGV requires a register for the PIC base, we cannot also have a
12569 // BaseReg specified.
12570 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12573 // If lower 4G is not available, then we must use rip-relative addressing.
12574 if ((M != CodeModel::Small || R != Reloc::Static) &&
12575 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12579 switch (AM.Scale) {
12585 // These scales always work.
12590 // These scales are formed with basereg+scalereg. Only accept if there is
12595 default: // Other stuff never works.
12602 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12603 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12605 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12606 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12607 return NumBits1 > NumBits2;
12610 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12611 return isInt<32>(Imm);
12614 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12615 // Can also use sub to handle negated immediates.
12616 return isInt<32>(Imm);
12619 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12620 if (!VT1.isInteger() || !VT2.isInteger())
12622 unsigned NumBits1 = VT1.getSizeInBits();
12623 unsigned NumBits2 = VT2.getSizeInBits();
12624 return NumBits1 > NumBits2;
12627 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12628 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12629 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12632 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12633 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12634 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12637 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12638 EVT VT1 = Val.getValueType();
12639 if (isZExtFree(VT1, VT2))
12642 if (Val.getOpcode() != ISD::LOAD)
12645 if (!VT1.isSimple() || !VT1.isInteger() ||
12646 !VT2.isSimple() || !VT2.isInteger())
12649 switch (VT1.getSimpleVT().SimpleTy) {
12654 // X86 has 8, 16, and 32-bit zero-extending loads.
12661 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12662 // i16 instructions are longer (0x66 prefix) and potentially slower.
12663 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12666 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12667 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12668 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12669 /// are assumed to be legal.
12671 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12673 // Very little shuffling can be done for 64-bit vectors right now.
12674 if (VT.getSizeInBits() == 64)
12677 // FIXME: pshufb, blends, shifts.
12678 return (VT.getVectorNumElements() == 2 ||
12679 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12680 isMOVLMask(M, VT) ||
12681 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12682 isPSHUFDMask(M, VT) ||
12683 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12684 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12685 isPALIGNRMask(M, VT, Subtarget) ||
12686 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12687 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12688 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12689 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12693 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12695 unsigned NumElts = VT.getVectorNumElements();
12696 // FIXME: This collection of masks seems suspect.
12699 if (NumElts == 4 && VT.is128BitVector()) {
12700 return (isMOVLMask(Mask, VT) ||
12701 isCommutedMOVLMask(Mask, VT, true) ||
12702 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12703 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12708 //===----------------------------------------------------------------------===//
12709 // X86 Scheduler Hooks
12710 //===----------------------------------------------------------------------===//
12712 /// Utility function to emit xbegin specifying the start of an RTM region.
12713 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12714 const TargetInstrInfo *TII) {
12715 DebugLoc DL = MI->getDebugLoc();
12717 const BasicBlock *BB = MBB->getBasicBlock();
12718 MachineFunction::iterator I = MBB;
12721 // For the v = xbegin(), we generate
12732 MachineBasicBlock *thisMBB = MBB;
12733 MachineFunction *MF = MBB->getParent();
12734 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12735 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12736 MF->insert(I, mainMBB);
12737 MF->insert(I, sinkMBB);
12739 // Transfer the remainder of BB and its successor edges to sinkMBB.
12740 sinkMBB->splice(sinkMBB->begin(), MBB,
12741 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12742 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12746 // # fallthrough to mainMBB
12747 // # abortion to sinkMBB
12748 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12749 thisMBB->addSuccessor(mainMBB);
12750 thisMBB->addSuccessor(sinkMBB);
12754 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12755 mainMBB->addSuccessor(sinkMBB);
12758 // EAX is live into the sinkMBB
12759 sinkMBB->addLiveIn(X86::EAX);
12760 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12761 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12764 MI->eraseFromParent();
12768 // Get CMPXCHG opcode for the specified data type.
12769 static unsigned getCmpXChgOpcode(EVT VT) {
12770 switch (VT.getSimpleVT().SimpleTy) {
12771 case MVT::i8: return X86::LCMPXCHG8;
12772 case MVT::i16: return X86::LCMPXCHG16;
12773 case MVT::i32: return X86::LCMPXCHG32;
12774 case MVT::i64: return X86::LCMPXCHG64;
12778 llvm_unreachable("Invalid operand size!");
12781 // Get LOAD opcode for the specified data type.
12782 static unsigned getLoadOpcode(EVT VT) {
12783 switch (VT.getSimpleVT().SimpleTy) {
12784 case MVT::i8: return X86::MOV8rm;
12785 case MVT::i16: return X86::MOV16rm;
12786 case MVT::i32: return X86::MOV32rm;
12787 case MVT::i64: return X86::MOV64rm;
12791 llvm_unreachable("Invalid operand size!");
12794 // Get opcode of the non-atomic one from the specified atomic instruction.
12795 static unsigned getNonAtomicOpcode(unsigned Opc) {
12797 case X86::ATOMAND8: return X86::AND8rr;
12798 case X86::ATOMAND16: return X86::AND16rr;
12799 case X86::ATOMAND32: return X86::AND32rr;
12800 case X86::ATOMAND64: return X86::AND64rr;
12801 case X86::ATOMOR8: return X86::OR8rr;
12802 case X86::ATOMOR16: return X86::OR16rr;
12803 case X86::ATOMOR32: return X86::OR32rr;
12804 case X86::ATOMOR64: return X86::OR64rr;
12805 case X86::ATOMXOR8: return X86::XOR8rr;
12806 case X86::ATOMXOR16: return X86::XOR16rr;
12807 case X86::ATOMXOR32: return X86::XOR32rr;
12808 case X86::ATOMXOR64: return X86::XOR64rr;
12810 llvm_unreachable("Unhandled atomic-load-op opcode!");
12813 // Get opcode of the non-atomic one from the specified atomic instruction with
12815 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12816 unsigned &ExtraOpc) {
12818 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12819 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12820 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12821 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12822 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12823 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12824 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12825 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12826 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12827 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12828 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12829 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12830 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12831 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12832 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12833 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12834 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12835 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12836 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12837 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12839 llvm_unreachable("Unhandled atomic-load-op opcode!");
12842 // Get opcode of the non-atomic one from the specified atomic instruction for
12843 // 64-bit data type on 32-bit target.
12844 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12846 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12847 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12848 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12849 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12850 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12851 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12852 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12853 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12854 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12855 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12857 llvm_unreachable("Unhandled atomic-load-op opcode!");
12860 // Get opcode of the non-atomic one from the specified atomic instruction for
12861 // 64-bit data type on 32-bit target with extra opcode.
12862 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12864 unsigned &ExtraOpc) {
12866 case X86::ATOMNAND6432:
12867 ExtraOpc = X86::NOT32r;
12868 HiOpc = X86::AND32rr;
12869 return X86::AND32rr;
12871 llvm_unreachable("Unhandled atomic-load-op opcode!");
12874 // Get pseudo CMOV opcode from the specified data type.
12875 static unsigned getPseudoCMOVOpc(EVT VT) {
12876 switch (VT.getSimpleVT().SimpleTy) {
12877 case MVT::i8: return X86::CMOV_GR8;
12878 case MVT::i16: return X86::CMOV_GR16;
12879 case MVT::i32: return X86::CMOV_GR32;
12883 llvm_unreachable("Unknown CMOV opcode!");
12886 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12887 // They will be translated into a spin-loop or compare-exchange loop from
12890 // dst = atomic-fetch-op MI.addr, MI.val
12896 // EAX = LOAD MI.addr
12898 // t1 = OP MI.val, EAX
12899 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12904 MachineBasicBlock *
12905 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12906 MachineBasicBlock *MBB) const {
12907 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12908 DebugLoc DL = MI->getDebugLoc();
12910 MachineFunction *MF = MBB->getParent();
12911 MachineRegisterInfo &MRI = MF->getRegInfo();
12913 const BasicBlock *BB = MBB->getBasicBlock();
12914 MachineFunction::iterator I = MBB;
12917 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12918 "Unexpected number of operands");
12920 assert(MI->hasOneMemOperand() &&
12921 "Expected atomic-load-op to have one memoperand");
12923 // Memory Reference
12924 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12925 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12927 unsigned DstReg, SrcReg;
12928 unsigned MemOpndSlot;
12930 unsigned CurOp = 0;
12932 DstReg = MI->getOperand(CurOp++).getReg();
12933 MemOpndSlot = CurOp;
12934 CurOp += X86::AddrNumOperands;
12935 SrcReg = MI->getOperand(CurOp++).getReg();
12937 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12938 MVT::SimpleValueType VT = *RC->vt_begin();
12939 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12941 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12942 unsigned LOADOpc = getLoadOpcode(VT);
12944 // For the atomic load-arith operator, we generate
12947 // EAX = LOAD [MI.addr]
12949 // t1 = OP MI.val, EAX
12950 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12954 MachineBasicBlock *thisMBB = MBB;
12955 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12956 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12957 MF->insert(I, mainMBB);
12958 MF->insert(I, sinkMBB);
12960 MachineInstrBuilder MIB;
12962 // Transfer the remainder of BB and its successor edges to sinkMBB.
12963 sinkMBB->splice(sinkMBB->begin(), MBB,
12964 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12965 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12968 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12969 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12970 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12971 MIB.setMemRefs(MMOBegin, MMOEnd);
12973 thisMBB->addSuccessor(mainMBB);
12976 MachineBasicBlock *origMainMBB = mainMBB;
12977 mainMBB->addLiveIn(AccPhyReg);
12979 // Copy AccPhyReg as it is used more than once.
12980 unsigned AccReg = MRI.createVirtualRegister(RC);
12981 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12982 .addReg(AccPhyReg);
12984 unsigned t1 = MRI.createVirtualRegister(RC);
12985 unsigned Opc = MI->getOpcode();
12988 llvm_unreachable("Unhandled atomic-load-op opcode!");
12989 case X86::ATOMAND8:
12990 case X86::ATOMAND16:
12991 case X86::ATOMAND32:
12992 case X86::ATOMAND64:
12994 case X86::ATOMOR16:
12995 case X86::ATOMOR32:
12996 case X86::ATOMOR64:
12997 case X86::ATOMXOR8:
12998 case X86::ATOMXOR16:
12999 case X86::ATOMXOR32:
13000 case X86::ATOMXOR64: {
13001 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13002 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
13006 case X86::ATOMNAND8:
13007 case X86::ATOMNAND16:
13008 case X86::ATOMNAND32:
13009 case X86::ATOMNAND64: {
13010 unsigned t2 = MRI.createVirtualRegister(RC);
13012 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13013 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
13015 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
13018 case X86::ATOMMAX8:
13019 case X86::ATOMMAX16:
13020 case X86::ATOMMAX32:
13021 case X86::ATOMMAX64:
13022 case X86::ATOMMIN8:
13023 case X86::ATOMMIN16:
13024 case X86::ATOMMIN32:
13025 case X86::ATOMMIN64:
13026 case X86::ATOMUMAX8:
13027 case X86::ATOMUMAX16:
13028 case X86::ATOMUMAX32:
13029 case X86::ATOMUMAX64:
13030 case X86::ATOMUMIN8:
13031 case X86::ATOMUMIN16:
13032 case X86::ATOMUMIN32:
13033 case X86::ATOMUMIN64: {
13035 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13037 BuildMI(mainMBB, DL, TII->get(CMPOpc))
13041 if (Subtarget->hasCMov()) {
13042 if (VT != MVT::i8) {
13044 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
13048 // Promote i8 to i32 to use CMOV32
13049 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
13050 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13051 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13052 unsigned t2 = MRI.createVirtualRegister(RC32);
13054 unsigned Undef = MRI.createVirtualRegister(RC32);
13055 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13057 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13060 .addImm(X86::sub_8bit);
13061 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13064 .addImm(X86::sub_8bit);
13066 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13070 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
13071 .addReg(t2, 0, X86::sub_8bit);
13074 // Use pseudo select and lower them.
13075 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13076 "Invalid atomic-load-op transformation!");
13077 unsigned SelOpc = getPseudoCMOVOpc(VT);
13078 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13079 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13080 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13081 .addReg(SrcReg).addReg(AccReg)
13083 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13089 // Copy AccPhyReg back from virtual register.
13090 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13093 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13094 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13095 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13097 MIB.setMemRefs(MMOBegin, MMOEnd);
13099 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13101 mainMBB->addSuccessor(origMainMBB);
13102 mainMBB->addSuccessor(sinkMBB);
13105 sinkMBB->addLiveIn(AccPhyReg);
13107 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13108 TII->get(TargetOpcode::COPY), DstReg)
13109 .addReg(AccPhyReg);
13111 MI->eraseFromParent();
13115 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13116 // instructions. They will be translated into a spin-loop or compare-exchange
13120 // dst = atomic-fetch-op MI.addr, MI.val
13126 // EAX = LOAD [MI.addr + 0]
13127 // EDX = LOAD [MI.addr + 4]
13129 // EBX = OP MI.val.lo, EAX
13130 // ECX = OP MI.val.hi, EDX
13131 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13136 MachineBasicBlock *
13137 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13138 MachineBasicBlock *MBB) const {
13139 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13140 DebugLoc DL = MI->getDebugLoc();
13142 MachineFunction *MF = MBB->getParent();
13143 MachineRegisterInfo &MRI = MF->getRegInfo();
13145 const BasicBlock *BB = MBB->getBasicBlock();
13146 MachineFunction::iterator I = MBB;
13149 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13150 "Unexpected number of operands");
13152 assert(MI->hasOneMemOperand() &&
13153 "Expected atomic-load-op32 to have one memoperand");
13155 // Memory Reference
13156 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13157 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13159 unsigned DstLoReg, DstHiReg;
13160 unsigned SrcLoReg, SrcHiReg;
13161 unsigned MemOpndSlot;
13163 unsigned CurOp = 0;
13165 DstLoReg = MI->getOperand(CurOp++).getReg();
13166 DstHiReg = MI->getOperand(CurOp++).getReg();
13167 MemOpndSlot = CurOp;
13168 CurOp += X86::AddrNumOperands;
13169 SrcLoReg = MI->getOperand(CurOp++).getReg();
13170 SrcHiReg = MI->getOperand(CurOp++).getReg();
13172 const TargetRegisterClass *RC = &X86::GR32RegClass;
13173 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13175 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13176 unsigned LOADOpc = X86::MOV32rm;
13178 // For the atomic load-arith operator, we generate
13181 // EAX = LOAD [MI.addr + 0]
13182 // EDX = LOAD [MI.addr + 4]
13184 // EBX = OP MI.vallo, EAX
13185 // ECX = OP MI.valhi, EDX
13186 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13190 MachineBasicBlock *thisMBB = MBB;
13191 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13192 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13193 MF->insert(I, mainMBB);
13194 MF->insert(I, sinkMBB);
13196 MachineInstrBuilder MIB;
13198 // Transfer the remainder of BB and its successor edges to sinkMBB.
13199 sinkMBB->splice(sinkMBB->begin(), MBB,
13200 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13201 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13205 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13206 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13207 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13208 MIB.setMemRefs(MMOBegin, MMOEnd);
13210 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13211 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13212 if (i == X86::AddrDisp)
13213 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13215 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13217 MIB.setMemRefs(MMOBegin, MMOEnd);
13219 thisMBB->addSuccessor(mainMBB);
13222 MachineBasicBlock *origMainMBB = mainMBB;
13223 mainMBB->addLiveIn(X86::EAX);
13224 mainMBB->addLiveIn(X86::EDX);
13226 // Copy EDX:EAX as they are used more than once.
13227 unsigned LoReg = MRI.createVirtualRegister(RC);
13228 unsigned HiReg = MRI.createVirtualRegister(RC);
13229 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13230 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13232 unsigned t1L = MRI.createVirtualRegister(RC);
13233 unsigned t1H = MRI.createVirtualRegister(RC);
13235 unsigned Opc = MI->getOpcode();
13238 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13239 case X86::ATOMAND6432:
13240 case X86::ATOMOR6432:
13241 case X86::ATOMXOR6432:
13242 case X86::ATOMADD6432:
13243 case X86::ATOMSUB6432: {
13245 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13246 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13247 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13250 case X86::ATOMNAND6432: {
13251 unsigned HiOpc, NOTOpc;
13252 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13253 unsigned t2L = MRI.createVirtualRegister(RC);
13254 unsigned t2H = MRI.createVirtualRegister(RC);
13255 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13256 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13257 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13258 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13261 case X86::ATOMMAX6432:
13262 case X86::ATOMMIN6432:
13263 case X86::ATOMUMAX6432:
13264 case X86::ATOMUMIN6432: {
13266 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13267 unsigned cL = MRI.createVirtualRegister(RC8);
13268 unsigned cH = MRI.createVirtualRegister(RC8);
13269 unsigned cL32 = MRI.createVirtualRegister(RC);
13270 unsigned cH32 = MRI.createVirtualRegister(RC);
13271 unsigned cc = MRI.createVirtualRegister(RC);
13272 // cl := cmp src_lo, lo
13273 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13274 .addReg(SrcLoReg).addReg(LoReg);
13275 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13276 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13277 // ch := cmp src_hi, hi
13278 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13279 .addReg(SrcHiReg).addReg(HiReg);
13280 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13281 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13282 // cc := if (src_hi == hi) ? cl : ch;
13283 if (Subtarget->hasCMov()) {
13284 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13285 .addReg(cH32).addReg(cL32);
13287 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13288 .addReg(cH32).addReg(cL32)
13289 .addImm(X86::COND_E);
13290 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13292 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13293 if (Subtarget->hasCMov()) {
13294 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13295 .addReg(SrcLoReg).addReg(LoReg);
13296 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13297 .addReg(SrcHiReg).addReg(HiReg);
13299 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13300 .addReg(SrcLoReg).addReg(LoReg)
13301 .addImm(X86::COND_NE);
13302 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13303 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13304 .addReg(SrcHiReg).addReg(HiReg)
13305 .addImm(X86::COND_NE);
13306 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13310 case X86::ATOMSWAP6432: {
13312 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13313 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13314 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13319 // Copy EDX:EAX back from HiReg:LoReg
13320 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13321 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13322 // Copy ECX:EBX from t1H:t1L
13323 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13324 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13326 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13327 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13328 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13329 MIB.setMemRefs(MMOBegin, MMOEnd);
13331 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13333 mainMBB->addSuccessor(origMainMBB);
13334 mainMBB->addSuccessor(sinkMBB);
13337 sinkMBB->addLiveIn(X86::EAX);
13338 sinkMBB->addLiveIn(X86::EDX);
13340 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13341 TII->get(TargetOpcode::COPY), DstLoReg)
13343 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13344 TII->get(TargetOpcode::COPY), DstHiReg)
13347 MI->eraseFromParent();
13351 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13352 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13353 // in the .td file.
13354 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13355 const TargetInstrInfo *TII) {
13357 switch (MI->getOpcode()) {
13358 default: llvm_unreachable("illegal opcode!");
13359 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13360 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13361 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13362 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13363 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13364 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13365 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13366 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13369 DebugLoc dl = MI->getDebugLoc();
13370 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13372 unsigned NumArgs = MI->getNumOperands();
13373 for (unsigned i = 1; i < NumArgs; ++i) {
13374 MachineOperand &Op = MI->getOperand(i);
13375 if (!(Op.isReg() && Op.isImplicit()))
13376 MIB.addOperand(Op);
13378 if (MI->hasOneMemOperand())
13379 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13381 BuildMI(*BB, MI, dl,
13382 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13383 .addReg(X86::XMM0);
13385 MI->eraseFromParent();
13389 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13390 // defs in an instruction pattern
13391 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13392 const TargetInstrInfo *TII) {
13394 switch (MI->getOpcode()) {
13395 default: llvm_unreachable("illegal opcode!");
13396 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13397 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13398 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13399 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13400 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13401 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13402 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13403 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13406 DebugLoc dl = MI->getDebugLoc();
13407 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13409 unsigned NumArgs = MI->getNumOperands(); // remove the results
13410 for (unsigned i = 1; i < NumArgs; ++i) {
13411 MachineOperand &Op = MI->getOperand(i);
13412 if (!(Op.isReg() && Op.isImplicit()))
13413 MIB.addOperand(Op);
13415 if (MI->hasOneMemOperand())
13416 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13418 BuildMI(*BB, MI, dl,
13419 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13422 MI->eraseFromParent();
13426 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13427 const TargetInstrInfo *TII,
13428 const X86Subtarget* Subtarget) {
13429 DebugLoc dl = MI->getDebugLoc();
13431 // Address into RAX/EAX, other two args into ECX, EDX.
13432 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13433 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13434 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13435 for (int i = 0; i < X86::AddrNumOperands; ++i)
13436 MIB.addOperand(MI->getOperand(i));
13438 unsigned ValOps = X86::AddrNumOperands;
13439 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13440 .addReg(MI->getOperand(ValOps).getReg());
13441 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13442 .addReg(MI->getOperand(ValOps+1).getReg());
13444 // The instruction doesn't actually take any operands though.
13445 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13447 MI->eraseFromParent(); // The pseudo is gone now.
13451 MachineBasicBlock *
13452 X86TargetLowering::EmitVAARG64WithCustomInserter(
13454 MachineBasicBlock *MBB) const {
13455 // Emit va_arg instruction on X86-64.
13457 // Operands to this pseudo-instruction:
13458 // 0 ) Output : destination address (reg)
13459 // 1-5) Input : va_list address (addr, i64mem)
13460 // 6 ) ArgSize : Size (in bytes) of vararg type
13461 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13462 // 8 ) Align : Alignment of type
13463 // 9 ) EFLAGS (implicit-def)
13465 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13466 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13468 unsigned DestReg = MI->getOperand(0).getReg();
13469 MachineOperand &Base = MI->getOperand(1);
13470 MachineOperand &Scale = MI->getOperand(2);
13471 MachineOperand &Index = MI->getOperand(3);
13472 MachineOperand &Disp = MI->getOperand(4);
13473 MachineOperand &Segment = MI->getOperand(5);
13474 unsigned ArgSize = MI->getOperand(6).getImm();
13475 unsigned ArgMode = MI->getOperand(7).getImm();
13476 unsigned Align = MI->getOperand(8).getImm();
13478 // Memory Reference
13479 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13480 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13481 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13483 // Machine Information
13484 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13485 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13486 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13487 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13488 DebugLoc DL = MI->getDebugLoc();
13490 // struct va_list {
13493 // i64 overflow_area (address)
13494 // i64 reg_save_area (address)
13496 // sizeof(va_list) = 24
13497 // alignment(va_list) = 8
13499 unsigned TotalNumIntRegs = 6;
13500 unsigned TotalNumXMMRegs = 8;
13501 bool UseGPOffset = (ArgMode == 1);
13502 bool UseFPOffset = (ArgMode == 2);
13503 unsigned MaxOffset = TotalNumIntRegs * 8 +
13504 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13506 /* Align ArgSize to a multiple of 8 */
13507 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13508 bool NeedsAlign = (Align > 8);
13510 MachineBasicBlock *thisMBB = MBB;
13511 MachineBasicBlock *overflowMBB;
13512 MachineBasicBlock *offsetMBB;
13513 MachineBasicBlock *endMBB;
13515 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13516 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13517 unsigned OffsetReg = 0;
13519 if (!UseGPOffset && !UseFPOffset) {
13520 // If we only pull from the overflow region, we don't create a branch.
13521 // We don't need to alter control flow.
13522 OffsetDestReg = 0; // unused
13523 OverflowDestReg = DestReg;
13526 overflowMBB = thisMBB;
13529 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13530 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13531 // If not, pull from overflow_area. (branch to overflowMBB)
13536 // offsetMBB overflowMBB
13541 // Registers for the PHI in endMBB
13542 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13543 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13545 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13546 MachineFunction *MF = MBB->getParent();
13547 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13548 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13549 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13551 MachineFunction::iterator MBBIter = MBB;
13554 // Insert the new basic blocks
13555 MF->insert(MBBIter, offsetMBB);
13556 MF->insert(MBBIter, overflowMBB);
13557 MF->insert(MBBIter, endMBB);
13559 // Transfer the remainder of MBB and its successor edges to endMBB.
13560 endMBB->splice(endMBB->begin(), thisMBB,
13561 llvm::next(MachineBasicBlock::iterator(MI)),
13563 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13565 // Make offsetMBB and overflowMBB successors of thisMBB
13566 thisMBB->addSuccessor(offsetMBB);
13567 thisMBB->addSuccessor(overflowMBB);
13569 // endMBB is a successor of both offsetMBB and overflowMBB
13570 offsetMBB->addSuccessor(endMBB);
13571 overflowMBB->addSuccessor(endMBB);
13573 // Load the offset value into a register
13574 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13575 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13579 .addDisp(Disp, UseFPOffset ? 4 : 0)
13580 .addOperand(Segment)
13581 .setMemRefs(MMOBegin, MMOEnd);
13583 // Check if there is enough room left to pull this argument.
13584 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13586 .addImm(MaxOffset + 8 - ArgSizeA8);
13588 // Branch to "overflowMBB" if offset >= max
13589 // Fall through to "offsetMBB" otherwise
13590 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13591 .addMBB(overflowMBB);
13594 // In offsetMBB, emit code to use the reg_save_area.
13596 assert(OffsetReg != 0);
13598 // Read the reg_save_area address.
13599 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13600 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13605 .addOperand(Segment)
13606 .setMemRefs(MMOBegin, MMOEnd);
13608 // Zero-extend the offset
13609 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13610 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13613 .addImm(X86::sub_32bit);
13615 // Add the offset to the reg_save_area to get the final address.
13616 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13617 .addReg(OffsetReg64)
13618 .addReg(RegSaveReg);
13620 // Compute the offset for the next argument
13621 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13622 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13624 .addImm(UseFPOffset ? 16 : 8);
13626 // Store it back into the va_list.
13627 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13631 .addDisp(Disp, UseFPOffset ? 4 : 0)
13632 .addOperand(Segment)
13633 .addReg(NextOffsetReg)
13634 .setMemRefs(MMOBegin, MMOEnd);
13637 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13642 // Emit code to use overflow area
13645 // Load the overflow_area address into a register.
13646 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13647 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13652 .addOperand(Segment)
13653 .setMemRefs(MMOBegin, MMOEnd);
13655 // If we need to align it, do so. Otherwise, just copy the address
13656 // to OverflowDestReg.
13658 // Align the overflow address
13659 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13660 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13662 // aligned_addr = (addr + (align-1)) & ~(align-1)
13663 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13664 .addReg(OverflowAddrReg)
13667 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13669 .addImm(~(uint64_t)(Align-1));
13671 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13672 .addReg(OverflowAddrReg);
13675 // Compute the next overflow address after this argument.
13676 // (the overflow address should be kept 8-byte aligned)
13677 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13678 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13679 .addReg(OverflowDestReg)
13680 .addImm(ArgSizeA8);
13682 // Store the new overflow address.
13683 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13688 .addOperand(Segment)
13689 .addReg(NextAddrReg)
13690 .setMemRefs(MMOBegin, MMOEnd);
13692 // If we branched, emit the PHI to the front of endMBB.
13694 BuildMI(*endMBB, endMBB->begin(), DL,
13695 TII->get(X86::PHI), DestReg)
13696 .addReg(OffsetDestReg).addMBB(offsetMBB)
13697 .addReg(OverflowDestReg).addMBB(overflowMBB);
13700 // Erase the pseudo instruction
13701 MI->eraseFromParent();
13706 MachineBasicBlock *
13707 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13709 MachineBasicBlock *MBB) const {
13710 // Emit code to save XMM registers to the stack. The ABI says that the
13711 // number of registers to save is given in %al, so it's theoretically
13712 // possible to do an indirect jump trick to avoid saving all of them,
13713 // however this code takes a simpler approach and just executes all
13714 // of the stores if %al is non-zero. It's less code, and it's probably
13715 // easier on the hardware branch predictor, and stores aren't all that
13716 // expensive anyway.
13718 // Create the new basic blocks. One block contains all the XMM stores,
13719 // and one block is the final destination regardless of whether any
13720 // stores were performed.
13721 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13722 MachineFunction *F = MBB->getParent();
13723 MachineFunction::iterator MBBIter = MBB;
13725 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13726 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13727 F->insert(MBBIter, XMMSaveMBB);
13728 F->insert(MBBIter, EndMBB);
13730 // Transfer the remainder of MBB and its successor edges to EndMBB.
13731 EndMBB->splice(EndMBB->begin(), MBB,
13732 llvm::next(MachineBasicBlock::iterator(MI)),
13734 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13736 // The original block will now fall through to the XMM save block.
13737 MBB->addSuccessor(XMMSaveMBB);
13738 // The XMMSaveMBB will fall through to the end block.
13739 XMMSaveMBB->addSuccessor(EndMBB);
13741 // Now add the instructions.
13742 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13743 DebugLoc DL = MI->getDebugLoc();
13745 unsigned CountReg = MI->getOperand(0).getReg();
13746 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13747 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13749 if (!Subtarget->isTargetWin64()) {
13750 // If %al is 0, branch around the XMM save block.
13751 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13752 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13753 MBB->addSuccessor(EndMBB);
13756 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13757 // In the XMM save block, save all the XMM argument registers.
13758 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13759 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13760 MachineMemOperand *MMO =
13761 F->getMachineMemOperand(
13762 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13763 MachineMemOperand::MOStore,
13764 /*Size=*/16, /*Align=*/16);
13765 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13766 .addFrameIndex(RegSaveFrameIndex)
13767 .addImm(/*Scale=*/1)
13768 .addReg(/*IndexReg=*/0)
13769 .addImm(/*Disp=*/Offset)
13770 .addReg(/*Segment=*/0)
13771 .addReg(MI->getOperand(i).getReg())
13772 .addMemOperand(MMO);
13775 MI->eraseFromParent(); // The pseudo instruction is gone now.
13780 // The EFLAGS operand of SelectItr might be missing a kill marker
13781 // because there were multiple uses of EFLAGS, and ISel didn't know
13782 // which to mark. Figure out whether SelectItr should have had a
13783 // kill marker, and set it if it should. Returns the correct kill
13785 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13786 MachineBasicBlock* BB,
13787 const TargetRegisterInfo* TRI) {
13788 // Scan forward through BB for a use/def of EFLAGS.
13789 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13790 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13791 const MachineInstr& mi = *miI;
13792 if (mi.readsRegister(X86::EFLAGS))
13794 if (mi.definesRegister(X86::EFLAGS))
13795 break; // Should have kill-flag - update below.
13798 // If we hit the end of the block, check whether EFLAGS is live into a
13800 if (miI == BB->end()) {
13801 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13802 sEnd = BB->succ_end();
13803 sItr != sEnd; ++sItr) {
13804 MachineBasicBlock* succ = *sItr;
13805 if (succ->isLiveIn(X86::EFLAGS))
13810 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13811 // out. SelectMI should have a kill flag on EFLAGS.
13812 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13816 MachineBasicBlock *
13817 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13818 MachineBasicBlock *BB) const {
13819 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13820 DebugLoc DL = MI->getDebugLoc();
13822 // To "insert" a SELECT_CC instruction, we actually have to insert the
13823 // diamond control-flow pattern. The incoming instruction knows the
13824 // destination vreg to set, the condition code register to branch on, the
13825 // true/false values to select between, and a branch opcode to use.
13826 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13827 MachineFunction::iterator It = BB;
13833 // cmpTY ccX, r1, r2
13835 // fallthrough --> copy0MBB
13836 MachineBasicBlock *thisMBB = BB;
13837 MachineFunction *F = BB->getParent();
13838 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13839 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13840 F->insert(It, copy0MBB);
13841 F->insert(It, sinkMBB);
13843 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13844 // live into the sink and copy blocks.
13845 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13846 if (!MI->killsRegister(X86::EFLAGS) &&
13847 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13848 copy0MBB->addLiveIn(X86::EFLAGS);
13849 sinkMBB->addLiveIn(X86::EFLAGS);
13852 // Transfer the remainder of BB and its successor edges to sinkMBB.
13853 sinkMBB->splice(sinkMBB->begin(), BB,
13854 llvm::next(MachineBasicBlock::iterator(MI)),
13856 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13858 // Add the true and fallthrough blocks as its successors.
13859 BB->addSuccessor(copy0MBB);
13860 BB->addSuccessor(sinkMBB);
13862 // Create the conditional branch instruction.
13864 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13865 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13868 // %FalseValue = ...
13869 // # fallthrough to sinkMBB
13870 copy0MBB->addSuccessor(sinkMBB);
13873 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13875 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13876 TII->get(X86::PHI), MI->getOperand(0).getReg())
13877 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13878 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13880 MI->eraseFromParent(); // The pseudo instruction is gone now.
13884 MachineBasicBlock *
13885 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13886 bool Is64Bit) const {
13887 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13888 DebugLoc DL = MI->getDebugLoc();
13889 MachineFunction *MF = BB->getParent();
13890 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13892 assert(getTargetMachine().Options.EnableSegmentedStacks);
13894 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13895 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13898 // ... [Till the alloca]
13899 // If stacklet is not large enough, jump to mallocMBB
13902 // Allocate by subtracting from RSP
13903 // Jump to continueMBB
13906 // Allocate by call to runtime
13910 // [rest of original BB]
13913 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13914 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13915 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13917 MachineRegisterInfo &MRI = MF->getRegInfo();
13918 const TargetRegisterClass *AddrRegClass =
13919 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13921 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13922 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13923 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13924 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13925 sizeVReg = MI->getOperand(1).getReg(),
13926 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13928 MachineFunction::iterator MBBIter = BB;
13931 MF->insert(MBBIter, bumpMBB);
13932 MF->insert(MBBIter, mallocMBB);
13933 MF->insert(MBBIter, continueMBB);
13935 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13936 (MachineBasicBlock::iterator(MI)), BB->end());
13937 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13939 // Add code to the main basic block to check if the stack limit has been hit,
13940 // and if so, jump to mallocMBB otherwise to bumpMBB.
13941 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13942 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13943 .addReg(tmpSPVReg).addReg(sizeVReg);
13944 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13945 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13946 .addReg(SPLimitVReg);
13947 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13949 // bumpMBB simply decreases the stack pointer, since we know the current
13950 // stacklet has enough space.
13951 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13952 .addReg(SPLimitVReg);
13953 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13954 .addReg(SPLimitVReg);
13955 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13957 // Calls into a routine in libgcc to allocate more space from the heap.
13958 const uint32_t *RegMask =
13959 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13961 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13963 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13964 .addExternalSymbol("__morestack_allocate_stack_space")
13965 .addRegMask(RegMask)
13966 .addReg(X86::RDI, RegState::Implicit)
13967 .addReg(X86::RAX, RegState::ImplicitDefine);
13969 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13971 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13972 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13973 .addExternalSymbol("__morestack_allocate_stack_space")
13974 .addRegMask(RegMask)
13975 .addReg(X86::EAX, RegState::ImplicitDefine);
13979 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13982 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13983 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13984 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13986 // Set up the CFG correctly.
13987 BB->addSuccessor(bumpMBB);
13988 BB->addSuccessor(mallocMBB);
13989 mallocMBB->addSuccessor(continueMBB);
13990 bumpMBB->addSuccessor(continueMBB);
13992 // Take care of the PHI nodes.
13993 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13994 MI->getOperand(0).getReg())
13995 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13996 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13998 // Delete the original pseudo instruction.
13999 MI->eraseFromParent();
14002 return continueMBB;
14005 MachineBasicBlock *
14006 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14007 MachineBasicBlock *BB) const {
14008 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14009 DebugLoc DL = MI->getDebugLoc();
14011 assert(!Subtarget->isTargetEnvMacho());
14013 // The lowering is pretty easy: we're just emitting the call to _alloca. The
14014 // non-trivial part is impdef of ESP.
14016 if (Subtarget->isTargetWin64()) {
14017 if (Subtarget->isTargetCygMing()) {
14018 // ___chkstk(Mingw64):
14019 // Clobbers R10, R11, RAX and EFLAGS.
14021 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14022 .addExternalSymbol("___chkstk")
14023 .addReg(X86::RAX, RegState::Implicit)
14024 .addReg(X86::RSP, RegState::Implicit)
14025 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14026 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14027 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14029 // __chkstk(MSVCRT): does not update stack pointer.
14030 // Clobbers R10, R11 and EFLAGS.
14031 // FIXME: RAX(allocated size) might be reused and not killed.
14032 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14033 .addExternalSymbol("__chkstk")
14034 .addReg(X86::RAX, RegState::Implicit)
14035 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14036 // RAX has the offset to subtracted from RSP.
14037 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14042 const char *StackProbeSymbol =
14043 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14045 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14046 .addExternalSymbol(StackProbeSymbol)
14047 .addReg(X86::EAX, RegState::Implicit)
14048 .addReg(X86::ESP, RegState::Implicit)
14049 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14050 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14051 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14054 MI->eraseFromParent(); // The pseudo instruction is gone now.
14058 MachineBasicBlock *
14059 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14060 MachineBasicBlock *BB) const {
14061 // This is pretty easy. We're taking the value that we received from
14062 // our load from the relocation, sticking it in either RDI (x86-64)
14063 // or EAX and doing an indirect call. The return value will then
14064 // be in the normal return register.
14065 const X86InstrInfo *TII
14066 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14067 DebugLoc DL = MI->getDebugLoc();
14068 MachineFunction *F = BB->getParent();
14070 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14071 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14073 // Get a register mask for the lowered call.
14074 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14075 // proper register mask.
14076 const uint32_t *RegMask =
14077 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14078 if (Subtarget->is64Bit()) {
14079 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14080 TII->get(X86::MOV64rm), X86::RDI)
14082 .addImm(0).addReg(0)
14083 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14084 MI->getOperand(3).getTargetFlags())
14086 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14087 addDirectMem(MIB, X86::RDI);
14088 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14089 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14090 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14091 TII->get(X86::MOV32rm), X86::EAX)
14093 .addImm(0).addReg(0)
14094 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14095 MI->getOperand(3).getTargetFlags())
14097 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14098 addDirectMem(MIB, X86::EAX);
14099 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14101 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14102 TII->get(X86::MOV32rm), X86::EAX)
14103 .addReg(TII->getGlobalBaseReg(F))
14104 .addImm(0).addReg(0)
14105 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14106 MI->getOperand(3).getTargetFlags())
14108 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14109 addDirectMem(MIB, X86::EAX);
14110 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14113 MI->eraseFromParent(); // The pseudo instruction is gone now.
14117 MachineBasicBlock *
14118 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14119 MachineBasicBlock *MBB) const {
14120 DebugLoc DL = MI->getDebugLoc();
14121 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14123 MachineFunction *MF = MBB->getParent();
14124 MachineRegisterInfo &MRI = MF->getRegInfo();
14126 const BasicBlock *BB = MBB->getBasicBlock();
14127 MachineFunction::iterator I = MBB;
14130 // Memory Reference
14131 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14132 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14135 unsigned MemOpndSlot = 0;
14137 unsigned CurOp = 0;
14139 DstReg = MI->getOperand(CurOp++).getReg();
14140 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14141 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14142 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14143 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14145 MemOpndSlot = CurOp;
14147 MVT PVT = getPointerTy();
14148 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14149 "Invalid Pointer Size!");
14151 // For v = setjmp(buf), we generate
14154 // buf[LabelOffset] = restoreMBB
14155 // SjLjSetup restoreMBB
14161 // v = phi(main, restore)
14166 MachineBasicBlock *thisMBB = MBB;
14167 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14168 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14169 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14170 MF->insert(I, mainMBB);
14171 MF->insert(I, sinkMBB);
14172 MF->push_back(restoreMBB);
14174 MachineInstrBuilder MIB;
14176 // Transfer the remainder of BB and its successor edges to sinkMBB.
14177 sinkMBB->splice(sinkMBB->begin(), MBB,
14178 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14179 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14182 unsigned PtrStoreOpc = 0;
14183 unsigned LabelReg = 0;
14184 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14185 Reloc::Model RM = getTargetMachine().getRelocationModel();
14186 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14187 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14189 // Prepare IP either in reg or imm.
14190 if (!UseImmLabel) {
14191 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14192 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14193 LabelReg = MRI.createVirtualRegister(PtrRC);
14194 if (Subtarget->is64Bit()) {
14195 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14199 .addMBB(restoreMBB)
14202 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14203 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14204 .addReg(XII->getGlobalBaseReg(MF))
14207 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14211 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14213 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14214 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14215 if (i == X86::AddrDisp)
14216 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14218 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14221 MIB.addReg(LabelReg);
14223 MIB.addMBB(restoreMBB);
14224 MIB.setMemRefs(MMOBegin, MMOEnd);
14226 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14227 .addMBB(restoreMBB);
14228 MIB.addRegMask(RegInfo->getNoPreservedMask());
14229 thisMBB->addSuccessor(mainMBB);
14230 thisMBB->addSuccessor(restoreMBB);
14234 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14235 mainMBB->addSuccessor(sinkMBB);
14238 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14239 TII->get(X86::PHI), DstReg)
14240 .addReg(mainDstReg).addMBB(mainMBB)
14241 .addReg(restoreDstReg).addMBB(restoreMBB);
14244 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14245 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14246 restoreMBB->addSuccessor(sinkMBB);
14248 MI->eraseFromParent();
14252 MachineBasicBlock *
14253 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14254 MachineBasicBlock *MBB) const {
14255 DebugLoc DL = MI->getDebugLoc();
14256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14258 MachineFunction *MF = MBB->getParent();
14259 MachineRegisterInfo &MRI = MF->getRegInfo();
14261 // Memory Reference
14262 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14263 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14265 MVT PVT = getPointerTy();
14266 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14267 "Invalid Pointer Size!");
14269 const TargetRegisterClass *RC =
14270 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14271 unsigned Tmp = MRI.createVirtualRegister(RC);
14272 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14273 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14274 unsigned SP = RegInfo->getStackRegister();
14276 MachineInstrBuilder MIB;
14278 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14279 const int64_t SPOffset = 2 * PVT.getStoreSize();
14281 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14282 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14285 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14286 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14287 MIB.addOperand(MI->getOperand(i));
14288 MIB.setMemRefs(MMOBegin, MMOEnd);
14290 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14291 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14292 if (i == X86::AddrDisp)
14293 MIB.addDisp(MI->getOperand(i), LabelOffset);
14295 MIB.addOperand(MI->getOperand(i));
14297 MIB.setMemRefs(MMOBegin, MMOEnd);
14299 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14300 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14301 if (i == X86::AddrDisp)
14302 MIB.addDisp(MI->getOperand(i), SPOffset);
14304 MIB.addOperand(MI->getOperand(i));
14306 MIB.setMemRefs(MMOBegin, MMOEnd);
14308 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14310 MI->eraseFromParent();
14314 MachineBasicBlock *
14315 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14316 MachineBasicBlock *BB) const {
14317 switch (MI->getOpcode()) {
14318 default: llvm_unreachable("Unexpected instr type to insert");
14319 case X86::TAILJMPd64:
14320 case X86::TAILJMPr64:
14321 case X86::TAILJMPm64:
14322 llvm_unreachable("TAILJMP64 would not be touched here.");
14323 case X86::TCRETURNdi64:
14324 case X86::TCRETURNri64:
14325 case X86::TCRETURNmi64:
14327 case X86::WIN_ALLOCA:
14328 return EmitLoweredWinAlloca(MI, BB);
14329 case X86::SEG_ALLOCA_32:
14330 return EmitLoweredSegAlloca(MI, BB, false);
14331 case X86::SEG_ALLOCA_64:
14332 return EmitLoweredSegAlloca(MI, BB, true);
14333 case X86::TLSCall_32:
14334 case X86::TLSCall_64:
14335 return EmitLoweredTLSCall(MI, BB);
14336 case X86::CMOV_GR8:
14337 case X86::CMOV_FR32:
14338 case X86::CMOV_FR64:
14339 case X86::CMOV_V4F32:
14340 case X86::CMOV_V2F64:
14341 case X86::CMOV_V2I64:
14342 case X86::CMOV_V8F32:
14343 case X86::CMOV_V4F64:
14344 case X86::CMOV_V4I64:
14345 case X86::CMOV_GR16:
14346 case X86::CMOV_GR32:
14347 case X86::CMOV_RFP32:
14348 case X86::CMOV_RFP64:
14349 case X86::CMOV_RFP80:
14350 return EmitLoweredSelect(MI, BB);
14352 case X86::FP32_TO_INT16_IN_MEM:
14353 case X86::FP32_TO_INT32_IN_MEM:
14354 case X86::FP32_TO_INT64_IN_MEM:
14355 case X86::FP64_TO_INT16_IN_MEM:
14356 case X86::FP64_TO_INT32_IN_MEM:
14357 case X86::FP64_TO_INT64_IN_MEM:
14358 case X86::FP80_TO_INT16_IN_MEM:
14359 case X86::FP80_TO_INT32_IN_MEM:
14360 case X86::FP80_TO_INT64_IN_MEM: {
14361 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14362 DebugLoc DL = MI->getDebugLoc();
14364 // Change the floating point control register to use "round towards zero"
14365 // mode when truncating to an integer value.
14366 MachineFunction *F = BB->getParent();
14367 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14368 addFrameReference(BuildMI(*BB, MI, DL,
14369 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14371 // Load the old value of the high byte of the control word...
14373 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14374 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14377 // Set the high part to be round to zero...
14378 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14381 // Reload the modified control word now...
14382 addFrameReference(BuildMI(*BB, MI, DL,
14383 TII->get(X86::FLDCW16m)), CWFrameIdx);
14385 // Restore the memory image of control word to original value
14386 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14389 // Get the X86 opcode to use.
14391 switch (MI->getOpcode()) {
14392 default: llvm_unreachable("illegal opcode!");
14393 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14394 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14395 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14396 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14397 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14398 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14399 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14400 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14401 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14405 MachineOperand &Op = MI->getOperand(0);
14407 AM.BaseType = X86AddressMode::RegBase;
14408 AM.Base.Reg = Op.getReg();
14410 AM.BaseType = X86AddressMode::FrameIndexBase;
14411 AM.Base.FrameIndex = Op.getIndex();
14413 Op = MI->getOperand(1);
14415 AM.Scale = Op.getImm();
14416 Op = MI->getOperand(2);
14418 AM.IndexReg = Op.getImm();
14419 Op = MI->getOperand(3);
14420 if (Op.isGlobal()) {
14421 AM.GV = Op.getGlobal();
14423 AM.Disp = Op.getImm();
14425 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14426 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14428 // Reload the original control word now.
14429 addFrameReference(BuildMI(*BB, MI, DL,
14430 TII->get(X86::FLDCW16m)), CWFrameIdx);
14432 MI->eraseFromParent(); // The pseudo instruction is gone now.
14435 // String/text processing lowering.
14436 case X86::PCMPISTRM128REG:
14437 case X86::VPCMPISTRM128REG:
14438 case X86::PCMPISTRM128MEM:
14439 case X86::VPCMPISTRM128MEM:
14440 case X86::PCMPESTRM128REG:
14441 case X86::VPCMPESTRM128REG:
14442 case X86::PCMPESTRM128MEM:
14443 case X86::VPCMPESTRM128MEM:
14444 assert(Subtarget->hasSSE42() &&
14445 "Target must have SSE4.2 or AVX features enabled");
14446 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14448 // String/text processing lowering.
14449 case X86::PCMPISTRIREG:
14450 case X86::VPCMPISTRIREG:
14451 case X86::PCMPISTRIMEM:
14452 case X86::VPCMPISTRIMEM:
14453 case X86::PCMPESTRIREG:
14454 case X86::VPCMPESTRIREG:
14455 case X86::PCMPESTRIMEM:
14456 case X86::VPCMPESTRIMEM:
14457 assert(Subtarget->hasSSE42() &&
14458 "Target must have SSE4.2 or AVX features enabled");
14459 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14461 // Thread synchronization.
14463 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14467 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14469 // Atomic Lowering.
14470 case X86::ATOMAND8:
14471 case X86::ATOMAND16:
14472 case X86::ATOMAND32:
14473 case X86::ATOMAND64:
14476 case X86::ATOMOR16:
14477 case X86::ATOMOR32:
14478 case X86::ATOMOR64:
14480 case X86::ATOMXOR16:
14481 case X86::ATOMXOR8:
14482 case X86::ATOMXOR32:
14483 case X86::ATOMXOR64:
14485 case X86::ATOMNAND8:
14486 case X86::ATOMNAND16:
14487 case X86::ATOMNAND32:
14488 case X86::ATOMNAND64:
14490 case X86::ATOMMAX8:
14491 case X86::ATOMMAX16:
14492 case X86::ATOMMAX32:
14493 case X86::ATOMMAX64:
14495 case X86::ATOMMIN8:
14496 case X86::ATOMMIN16:
14497 case X86::ATOMMIN32:
14498 case X86::ATOMMIN64:
14500 case X86::ATOMUMAX8:
14501 case X86::ATOMUMAX16:
14502 case X86::ATOMUMAX32:
14503 case X86::ATOMUMAX64:
14505 case X86::ATOMUMIN8:
14506 case X86::ATOMUMIN16:
14507 case X86::ATOMUMIN32:
14508 case X86::ATOMUMIN64:
14509 return EmitAtomicLoadArith(MI, BB);
14511 // This group does 64-bit operations on a 32-bit host.
14512 case X86::ATOMAND6432:
14513 case X86::ATOMOR6432:
14514 case X86::ATOMXOR6432:
14515 case X86::ATOMNAND6432:
14516 case X86::ATOMADD6432:
14517 case X86::ATOMSUB6432:
14518 case X86::ATOMMAX6432:
14519 case X86::ATOMMIN6432:
14520 case X86::ATOMUMAX6432:
14521 case X86::ATOMUMIN6432:
14522 case X86::ATOMSWAP6432:
14523 return EmitAtomicLoadArith6432(MI, BB);
14525 case X86::VASTART_SAVE_XMM_REGS:
14526 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14528 case X86::VAARG_64:
14529 return EmitVAARG64WithCustomInserter(MI, BB);
14531 case X86::EH_SjLj_SetJmp32:
14532 case X86::EH_SjLj_SetJmp64:
14533 return emitEHSjLjSetJmp(MI, BB);
14535 case X86::EH_SjLj_LongJmp32:
14536 case X86::EH_SjLj_LongJmp64:
14537 return emitEHSjLjLongJmp(MI, BB);
14541 //===----------------------------------------------------------------------===//
14542 // X86 Optimization Hooks
14543 //===----------------------------------------------------------------------===//
14545 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14548 const SelectionDAG &DAG,
14549 unsigned Depth) const {
14550 unsigned BitWidth = KnownZero.getBitWidth();
14551 unsigned Opc = Op.getOpcode();
14552 assert((Opc >= ISD::BUILTIN_OP_END ||
14553 Opc == ISD::INTRINSIC_WO_CHAIN ||
14554 Opc == ISD::INTRINSIC_W_CHAIN ||
14555 Opc == ISD::INTRINSIC_VOID) &&
14556 "Should use MaskedValueIsZero if you don't know whether Op"
14557 " is a target node!");
14559 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14573 // These nodes' second result is a boolean.
14574 if (Op.getResNo() == 0)
14577 case X86ISD::SETCC:
14578 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14580 case ISD::INTRINSIC_WO_CHAIN: {
14581 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14582 unsigned NumLoBits = 0;
14585 case Intrinsic::x86_sse_movmsk_ps:
14586 case Intrinsic::x86_avx_movmsk_ps_256:
14587 case Intrinsic::x86_sse2_movmsk_pd:
14588 case Intrinsic::x86_avx_movmsk_pd_256:
14589 case Intrinsic::x86_mmx_pmovmskb:
14590 case Intrinsic::x86_sse2_pmovmskb_128:
14591 case Intrinsic::x86_avx2_pmovmskb: {
14592 // High bits of movmskp{s|d}, pmovmskb are known zero.
14594 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14595 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14596 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14597 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14598 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14599 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14600 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14601 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14603 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14612 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14613 unsigned Depth) const {
14614 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14615 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14616 return Op.getValueType().getScalarType().getSizeInBits();
14622 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14623 /// node is a GlobalAddress + offset.
14624 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14625 const GlobalValue* &GA,
14626 int64_t &Offset) const {
14627 if (N->getOpcode() == X86ISD::Wrapper) {
14628 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14629 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14630 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14634 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14637 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14638 /// same as extracting the high 128-bit part of 256-bit vector and then
14639 /// inserting the result into the low part of a new 256-bit vector
14640 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14641 EVT VT = SVOp->getValueType(0);
14642 unsigned NumElems = VT.getVectorNumElements();
14644 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14645 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14646 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14647 SVOp->getMaskElt(j) >= 0)
14653 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14654 /// same as extracting the low 128-bit part of 256-bit vector and then
14655 /// inserting the result into the high part of a new 256-bit vector
14656 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14657 EVT VT = SVOp->getValueType(0);
14658 unsigned NumElems = VT.getVectorNumElements();
14660 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14661 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14662 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14663 SVOp->getMaskElt(j) >= 0)
14669 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14670 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14671 TargetLowering::DAGCombinerInfo &DCI,
14672 const X86Subtarget* Subtarget) {
14673 DebugLoc dl = N->getDebugLoc();
14674 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14675 SDValue V1 = SVOp->getOperand(0);
14676 SDValue V2 = SVOp->getOperand(1);
14677 EVT VT = SVOp->getValueType(0);
14678 unsigned NumElems = VT.getVectorNumElements();
14680 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14681 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14685 // V UNDEF BUILD_VECTOR UNDEF
14687 // CONCAT_VECTOR CONCAT_VECTOR
14690 // RESULT: V + zero extended
14692 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14693 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14694 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14697 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14700 // To match the shuffle mask, the first half of the mask should
14701 // be exactly the first vector, and all the rest a splat with the
14702 // first element of the second one.
14703 for (unsigned i = 0; i != NumElems/2; ++i)
14704 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14705 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14708 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14709 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14710 if (Ld->hasNUsesOfValue(1, 0)) {
14711 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14712 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14714 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14716 Ld->getPointerInfo(),
14717 Ld->getAlignment(),
14718 false/*isVolatile*/, true/*ReadMem*/,
14719 false/*WriteMem*/);
14721 // Make sure the newly-created LOAD is in the same position as Ld in
14722 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14723 // and update uses of Ld's output chain to use the TokenFactor.
14724 if (Ld->hasAnyUseOfValue(1)) {
14725 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14726 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14727 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14728 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14729 SDValue(ResNode.getNode(), 1));
14732 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14736 // Emit a zeroed vector and insert the desired subvector on its
14738 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14739 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14740 return DCI.CombineTo(N, InsV);
14743 //===--------------------------------------------------------------------===//
14744 // Combine some shuffles into subvector extracts and inserts:
14747 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14748 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14749 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14750 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14751 return DCI.CombineTo(N, InsV);
14754 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14755 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14756 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14757 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14758 return DCI.CombineTo(N, InsV);
14764 /// PerformShuffleCombine - Performs several different shuffle combines.
14765 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14766 TargetLowering::DAGCombinerInfo &DCI,
14767 const X86Subtarget *Subtarget) {
14768 DebugLoc dl = N->getDebugLoc();
14769 EVT VT = N->getValueType(0);
14771 // Don't create instructions with illegal types after legalize types has run.
14772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14773 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14776 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14777 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14778 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14779 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14781 // Only handle 128 wide vector from here on.
14782 if (!VT.is128BitVector())
14785 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14786 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14787 // consecutive, non-overlapping, and in the right order.
14788 SmallVector<SDValue, 16> Elts;
14789 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14790 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14792 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14795 /// PerformTruncateCombine - Converts truncate operation to
14796 /// a sequence of vector shuffle operations.
14797 /// It is possible when we truncate 256-bit vector to 128-bit vector
14798 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14799 TargetLowering::DAGCombinerInfo &DCI,
14800 const X86Subtarget *Subtarget) {
14804 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14805 /// specific shuffle of a load can be folded into a single element load.
14806 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14807 /// shuffles have been customed lowered so we need to handle those here.
14808 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14809 TargetLowering::DAGCombinerInfo &DCI) {
14810 if (DCI.isBeforeLegalizeOps())
14813 SDValue InVec = N->getOperand(0);
14814 SDValue EltNo = N->getOperand(1);
14816 if (!isa<ConstantSDNode>(EltNo))
14819 EVT VT = InVec.getValueType();
14821 bool HasShuffleIntoBitcast = false;
14822 if (InVec.getOpcode() == ISD::BITCAST) {
14823 // Don't duplicate a load with other uses.
14824 if (!InVec.hasOneUse())
14826 EVT BCVT = InVec.getOperand(0).getValueType();
14827 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14829 InVec = InVec.getOperand(0);
14830 HasShuffleIntoBitcast = true;
14833 if (!isTargetShuffle(InVec.getOpcode()))
14836 // Don't duplicate a load with other uses.
14837 if (!InVec.hasOneUse())
14840 SmallVector<int, 16> ShuffleMask;
14842 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14846 // Select the input vector, guarding against out of range extract vector.
14847 unsigned NumElems = VT.getVectorNumElements();
14848 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14849 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14850 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14851 : InVec.getOperand(1);
14853 // If inputs to shuffle are the same for both ops, then allow 2 uses
14854 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14856 if (LdNode.getOpcode() == ISD::BITCAST) {
14857 // Don't duplicate a load with other uses.
14858 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14861 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14862 LdNode = LdNode.getOperand(0);
14865 if (!ISD::isNormalLoad(LdNode.getNode()))
14868 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14870 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14873 if (HasShuffleIntoBitcast) {
14874 // If there's a bitcast before the shuffle, check if the load type and
14875 // alignment is valid.
14876 unsigned Align = LN0->getAlignment();
14877 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14878 unsigned NewAlign = TLI.getDataLayout()->
14879 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14881 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14885 // All checks match so transform back to vector_shuffle so that DAG combiner
14886 // can finish the job
14887 DebugLoc dl = N->getDebugLoc();
14889 // Create shuffle node taking into account the case that its a unary shuffle
14890 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14891 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14892 InVec.getOperand(0), Shuffle,
14894 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14895 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14899 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14900 /// generation and convert it from being a bunch of shuffles and extracts
14901 /// to a simple store and scalar loads to extract the elements.
14902 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14903 TargetLowering::DAGCombinerInfo &DCI) {
14904 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14905 if (NewOp.getNode())
14908 SDValue InputVector = N->getOperand(0);
14909 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14910 // from mmx to v2i32 has a single usage.
14911 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14912 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14913 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14914 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14915 N->getValueType(0),
14916 InputVector.getNode()->getOperand(0));
14918 // Only operate on vectors of 4 elements, where the alternative shuffling
14919 // gets to be more expensive.
14920 if (InputVector.getValueType() != MVT::v4i32)
14923 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14924 // single use which is a sign-extend or zero-extend, and all elements are
14926 SmallVector<SDNode *, 4> Uses;
14927 unsigned ExtractedElements = 0;
14928 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14929 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14930 if (UI.getUse().getResNo() != InputVector.getResNo())
14933 SDNode *Extract = *UI;
14934 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14937 if (Extract->getValueType(0) != MVT::i32)
14939 if (!Extract->hasOneUse())
14941 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14942 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14944 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14947 // Record which element was extracted.
14948 ExtractedElements |=
14949 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14951 Uses.push_back(Extract);
14954 // If not all the elements were used, this may not be worthwhile.
14955 if (ExtractedElements != 15)
14958 // Ok, we've now decided to do the transformation.
14959 DebugLoc dl = InputVector.getDebugLoc();
14961 // Store the value to a temporary stack slot.
14962 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14963 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14964 MachinePointerInfo(), false, false, 0);
14966 // Replace each use (extract) with a load of the appropriate element.
14967 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14968 UE = Uses.end(); UI != UE; ++UI) {
14969 SDNode *Extract = *UI;
14971 // cOMpute the element's address.
14972 SDValue Idx = Extract->getOperand(1);
14974 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14975 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14976 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14977 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14979 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14980 StackPtr, OffsetVal);
14982 // Load the scalar.
14983 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14984 ScalarAddr, MachinePointerInfo(),
14985 false, false, false, 0);
14987 // Replace the exact with the load.
14988 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14991 // The replacement was made in place; don't return anything.
14995 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14996 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14997 SDValue RHS, SelectionDAG &DAG,
14998 const X86Subtarget *Subtarget) {
14999 if (!VT.isVector())
15002 switch (VT.getSimpleVT().SimpleTy) {
15007 if (!Subtarget->hasAVX2())
15012 if (!Subtarget->hasSSE2())
15016 // SSE2 has only a small subset of the operations.
15017 bool hasUnsigned = Subtarget->hasSSE41() ||
15018 (Subtarget->hasSSE2() && VT == MVT::v16i8);
15019 bool hasSigned = Subtarget->hasSSE41() ||
15020 (Subtarget->hasSSE2() && VT == MVT::v8i16);
15022 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15024 // Check for x CC y ? x : y.
15025 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15026 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15031 return hasUnsigned ? X86ISD::UMIN : 0;
15034 return hasUnsigned ? X86ISD::UMAX : 0;
15037 return hasSigned ? X86ISD::SMIN : 0;
15040 return hasSigned ? X86ISD::SMAX : 0;
15042 // Check for x CC y ? y : x -- a min/max with reversed arms.
15043 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15044 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15049 return hasUnsigned ? X86ISD::UMAX : 0;
15052 return hasUnsigned ? X86ISD::UMIN : 0;
15055 return hasSigned ? X86ISD::SMAX : 0;
15058 return hasSigned ? X86ISD::SMIN : 0;
15065 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15067 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15068 TargetLowering::DAGCombinerInfo &DCI,
15069 const X86Subtarget *Subtarget) {
15070 DebugLoc DL = N->getDebugLoc();
15071 SDValue Cond = N->getOperand(0);
15072 // Get the LHS/RHS of the select.
15073 SDValue LHS = N->getOperand(1);
15074 SDValue RHS = N->getOperand(2);
15075 EVT VT = LHS.getValueType();
15077 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15078 // instructions match the semantics of the common C idiom x<y?x:y but not
15079 // x<=y?x:y, because of how they handle negative zero (which can be
15080 // ignored in unsafe-math mode).
15081 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15082 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15083 (Subtarget->hasSSE2() ||
15084 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15085 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15087 unsigned Opcode = 0;
15088 // Check for x CC y ? x : y.
15089 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15090 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15094 // Converting this to a min would handle NaNs incorrectly, and swapping
15095 // the operands would cause it to handle comparisons between positive
15096 // and negative zero incorrectly.
15097 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15098 if (!DAG.getTarget().Options.UnsafeFPMath &&
15099 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15101 std::swap(LHS, RHS);
15103 Opcode = X86ISD::FMIN;
15106 // Converting this to a min would handle comparisons between positive
15107 // and negative zero incorrectly.
15108 if (!DAG.getTarget().Options.UnsafeFPMath &&
15109 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15111 Opcode = X86ISD::FMIN;
15114 // Converting this to a min would handle both negative zeros and NaNs
15115 // incorrectly, but we can swap the operands to fix both.
15116 std::swap(LHS, RHS);
15120 Opcode = X86ISD::FMIN;
15124 // Converting this to a max would handle comparisons between positive
15125 // and negative zero incorrectly.
15126 if (!DAG.getTarget().Options.UnsafeFPMath &&
15127 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15129 Opcode = X86ISD::FMAX;
15132 // Converting this to a max would handle NaNs incorrectly, and swapping
15133 // the operands would cause it to handle comparisons between positive
15134 // and negative zero incorrectly.
15135 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15136 if (!DAG.getTarget().Options.UnsafeFPMath &&
15137 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15139 std::swap(LHS, RHS);
15141 Opcode = X86ISD::FMAX;
15144 // Converting this to a max would handle both negative zeros and NaNs
15145 // incorrectly, but we can swap the operands to fix both.
15146 std::swap(LHS, RHS);
15150 Opcode = X86ISD::FMAX;
15153 // Check for x CC y ? y : x -- a min/max with reversed arms.
15154 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15155 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15159 // Converting this to a min would handle comparisons between positive
15160 // and negative zero incorrectly, and swapping the operands would
15161 // cause it to handle NaNs incorrectly.
15162 if (!DAG.getTarget().Options.UnsafeFPMath &&
15163 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15164 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15166 std::swap(LHS, RHS);
15168 Opcode = X86ISD::FMIN;
15171 // Converting this to a min would handle NaNs incorrectly.
15172 if (!DAG.getTarget().Options.UnsafeFPMath &&
15173 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15175 Opcode = X86ISD::FMIN;
15178 // Converting this to a min would handle both negative zeros and NaNs
15179 // incorrectly, but we can swap the operands to fix both.
15180 std::swap(LHS, RHS);
15184 Opcode = X86ISD::FMIN;
15188 // Converting this to a max would handle NaNs incorrectly.
15189 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15191 Opcode = X86ISD::FMAX;
15194 // Converting this to a max would handle comparisons between positive
15195 // and negative zero incorrectly, and swapping the operands would
15196 // cause it to handle NaNs incorrectly.
15197 if (!DAG.getTarget().Options.UnsafeFPMath &&
15198 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15199 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15201 std::swap(LHS, RHS);
15203 Opcode = X86ISD::FMAX;
15206 // Converting this to a max would handle both negative zeros and NaNs
15207 // incorrectly, but we can swap the operands to fix both.
15208 std::swap(LHS, RHS);
15212 Opcode = X86ISD::FMAX;
15218 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15221 // If this is a select between two integer constants, try to do some
15223 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15224 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15225 // Don't do this for crazy integer types.
15226 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15227 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15228 // so that TrueC (the true value) is larger than FalseC.
15229 bool NeedsCondInvert = false;
15231 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15232 // Efficiently invertible.
15233 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15234 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15235 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15236 NeedsCondInvert = true;
15237 std::swap(TrueC, FalseC);
15240 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15241 if (FalseC->getAPIntValue() == 0 &&
15242 TrueC->getAPIntValue().isPowerOf2()) {
15243 if (NeedsCondInvert) // Invert the condition if needed.
15244 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15245 DAG.getConstant(1, Cond.getValueType()));
15247 // Zero extend the condition if needed.
15248 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15250 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15251 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15252 DAG.getConstant(ShAmt, MVT::i8));
15255 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15256 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15257 if (NeedsCondInvert) // Invert the condition if needed.
15258 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15259 DAG.getConstant(1, Cond.getValueType()));
15261 // Zero extend the condition if needed.
15262 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15263 FalseC->getValueType(0), Cond);
15264 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15265 SDValue(FalseC, 0));
15268 // Optimize cases that will turn into an LEA instruction. This requires
15269 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15270 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15271 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15272 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15274 bool isFastMultiplier = false;
15276 switch ((unsigned char)Diff) {
15278 case 1: // result = add base, cond
15279 case 2: // result = lea base( , cond*2)
15280 case 3: // result = lea base(cond, cond*2)
15281 case 4: // result = lea base( , cond*4)
15282 case 5: // result = lea base(cond, cond*4)
15283 case 8: // result = lea base( , cond*8)
15284 case 9: // result = lea base(cond, cond*8)
15285 isFastMultiplier = true;
15290 if (isFastMultiplier) {
15291 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15292 if (NeedsCondInvert) // Invert the condition if needed.
15293 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15294 DAG.getConstant(1, Cond.getValueType()));
15296 // Zero extend the condition if needed.
15297 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15299 // Scale the condition by the difference.
15301 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15302 DAG.getConstant(Diff, Cond.getValueType()));
15304 // Add the base if non-zero.
15305 if (FalseC->getAPIntValue() != 0)
15306 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15307 SDValue(FalseC, 0));
15314 // Canonicalize max and min:
15315 // (x > y) ? x : y -> (x >= y) ? x : y
15316 // (x < y) ? x : y -> (x <= y) ? x : y
15317 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15318 // the need for an extra compare
15319 // against zero. e.g.
15320 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15322 // testl %edi, %edi
15324 // cmovgl %edi, %eax
15328 // cmovsl %eax, %edi
15329 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15330 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15331 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15332 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15337 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15338 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15339 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15340 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15345 // Match VSELECTs into subs with unsigned saturation.
15346 if (!DCI.isBeforeLegalize() &&
15347 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15348 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15349 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15350 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15351 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15353 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15354 // left side invert the predicate to simplify logic below.
15356 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15358 CC = ISD::getSetCCInverse(CC, true);
15359 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15363 if (Other.getNode() && Other->getNumOperands() == 2 &&
15364 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15365 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15366 SDValue CondRHS = Cond->getOperand(1);
15368 // Look for a general sub with unsigned saturation first.
15369 // x >= y ? x-y : 0 --> subus x, y
15370 // x > y ? x-y : 0 --> subus x, y
15371 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15372 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15373 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15375 // If the RHS is a constant we have to reverse the const canonicalization.
15376 // x > C-1 ? x+-C : 0 --> subus x, C
15377 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15378 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15379 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15380 if (CondRHS.getConstantOperandVal(0) == -A-1)
15381 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15382 DAG.getConstant(-A, VT));
15385 // Another special case: If C was a sign bit, the sub has been
15386 // canonicalized into a xor.
15387 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15388 // it's safe to decanonicalize the xor?
15389 // x s< 0 ? x^C : 0 --> subus x, C
15390 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15391 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15392 isSplatVector(OpRHS.getNode())) {
15393 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15395 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15400 // Try to match a min/max vector operation.
15401 if (!DCI.isBeforeLegalize() &&
15402 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15403 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15404 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15406 // If we know that this node is legal then we know that it is going to be
15407 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15408 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15409 // to simplify previous instructions.
15410 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15411 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15412 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15413 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15415 // Don't optimize vector selects that map to mask-registers.
15419 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15420 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15422 APInt KnownZero, KnownOne;
15423 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15424 DCI.isBeforeLegalizeOps());
15425 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15426 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15427 DCI.CommitTargetLoweringOpt(TLO);
15433 // Check whether a boolean test is testing a boolean value generated by
15434 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15437 // Simplify the following patterns:
15438 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15439 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15440 // to (Op EFLAGS Cond)
15442 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15443 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15444 // to (Op EFLAGS !Cond)
15446 // where Op could be BRCOND or CMOV.
15448 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15449 // Quit if not CMP and SUB with its value result used.
15450 if (Cmp.getOpcode() != X86ISD::CMP &&
15451 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15454 // Quit if not used as a boolean value.
15455 if (CC != X86::COND_E && CC != X86::COND_NE)
15458 // Check CMP operands. One of them should be 0 or 1 and the other should be
15459 // an SetCC or extended from it.
15460 SDValue Op1 = Cmp.getOperand(0);
15461 SDValue Op2 = Cmp.getOperand(1);
15464 const ConstantSDNode* C = 0;
15465 bool needOppositeCond = (CC == X86::COND_E);
15467 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15469 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15471 else // Quit if all operands are not constants.
15474 if (C->getZExtValue() == 1)
15475 needOppositeCond = !needOppositeCond;
15476 else if (C->getZExtValue() != 0)
15477 // Quit if the constant is neither 0 or 1.
15480 // Skip 'zext' node.
15481 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15482 SetCC = SetCC.getOperand(0);
15484 switch (SetCC.getOpcode()) {
15485 case X86ISD::SETCC:
15486 // Set the condition code or opposite one if necessary.
15487 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15488 if (needOppositeCond)
15489 CC = X86::GetOppositeBranchCondition(CC);
15490 return SetCC.getOperand(1);
15491 case X86ISD::CMOV: {
15492 // Check whether false/true value has canonical one, i.e. 0 or 1.
15493 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15494 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15495 // Quit if true value is not a constant.
15498 // Quit if false value is not a constant.
15500 // A special case for rdrand, where 0 is set if false cond is found.
15501 SDValue Op = SetCC.getOperand(0);
15502 if (Op.getOpcode() != X86ISD::RDRAND)
15505 // Quit if false value is not the constant 0 or 1.
15506 bool FValIsFalse = true;
15507 if (FVal && FVal->getZExtValue() != 0) {
15508 if (FVal->getZExtValue() != 1)
15510 // If FVal is 1, opposite cond is needed.
15511 needOppositeCond = !needOppositeCond;
15512 FValIsFalse = false;
15514 // Quit if TVal is not the constant opposite of FVal.
15515 if (FValIsFalse && TVal->getZExtValue() != 1)
15517 if (!FValIsFalse && TVal->getZExtValue() != 0)
15519 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15520 if (needOppositeCond)
15521 CC = X86::GetOppositeBranchCondition(CC);
15522 return SetCC.getOperand(3);
15529 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15530 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15531 TargetLowering::DAGCombinerInfo &DCI,
15532 const X86Subtarget *Subtarget) {
15533 DebugLoc DL = N->getDebugLoc();
15535 // If the flag operand isn't dead, don't touch this CMOV.
15536 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15539 SDValue FalseOp = N->getOperand(0);
15540 SDValue TrueOp = N->getOperand(1);
15541 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15542 SDValue Cond = N->getOperand(3);
15544 if (CC == X86::COND_E || CC == X86::COND_NE) {
15545 switch (Cond.getOpcode()) {
15549 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15550 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15551 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15557 Flags = checkBoolTestSetCCCombine(Cond, CC);
15558 if (Flags.getNode() &&
15559 // Extra check as FCMOV only supports a subset of X86 cond.
15560 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15561 SDValue Ops[] = { FalseOp, TrueOp,
15562 DAG.getConstant(CC, MVT::i8), Flags };
15563 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15564 Ops, array_lengthof(Ops));
15567 // If this is a select between two integer constants, try to do some
15568 // optimizations. Note that the operands are ordered the opposite of SELECT
15570 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15571 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15572 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15573 // larger than FalseC (the false value).
15574 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15575 CC = X86::GetOppositeBranchCondition(CC);
15576 std::swap(TrueC, FalseC);
15577 std::swap(TrueOp, FalseOp);
15580 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15581 // This is efficient for any integer data type (including i8/i16) and
15583 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15584 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15585 DAG.getConstant(CC, MVT::i8), Cond);
15587 // Zero extend the condition if needed.
15588 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15590 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15591 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15592 DAG.getConstant(ShAmt, MVT::i8));
15593 if (N->getNumValues() == 2) // Dead flag value?
15594 return DCI.CombineTo(N, Cond, SDValue());
15598 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15599 // for any integer data type, including i8/i16.
15600 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15601 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15602 DAG.getConstant(CC, MVT::i8), Cond);
15604 // Zero extend the condition if needed.
15605 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15606 FalseC->getValueType(0), Cond);
15607 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15608 SDValue(FalseC, 0));
15610 if (N->getNumValues() == 2) // Dead flag value?
15611 return DCI.CombineTo(N, Cond, SDValue());
15615 // Optimize cases that will turn into an LEA instruction. This requires
15616 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15617 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15618 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15619 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15621 bool isFastMultiplier = false;
15623 switch ((unsigned char)Diff) {
15625 case 1: // result = add base, cond
15626 case 2: // result = lea base( , cond*2)
15627 case 3: // result = lea base(cond, cond*2)
15628 case 4: // result = lea base( , cond*4)
15629 case 5: // result = lea base(cond, cond*4)
15630 case 8: // result = lea base( , cond*8)
15631 case 9: // result = lea base(cond, cond*8)
15632 isFastMultiplier = true;
15637 if (isFastMultiplier) {
15638 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15639 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15640 DAG.getConstant(CC, MVT::i8), Cond);
15641 // Zero extend the condition if needed.
15642 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15644 // Scale the condition by the difference.
15646 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15647 DAG.getConstant(Diff, Cond.getValueType()));
15649 // Add the base if non-zero.
15650 if (FalseC->getAPIntValue() != 0)
15651 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15652 SDValue(FalseC, 0));
15653 if (N->getNumValues() == 2) // Dead flag value?
15654 return DCI.CombineTo(N, Cond, SDValue());
15661 // Handle these cases:
15662 // (select (x != c), e, c) -> select (x != c), e, x),
15663 // (select (x == c), c, e) -> select (x == c), x, e)
15664 // where the c is an integer constant, and the "select" is the combination
15665 // of CMOV and CMP.
15667 // The rationale for this change is that the conditional-move from a constant
15668 // needs two instructions, however, conditional-move from a register needs
15669 // only one instruction.
15671 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15672 // some instruction-combining opportunities. This opt needs to be
15673 // postponed as late as possible.
15675 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15676 // the DCI.xxxx conditions are provided to postpone the optimization as
15677 // late as possible.
15679 ConstantSDNode *CmpAgainst = 0;
15680 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15681 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15682 !isa<ConstantSDNode>(Cond.getOperand(0))) {
15684 if (CC == X86::COND_NE &&
15685 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15686 CC = X86::GetOppositeBranchCondition(CC);
15687 std::swap(TrueOp, FalseOp);
15690 if (CC == X86::COND_E &&
15691 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15692 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15693 DAG.getConstant(CC, MVT::i8), Cond };
15694 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15695 array_lengthof(Ops));
15703 /// PerformMulCombine - Optimize a single multiply with constant into two
15704 /// in order to implement it with two cheaper instructions, e.g.
15705 /// LEA + SHL, LEA + LEA.
15706 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15707 TargetLowering::DAGCombinerInfo &DCI) {
15708 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15711 EVT VT = N->getValueType(0);
15712 if (VT != MVT::i64)
15715 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15718 uint64_t MulAmt = C->getZExtValue();
15719 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15722 uint64_t MulAmt1 = 0;
15723 uint64_t MulAmt2 = 0;
15724 if ((MulAmt % 9) == 0) {
15726 MulAmt2 = MulAmt / 9;
15727 } else if ((MulAmt % 5) == 0) {
15729 MulAmt2 = MulAmt / 5;
15730 } else if ((MulAmt % 3) == 0) {
15732 MulAmt2 = MulAmt / 3;
15735 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15736 DebugLoc DL = N->getDebugLoc();
15738 if (isPowerOf2_64(MulAmt2) &&
15739 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15740 // If second multiplifer is pow2, issue it first. We want the multiply by
15741 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15743 std::swap(MulAmt1, MulAmt2);
15746 if (isPowerOf2_64(MulAmt1))
15747 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15748 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15750 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15751 DAG.getConstant(MulAmt1, VT));
15753 if (isPowerOf2_64(MulAmt2))
15754 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15755 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15757 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15758 DAG.getConstant(MulAmt2, VT));
15760 // Do not add new nodes to DAG combiner worklist.
15761 DCI.CombineTo(N, NewMul, false);
15766 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15767 SDValue N0 = N->getOperand(0);
15768 SDValue N1 = N->getOperand(1);
15769 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15770 EVT VT = N0.getValueType();
15772 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15773 // since the result of setcc_c is all zero's or all ones.
15774 if (VT.isInteger() && !VT.isVector() &&
15775 N1C && N0.getOpcode() == ISD::AND &&
15776 N0.getOperand(1).getOpcode() == ISD::Constant) {
15777 SDValue N00 = N0.getOperand(0);
15778 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15779 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15780 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15781 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15782 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15783 APInt ShAmt = N1C->getAPIntValue();
15784 Mask = Mask.shl(ShAmt);
15786 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15787 N00, DAG.getConstant(Mask, VT));
15791 // Hardware support for vector shifts is sparse which makes us scalarize the
15792 // vector operations in many cases. Also, on sandybridge ADD is faster than
15794 // (shl V, 1) -> add V,V
15795 if (isSplatVector(N1.getNode())) {
15796 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15797 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15798 // We shift all of the values by one. In many cases we do not have
15799 // hardware support for this operation. This is better expressed as an ADD
15801 if (N1C && (1 == N1C->getZExtValue())) {
15802 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15809 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15811 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15812 TargetLowering::DAGCombinerInfo &DCI,
15813 const X86Subtarget *Subtarget) {
15814 EVT VT = N->getValueType(0);
15815 if (N->getOpcode() == ISD::SHL) {
15816 SDValue V = PerformSHLCombine(N, DAG);
15817 if (V.getNode()) return V;
15820 // On X86 with SSE2 support, we can transform this to a vector shift if
15821 // all elements are shifted by the same amount. We can't do this in legalize
15822 // because the a constant vector is typically transformed to a constant pool
15823 // so we have no knowledge of the shift amount.
15824 if (!Subtarget->hasSSE2())
15827 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15828 (!Subtarget->hasInt256() ||
15829 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15832 SDValue ShAmtOp = N->getOperand(1);
15833 EVT EltVT = VT.getVectorElementType();
15834 DebugLoc DL = N->getDebugLoc();
15835 SDValue BaseShAmt = SDValue();
15836 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15837 unsigned NumElts = VT.getVectorNumElements();
15839 for (; i != NumElts; ++i) {
15840 SDValue Arg = ShAmtOp.getOperand(i);
15841 if (Arg.getOpcode() == ISD::UNDEF) continue;
15845 // Handle the case where the build_vector is all undef
15846 // FIXME: Should DAG allow this?
15850 for (; i != NumElts; ++i) {
15851 SDValue Arg = ShAmtOp.getOperand(i);
15852 if (Arg.getOpcode() == ISD::UNDEF) continue;
15853 if (Arg != BaseShAmt) {
15857 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15858 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15859 SDValue InVec = ShAmtOp.getOperand(0);
15860 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15861 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15863 for (; i != NumElts; ++i) {
15864 SDValue Arg = InVec.getOperand(i);
15865 if (Arg.getOpcode() == ISD::UNDEF) continue;
15869 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15871 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15872 if (C->getZExtValue() == SplatIdx)
15873 BaseShAmt = InVec.getOperand(1);
15876 if (BaseShAmt.getNode() == 0) {
15877 // Don't create instructions with illegal types after legalize
15879 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15880 !DCI.isBeforeLegalize())
15883 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15884 DAG.getIntPtrConstant(0));
15889 // The shift amount is an i32.
15890 if (EltVT.bitsGT(MVT::i32))
15891 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15892 else if (EltVT.bitsLT(MVT::i32))
15893 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15895 // The shift amount is identical so we can do a vector shift.
15896 SDValue ValOp = N->getOperand(0);
15897 switch (N->getOpcode()) {
15899 llvm_unreachable("Unknown shift opcode!");
15901 switch (VT.getSimpleVT().SimpleTy) {
15902 default: return SDValue();
15909 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15912 switch (VT.getSimpleVT().SimpleTy) {
15913 default: return SDValue();
15918 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15921 switch (VT.getSimpleVT().SimpleTy) {
15922 default: return SDValue();
15929 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15934 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15935 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15936 // and friends. Likewise for OR -> CMPNEQSS.
15937 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15938 TargetLowering::DAGCombinerInfo &DCI,
15939 const X86Subtarget *Subtarget) {
15942 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15943 // we're requiring SSE2 for both.
15944 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15945 SDValue N0 = N->getOperand(0);
15946 SDValue N1 = N->getOperand(1);
15947 SDValue CMP0 = N0->getOperand(1);
15948 SDValue CMP1 = N1->getOperand(1);
15949 DebugLoc DL = N->getDebugLoc();
15951 // The SETCCs should both refer to the same CMP.
15952 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15955 SDValue CMP00 = CMP0->getOperand(0);
15956 SDValue CMP01 = CMP0->getOperand(1);
15957 EVT VT = CMP00.getValueType();
15959 if (VT == MVT::f32 || VT == MVT::f64) {
15960 bool ExpectingFlags = false;
15961 // Check for any users that want flags:
15962 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
15963 !ExpectingFlags && UI != UE; ++UI)
15964 switch (UI->getOpcode()) {
15969 ExpectingFlags = true;
15971 case ISD::CopyToReg:
15972 case ISD::SIGN_EXTEND:
15973 case ISD::ZERO_EXTEND:
15974 case ISD::ANY_EXTEND:
15978 if (!ExpectingFlags) {
15979 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15980 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15982 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15983 X86::CondCode tmp = cc0;
15988 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15989 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15990 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15991 X86ISD::NodeType NTOperator = is64BitFP ?
15992 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15993 // FIXME: need symbolic constants for these magic numbers.
15994 // See X86ATTInstPrinter.cpp:printSSECC().
15995 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15996 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15997 DAG.getConstant(x86cc, MVT::i8));
15998 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16000 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16001 DAG.getConstant(1, MVT::i32));
16002 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16003 return OneBitOfTruth;
16011 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16012 /// so it can be folded inside ANDNP.
16013 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16014 EVT VT = N->getValueType(0);
16016 // Match direct AllOnes for 128 and 256-bit vectors
16017 if (ISD::isBuildVectorAllOnes(N))
16020 // Look through a bit convert.
16021 if (N->getOpcode() == ISD::BITCAST)
16022 N = N->getOperand(0).getNode();
16024 // Sometimes the operand may come from a insert_subvector building a 256-bit
16026 if (VT.is256BitVector() &&
16027 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16028 SDValue V1 = N->getOperand(0);
16029 SDValue V2 = N->getOperand(1);
16031 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16032 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16033 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16034 ISD::isBuildVectorAllOnes(V2.getNode()))
16041 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16042 // register. In most cases we actually compare or select YMM-sized registers
16043 // and mixing the two types creates horrible code. This method optimizes
16044 // some of the transition sequences.
16045 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16046 TargetLowering::DAGCombinerInfo &DCI,
16047 const X86Subtarget *Subtarget) {
16048 EVT VT = N->getValueType(0);
16049 if (!VT.is256BitVector())
16052 assert((N->getOpcode() == ISD::ANY_EXTEND ||
16053 N->getOpcode() == ISD::ZERO_EXTEND ||
16054 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16056 SDValue Narrow = N->getOperand(0);
16057 EVT NarrowVT = Narrow->getValueType(0);
16058 if (!NarrowVT.is128BitVector())
16061 if (Narrow->getOpcode() != ISD::XOR &&
16062 Narrow->getOpcode() != ISD::AND &&
16063 Narrow->getOpcode() != ISD::OR)
16066 SDValue N0 = Narrow->getOperand(0);
16067 SDValue N1 = Narrow->getOperand(1);
16068 DebugLoc DL = Narrow->getDebugLoc();
16070 // The Left side has to be a trunc.
16071 if (N0.getOpcode() != ISD::TRUNCATE)
16074 // The type of the truncated inputs.
16075 EVT WideVT = N0->getOperand(0)->getValueType(0);
16079 // The right side has to be a 'trunc' or a constant vector.
16080 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16081 bool RHSConst = (isSplatVector(N1.getNode()) &&
16082 isa<ConstantSDNode>(N1->getOperand(0)));
16083 if (!RHSTrunc && !RHSConst)
16086 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16088 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16091 // Set N0 and N1 to hold the inputs to the new wide operation.
16092 N0 = N0->getOperand(0);
16094 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16095 N1->getOperand(0));
16096 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16097 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16098 } else if (RHSTrunc) {
16099 N1 = N1->getOperand(0);
16102 // Generate the wide operation.
16103 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16104 unsigned Opcode = N->getOpcode();
16106 case ISD::ANY_EXTEND:
16108 case ISD::ZERO_EXTEND: {
16109 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16110 APInt Mask = APInt::getAllOnesValue(InBits);
16111 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16112 return DAG.getNode(ISD::AND, DL, VT,
16113 Op, DAG.getConstant(Mask, VT));
16115 case ISD::SIGN_EXTEND:
16116 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16117 Op, DAG.getValueType(NarrowVT));
16119 llvm_unreachable("Unexpected opcode");
16123 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16124 TargetLowering::DAGCombinerInfo &DCI,
16125 const X86Subtarget *Subtarget) {
16126 EVT VT = N->getValueType(0);
16127 if (DCI.isBeforeLegalizeOps())
16130 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16134 // Create BLSI, and BLSR instructions
16135 // BLSI is X & (-X)
16136 // BLSR is X & (X-1)
16137 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16138 SDValue N0 = N->getOperand(0);
16139 SDValue N1 = N->getOperand(1);
16140 DebugLoc DL = N->getDebugLoc();
16142 // Check LHS for neg
16143 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16144 isZero(N0.getOperand(0)))
16145 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16147 // Check RHS for neg
16148 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16149 isZero(N1.getOperand(0)))
16150 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16152 // Check LHS for X-1
16153 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16154 isAllOnes(N0.getOperand(1)))
16155 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16157 // Check RHS for X-1
16158 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16159 isAllOnes(N1.getOperand(1)))
16160 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16165 // Want to form ANDNP nodes:
16166 // 1) In the hopes of then easily combining them with OR and AND nodes
16167 // to form PBLEND/PSIGN.
16168 // 2) To match ANDN packed intrinsics
16169 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16172 SDValue N0 = N->getOperand(0);
16173 SDValue N1 = N->getOperand(1);
16174 DebugLoc DL = N->getDebugLoc();
16176 // Check LHS for vnot
16177 if (N0.getOpcode() == ISD::XOR &&
16178 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16179 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16180 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16182 // Check RHS for vnot
16183 if (N1.getOpcode() == ISD::XOR &&
16184 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16185 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16186 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16191 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16192 TargetLowering::DAGCombinerInfo &DCI,
16193 const X86Subtarget *Subtarget) {
16194 EVT VT = N->getValueType(0);
16195 if (DCI.isBeforeLegalizeOps())
16198 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16202 SDValue N0 = N->getOperand(0);
16203 SDValue N1 = N->getOperand(1);
16205 // look for psign/blend
16206 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16207 if (!Subtarget->hasSSSE3() ||
16208 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16211 // Canonicalize pandn to RHS
16212 if (N0.getOpcode() == X86ISD::ANDNP)
16214 // or (and (m, y), (pandn m, x))
16215 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16216 SDValue Mask = N1.getOperand(0);
16217 SDValue X = N1.getOperand(1);
16219 if (N0.getOperand(0) == Mask)
16220 Y = N0.getOperand(1);
16221 if (N0.getOperand(1) == Mask)
16222 Y = N0.getOperand(0);
16224 // Check to see if the mask appeared in both the AND and ANDNP and
16228 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16229 // Look through mask bitcast.
16230 if (Mask.getOpcode() == ISD::BITCAST)
16231 Mask = Mask.getOperand(0);
16232 if (X.getOpcode() == ISD::BITCAST)
16233 X = X.getOperand(0);
16234 if (Y.getOpcode() == ISD::BITCAST)
16235 Y = Y.getOperand(0);
16237 EVT MaskVT = Mask.getValueType();
16239 // Validate that the Mask operand is a vector sra node.
16240 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16241 // there is no psrai.b
16242 if (Mask.getOpcode() != X86ISD::VSRAI)
16245 // Check that the SRA is all signbits.
16246 SDValue SraC = Mask.getOperand(1);
16247 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16248 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16249 if ((SraAmt + 1) != EltBits)
16252 DebugLoc DL = N->getDebugLoc();
16254 // Now we know we at least have a plendvb with the mask val. See if
16255 // we can form a psignb/w/d.
16256 // psign = x.type == y.type == mask.type && y = sub(0, x);
16257 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16258 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16259 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16260 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16261 "Unsupported VT for PSIGN");
16262 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16263 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16265 // PBLENDVB only available on SSE 4.1
16266 if (!Subtarget->hasSSE41())
16269 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16271 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16272 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16273 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16274 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16275 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16279 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16282 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16283 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16285 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16287 if (!N0.hasOneUse() || !N1.hasOneUse())
16290 SDValue ShAmt0 = N0.getOperand(1);
16291 if (ShAmt0.getValueType() != MVT::i8)
16293 SDValue ShAmt1 = N1.getOperand(1);
16294 if (ShAmt1.getValueType() != MVT::i8)
16296 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16297 ShAmt0 = ShAmt0.getOperand(0);
16298 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16299 ShAmt1 = ShAmt1.getOperand(0);
16301 DebugLoc DL = N->getDebugLoc();
16302 unsigned Opc = X86ISD::SHLD;
16303 SDValue Op0 = N0.getOperand(0);
16304 SDValue Op1 = N1.getOperand(0);
16305 if (ShAmt0.getOpcode() == ISD::SUB) {
16306 Opc = X86ISD::SHRD;
16307 std::swap(Op0, Op1);
16308 std::swap(ShAmt0, ShAmt1);
16311 unsigned Bits = VT.getSizeInBits();
16312 if (ShAmt1.getOpcode() == ISD::SUB) {
16313 SDValue Sum = ShAmt1.getOperand(0);
16314 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16315 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16316 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16317 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16318 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16319 return DAG.getNode(Opc, DL, VT,
16321 DAG.getNode(ISD::TRUNCATE, DL,
16324 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16325 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16327 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16328 return DAG.getNode(Opc, DL, VT,
16329 N0.getOperand(0), N1.getOperand(0),
16330 DAG.getNode(ISD::TRUNCATE, DL,
16337 // Generate NEG and CMOV for integer abs.
16338 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16339 EVT VT = N->getValueType(0);
16341 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16342 // 8-bit integer abs to NEG and CMOV.
16343 if (VT.isInteger() && VT.getSizeInBits() == 8)
16346 SDValue N0 = N->getOperand(0);
16347 SDValue N1 = N->getOperand(1);
16348 DebugLoc DL = N->getDebugLoc();
16350 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16351 // and change it to SUB and CMOV.
16352 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16353 N0.getOpcode() == ISD::ADD &&
16354 N0.getOperand(1) == N1 &&
16355 N1.getOpcode() == ISD::SRA &&
16356 N1.getOperand(0) == N0.getOperand(0))
16357 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16358 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16359 // Generate SUB & CMOV.
16360 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16361 DAG.getConstant(0, VT), N0.getOperand(0));
16363 SDValue Ops[] = { N0.getOperand(0), Neg,
16364 DAG.getConstant(X86::COND_GE, MVT::i8),
16365 SDValue(Neg.getNode(), 1) };
16366 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16367 Ops, array_lengthof(Ops));
16372 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16373 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16374 TargetLowering::DAGCombinerInfo &DCI,
16375 const X86Subtarget *Subtarget) {
16376 EVT VT = N->getValueType(0);
16377 if (DCI.isBeforeLegalizeOps())
16380 if (Subtarget->hasCMov()) {
16381 SDValue RV = performIntegerAbsCombine(N, DAG);
16386 // Try forming BMI if it is available.
16387 if (!Subtarget->hasBMI())
16390 if (VT != MVT::i32 && VT != MVT::i64)
16393 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16395 // Create BLSMSK instructions by finding X ^ (X-1)
16396 SDValue N0 = N->getOperand(0);
16397 SDValue N1 = N->getOperand(1);
16398 DebugLoc DL = N->getDebugLoc();
16400 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16401 isAllOnes(N0.getOperand(1)))
16402 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16404 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16405 isAllOnes(N1.getOperand(1)))
16406 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16411 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16412 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16413 TargetLowering::DAGCombinerInfo &DCI,
16414 const X86Subtarget *Subtarget) {
16415 LoadSDNode *Ld = cast<LoadSDNode>(N);
16416 EVT RegVT = Ld->getValueType(0);
16417 EVT MemVT = Ld->getMemoryVT();
16418 DebugLoc dl = Ld->getDebugLoc();
16419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16420 unsigned RegSz = RegVT.getSizeInBits();
16422 ISD::LoadExtType Ext = Ld->getExtensionType();
16423 unsigned Alignment = Ld->getAlignment();
16424 bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16426 // On Sandybridge unaligned 256bit loads are inefficient.
16427 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16428 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16429 unsigned NumElems = RegVT.getVectorNumElements();
16433 SDValue Ptr = Ld->getBasePtr();
16434 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16436 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16438 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16439 Ld->getPointerInfo(), Ld->isVolatile(),
16440 Ld->isNonTemporal(), Ld->isInvariant(),
16442 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16443 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16444 Ld->getPointerInfo(), Ld->isVolatile(),
16445 Ld->isNonTemporal(), Ld->isInvariant(),
16446 std::max(Alignment/2U, 1U));
16447 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16449 Load2.getValue(1));
16451 SDValue NewVec = DAG.getUNDEF(RegVT);
16452 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16453 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16454 return DCI.CombineTo(N, NewVec, TF, true);
16457 // If this is a vector EXT Load then attempt to optimize it using a
16458 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16459 // expansion is still better than scalar code.
16460 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16461 // emit a shuffle and a arithmetic shift.
16462 // TODO: It is possible to support ZExt by zeroing the undef values
16463 // during the shuffle phase or after the shuffle.
16464 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16465 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16466 assert(MemVT != RegVT && "Cannot extend to the same type");
16467 assert(MemVT.isVector() && "Must load a vector from memory");
16469 unsigned NumElems = RegVT.getVectorNumElements();
16470 unsigned MemSz = MemVT.getSizeInBits();
16471 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16473 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16476 // All sizes must be a power of two.
16477 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16480 // Attempt to load the original value using scalar loads.
16481 // Find the largest scalar type that divides the total loaded size.
16482 MVT SclrLoadTy = MVT::i8;
16483 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16484 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16485 MVT Tp = (MVT::SimpleValueType)tp;
16486 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16491 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16492 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16494 SclrLoadTy = MVT::f64;
16496 // Calculate the number of scalar loads that we need to perform
16497 // in order to load our vector from memory.
16498 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16499 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16502 unsigned loadRegZize = RegSz;
16503 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16506 // Represent our vector as a sequence of elements which are the
16507 // largest scalar that we can load.
16508 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16509 loadRegZize/SclrLoadTy.getSizeInBits());
16511 // Represent the data using the same element type that is stored in
16512 // memory. In practice, we ''widen'' MemVT.
16514 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16515 loadRegZize/MemVT.getScalarType().getSizeInBits());
16517 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16518 "Invalid vector type");
16520 // We can't shuffle using an illegal type.
16521 if (!TLI.isTypeLegal(WideVecVT))
16524 SmallVector<SDValue, 8> Chains;
16525 SDValue Ptr = Ld->getBasePtr();
16526 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16527 TLI.getPointerTy());
16528 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16530 for (unsigned i = 0; i < NumLoads; ++i) {
16531 // Perform a single load.
16532 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16533 Ptr, Ld->getPointerInfo(),
16534 Ld->isVolatile(), Ld->isNonTemporal(),
16535 Ld->isInvariant(), Ld->getAlignment());
16536 Chains.push_back(ScalarLoad.getValue(1));
16537 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16538 // another round of DAGCombining.
16540 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16542 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16543 ScalarLoad, DAG.getIntPtrConstant(i));
16545 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16548 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16551 // Bitcast the loaded value to a vector of the original element type, in
16552 // the size of the target vector type.
16553 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16554 unsigned SizeRatio = RegSz/MemSz;
16556 if (Ext == ISD::SEXTLOAD) {
16557 // If we have SSE4.1 we can directly emit a VSEXT node.
16558 if (Subtarget->hasSSE41()) {
16559 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16560 return DCI.CombineTo(N, Sext, TF, true);
16563 // Otherwise we'll shuffle the small elements in the high bits of the
16564 // larger type and perform an arithmetic shift. If the shift is not legal
16565 // it's better to scalarize.
16566 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16569 // Redistribute the loaded elements into the different locations.
16570 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16571 for (unsigned i = 0; i != NumElems; ++i)
16572 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16574 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16575 DAG.getUNDEF(WideVecVT),
16578 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16580 // Build the arithmetic shift.
16581 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16582 MemVT.getVectorElementType().getSizeInBits();
16583 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16584 DAG.getConstant(Amt, RegVT));
16586 return DCI.CombineTo(N, Shuff, TF, true);
16589 // Redistribute the loaded elements into the different locations.
16590 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16591 for (unsigned i = 0; i != NumElems; ++i)
16592 ShuffleVec[i*SizeRatio] = i;
16594 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16595 DAG.getUNDEF(WideVecVT),
16598 // Bitcast to the requested type.
16599 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16600 // Replace the original load with the new sequence
16601 // and return the new chain.
16602 return DCI.CombineTo(N, Shuff, TF, true);
16608 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16609 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16610 const X86Subtarget *Subtarget) {
16611 StoreSDNode *St = cast<StoreSDNode>(N);
16612 EVT VT = St->getValue().getValueType();
16613 EVT StVT = St->getMemoryVT();
16614 DebugLoc dl = St->getDebugLoc();
16615 SDValue StoredVal = St->getOperand(1);
16616 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16617 unsigned Alignment = St->getAlignment();
16618 bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16620 // If we are saving a concatenation of two XMM registers, perform two stores.
16621 // On Sandy Bridge, 256-bit memory operations are executed by two
16622 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16623 // memory operation.
16624 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16625 StVT == VT && !IsAligned) {
16626 unsigned NumElems = VT.getVectorNumElements();
16630 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16631 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16633 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16634 SDValue Ptr0 = St->getBasePtr();
16635 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16637 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16638 St->getPointerInfo(), St->isVolatile(),
16639 St->isNonTemporal(), Alignment);
16640 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16641 St->getPointerInfo(), St->isVolatile(),
16642 St->isNonTemporal(),
16643 std::max(Alignment/2U, 1U));
16644 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16647 // Optimize trunc store (of multiple scalars) to shuffle and store.
16648 // First, pack all of the elements in one place. Next, store to memory
16649 // in fewer chunks.
16650 if (St->isTruncatingStore() && VT.isVector()) {
16651 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16652 unsigned NumElems = VT.getVectorNumElements();
16653 assert(StVT != VT && "Cannot truncate to the same type");
16654 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16655 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16657 // From, To sizes and ElemCount must be pow of two
16658 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16659 // We are going to use the original vector elt for storing.
16660 // Accumulated smaller vector elements must be a multiple of the store size.
16661 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16663 unsigned SizeRatio = FromSz / ToSz;
16665 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16667 // Create a type on which we perform the shuffle
16668 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16669 StVT.getScalarType(), NumElems*SizeRatio);
16671 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16673 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16674 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16675 for (unsigned i = 0; i != NumElems; ++i)
16676 ShuffleVec[i] = i * SizeRatio;
16678 // Can't shuffle using an illegal type.
16679 if (!TLI.isTypeLegal(WideVecVT))
16682 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16683 DAG.getUNDEF(WideVecVT),
16685 // At this point all of the data is stored at the bottom of the
16686 // register. We now need to save it to mem.
16688 // Find the largest store unit
16689 MVT StoreType = MVT::i8;
16690 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16691 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16692 MVT Tp = (MVT::SimpleValueType)tp;
16693 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16697 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16698 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16699 (64 <= NumElems * ToSz))
16700 StoreType = MVT::f64;
16702 // Bitcast the original vector into a vector of store-size units
16703 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16704 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16705 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16706 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16707 SmallVector<SDValue, 8> Chains;
16708 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16709 TLI.getPointerTy());
16710 SDValue Ptr = St->getBasePtr();
16712 // Perform one or more big stores into memory.
16713 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16714 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16715 StoreType, ShuffWide,
16716 DAG.getIntPtrConstant(i));
16717 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16718 St->getPointerInfo(), St->isVolatile(),
16719 St->isNonTemporal(), St->getAlignment());
16720 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16721 Chains.push_back(Ch);
16724 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16728 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16729 // the FP state in cases where an emms may be missing.
16730 // A preferable solution to the general problem is to figure out the right
16731 // places to insert EMMS. This qualifies as a quick hack.
16733 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16734 if (VT.getSizeInBits() != 64)
16737 const Function *F = DAG.getMachineFunction().getFunction();
16738 bool NoImplicitFloatOps = F->getAttributes().
16739 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16740 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16741 && Subtarget->hasSSE2();
16742 if ((VT.isVector() ||
16743 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16744 isa<LoadSDNode>(St->getValue()) &&
16745 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16746 St->getChain().hasOneUse() && !St->isVolatile()) {
16747 SDNode* LdVal = St->getValue().getNode();
16748 LoadSDNode *Ld = 0;
16749 int TokenFactorIndex = -1;
16750 SmallVector<SDValue, 8> Ops;
16751 SDNode* ChainVal = St->getChain().getNode();
16752 // Must be a store of a load. We currently handle two cases: the load
16753 // is a direct child, and it's under an intervening TokenFactor. It is
16754 // possible to dig deeper under nested TokenFactors.
16755 if (ChainVal == LdVal)
16756 Ld = cast<LoadSDNode>(St->getChain());
16757 else if (St->getValue().hasOneUse() &&
16758 ChainVal->getOpcode() == ISD::TokenFactor) {
16759 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16760 if (ChainVal->getOperand(i).getNode() == LdVal) {
16761 TokenFactorIndex = i;
16762 Ld = cast<LoadSDNode>(St->getValue());
16764 Ops.push_back(ChainVal->getOperand(i));
16768 if (!Ld || !ISD::isNormalLoad(Ld))
16771 // If this is not the MMX case, i.e. we are just turning i64 load/store
16772 // into f64 load/store, avoid the transformation if there are multiple
16773 // uses of the loaded value.
16774 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16777 DebugLoc LdDL = Ld->getDebugLoc();
16778 DebugLoc StDL = N->getDebugLoc();
16779 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16780 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16782 if (Subtarget->is64Bit() || F64IsLegal) {
16783 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16784 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16785 Ld->getPointerInfo(), Ld->isVolatile(),
16786 Ld->isNonTemporal(), Ld->isInvariant(),
16787 Ld->getAlignment());
16788 SDValue NewChain = NewLd.getValue(1);
16789 if (TokenFactorIndex != -1) {
16790 Ops.push_back(NewChain);
16791 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16794 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16795 St->getPointerInfo(),
16796 St->isVolatile(), St->isNonTemporal(),
16797 St->getAlignment());
16800 // Otherwise, lower to two pairs of 32-bit loads / stores.
16801 SDValue LoAddr = Ld->getBasePtr();
16802 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16803 DAG.getConstant(4, MVT::i32));
16805 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16806 Ld->getPointerInfo(),
16807 Ld->isVolatile(), Ld->isNonTemporal(),
16808 Ld->isInvariant(), Ld->getAlignment());
16809 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16810 Ld->getPointerInfo().getWithOffset(4),
16811 Ld->isVolatile(), Ld->isNonTemporal(),
16813 MinAlign(Ld->getAlignment(), 4));
16815 SDValue NewChain = LoLd.getValue(1);
16816 if (TokenFactorIndex != -1) {
16817 Ops.push_back(LoLd);
16818 Ops.push_back(HiLd);
16819 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16823 LoAddr = St->getBasePtr();
16824 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16825 DAG.getConstant(4, MVT::i32));
16827 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16828 St->getPointerInfo(),
16829 St->isVolatile(), St->isNonTemporal(),
16830 St->getAlignment());
16831 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16832 St->getPointerInfo().getWithOffset(4),
16834 St->isNonTemporal(),
16835 MinAlign(St->getAlignment(), 4));
16836 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16841 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16842 /// and return the operands for the horizontal operation in LHS and RHS. A
16843 /// horizontal operation performs the binary operation on successive elements
16844 /// of its first operand, then on successive elements of its second operand,
16845 /// returning the resulting values in a vector. For example, if
16846 /// A = < float a0, float a1, float a2, float a3 >
16848 /// B = < float b0, float b1, float b2, float b3 >
16849 /// then the result of doing a horizontal operation on A and B is
16850 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16851 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16852 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16853 /// set to A, RHS to B, and the routine returns 'true'.
16854 /// Note that the binary operation should have the property that if one of the
16855 /// operands is UNDEF then the result is UNDEF.
16856 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16857 // Look for the following pattern: if
16858 // A = < float a0, float a1, float a2, float a3 >
16859 // B = < float b0, float b1, float b2, float b3 >
16861 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16862 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16863 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16864 // which is A horizontal-op B.
16866 // At least one of the operands should be a vector shuffle.
16867 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16868 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16871 EVT VT = LHS.getValueType();
16873 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16874 "Unsupported vector type for horizontal add/sub");
16876 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16877 // operate independently on 128-bit lanes.
16878 unsigned NumElts = VT.getVectorNumElements();
16879 unsigned NumLanes = VT.getSizeInBits()/128;
16880 unsigned NumLaneElts = NumElts / NumLanes;
16881 assert((NumLaneElts % 2 == 0) &&
16882 "Vector type should have an even number of elements in each lane");
16883 unsigned HalfLaneElts = NumLaneElts/2;
16885 // View LHS in the form
16886 // LHS = VECTOR_SHUFFLE A, B, LMask
16887 // If LHS is not a shuffle then pretend it is the shuffle
16888 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16889 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16892 SmallVector<int, 16> LMask(NumElts);
16893 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16894 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16895 A = LHS.getOperand(0);
16896 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16897 B = LHS.getOperand(1);
16898 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16899 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16901 if (LHS.getOpcode() != ISD::UNDEF)
16903 for (unsigned i = 0; i != NumElts; ++i)
16907 // Likewise, view RHS in the form
16908 // RHS = VECTOR_SHUFFLE C, D, RMask
16910 SmallVector<int, 16> RMask(NumElts);
16911 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16912 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16913 C = RHS.getOperand(0);
16914 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16915 D = RHS.getOperand(1);
16916 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16917 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16919 if (RHS.getOpcode() != ISD::UNDEF)
16921 for (unsigned i = 0; i != NumElts; ++i)
16925 // Check that the shuffles are both shuffling the same vectors.
16926 if (!(A == C && B == D) && !(A == D && B == C))
16929 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16930 if (!A.getNode() && !B.getNode())
16933 // If A and B occur in reverse order in RHS, then "swap" them (which means
16934 // rewriting the mask).
16936 CommuteVectorShuffleMask(RMask, NumElts);
16938 // At this point LHS and RHS are equivalent to
16939 // LHS = VECTOR_SHUFFLE A, B, LMask
16940 // RHS = VECTOR_SHUFFLE A, B, RMask
16941 // Check that the masks correspond to performing a horizontal operation.
16942 for (unsigned i = 0; i != NumElts; ++i) {
16943 int LIdx = LMask[i], RIdx = RMask[i];
16945 // Ignore any UNDEF components.
16946 if (LIdx < 0 || RIdx < 0 ||
16947 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16948 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16951 // Check that successive elements are being operated on. If not, this is
16952 // not a horizontal operation.
16953 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16954 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16955 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16956 if (!(LIdx == Index && RIdx == Index + 1) &&
16957 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16961 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16962 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16966 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16967 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16968 const X86Subtarget *Subtarget) {
16969 EVT VT = N->getValueType(0);
16970 SDValue LHS = N->getOperand(0);
16971 SDValue RHS = N->getOperand(1);
16973 // Try to synthesize horizontal adds from adds of shuffles.
16974 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16975 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16976 isHorizontalBinOp(LHS, RHS, true))
16977 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16981 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16982 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16983 const X86Subtarget *Subtarget) {
16984 EVT VT = N->getValueType(0);
16985 SDValue LHS = N->getOperand(0);
16986 SDValue RHS = N->getOperand(1);
16988 // Try to synthesize horizontal subs from subs of shuffles.
16989 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16990 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16991 isHorizontalBinOp(LHS, RHS, false))
16992 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16996 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16997 /// X86ISD::FXOR nodes.
16998 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16999 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17000 // F[X]OR(0.0, x) -> x
17001 // F[X]OR(x, 0.0) -> x
17002 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17003 if (C->getValueAPF().isPosZero())
17004 return N->getOperand(1);
17005 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17006 if (C->getValueAPF().isPosZero())
17007 return N->getOperand(0);
17011 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17012 /// X86ISD::FMAX nodes.
17013 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17014 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17016 // Only perform optimizations if UnsafeMath is used.
17017 if (!DAG.getTarget().Options.UnsafeFPMath)
17020 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17021 // into FMINC and FMAXC, which are Commutative operations.
17022 unsigned NewOp = 0;
17023 switch (N->getOpcode()) {
17024 default: llvm_unreachable("unknown opcode");
17025 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
17026 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
17029 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17030 N->getOperand(0), N->getOperand(1));
17033 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17034 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17035 // FAND(0.0, x) -> 0.0
17036 // FAND(x, 0.0) -> 0.0
17037 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17038 if (C->getValueAPF().isPosZero())
17039 return N->getOperand(0);
17040 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17041 if (C->getValueAPF().isPosZero())
17042 return N->getOperand(1);
17046 static SDValue PerformBTCombine(SDNode *N,
17048 TargetLowering::DAGCombinerInfo &DCI) {
17049 // BT ignores high bits in the bit index operand.
17050 SDValue Op1 = N->getOperand(1);
17051 if (Op1.hasOneUse()) {
17052 unsigned BitWidth = Op1.getValueSizeInBits();
17053 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17054 APInt KnownZero, KnownOne;
17055 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17056 !DCI.isBeforeLegalizeOps());
17057 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17058 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17059 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17060 DCI.CommitTargetLoweringOpt(TLO);
17065 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17066 SDValue Op = N->getOperand(0);
17067 if (Op.getOpcode() == ISD::BITCAST)
17068 Op = Op.getOperand(0);
17069 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17070 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17071 VT.getVectorElementType().getSizeInBits() ==
17072 OpVT.getVectorElementType().getSizeInBits()) {
17073 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17078 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17079 const X86Subtarget *Subtarget) {
17080 EVT VT = N->getValueType(0);
17081 if (!VT.isVector())
17084 SDValue N0 = N->getOperand(0);
17085 SDValue N1 = N->getOperand(1);
17086 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17087 DebugLoc dl = N->getDebugLoc();
17089 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17090 // both SSE and AVX2 since there is no sign-extended shift right
17091 // operation on a vector with 64-bit elements.
17092 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17093 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17094 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17095 N0.getOpcode() == ISD::SIGN_EXTEND)) {
17096 SDValue N00 = N0.getOperand(0);
17098 // EXTLOAD has a better solution on AVX2,
17099 // it may be replaced with X86ISD::VSEXT node.
17100 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17101 if (!ISD::isNormalLoad(N00.getNode()))
17104 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17105 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17107 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17113 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17114 TargetLowering::DAGCombinerInfo &DCI,
17115 const X86Subtarget *Subtarget) {
17116 if (!DCI.isBeforeLegalizeOps())
17119 if (!Subtarget->hasFp256())
17122 EVT VT = N->getValueType(0);
17123 if (VT.isVector() && VT.getSizeInBits() == 256) {
17124 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17132 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17133 const X86Subtarget* Subtarget) {
17134 DebugLoc dl = N->getDebugLoc();
17135 EVT VT = N->getValueType(0);
17137 // Let legalize expand this if it isn't a legal type yet.
17138 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17141 EVT ScalarVT = VT.getScalarType();
17142 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17143 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17146 SDValue A = N->getOperand(0);
17147 SDValue B = N->getOperand(1);
17148 SDValue C = N->getOperand(2);
17150 bool NegA = (A.getOpcode() == ISD::FNEG);
17151 bool NegB = (B.getOpcode() == ISD::FNEG);
17152 bool NegC = (C.getOpcode() == ISD::FNEG);
17154 // Negative multiplication when NegA xor NegB
17155 bool NegMul = (NegA != NegB);
17157 A = A.getOperand(0);
17159 B = B.getOperand(0);
17161 C = C.getOperand(0);
17165 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17167 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17169 return DAG.getNode(Opcode, dl, VT, A, B, C);
17172 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17173 TargetLowering::DAGCombinerInfo &DCI,
17174 const X86Subtarget *Subtarget) {
17175 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17176 // (and (i32 x86isd::setcc_carry), 1)
17177 // This eliminates the zext. This transformation is necessary because
17178 // ISD::SETCC is always legalized to i8.
17179 DebugLoc dl = N->getDebugLoc();
17180 SDValue N0 = N->getOperand(0);
17181 EVT VT = N->getValueType(0);
17183 if (N0.getOpcode() == ISD::AND &&
17185 N0.getOperand(0).hasOneUse()) {
17186 SDValue N00 = N0.getOperand(0);
17187 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17188 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17189 if (!C || C->getZExtValue() != 1)
17191 return DAG.getNode(ISD::AND, dl, VT,
17192 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17193 N00.getOperand(0), N00.getOperand(1)),
17194 DAG.getConstant(1, VT));
17198 if (VT.is256BitVector()) {
17199 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17207 // Optimize x == -y --> x+y == 0
17208 // x != -y --> x+y != 0
17209 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17210 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17211 SDValue LHS = N->getOperand(0);
17212 SDValue RHS = N->getOperand(1);
17214 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17216 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17217 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17218 LHS.getValueType(), RHS, LHS.getOperand(1));
17219 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17220 addV, DAG.getConstant(0, addV.getValueType()), CC);
17222 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17223 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17224 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17225 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17226 RHS.getValueType(), LHS, RHS.getOperand(1));
17227 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17228 addV, DAG.getConstant(0, addV.getValueType()), CC);
17233 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17234 // as "sbb reg,reg", since it can be extended without zext and produces
17235 // an all-ones bit which is more useful than 0/1 in some cases.
17236 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17237 return DAG.getNode(ISD::AND, DL, MVT::i8,
17238 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17239 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17240 DAG.getConstant(1, MVT::i8));
17243 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17244 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17245 TargetLowering::DAGCombinerInfo &DCI,
17246 const X86Subtarget *Subtarget) {
17247 DebugLoc DL = N->getDebugLoc();
17248 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17249 SDValue EFLAGS = N->getOperand(1);
17251 if (CC == X86::COND_A) {
17252 // Try to convert COND_A into COND_B in an attempt to facilitate
17253 // materializing "setb reg".
17255 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17256 // cannot take an immediate as its first operand.
17258 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17259 EFLAGS.getValueType().isInteger() &&
17260 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17261 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17262 EFLAGS.getNode()->getVTList(),
17263 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17264 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17265 return MaterializeSETB(DL, NewEFLAGS, DAG);
17269 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17270 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17272 if (CC == X86::COND_B)
17273 return MaterializeSETB(DL, EFLAGS, DAG);
17277 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17278 if (Flags.getNode()) {
17279 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17280 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17286 // Optimize branch condition evaluation.
17288 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17289 TargetLowering::DAGCombinerInfo &DCI,
17290 const X86Subtarget *Subtarget) {
17291 DebugLoc DL = N->getDebugLoc();
17292 SDValue Chain = N->getOperand(0);
17293 SDValue Dest = N->getOperand(1);
17294 SDValue EFLAGS = N->getOperand(3);
17295 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17299 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17300 if (Flags.getNode()) {
17301 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17302 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17309 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17310 const X86TargetLowering *XTLI) {
17311 SDValue Op0 = N->getOperand(0);
17312 EVT InVT = Op0->getValueType(0);
17314 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17315 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17316 DebugLoc dl = N->getDebugLoc();
17317 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17318 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17319 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17322 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17323 // a 32-bit target where SSE doesn't support i64->FP operations.
17324 if (Op0.getOpcode() == ISD::LOAD) {
17325 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17326 EVT VT = Ld->getValueType(0);
17327 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17328 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17329 !XTLI->getSubtarget()->is64Bit() &&
17330 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17331 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17332 Ld->getChain(), Op0, DAG);
17333 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17340 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17341 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17342 X86TargetLowering::DAGCombinerInfo &DCI) {
17343 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17344 // the result is either zero or one (depending on the input carry bit).
17345 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17346 if (X86::isZeroNode(N->getOperand(0)) &&
17347 X86::isZeroNode(N->getOperand(1)) &&
17348 // We don't have a good way to replace an EFLAGS use, so only do this when
17350 SDValue(N, 1).use_empty()) {
17351 DebugLoc DL = N->getDebugLoc();
17352 EVT VT = N->getValueType(0);
17353 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17354 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17355 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17356 DAG.getConstant(X86::COND_B,MVT::i8),
17358 DAG.getConstant(1, VT));
17359 return DCI.CombineTo(N, Res1, CarryOut);
17365 // fold (add Y, (sete X, 0)) -> adc 0, Y
17366 // (add Y, (setne X, 0)) -> sbb -1, Y
17367 // (sub (sete X, 0), Y) -> sbb 0, Y
17368 // (sub (setne X, 0), Y) -> adc -1, Y
17369 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17370 DebugLoc DL = N->getDebugLoc();
17372 // Look through ZExts.
17373 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17374 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17377 SDValue SetCC = Ext.getOperand(0);
17378 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17381 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17382 if (CC != X86::COND_E && CC != X86::COND_NE)
17385 SDValue Cmp = SetCC.getOperand(1);
17386 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17387 !X86::isZeroNode(Cmp.getOperand(1)) ||
17388 !Cmp.getOperand(0).getValueType().isInteger())
17391 SDValue CmpOp0 = Cmp.getOperand(0);
17392 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17393 DAG.getConstant(1, CmpOp0.getValueType()));
17395 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17396 if (CC == X86::COND_NE)
17397 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17398 DL, OtherVal.getValueType(), OtherVal,
17399 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17400 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17401 DL, OtherVal.getValueType(), OtherVal,
17402 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17405 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17406 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17407 const X86Subtarget *Subtarget) {
17408 EVT VT = N->getValueType(0);
17409 SDValue Op0 = N->getOperand(0);
17410 SDValue Op1 = N->getOperand(1);
17412 // Try to synthesize horizontal adds from adds of shuffles.
17413 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17414 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17415 isHorizontalBinOp(Op0, Op1, true))
17416 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17418 return OptimizeConditionalInDecrement(N, DAG);
17421 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17422 const X86Subtarget *Subtarget) {
17423 SDValue Op0 = N->getOperand(0);
17424 SDValue Op1 = N->getOperand(1);
17426 // X86 can't encode an immediate LHS of a sub. See if we can push the
17427 // negation into a preceding instruction.
17428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17429 // If the RHS of the sub is a XOR with one use and a constant, invert the
17430 // immediate. Then add one to the LHS of the sub so we can turn
17431 // X-Y -> X+~Y+1, saving one register.
17432 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17433 isa<ConstantSDNode>(Op1.getOperand(1))) {
17434 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17435 EVT VT = Op0.getValueType();
17436 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17438 DAG.getConstant(~XorC, VT));
17439 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17440 DAG.getConstant(C->getAPIntValue()+1, VT));
17444 // Try to synthesize horizontal adds from adds of shuffles.
17445 EVT VT = N->getValueType(0);
17446 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17447 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17448 isHorizontalBinOp(Op0, Op1, true))
17449 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17451 return OptimizeConditionalInDecrement(N, DAG);
17454 /// performVZEXTCombine - Performs build vector combines
17455 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17456 TargetLowering::DAGCombinerInfo &DCI,
17457 const X86Subtarget *Subtarget) {
17458 // (vzext (bitcast (vzext (x)) -> (vzext x)
17459 SDValue In = N->getOperand(0);
17460 while (In.getOpcode() == ISD::BITCAST)
17461 In = In.getOperand(0);
17463 if (In.getOpcode() != X86ISD::VZEXT)
17466 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17470 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17471 DAGCombinerInfo &DCI) const {
17472 SelectionDAG &DAG = DCI.DAG;
17473 switch (N->getOpcode()) {
17475 case ISD::EXTRACT_VECTOR_ELT:
17476 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17478 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17479 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17480 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17481 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17482 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17483 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17486 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17487 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17488 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17489 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17490 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17491 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17492 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17493 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17494 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17496 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17498 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17499 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17500 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17501 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17502 case ISD::ANY_EXTEND:
17503 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17504 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17505 case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17506 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17507 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17508 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17509 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17510 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17511 case X86ISD::SHUFP: // Handle all target specific shuffles
17512 case X86ISD::PALIGNR:
17513 case X86ISD::UNPCKH:
17514 case X86ISD::UNPCKL:
17515 case X86ISD::MOVHLPS:
17516 case X86ISD::MOVLHPS:
17517 case X86ISD::PSHUFD:
17518 case X86ISD::PSHUFHW:
17519 case X86ISD::PSHUFLW:
17520 case X86ISD::MOVSS:
17521 case X86ISD::MOVSD:
17522 case X86ISD::VPERMILP:
17523 case X86ISD::VPERM2X128:
17524 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17525 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17531 /// isTypeDesirableForOp - Return true if the target has native support for
17532 /// the specified value type and it is 'desirable' to use the type for the
17533 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17534 /// instruction encodings are longer and some i16 instructions are slow.
17535 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17536 if (!isTypeLegal(VT))
17538 if (VT != MVT::i16)
17545 case ISD::SIGN_EXTEND:
17546 case ISD::ZERO_EXTEND:
17547 case ISD::ANY_EXTEND:
17560 /// IsDesirableToPromoteOp - This method query the target whether it is
17561 /// beneficial for dag combiner to promote the specified node. If true, it
17562 /// should return the desired promotion type by reference.
17563 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17564 EVT VT = Op.getValueType();
17565 if (VT != MVT::i16)
17568 bool Promote = false;
17569 bool Commute = false;
17570 switch (Op.getOpcode()) {
17573 LoadSDNode *LD = cast<LoadSDNode>(Op);
17574 // If the non-extending load has a single use and it's not live out, then it
17575 // might be folded.
17576 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17577 Op.hasOneUse()*/) {
17578 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17579 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17580 // The only case where we'd want to promote LOAD (rather then it being
17581 // promoted as an operand is when it's only use is liveout.
17582 if (UI->getOpcode() != ISD::CopyToReg)
17589 case ISD::SIGN_EXTEND:
17590 case ISD::ZERO_EXTEND:
17591 case ISD::ANY_EXTEND:
17596 SDValue N0 = Op.getOperand(0);
17597 // Look out for (store (shl (load), x)).
17598 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17611 SDValue N0 = Op.getOperand(0);
17612 SDValue N1 = Op.getOperand(1);
17613 if (!Commute && MayFoldLoad(N1))
17615 // Avoid disabling potential load folding opportunities.
17616 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17618 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17628 //===----------------------------------------------------------------------===//
17629 // X86 Inline Assembly Support
17630 //===----------------------------------------------------------------------===//
17633 // Helper to match a string separated by whitespace.
17634 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17635 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17637 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17638 StringRef piece(*args[i]);
17639 if (!s.startswith(piece)) // Check if the piece matches.
17642 s = s.substr(piece.size());
17643 StringRef::size_type pos = s.find_first_not_of(" \t");
17644 if (pos == 0) // We matched a prefix.
17652 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17655 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17656 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17658 std::string AsmStr = IA->getAsmString();
17660 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17661 if (!Ty || Ty->getBitWidth() % 16 != 0)
17664 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17665 SmallVector<StringRef, 4> AsmPieces;
17666 SplitString(AsmStr, AsmPieces, ";\n");
17668 switch (AsmPieces.size()) {
17669 default: return false;
17671 // FIXME: this should verify that we are targeting a 486 or better. If not,
17672 // we will turn this bswap into something that will be lowered to logical
17673 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17674 // lower so don't worry about this.
17676 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17677 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17678 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17679 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17680 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17681 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17682 // No need to check constraints, nothing other than the equivalent of
17683 // "=r,0" would be valid here.
17684 return IntrinsicLowering::LowerToByteSwap(CI);
17687 // rorw $$8, ${0:w} --> llvm.bswap.i16
17688 if (CI->getType()->isIntegerTy(16) &&
17689 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17690 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17691 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17693 const std::string &ConstraintsStr = IA->getConstraintString();
17694 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17695 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17696 if (AsmPieces.size() == 4 &&
17697 AsmPieces[0] == "~{cc}" &&
17698 AsmPieces[1] == "~{dirflag}" &&
17699 AsmPieces[2] == "~{flags}" &&
17700 AsmPieces[3] == "~{fpsr}")
17701 return IntrinsicLowering::LowerToByteSwap(CI);
17705 if (CI->getType()->isIntegerTy(32) &&
17706 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17707 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17708 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17709 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17711 const std::string &ConstraintsStr = IA->getConstraintString();
17712 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17713 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17714 if (AsmPieces.size() == 4 &&
17715 AsmPieces[0] == "~{cc}" &&
17716 AsmPieces[1] == "~{dirflag}" &&
17717 AsmPieces[2] == "~{flags}" &&
17718 AsmPieces[3] == "~{fpsr}")
17719 return IntrinsicLowering::LowerToByteSwap(CI);
17722 if (CI->getType()->isIntegerTy(64)) {
17723 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17724 if (Constraints.size() >= 2 &&
17725 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17726 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17727 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17728 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17729 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17730 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17731 return IntrinsicLowering::LowerToByteSwap(CI);
17739 /// getConstraintType - Given a constraint letter, return the type of
17740 /// constraint it is for this target.
17741 X86TargetLowering::ConstraintType
17742 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17743 if (Constraint.size() == 1) {
17744 switch (Constraint[0]) {
17755 return C_RegisterClass;
17779 return TargetLowering::getConstraintType(Constraint);
17782 /// Examine constraint type and operand type and determine a weight value.
17783 /// This object must already have been set up with the operand type
17784 /// and the current alternative constraint selected.
17785 TargetLowering::ConstraintWeight
17786 X86TargetLowering::getSingleConstraintMatchWeight(
17787 AsmOperandInfo &info, const char *constraint) const {
17788 ConstraintWeight weight = CW_Invalid;
17789 Value *CallOperandVal = info.CallOperandVal;
17790 // If we don't have a value, we can't do a match,
17791 // but allow it at the lowest weight.
17792 if (CallOperandVal == NULL)
17794 Type *type = CallOperandVal->getType();
17795 // Look at the constraint type.
17796 switch (*constraint) {
17798 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17809 if (CallOperandVal->getType()->isIntegerTy())
17810 weight = CW_SpecificReg;
17815 if (type->isFloatingPointTy())
17816 weight = CW_SpecificReg;
17819 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17820 weight = CW_SpecificReg;
17824 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17825 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17826 weight = CW_Register;
17829 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17830 if (C->getZExtValue() <= 31)
17831 weight = CW_Constant;
17835 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17836 if (C->getZExtValue() <= 63)
17837 weight = CW_Constant;
17841 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17842 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17843 weight = CW_Constant;
17847 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17848 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17849 weight = CW_Constant;
17853 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17854 if (C->getZExtValue() <= 3)
17855 weight = CW_Constant;
17859 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17860 if (C->getZExtValue() <= 0xff)
17861 weight = CW_Constant;
17866 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17867 weight = CW_Constant;
17871 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17872 if ((C->getSExtValue() >= -0x80000000LL) &&
17873 (C->getSExtValue() <= 0x7fffffffLL))
17874 weight = CW_Constant;
17878 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17879 if (C->getZExtValue() <= 0xffffffff)
17880 weight = CW_Constant;
17887 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17888 /// with another that has more specific requirements based on the type of the
17889 /// corresponding operand.
17890 const char *X86TargetLowering::
17891 LowerXConstraint(EVT ConstraintVT) const {
17892 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17893 // 'f' like normal targets.
17894 if (ConstraintVT.isFloatingPoint()) {
17895 if (Subtarget->hasSSE2())
17897 if (Subtarget->hasSSE1())
17901 return TargetLowering::LowerXConstraint(ConstraintVT);
17904 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17905 /// vector. If it is invalid, don't add anything to Ops.
17906 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17907 std::string &Constraint,
17908 std::vector<SDValue>&Ops,
17909 SelectionDAG &DAG) const {
17910 SDValue Result(0, 0);
17912 // Only support length 1 constraints for now.
17913 if (Constraint.length() > 1) return;
17915 char ConstraintLetter = Constraint[0];
17916 switch (ConstraintLetter) {
17919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17920 if (C->getZExtValue() <= 31) {
17921 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17927 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17928 if (C->getZExtValue() <= 63) {
17929 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17936 if (isInt<8>(C->getSExtValue())) {
17937 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17943 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17944 if (C->getZExtValue() <= 255) {
17945 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17951 // 32-bit signed value
17952 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17953 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17954 C->getSExtValue())) {
17955 // Widen to 64 bits here to get it sign extended.
17956 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17959 // FIXME gcc accepts some relocatable values here too, but only in certain
17960 // memory models; it's complicated.
17965 // 32-bit unsigned value
17966 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17967 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17968 C->getZExtValue())) {
17969 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17973 // FIXME gcc accepts some relocatable values here too, but only in certain
17974 // memory models; it's complicated.
17978 // Literal immediates are always ok.
17979 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17980 // Widen to 64 bits here to get it sign extended.
17981 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17985 // In any sort of PIC mode addresses need to be computed at runtime by
17986 // adding in a register or some sort of table lookup. These can't
17987 // be used as immediates.
17988 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17991 // If we are in non-pic codegen mode, we allow the address of a global (with
17992 // an optional displacement) to be used with 'i'.
17993 GlobalAddressSDNode *GA = 0;
17994 int64_t Offset = 0;
17996 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17998 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17999 Offset += GA->getOffset();
18001 } else if (Op.getOpcode() == ISD::ADD) {
18002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18003 Offset += C->getZExtValue();
18004 Op = Op.getOperand(0);
18007 } else if (Op.getOpcode() == ISD::SUB) {
18008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18009 Offset += -C->getZExtValue();
18010 Op = Op.getOperand(0);
18015 // Otherwise, this isn't something we can handle, reject it.
18019 const GlobalValue *GV = GA->getGlobal();
18020 // If we require an extra load to get this address, as in PIC mode, we
18021 // can't accept it.
18022 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18023 getTargetMachine())))
18026 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18027 GA->getValueType(0), Offset);
18032 if (Result.getNode()) {
18033 Ops.push_back(Result);
18036 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18039 std::pair<unsigned, const TargetRegisterClass*>
18040 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18042 // First, see if this is a constraint that directly corresponds to an LLVM
18044 if (Constraint.size() == 1) {
18045 // GCC Constraint Letters
18046 switch (Constraint[0]) {
18048 // TODO: Slight differences here in allocation order and leaving
18049 // RIP in the class. Do they matter any more here than they do
18050 // in the normal allocation?
18051 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18052 if (Subtarget->is64Bit()) {
18053 if (VT == MVT::i32 || VT == MVT::f32)
18054 return std::make_pair(0U, &X86::GR32RegClass);
18055 if (VT == MVT::i16)
18056 return std::make_pair(0U, &X86::GR16RegClass);
18057 if (VT == MVT::i8 || VT == MVT::i1)
18058 return std::make_pair(0U, &X86::GR8RegClass);
18059 if (VT == MVT::i64 || VT == MVT::f64)
18060 return std::make_pair(0U, &X86::GR64RegClass);
18063 // 32-bit fallthrough
18064 case 'Q': // Q_REGS
18065 if (VT == MVT::i32 || VT == MVT::f32)
18066 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18067 if (VT == MVT::i16)
18068 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18069 if (VT == MVT::i8 || VT == MVT::i1)
18070 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18071 if (VT == MVT::i64)
18072 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18074 case 'r': // GENERAL_REGS
18075 case 'l': // INDEX_REGS
18076 if (VT == MVT::i8 || VT == MVT::i1)
18077 return std::make_pair(0U, &X86::GR8RegClass);
18078 if (VT == MVT::i16)
18079 return std::make_pair(0U, &X86::GR16RegClass);
18080 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18081 return std::make_pair(0U, &X86::GR32RegClass);
18082 return std::make_pair(0U, &X86::GR64RegClass);
18083 case 'R': // LEGACY_REGS
18084 if (VT == MVT::i8 || VT == MVT::i1)
18085 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18086 if (VT == MVT::i16)
18087 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18088 if (VT == MVT::i32 || !Subtarget->is64Bit())
18089 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18090 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18091 case 'f': // FP Stack registers.
18092 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18093 // value to the correct fpstack register class.
18094 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18095 return std::make_pair(0U, &X86::RFP32RegClass);
18096 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18097 return std::make_pair(0U, &X86::RFP64RegClass);
18098 return std::make_pair(0U, &X86::RFP80RegClass);
18099 case 'y': // MMX_REGS if MMX allowed.
18100 if (!Subtarget->hasMMX()) break;
18101 return std::make_pair(0U, &X86::VR64RegClass);
18102 case 'Y': // SSE_REGS if SSE2 allowed
18103 if (!Subtarget->hasSSE2()) break;
18105 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18106 if (!Subtarget->hasSSE1()) break;
18108 switch (VT.getSimpleVT().SimpleTy) {
18110 // Scalar SSE types.
18113 return std::make_pair(0U, &X86::FR32RegClass);
18116 return std::make_pair(0U, &X86::FR64RegClass);
18124 return std::make_pair(0U, &X86::VR128RegClass);
18132 return std::make_pair(0U, &X86::VR256RegClass);
18138 // Use the default implementation in TargetLowering to convert the register
18139 // constraint into a member of a register class.
18140 std::pair<unsigned, const TargetRegisterClass*> Res;
18141 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18143 // Not found as a standard register?
18144 if (Res.second == 0) {
18145 // Map st(0) -> st(7) -> ST0
18146 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18147 tolower(Constraint[1]) == 's' &&
18148 tolower(Constraint[2]) == 't' &&
18149 Constraint[3] == '(' &&
18150 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18151 Constraint[5] == ')' &&
18152 Constraint[6] == '}') {
18154 Res.first = X86::ST0+Constraint[4]-'0';
18155 Res.second = &X86::RFP80RegClass;
18159 // GCC allows "st(0)" to be called just plain "st".
18160 if (StringRef("{st}").equals_lower(Constraint)) {
18161 Res.first = X86::ST0;
18162 Res.second = &X86::RFP80RegClass;
18167 if (StringRef("{flags}").equals_lower(Constraint)) {
18168 Res.first = X86::EFLAGS;
18169 Res.second = &X86::CCRRegClass;
18173 // 'A' means EAX + EDX.
18174 if (Constraint == "A") {
18175 Res.first = X86::EAX;
18176 Res.second = &X86::GR32_ADRegClass;
18182 // Otherwise, check to see if this is a register class of the wrong value
18183 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18184 // turn into {ax},{dx}.
18185 if (Res.second->hasType(VT))
18186 return Res; // Correct type already, nothing to do.
18188 // All of the single-register GCC register classes map their values onto
18189 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18190 // really want an 8-bit or 32-bit register, map to the appropriate register
18191 // class and return the appropriate register.
18192 if (Res.second == &X86::GR16RegClass) {
18193 if (VT == MVT::i8 || VT == MVT::i1) {
18194 unsigned DestReg = 0;
18195 switch (Res.first) {
18197 case X86::AX: DestReg = X86::AL; break;
18198 case X86::DX: DestReg = X86::DL; break;
18199 case X86::CX: DestReg = X86::CL; break;
18200 case X86::BX: DestReg = X86::BL; break;
18203 Res.first = DestReg;
18204 Res.second = &X86::GR8RegClass;
18206 } else if (VT == MVT::i32 || VT == MVT::f32) {
18207 unsigned DestReg = 0;
18208 switch (Res.first) {
18210 case X86::AX: DestReg = X86::EAX; break;
18211 case X86::DX: DestReg = X86::EDX; break;
18212 case X86::CX: DestReg = X86::ECX; break;
18213 case X86::BX: DestReg = X86::EBX; break;
18214 case X86::SI: DestReg = X86::ESI; break;
18215 case X86::DI: DestReg = X86::EDI; break;
18216 case X86::BP: DestReg = X86::EBP; break;
18217 case X86::SP: DestReg = X86::ESP; break;
18220 Res.first = DestReg;
18221 Res.second = &X86::GR32RegClass;
18223 } else if (VT == MVT::i64 || VT == MVT::f64) {
18224 unsigned DestReg = 0;
18225 switch (Res.first) {
18227 case X86::AX: DestReg = X86::RAX; break;
18228 case X86::DX: DestReg = X86::RDX; break;
18229 case X86::CX: DestReg = X86::RCX; break;
18230 case X86::BX: DestReg = X86::RBX; break;
18231 case X86::SI: DestReg = X86::RSI; break;
18232 case X86::DI: DestReg = X86::RDI; break;
18233 case X86::BP: DestReg = X86::RBP; break;
18234 case X86::SP: DestReg = X86::RSP; break;
18237 Res.first = DestReg;
18238 Res.second = &X86::GR64RegClass;
18241 } else if (Res.second == &X86::FR32RegClass ||
18242 Res.second == &X86::FR64RegClass ||
18243 Res.second == &X86::VR128RegClass) {
18244 // Handle references to XMM physical registers that got mapped into the
18245 // wrong class. This can happen with constraints like {xmm0} where the
18246 // target independent register mapper will just pick the first match it can
18247 // find, ignoring the required type.
18249 if (VT == MVT::f32 || VT == MVT::i32)
18250 Res.second = &X86::FR32RegClass;
18251 else if (VT == MVT::f64 || VT == MVT::i64)
18252 Res.second = &X86::FR64RegClass;
18253 else if (X86::VR128RegClass.hasType(VT))
18254 Res.second = &X86::VR128RegClass;
18255 else if (X86::VR256RegClass.hasType(VT))
18256 Res.second = &X86::VR256RegClass;