1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/Constants.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Function.h"
37 #include "llvm/GlobalAlias.h"
38 #include "llvm/GlobalVariable.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Intrinsics.h"
41 #include "llvm/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
874 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
875 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
876 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
877 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
878 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
879 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
880 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
881 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
882 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
883 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
884 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
885 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
887 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
889 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
890 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
892 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
894 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
898 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
899 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
900 MVT VT = (MVT::SimpleValueType)i;
901 // Do not attempt to custom lower non-power-of-2 vectors
902 if (!isPowerOf2_32(VT.getVectorNumElements()))
904 // Do not attempt to custom lower non-128-bit vectors
905 if (!VT.is128BitVector())
907 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
908 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
909 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
912 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
914 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
916 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
919 if (Subtarget->is64Bit()) {
920 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
921 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
924 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
925 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
926 MVT VT = (MVT::SimpleValueType)i;
928 // Do not attempt to promote non-128-bit vectors
929 if (!VT.is128BitVector())
932 setOperationAction(ISD::AND, VT, Promote);
933 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
934 setOperationAction(ISD::OR, VT, Promote);
935 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
936 setOperationAction(ISD::XOR, VT, Promote);
937 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
938 setOperationAction(ISD::LOAD, VT, Promote);
939 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
940 setOperationAction(ISD::SELECT, VT, Promote);
941 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
944 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
946 // Custom lower v2i64 and v2f64 selects.
947 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
948 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
949 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
950 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
952 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
953 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
955 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
957 // As there is no 64-bit GPR available, we need build a special custom
958 // sequence to convert from v2i32 to v2f32.
959 if (!Subtarget->is64Bit())
960 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
962 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
965 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
968 if (Subtarget->hasSSE41()) {
969 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
970 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
971 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
972 setOperationAction(ISD::FRINT, MVT::f32, Legal);
973 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
974 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
975 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
976 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
977 setOperationAction(ISD::FRINT, MVT::f64, Legal);
978 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
980 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
981 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
982 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
983 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
984 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
986 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
987 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
988 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
989 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
991 // FIXME: Do we need to handle scalar-to-vector here?
992 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
994 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1000 // i8 and i16 vectors are custom , because the source register and source
1001 // source memory operand types are not the same width. f32 vectors are
1002 // custom since the immediate controlling the insert encodes additional
1004 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1009 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1014 // FIXME: these should be Legal but thats only for the case where
1015 // the index is constant. For now custom expand to deal with that.
1016 if (Subtarget->is64Bit()) {
1017 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1018 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1022 if (Subtarget->hasSSE2()) {
1023 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1024 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1026 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1027 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1029 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1030 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1032 if (Subtarget->hasInt256()) {
1033 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1034 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1036 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1037 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1039 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1041 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1042 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1044 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1045 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1047 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1051 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1052 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1053 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1054 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1055 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1059 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1060 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1061 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1063 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1064 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1065 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1066 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1074 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1076 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1077 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1078 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1079 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1087 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1089 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1091 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1093 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1094 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1095 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1097 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1098 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1099 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1101 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1103 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1104 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1106 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1107 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1109 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1110 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1112 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1114 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1115 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1117 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1118 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1119 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1121 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1122 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1123 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1124 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1126 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1127 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1128 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1129 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1130 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1131 setOperationAction(ISD::FMA, MVT::f32, Legal);
1132 setOperationAction(ISD::FMA, MVT::f64, Legal);
1135 if (Subtarget->hasInt256()) {
1136 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1137 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1138 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1139 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1141 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1142 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1143 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1144 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1146 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1147 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1148 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1149 // Don't lower v32i8 because there is no 128-bit byte mul
1151 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1153 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1154 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1156 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1157 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1159 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1161 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1162 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1163 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1164 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1166 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1167 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1168 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1169 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1171 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1172 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1173 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1174 // Don't lower v32i8 because there is no 128-bit byte mul
1176 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1177 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1179 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1180 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1182 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1185 // Custom lower several nodes for 256-bit types.
1186 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1187 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1188 MVT VT = (MVT::SimpleValueType)i;
1190 // Extract subvector is special because the value type
1191 // (result) is 128-bit but the source is 256-bit wide.
1192 if (VT.is128BitVector())
1193 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1195 // Do not attempt to custom lower other non-256-bit vectors
1196 if (!VT.is256BitVector())
1199 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1200 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1201 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1202 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1203 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1204 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1205 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1208 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1209 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1210 MVT VT = (MVT::SimpleValueType)i;
1212 // Do not attempt to promote non-256-bit vectors
1213 if (!VT.is256BitVector())
1216 setOperationAction(ISD::AND, VT, Promote);
1217 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1218 setOperationAction(ISD::OR, VT, Promote);
1219 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1220 setOperationAction(ISD::XOR, VT, Promote);
1221 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1222 setOperationAction(ISD::LOAD, VT, Promote);
1223 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1224 setOperationAction(ISD::SELECT, VT, Promote);
1225 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1229 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1230 // of this type with custom code.
1231 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1232 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1233 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1237 // We want to custom lower some of our intrinsics.
1238 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1239 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1242 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1243 // handle type legalization for these operations here.
1245 // FIXME: We really should do custom legalization for addition and
1246 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1247 // than generic legalization for 64-bit multiplication-with-overflow, though.
1248 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1249 // Add/Sub/Mul with overflow operations are custom lowered.
1251 setOperationAction(ISD::SADDO, VT, Custom);
1252 setOperationAction(ISD::UADDO, VT, Custom);
1253 setOperationAction(ISD::SSUBO, VT, Custom);
1254 setOperationAction(ISD::USUBO, VT, Custom);
1255 setOperationAction(ISD::SMULO, VT, Custom);
1256 setOperationAction(ISD::UMULO, VT, Custom);
1259 // There are no 8-bit 3-address imul/mul instructions
1260 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1261 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1263 if (!Subtarget->is64Bit()) {
1264 // These libcalls are not available in 32-bit.
1265 setLibcallName(RTLIB::SHL_I128, 0);
1266 setLibcallName(RTLIB::SRL_I128, 0);
1267 setLibcallName(RTLIB::SRA_I128, 0);
1270 // We have target-specific dag combine patterns for the following nodes:
1271 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1272 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1273 setTargetDAGCombine(ISD::VSELECT);
1274 setTargetDAGCombine(ISD::SELECT);
1275 setTargetDAGCombine(ISD::SHL);
1276 setTargetDAGCombine(ISD::SRA);
1277 setTargetDAGCombine(ISD::SRL);
1278 setTargetDAGCombine(ISD::OR);
1279 setTargetDAGCombine(ISD::AND);
1280 setTargetDAGCombine(ISD::ADD);
1281 setTargetDAGCombine(ISD::FADD);
1282 setTargetDAGCombine(ISD::FSUB);
1283 setTargetDAGCombine(ISD::FMA);
1284 setTargetDAGCombine(ISD::SUB);
1285 setTargetDAGCombine(ISD::LOAD);
1286 setTargetDAGCombine(ISD::STORE);
1287 setTargetDAGCombine(ISD::ZERO_EXTEND);
1288 setTargetDAGCombine(ISD::ANY_EXTEND);
1289 setTargetDAGCombine(ISD::SIGN_EXTEND);
1290 setTargetDAGCombine(ISD::TRUNCATE);
1291 setTargetDAGCombine(ISD::SINT_TO_FP);
1292 setTargetDAGCombine(ISD::SETCC);
1293 if (Subtarget->is64Bit())
1294 setTargetDAGCombine(ISD::MUL);
1295 setTargetDAGCombine(ISD::XOR);
1297 computeRegisterProperties();
1299 // On Darwin, -Os means optimize for size without hurting performance,
1300 // do not reduce the limit.
1301 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1302 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1303 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1304 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1305 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1306 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1307 setPrefLoopAlignment(4); // 2^4 bytes.
1308 benefitFromCodePlacementOpt = true;
1310 // Predictable cmov don't hurt on atom because it's in-order.
1311 predictableSelectIsExpensive = !Subtarget->isAtom();
1313 setPrefFunctionAlignment(4); // 2^4 bytes.
1317 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1318 if (!VT.isVector()) return MVT::i8;
1319 return VT.changeVectorElementTypeToInteger();
1323 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1324 /// the desired ByVal argument alignment.
1325 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1328 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1329 if (VTy->getBitWidth() == 128)
1331 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1332 unsigned EltAlign = 0;
1333 getMaxByValAlign(ATy->getElementType(), EltAlign);
1334 if (EltAlign > MaxAlign)
1335 MaxAlign = EltAlign;
1336 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1337 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1338 unsigned EltAlign = 0;
1339 getMaxByValAlign(STy->getElementType(i), EltAlign);
1340 if (EltAlign > MaxAlign)
1341 MaxAlign = EltAlign;
1348 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1349 /// function arguments in the caller parameter area. For X86, aggregates
1350 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1351 /// are at 4-byte boundaries.
1352 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1353 if (Subtarget->is64Bit()) {
1354 // Max of 8 and alignment of type.
1355 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1362 if (Subtarget->hasSSE1())
1363 getMaxByValAlign(Ty, Align);
1367 /// getOptimalMemOpType - Returns the target specific optimal type for load
1368 /// and store operations as a result of memset, memcpy, and memmove
1369 /// lowering. If DstAlign is zero that means it's safe to destination
1370 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1371 /// means there isn't a need to check it against alignment requirement,
1372 /// probably because the source does not need to be loaded. If
1373 /// 'IsZeroVal' is true, that means it's safe to return a
1374 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1375 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1376 /// constant so it does not need to be loaded.
1377 /// It returns EVT::Other if the type should be determined using generic
1378 /// target-independent logic.
1380 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1381 unsigned DstAlign, unsigned SrcAlign,
1384 MachineFunction &MF) const {
1385 const Function *F = MF.getFunction();
1387 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1389 (Subtarget->isUnalignedMemAccessFast() ||
1390 ((DstAlign == 0 || DstAlign >= 16) &&
1391 (SrcAlign == 0 || SrcAlign >= 16)))) {
1393 if (Subtarget->hasInt256())
1395 if (Subtarget->hasFp256())
1398 if (Subtarget->hasSSE2())
1400 if (Subtarget->hasSSE1())
1402 } else if (!MemcpyStrSrc && Size >= 8 &&
1403 !Subtarget->is64Bit() &&
1404 Subtarget->hasSSE2()) {
1405 // Do not use f64 to lower memcpy if source is string constant. It's
1406 // better to use i32 to avoid the loads.
1410 if (Subtarget->is64Bit() && Size >= 8)
1415 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1416 /// current function. The returned value is a member of the
1417 /// MachineJumpTableInfo::JTEntryKind enum.
1418 unsigned X86TargetLowering::getJumpTableEncoding() const {
1419 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1421 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1422 Subtarget->isPICStyleGOT())
1423 return MachineJumpTableInfo::EK_Custom32;
1425 // Otherwise, use the normal jump table encoding heuristics.
1426 return TargetLowering::getJumpTableEncoding();
1430 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1431 const MachineBasicBlock *MBB,
1432 unsigned uid,MCContext &Ctx) const{
1433 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1434 Subtarget->isPICStyleGOT());
1435 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1437 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1438 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1441 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1443 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1444 SelectionDAG &DAG) const {
1445 if (!Subtarget->is64Bit())
1446 // This doesn't have DebugLoc associated with it, but is not really the
1447 // same as a Register.
1448 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1452 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1453 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1455 const MCExpr *X86TargetLowering::
1456 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1457 MCContext &Ctx) const {
1458 // X86-64 uses RIP relative addressing based on the jump table label.
1459 if (Subtarget->isPICStyleRIPRel())
1460 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1462 // Otherwise, the reference is relative to the PIC base.
1463 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1466 // FIXME: Why this routine is here? Move to RegInfo!
1467 std::pair<const TargetRegisterClass*, uint8_t>
1468 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1469 const TargetRegisterClass *RRC = 0;
1471 switch (VT.getSimpleVT().SimpleTy) {
1473 return TargetLowering::findRepresentativeClass(VT);
1474 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1475 RRC = Subtarget->is64Bit() ?
1476 (const TargetRegisterClass*)&X86::GR64RegClass :
1477 (const TargetRegisterClass*)&X86::GR32RegClass;
1480 RRC = &X86::VR64RegClass;
1482 case MVT::f32: case MVT::f64:
1483 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1484 case MVT::v4f32: case MVT::v2f64:
1485 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1487 RRC = &X86::VR128RegClass;
1490 return std::make_pair(RRC, Cost);
1493 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1494 unsigned &Offset) const {
1495 if (!Subtarget->isTargetLinux())
1498 if (Subtarget->is64Bit()) {
1499 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1501 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1514 //===----------------------------------------------------------------------===//
1515 // Return Value Calling Convention Implementation
1516 //===----------------------------------------------------------------------===//
1518 #include "X86GenCallingConv.inc"
1521 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1522 MachineFunction &MF, bool isVarArg,
1523 const SmallVectorImpl<ISD::OutputArg> &Outs,
1524 LLVMContext &Context) const {
1525 SmallVector<CCValAssign, 16> RVLocs;
1526 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1528 return CCInfo.CheckReturn(Outs, RetCC_X86);
1532 X86TargetLowering::LowerReturn(SDValue Chain,
1533 CallingConv::ID CallConv, bool isVarArg,
1534 const SmallVectorImpl<ISD::OutputArg> &Outs,
1535 const SmallVectorImpl<SDValue> &OutVals,
1536 DebugLoc dl, SelectionDAG &DAG) const {
1537 MachineFunction &MF = DAG.getMachineFunction();
1538 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1540 SmallVector<CCValAssign, 16> RVLocs;
1541 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1542 RVLocs, *DAG.getContext());
1543 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1545 // Add the regs to the liveout set for the function.
1546 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1547 for (unsigned i = 0; i != RVLocs.size(); ++i)
1548 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1549 MRI.addLiveOut(RVLocs[i].getLocReg());
1553 SmallVector<SDValue, 6> RetOps;
1554 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1555 // Operand #1 = Bytes To Pop
1556 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1559 // Copy the result values into the output registers.
1560 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1561 CCValAssign &VA = RVLocs[i];
1562 assert(VA.isRegLoc() && "Can only return in registers!");
1563 SDValue ValToCopy = OutVals[i];
1564 EVT ValVT = ValToCopy.getValueType();
1566 // Promote values to the appropriate types
1567 if (VA.getLocInfo() == CCValAssign::SExt)
1568 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1569 else if (VA.getLocInfo() == CCValAssign::ZExt)
1570 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1571 else if (VA.getLocInfo() == CCValAssign::AExt)
1572 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1573 else if (VA.getLocInfo() == CCValAssign::BCvt)
1574 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1576 // If this is x86-64, and we disabled SSE, we can't return FP values,
1577 // or SSE or MMX vectors.
1578 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1579 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1580 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1581 report_fatal_error("SSE register return with SSE disabled");
1583 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1584 // llvm-gcc has never done it right and no one has noticed, so this
1585 // should be OK for now.
1586 if (ValVT == MVT::f64 &&
1587 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1588 report_fatal_error("SSE2 register return with SSE2 disabled");
1590 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1591 // the RET instruction and handled by the FP Stackifier.
1592 if (VA.getLocReg() == X86::ST0 ||
1593 VA.getLocReg() == X86::ST1) {
1594 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1595 // change the value to the FP stack register class.
1596 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1597 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1598 RetOps.push_back(ValToCopy);
1599 // Don't emit a copytoreg.
1603 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1604 // which is returned in RAX / RDX.
1605 if (Subtarget->is64Bit()) {
1606 if (ValVT == MVT::x86mmx) {
1607 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1608 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1609 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1611 // If we don't have SSE2 available, convert to v4f32 so the generated
1612 // register is legal.
1613 if (!Subtarget->hasSSE2())
1614 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1619 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1620 Flag = Chain.getValue(1);
1623 // The x86-64 ABI for returning structs by value requires that we copy
1624 // the sret argument into %rax for the return. We saved the argument into
1625 // a virtual register in the entry block, so now we copy the value out
1627 if (Subtarget->is64Bit() &&
1628 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1629 MachineFunction &MF = DAG.getMachineFunction();
1630 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1631 unsigned Reg = FuncInfo->getSRetReturnReg();
1633 "SRetReturnReg should have been set in LowerFormalArguments().");
1634 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1636 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1637 Flag = Chain.getValue(1);
1639 // RAX now acts like a return value.
1640 MRI.addLiveOut(X86::RAX);
1643 RetOps[0] = Chain; // Update chain.
1645 // Add the flag if we have it.
1647 RetOps.push_back(Flag);
1649 return DAG.getNode(X86ISD::RET_FLAG, dl,
1650 MVT::Other, &RetOps[0], RetOps.size());
1653 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1654 if (N->getNumValues() != 1)
1656 if (!N->hasNUsesOfValue(1, 0))
1659 SDValue TCChain = Chain;
1660 SDNode *Copy = *N->use_begin();
1661 if (Copy->getOpcode() == ISD::CopyToReg) {
1662 // If the copy has a glue operand, we conservatively assume it isn't safe to
1663 // perform a tail call.
1664 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1666 TCChain = Copy->getOperand(0);
1667 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1670 bool HasRet = false;
1671 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1673 if (UI->getOpcode() != X86ISD::RET_FLAG)
1686 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1687 ISD::NodeType ExtendKind) const {
1689 // TODO: Is this also valid on 32-bit?
1690 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1691 ReturnMVT = MVT::i8;
1693 ReturnMVT = MVT::i32;
1695 EVT MinVT = getRegisterType(Context, ReturnMVT);
1696 return VT.bitsLT(MinVT) ? MinVT : VT;
1699 /// LowerCallResult - Lower the result values of a call into the
1700 /// appropriate copies out of appropriate physical registers.
1703 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1704 CallingConv::ID CallConv, bool isVarArg,
1705 const SmallVectorImpl<ISD::InputArg> &Ins,
1706 DebugLoc dl, SelectionDAG &DAG,
1707 SmallVectorImpl<SDValue> &InVals) const {
1709 // Assign locations to each value returned by this call.
1710 SmallVector<CCValAssign, 16> RVLocs;
1711 bool Is64Bit = Subtarget->is64Bit();
1712 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1713 getTargetMachine(), RVLocs, *DAG.getContext());
1714 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1716 // Copy all of the result registers out of their specified physreg.
1717 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1718 CCValAssign &VA = RVLocs[i];
1719 EVT CopyVT = VA.getValVT();
1721 // If this is x86-64, and we disabled SSE, we can't return FP values
1722 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1723 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1724 report_fatal_error("SSE register return with SSE disabled");
1729 // If this is a call to a function that returns an fp value on the floating
1730 // point stack, we must guarantee the value is popped from the stack, so
1731 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1732 // if the return value is not used. We use the FpPOP_RETVAL instruction
1734 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1735 // If we prefer to use the value in xmm registers, copy it out as f80 and
1736 // use a truncate to move it from fp stack reg to xmm reg.
1737 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1738 SDValue Ops[] = { Chain, InFlag };
1739 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1740 MVT::Other, MVT::Glue, Ops, 2), 1);
1741 Val = Chain.getValue(0);
1743 // Round the f80 to the right size, which also moves it to the appropriate
1745 if (CopyVT != VA.getValVT())
1746 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1747 // This truncation won't change the value.
1748 DAG.getIntPtrConstant(1));
1750 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1751 CopyVT, InFlag).getValue(1);
1752 Val = Chain.getValue(0);
1754 InFlag = Chain.getValue(2);
1755 InVals.push_back(Val);
1762 //===----------------------------------------------------------------------===//
1763 // C & StdCall & Fast Calling Convention implementation
1764 //===----------------------------------------------------------------------===//
1765 // StdCall calling convention seems to be standard for many Windows' API
1766 // routines and around. It differs from C calling convention just a little:
1767 // callee should clean up the stack, not caller. Symbols should be also
1768 // decorated in some fancy way :) It doesn't support any vector arguments.
1769 // For info on fast calling convention see Fast Calling Convention (tail call)
1770 // implementation LowerX86_32FastCCCallTo.
1772 /// CallIsStructReturn - Determines whether a call uses struct return
1774 enum StructReturnType {
1779 static StructReturnType
1780 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1782 return NotStructReturn;
1784 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1785 if (!Flags.isSRet())
1786 return NotStructReturn;
1787 if (Flags.isInReg())
1788 return RegStructReturn;
1789 return StackStructReturn;
1792 /// ArgsAreStructReturn - Determines whether a function uses struct
1793 /// return semantics.
1794 static StructReturnType
1795 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1797 return NotStructReturn;
1799 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1800 if (!Flags.isSRet())
1801 return NotStructReturn;
1802 if (Flags.isInReg())
1803 return RegStructReturn;
1804 return StackStructReturn;
1807 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1808 /// by "Src" to address "Dst" with size and alignment information specified by
1809 /// the specific parameter attribute. The copy will be passed as a byval
1810 /// function parameter.
1812 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1813 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1815 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1817 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1818 /*isVolatile*/false, /*AlwaysInline=*/true,
1819 MachinePointerInfo(), MachinePointerInfo());
1822 /// IsTailCallConvention - Return true if the calling convention is one that
1823 /// supports tail call optimization.
1824 static bool IsTailCallConvention(CallingConv::ID CC) {
1825 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1826 CC == CallingConv::HiPE);
1829 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1830 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1834 CallingConv::ID CalleeCC = CS.getCallingConv();
1835 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1841 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1842 /// a tailcall target by changing its ABI.
1843 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1844 bool GuaranteedTailCallOpt) {
1845 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1849 X86TargetLowering::LowerMemArgument(SDValue Chain,
1850 CallingConv::ID CallConv,
1851 const SmallVectorImpl<ISD::InputArg> &Ins,
1852 DebugLoc dl, SelectionDAG &DAG,
1853 const CCValAssign &VA,
1854 MachineFrameInfo *MFI,
1856 // Create the nodes corresponding to a load from this parameter slot.
1857 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1858 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1859 getTargetMachine().Options.GuaranteedTailCallOpt);
1860 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1863 // If value is passed by pointer we have address passed instead of the value
1865 if (VA.getLocInfo() == CCValAssign::Indirect)
1866 ValVT = VA.getLocVT();
1868 ValVT = VA.getValVT();
1870 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1871 // changed with more analysis.
1872 // In case of tail call optimization mark all arguments mutable. Since they
1873 // could be overwritten by lowering of arguments in case of a tail call.
1874 if (Flags.isByVal()) {
1875 unsigned Bytes = Flags.getByValSize();
1876 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1877 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1878 return DAG.getFrameIndex(FI, getPointerTy());
1880 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1881 VA.getLocMemOffset(), isImmutable);
1882 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1883 return DAG.getLoad(ValVT, dl, Chain, FIN,
1884 MachinePointerInfo::getFixedStack(FI),
1885 false, false, false, 0);
1890 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1891 CallingConv::ID CallConv,
1893 const SmallVectorImpl<ISD::InputArg> &Ins,
1896 SmallVectorImpl<SDValue> &InVals)
1898 MachineFunction &MF = DAG.getMachineFunction();
1899 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1901 const Function* Fn = MF.getFunction();
1902 if (Fn->hasExternalLinkage() &&
1903 Subtarget->isTargetCygMing() &&
1904 Fn->getName() == "main")
1905 FuncInfo->setForceFramePointer(true);
1907 MachineFrameInfo *MFI = MF.getFrameInfo();
1908 bool Is64Bit = Subtarget->is64Bit();
1909 bool IsWindows = Subtarget->isTargetWindows();
1910 bool IsWin64 = Subtarget->isTargetWin64();
1912 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1913 "Var args not supported with calling convention fastcc, ghc or hipe");
1915 // Assign locations to all of the incoming arguments.
1916 SmallVector<CCValAssign, 16> ArgLocs;
1917 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1918 ArgLocs, *DAG.getContext());
1920 // Allocate shadow area for Win64
1922 CCInfo.AllocateStack(32, 8);
1925 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1927 unsigned LastVal = ~0U;
1929 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1930 CCValAssign &VA = ArgLocs[i];
1931 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1933 assert(VA.getValNo() != LastVal &&
1934 "Don't support value assigned to multiple locs yet");
1936 LastVal = VA.getValNo();
1938 if (VA.isRegLoc()) {
1939 EVT RegVT = VA.getLocVT();
1940 const TargetRegisterClass *RC;
1941 if (RegVT == MVT::i32)
1942 RC = &X86::GR32RegClass;
1943 else if (Is64Bit && RegVT == MVT::i64)
1944 RC = &X86::GR64RegClass;
1945 else if (RegVT == MVT::f32)
1946 RC = &X86::FR32RegClass;
1947 else if (RegVT == MVT::f64)
1948 RC = &X86::FR64RegClass;
1949 else if (RegVT.is256BitVector())
1950 RC = &X86::VR256RegClass;
1951 else if (RegVT.is128BitVector())
1952 RC = &X86::VR128RegClass;
1953 else if (RegVT == MVT::x86mmx)
1954 RC = &X86::VR64RegClass;
1956 llvm_unreachable("Unknown argument type!");
1958 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1959 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1961 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1962 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1964 if (VA.getLocInfo() == CCValAssign::SExt)
1965 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1966 DAG.getValueType(VA.getValVT()));
1967 else if (VA.getLocInfo() == CCValAssign::ZExt)
1968 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1969 DAG.getValueType(VA.getValVT()));
1970 else if (VA.getLocInfo() == CCValAssign::BCvt)
1971 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1973 if (VA.isExtInLoc()) {
1974 // Handle MMX values passed in XMM regs.
1975 if (RegVT.isVector()) {
1976 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1979 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1982 assert(VA.isMemLoc());
1983 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1986 // If value is passed via pointer - do a load.
1987 if (VA.getLocInfo() == CCValAssign::Indirect)
1988 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1989 MachinePointerInfo(), false, false, false, 0);
1991 InVals.push_back(ArgValue);
1994 // The x86-64 ABI for returning structs by value requires that we copy
1995 // the sret argument into %rax for the return. Save the argument into
1996 // a virtual register so that we can access it from the return points.
1997 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1998 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1999 unsigned Reg = FuncInfo->getSRetReturnReg();
2001 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
2002 FuncInfo->setSRetReturnReg(Reg);
2004 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2005 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2008 unsigned StackSize = CCInfo.getNextStackOffset();
2009 // Align stack specially for tail calls.
2010 if (FuncIsMadeTailCallSafe(CallConv,
2011 MF.getTarget().Options.GuaranteedTailCallOpt))
2012 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2014 // If the function takes variable number of arguments, make a frame index for
2015 // the start of the first vararg value... for expansion of llvm.va_start.
2017 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2018 CallConv != CallingConv::X86_ThisCall)) {
2019 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2022 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2024 // FIXME: We should really autogenerate these arrays
2025 static const uint16_t GPR64ArgRegsWin64[] = {
2026 X86::RCX, X86::RDX, X86::R8, X86::R9
2028 static const uint16_t GPR64ArgRegs64Bit[] = {
2029 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2031 static const uint16_t XMMArgRegs64Bit[] = {
2032 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2033 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2035 const uint16_t *GPR64ArgRegs;
2036 unsigned NumXMMRegs = 0;
2039 // The XMM registers which might contain var arg parameters are shadowed
2040 // in their paired GPR. So we only need to save the GPR to their home
2042 TotalNumIntRegs = 4;
2043 GPR64ArgRegs = GPR64ArgRegsWin64;
2045 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2046 GPR64ArgRegs = GPR64ArgRegs64Bit;
2048 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2051 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2054 bool NoImplicitFloatOps = Fn->getFnAttributes().
2055 hasAttribute(Attributes::NoImplicitFloat);
2056 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2057 "SSE register cannot be used when SSE is disabled!");
2058 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2059 NoImplicitFloatOps) &&
2060 "SSE register cannot be used when SSE is disabled!");
2061 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2062 !Subtarget->hasSSE1())
2063 // Kernel mode asks for SSE to be disabled, so don't push them
2065 TotalNumXMMRegs = 0;
2068 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2069 // Get to the caller-allocated home save location. Add 8 to account
2070 // for the return address.
2071 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2072 FuncInfo->setRegSaveFrameIndex(
2073 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2074 // Fixup to set vararg frame on shadow area (4 x i64).
2076 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2078 // For X86-64, if there are vararg parameters that are passed via
2079 // registers, then we must store them to their spots on the stack so
2080 // they may be loaded by deferencing the result of va_next.
2081 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2082 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2083 FuncInfo->setRegSaveFrameIndex(
2084 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2088 // Store the integer parameter registers.
2089 SmallVector<SDValue, 8> MemOps;
2090 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2092 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2093 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2094 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2095 DAG.getIntPtrConstant(Offset));
2096 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2097 &X86::GR64RegClass);
2098 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2100 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2101 MachinePointerInfo::getFixedStack(
2102 FuncInfo->getRegSaveFrameIndex(), Offset),
2104 MemOps.push_back(Store);
2108 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2109 // Now store the XMM (fp + vector) parameter registers.
2110 SmallVector<SDValue, 11> SaveXMMOps;
2111 SaveXMMOps.push_back(Chain);
2113 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2114 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2115 SaveXMMOps.push_back(ALVal);
2117 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2118 FuncInfo->getRegSaveFrameIndex()));
2119 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2120 FuncInfo->getVarArgsFPOffset()));
2122 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2123 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2124 &X86::VR128RegClass);
2125 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2126 SaveXMMOps.push_back(Val);
2128 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2130 &SaveXMMOps[0], SaveXMMOps.size()));
2133 if (!MemOps.empty())
2134 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2135 &MemOps[0], MemOps.size());
2139 // Some CCs need callee pop.
2140 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2141 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2142 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2144 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2145 // If this is an sret function, the return should pop the hidden pointer.
2146 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2147 argsAreStructReturn(Ins) == StackStructReturn)
2148 FuncInfo->setBytesToPopOnReturn(4);
2152 // RegSaveFrameIndex is X86-64 only.
2153 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2154 if (CallConv == CallingConv::X86_FastCall ||
2155 CallConv == CallingConv::X86_ThisCall)
2156 // fastcc functions can't have varargs.
2157 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2160 FuncInfo->setArgumentStackSize(StackSize);
2166 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2167 SDValue StackPtr, SDValue Arg,
2168 DebugLoc dl, SelectionDAG &DAG,
2169 const CCValAssign &VA,
2170 ISD::ArgFlagsTy Flags) const {
2171 unsigned LocMemOffset = VA.getLocMemOffset();
2172 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2173 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2174 if (Flags.isByVal())
2175 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2177 return DAG.getStore(Chain, dl, Arg, PtrOff,
2178 MachinePointerInfo::getStack(LocMemOffset),
2182 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2183 /// optimization is performed and it is required.
2185 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2186 SDValue &OutRetAddr, SDValue Chain,
2187 bool IsTailCall, bool Is64Bit,
2188 int FPDiff, DebugLoc dl) const {
2189 // Adjust the Return address stack slot.
2190 EVT VT = getPointerTy();
2191 OutRetAddr = getReturnAddressFrameIndex(DAG);
2193 // Load the "old" Return address.
2194 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2195 false, false, false, 0);
2196 return SDValue(OutRetAddr.getNode(), 1);
2199 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2200 /// optimization is performed and it is required (FPDiff!=0).
2202 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2203 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2204 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2205 // Store the return address to the appropriate stack slot.
2206 if (!FPDiff) return Chain;
2207 // Calculate the new stack slot for the return address.
2208 int NewReturnAddrFI =
2209 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2210 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2211 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2212 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2218 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2219 SmallVectorImpl<SDValue> &InVals) const {
2220 SelectionDAG &DAG = CLI.DAG;
2221 DebugLoc &dl = CLI.DL;
2222 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2223 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2224 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2225 SDValue Chain = CLI.Chain;
2226 SDValue Callee = CLI.Callee;
2227 CallingConv::ID CallConv = CLI.CallConv;
2228 bool &isTailCall = CLI.IsTailCall;
2229 bool isVarArg = CLI.IsVarArg;
2231 MachineFunction &MF = DAG.getMachineFunction();
2232 bool Is64Bit = Subtarget->is64Bit();
2233 bool IsWin64 = Subtarget->isTargetWin64();
2234 bool IsWindows = Subtarget->isTargetWindows();
2235 StructReturnType SR = callIsStructReturn(Outs);
2236 bool IsSibcall = false;
2238 if (MF.getTarget().Options.DisableTailCalls)
2242 // Check if it's really possible to do a tail call.
2243 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2244 isVarArg, SR != NotStructReturn,
2245 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2246 Outs, OutVals, Ins, DAG);
2248 // Sibcalls are automatically detected tailcalls which do not require
2250 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2257 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2258 "Var args not supported with calling convention fastcc, ghc or hipe");
2260 // Analyze operands of the call, assigning locations to each operand.
2261 SmallVector<CCValAssign, 16> ArgLocs;
2262 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2263 ArgLocs, *DAG.getContext());
2265 // Allocate shadow area for Win64
2267 CCInfo.AllocateStack(32, 8);
2270 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2272 // Get a count of how many bytes are to be pushed on the stack.
2273 unsigned NumBytes = CCInfo.getNextStackOffset();
2275 // This is a sibcall. The memory operands are available in caller's
2276 // own caller's stack.
2278 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2279 IsTailCallConvention(CallConv))
2280 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2283 if (isTailCall && !IsSibcall) {
2284 // Lower arguments at fp - stackoffset + fpdiff.
2285 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2286 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2288 FPDiff = NumBytesCallerPushed - NumBytes;
2290 // Set the delta of movement of the returnaddr stackslot.
2291 // But only set if delta is greater than previous delta.
2292 if (FPDiff < X86Info->getTCReturnAddrDelta())
2293 X86Info->setTCReturnAddrDelta(FPDiff);
2297 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2299 SDValue RetAddrFrIdx;
2300 // Load return address for tail calls.
2301 if (isTailCall && FPDiff)
2302 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2303 Is64Bit, FPDiff, dl);
2305 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2306 SmallVector<SDValue, 8> MemOpChains;
2309 // Walk the register/memloc assignments, inserting copies/loads. In the case
2310 // of tail call optimization arguments are handle later.
2311 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2312 CCValAssign &VA = ArgLocs[i];
2313 EVT RegVT = VA.getLocVT();
2314 SDValue Arg = OutVals[i];
2315 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316 bool isByVal = Flags.isByVal();
2318 // Promote the value if needed.
2319 switch (VA.getLocInfo()) {
2320 default: llvm_unreachable("Unknown loc info!");
2321 case CCValAssign::Full: break;
2322 case CCValAssign::SExt:
2323 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2325 case CCValAssign::ZExt:
2326 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2328 case CCValAssign::AExt:
2329 if (RegVT.is128BitVector()) {
2330 // Special case: passing MMX values in XMM registers.
2331 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2332 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2333 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2335 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2337 case CCValAssign::BCvt:
2338 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2340 case CCValAssign::Indirect: {
2341 // Store the argument.
2342 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2343 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2344 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2345 MachinePointerInfo::getFixedStack(FI),
2352 if (VA.isRegLoc()) {
2353 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2354 if (isVarArg && IsWin64) {
2355 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2356 // shadow reg if callee is a varargs function.
2357 unsigned ShadowReg = 0;
2358 switch (VA.getLocReg()) {
2359 case X86::XMM0: ShadowReg = X86::RCX; break;
2360 case X86::XMM1: ShadowReg = X86::RDX; break;
2361 case X86::XMM2: ShadowReg = X86::R8; break;
2362 case X86::XMM3: ShadowReg = X86::R9; break;
2365 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2367 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2368 assert(VA.isMemLoc());
2369 if (StackPtr.getNode() == 0)
2370 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2372 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2373 dl, DAG, VA, Flags));
2377 if (!MemOpChains.empty())
2378 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2379 &MemOpChains[0], MemOpChains.size());
2381 if (Subtarget->isPICStyleGOT()) {
2382 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2385 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2386 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2388 // If we are tail calling and generating PIC/GOT style code load the
2389 // address of the callee into ECX. The value in ecx is used as target of
2390 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2391 // for tail calls on PIC/GOT architectures. Normally we would just put the
2392 // address of GOT into ebx and then call target@PLT. But for tail calls
2393 // ebx would be restored (since ebx is callee saved) before jumping to the
2396 // Note: The actual moving to ECX is done further down.
2397 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2398 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2399 !G->getGlobal()->hasProtectedVisibility())
2400 Callee = LowerGlobalAddress(Callee, DAG);
2401 else if (isa<ExternalSymbolSDNode>(Callee))
2402 Callee = LowerExternalSymbol(Callee, DAG);
2406 if (Is64Bit && isVarArg && !IsWin64) {
2407 // From AMD64 ABI document:
2408 // For calls that may call functions that use varargs or stdargs
2409 // (prototype-less calls or calls to functions containing ellipsis (...) in
2410 // the declaration) %al is used as hidden argument to specify the number
2411 // of SSE registers used. The contents of %al do not need to match exactly
2412 // the number of registers, but must be an ubound on the number of SSE
2413 // registers used and is in the range 0 - 8 inclusive.
2415 // Count the number of XMM registers allocated.
2416 static const uint16_t XMMArgRegs[] = {
2417 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2418 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2420 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2421 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2422 && "SSE registers cannot be used when SSE is disabled");
2424 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2425 DAG.getConstant(NumXMMRegs, MVT::i8)));
2428 // For tail calls lower the arguments to the 'real' stack slot.
2430 // Force all the incoming stack arguments to be loaded from the stack
2431 // before any new outgoing arguments are stored to the stack, because the
2432 // outgoing stack slots may alias the incoming argument stack slots, and
2433 // the alias isn't otherwise explicit. This is slightly more conservative
2434 // than necessary, because it means that each store effectively depends
2435 // on every argument instead of just those arguments it would clobber.
2436 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2438 SmallVector<SDValue, 8> MemOpChains2;
2441 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2442 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2443 CCValAssign &VA = ArgLocs[i];
2446 assert(VA.isMemLoc());
2447 SDValue Arg = OutVals[i];
2448 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2449 // Create frame index.
2450 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2451 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2452 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2453 FIN = DAG.getFrameIndex(FI, getPointerTy());
2455 if (Flags.isByVal()) {
2456 // Copy relative to framepointer.
2457 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2458 if (StackPtr.getNode() == 0)
2459 StackPtr = DAG.getCopyFromReg(Chain, dl,
2460 RegInfo->getStackRegister(),
2462 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2464 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2468 // Store relative to framepointer.
2469 MemOpChains2.push_back(
2470 DAG.getStore(ArgChain, dl, Arg, FIN,
2471 MachinePointerInfo::getFixedStack(FI),
2477 if (!MemOpChains2.empty())
2478 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2479 &MemOpChains2[0], MemOpChains2.size());
2481 // Store the return address to the appropriate stack slot.
2482 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2483 getPointerTy(), RegInfo->getSlotSize(),
2487 // Build a sequence of copy-to-reg nodes chained together with token chain
2488 // and flag operands which copy the outgoing args into registers.
2490 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2491 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2492 RegsToPass[i].second, InFlag);
2493 InFlag = Chain.getValue(1);
2496 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2497 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2498 // In the 64-bit large code model, we have to make all calls
2499 // through a register, since the call instruction's 32-bit
2500 // pc-relative offset may not be large enough to hold the whole
2502 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2503 // If the callee is a GlobalAddress node (quite common, every direct call
2504 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2507 // We should use extra load for direct calls to dllimported functions in
2509 const GlobalValue *GV = G->getGlobal();
2510 if (!GV->hasDLLImportLinkage()) {
2511 unsigned char OpFlags = 0;
2512 bool ExtraLoad = false;
2513 unsigned WrapperKind = ISD::DELETED_NODE;
2515 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2516 // external symbols most go through the PLT in PIC mode. If the symbol
2517 // has hidden or protected visibility, or if it is static or local, then
2518 // we don't need to use the PLT - we can directly call it.
2519 if (Subtarget->isTargetELF() &&
2520 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2521 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2522 OpFlags = X86II::MO_PLT;
2523 } else if (Subtarget->isPICStyleStubAny() &&
2524 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2525 (!Subtarget->getTargetTriple().isMacOSX() ||
2526 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2527 // PC-relative references to external symbols should go through $stub,
2528 // unless we're building with the leopard linker or later, which
2529 // automatically synthesizes these stubs.
2530 OpFlags = X86II::MO_DARWIN_STUB;
2531 } else if (Subtarget->isPICStyleRIPRel() &&
2532 isa<Function>(GV) &&
2533 cast<Function>(GV)->getFnAttributes().
2534 hasAttribute(Attributes::NonLazyBind)) {
2535 // If the function is marked as non-lazy, generate an indirect call
2536 // which loads from the GOT directly. This avoids runtime overhead
2537 // at the cost of eager binding (and one extra byte of encoding).
2538 OpFlags = X86II::MO_GOTPCREL;
2539 WrapperKind = X86ISD::WrapperRIP;
2543 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2544 G->getOffset(), OpFlags);
2546 // Add a wrapper if needed.
2547 if (WrapperKind != ISD::DELETED_NODE)
2548 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2549 // Add extra indirection if needed.
2551 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2552 MachinePointerInfo::getGOT(),
2553 false, false, false, 0);
2555 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2556 unsigned char OpFlags = 0;
2558 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2559 // external symbols should go through the PLT.
2560 if (Subtarget->isTargetELF() &&
2561 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2562 OpFlags = X86II::MO_PLT;
2563 } else if (Subtarget->isPICStyleStubAny() &&
2564 (!Subtarget->getTargetTriple().isMacOSX() ||
2565 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2566 // PC-relative references to external symbols should go through $stub,
2567 // unless we're building with the leopard linker or later, which
2568 // automatically synthesizes these stubs.
2569 OpFlags = X86II::MO_DARWIN_STUB;
2572 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2576 // Returns a chain & a flag for retval copy to use.
2577 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2578 SmallVector<SDValue, 8> Ops;
2580 if (!IsSibcall && isTailCall) {
2581 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2582 DAG.getIntPtrConstant(0, true), InFlag);
2583 InFlag = Chain.getValue(1);
2586 Ops.push_back(Chain);
2587 Ops.push_back(Callee);
2590 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2592 // Add argument registers to the end of the list so that they are known live
2594 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2595 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2596 RegsToPass[i].second.getValueType()));
2598 // Add a register mask operand representing the call-preserved registers.
2599 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2600 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2601 assert(Mask && "Missing call preserved mask for calling convention");
2602 Ops.push_back(DAG.getRegisterMask(Mask));
2604 if (InFlag.getNode())
2605 Ops.push_back(InFlag);
2609 //// If this is the first return lowered for this function, add the regs
2610 //// to the liveout set for the function.
2611 // This isn't right, although it's probably harmless on x86; liveouts
2612 // should be computed from returns not tail calls. Consider a void
2613 // function making a tail call to a function returning int.
2614 return DAG.getNode(X86ISD::TC_RETURN, dl,
2615 NodeTys, &Ops[0], Ops.size());
2618 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2619 InFlag = Chain.getValue(1);
2621 // Create the CALLSEQ_END node.
2622 unsigned NumBytesForCalleeToPush;
2623 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2624 getTargetMachine().Options.GuaranteedTailCallOpt))
2625 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2626 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2627 SR == StackStructReturn)
2628 // If this is a call to a struct-return function, the callee
2629 // pops the hidden struct pointer, so we have to push it back.
2630 // This is common for Darwin/X86, Linux & Mingw32 targets.
2631 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2632 NumBytesForCalleeToPush = 4;
2634 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2636 // Returns a flag for retval copy to use.
2638 Chain = DAG.getCALLSEQ_END(Chain,
2639 DAG.getIntPtrConstant(NumBytes, true),
2640 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2643 InFlag = Chain.getValue(1);
2646 // Handle result values, copying them out of physregs into vregs that we
2648 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2649 Ins, dl, DAG, InVals);
2653 //===----------------------------------------------------------------------===//
2654 // Fast Calling Convention (tail call) implementation
2655 //===----------------------------------------------------------------------===//
2657 // Like std call, callee cleans arguments, convention except that ECX is
2658 // reserved for storing the tail called function address. Only 2 registers are
2659 // free for argument passing (inreg). Tail call optimization is performed
2661 // * tailcallopt is enabled
2662 // * caller/callee are fastcc
2663 // On X86_64 architecture with GOT-style position independent code only local
2664 // (within module) calls are supported at the moment.
2665 // To keep the stack aligned according to platform abi the function
2666 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2667 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2668 // If a tail called function callee has more arguments than the caller the
2669 // caller needs to make sure that there is room to move the RETADDR to. This is
2670 // achieved by reserving an area the size of the argument delta right after the
2671 // original REtADDR, but before the saved framepointer or the spilled registers
2672 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2684 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2685 /// for a 16 byte align requirement.
2687 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2688 SelectionDAG& DAG) const {
2689 MachineFunction &MF = DAG.getMachineFunction();
2690 const TargetMachine &TM = MF.getTarget();
2691 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2692 unsigned StackAlignment = TFI.getStackAlignment();
2693 uint64_t AlignMask = StackAlignment - 1;
2694 int64_t Offset = StackSize;
2695 unsigned SlotSize = RegInfo->getSlotSize();
2696 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2697 // Number smaller than 12 so just add the difference.
2698 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2700 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2701 Offset = ((~AlignMask) & Offset) + StackAlignment +
2702 (StackAlignment-SlotSize);
2707 /// MatchingStackOffset - Return true if the given stack call argument is
2708 /// already available in the same position (relatively) of the caller's
2709 /// incoming argument stack.
2711 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2712 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2713 const X86InstrInfo *TII) {
2714 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2716 if (Arg.getOpcode() == ISD::CopyFromReg) {
2717 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2718 if (!TargetRegisterInfo::isVirtualRegister(VR))
2720 MachineInstr *Def = MRI->getVRegDef(VR);
2723 if (!Flags.isByVal()) {
2724 if (!TII->isLoadFromStackSlot(Def, FI))
2727 unsigned Opcode = Def->getOpcode();
2728 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2729 Def->getOperand(1).isFI()) {
2730 FI = Def->getOperand(1).getIndex();
2731 Bytes = Flags.getByValSize();
2735 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2736 if (Flags.isByVal())
2737 // ByVal argument is passed in as a pointer but it's now being
2738 // dereferenced. e.g.
2739 // define @foo(%struct.X* %A) {
2740 // tail call @bar(%struct.X* byval %A)
2743 SDValue Ptr = Ld->getBasePtr();
2744 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2747 FI = FINode->getIndex();
2748 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2749 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2750 FI = FINode->getIndex();
2751 Bytes = Flags.getByValSize();
2755 assert(FI != INT_MAX);
2756 if (!MFI->isFixedObjectIndex(FI))
2758 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2761 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2762 /// for tail call optimization. Targets which want to do tail call
2763 /// optimization should implement this function.
2765 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2766 CallingConv::ID CalleeCC,
2768 bool isCalleeStructRet,
2769 bool isCallerStructRet,
2771 const SmallVectorImpl<ISD::OutputArg> &Outs,
2772 const SmallVectorImpl<SDValue> &OutVals,
2773 const SmallVectorImpl<ISD::InputArg> &Ins,
2774 SelectionDAG& DAG) const {
2775 if (!IsTailCallConvention(CalleeCC) &&
2776 CalleeCC != CallingConv::C)
2779 // If -tailcallopt is specified, make fastcc functions tail-callable.
2780 const MachineFunction &MF = DAG.getMachineFunction();
2781 const Function *CallerF = DAG.getMachineFunction().getFunction();
2783 // If the function return type is x86_fp80 and the callee return type is not,
2784 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2785 // perform a tailcall optimization here.
2786 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2789 CallingConv::ID CallerCC = CallerF->getCallingConv();
2790 bool CCMatch = CallerCC == CalleeCC;
2792 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2793 if (IsTailCallConvention(CalleeCC) && CCMatch)
2798 // Look for obvious safe cases to perform tail call optimization that do not
2799 // require ABI changes. This is what gcc calls sibcall.
2801 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2802 // emit a special epilogue.
2803 if (RegInfo->needsStackRealignment(MF))
2806 // Also avoid sibcall optimization if either caller or callee uses struct
2807 // return semantics.
2808 if (isCalleeStructRet || isCallerStructRet)
2811 // An stdcall caller is expected to clean up its arguments; the callee
2812 // isn't going to do that.
2813 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2816 // Do not sibcall optimize vararg calls unless all arguments are passed via
2818 if (isVarArg && !Outs.empty()) {
2820 // Optimizing for varargs on Win64 is unlikely to be safe without
2821 // additional testing.
2822 if (Subtarget->isTargetWin64())
2825 SmallVector<CCValAssign, 16> ArgLocs;
2826 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2827 getTargetMachine(), ArgLocs, *DAG.getContext());
2829 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2830 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2831 if (!ArgLocs[i].isRegLoc())
2835 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2836 // stack. Therefore, if it's not used by the call it is not safe to optimize
2837 // this into a sibcall.
2838 bool Unused = false;
2839 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2846 SmallVector<CCValAssign, 16> RVLocs;
2847 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2848 getTargetMachine(), RVLocs, *DAG.getContext());
2849 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2850 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2851 CCValAssign &VA = RVLocs[i];
2852 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2857 // If the calling conventions do not match, then we'd better make sure the
2858 // results are returned in the same way as what the caller expects.
2860 SmallVector<CCValAssign, 16> RVLocs1;
2861 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2862 getTargetMachine(), RVLocs1, *DAG.getContext());
2863 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2865 SmallVector<CCValAssign, 16> RVLocs2;
2866 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2867 getTargetMachine(), RVLocs2, *DAG.getContext());
2868 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2870 if (RVLocs1.size() != RVLocs2.size())
2872 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2873 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2875 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2877 if (RVLocs1[i].isRegLoc()) {
2878 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2881 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2887 // If the callee takes no arguments then go on to check the results of the
2889 if (!Outs.empty()) {
2890 // Check if stack adjustment is needed. For now, do not do this if any
2891 // argument is passed on the stack.
2892 SmallVector<CCValAssign, 16> ArgLocs;
2893 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894 getTargetMachine(), ArgLocs, *DAG.getContext());
2896 // Allocate shadow area for Win64
2897 if (Subtarget->isTargetWin64()) {
2898 CCInfo.AllocateStack(32, 8);
2901 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2902 if (CCInfo.getNextStackOffset()) {
2903 MachineFunction &MF = DAG.getMachineFunction();
2904 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2907 // Check if the arguments are already laid out in the right way as
2908 // the caller's fixed stack objects.
2909 MachineFrameInfo *MFI = MF.getFrameInfo();
2910 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2911 const X86InstrInfo *TII =
2912 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2913 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2914 CCValAssign &VA = ArgLocs[i];
2915 SDValue Arg = OutVals[i];
2916 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2917 if (VA.getLocInfo() == CCValAssign::Indirect)
2919 if (!VA.isRegLoc()) {
2920 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2927 // If the tailcall address may be in a register, then make sure it's
2928 // possible to register allocate for it. In 32-bit, the call address can
2929 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2930 // callee-saved registers are restored. These happen to be the same
2931 // registers used to pass 'inreg' arguments so watch out for those.
2932 if (!Subtarget->is64Bit() &&
2933 !isa<GlobalAddressSDNode>(Callee) &&
2934 !isa<ExternalSymbolSDNode>(Callee)) {
2935 unsigned NumInRegs = 0;
2936 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2937 CCValAssign &VA = ArgLocs[i];
2940 unsigned Reg = VA.getLocReg();
2943 case X86::EAX: case X86::EDX: case X86::ECX:
2944 if (++NumInRegs == 3)
2956 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2957 const TargetLibraryInfo *libInfo) const {
2958 return X86::createFastISel(funcInfo, libInfo);
2962 //===----------------------------------------------------------------------===//
2963 // Other Lowering Hooks
2964 //===----------------------------------------------------------------------===//
2966 static bool MayFoldLoad(SDValue Op) {
2967 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2970 static bool MayFoldIntoStore(SDValue Op) {
2971 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2974 static bool isTargetShuffle(unsigned Opcode) {
2976 default: return false;
2977 case X86ISD::PSHUFD:
2978 case X86ISD::PSHUFHW:
2979 case X86ISD::PSHUFLW:
2981 case X86ISD::PALIGN:
2982 case X86ISD::MOVLHPS:
2983 case X86ISD::MOVLHPD:
2984 case X86ISD::MOVHLPS:
2985 case X86ISD::MOVLPS:
2986 case X86ISD::MOVLPD:
2987 case X86ISD::MOVSHDUP:
2988 case X86ISD::MOVSLDUP:
2989 case X86ISD::MOVDDUP:
2992 case X86ISD::UNPCKL:
2993 case X86ISD::UNPCKH:
2994 case X86ISD::VPERMILP:
2995 case X86ISD::VPERM2X128:
2996 case X86ISD::VPERMI:
3001 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3002 SDValue V1, SelectionDAG &DAG) {
3004 default: llvm_unreachable("Unknown x86 shuffle node");
3005 case X86ISD::MOVSHDUP:
3006 case X86ISD::MOVSLDUP:
3007 case X86ISD::MOVDDUP:
3008 return DAG.getNode(Opc, dl, VT, V1);
3012 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3013 SDValue V1, unsigned TargetMask,
3014 SelectionDAG &DAG) {
3016 default: llvm_unreachable("Unknown x86 shuffle node");
3017 case X86ISD::PSHUFD:
3018 case X86ISD::PSHUFHW:
3019 case X86ISD::PSHUFLW:
3020 case X86ISD::VPERMILP:
3021 case X86ISD::VPERMI:
3022 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3026 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3027 SDValue V1, SDValue V2, unsigned TargetMask,
3028 SelectionDAG &DAG) {
3030 default: llvm_unreachable("Unknown x86 shuffle node");
3031 case X86ISD::PALIGN:
3033 case X86ISD::VPERM2X128:
3034 return DAG.getNode(Opc, dl, VT, V1, V2,
3035 DAG.getConstant(TargetMask, MVT::i8));
3039 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3040 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3042 default: llvm_unreachable("Unknown x86 shuffle node");
3043 case X86ISD::MOVLHPS:
3044 case X86ISD::MOVLHPD:
3045 case X86ISD::MOVHLPS:
3046 case X86ISD::MOVLPS:
3047 case X86ISD::MOVLPD:
3050 case X86ISD::UNPCKL:
3051 case X86ISD::UNPCKH:
3052 return DAG.getNode(Opc, dl, VT, V1, V2);
3056 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3057 MachineFunction &MF = DAG.getMachineFunction();
3058 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3059 int ReturnAddrIndex = FuncInfo->getRAIndex();
3061 if (ReturnAddrIndex == 0) {
3062 // Set up a frame object for the return address.
3063 unsigned SlotSize = RegInfo->getSlotSize();
3064 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3066 FuncInfo->setRAIndex(ReturnAddrIndex);
3069 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3073 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3074 bool hasSymbolicDisplacement) {
3075 // Offset should fit into 32 bit immediate field.
3076 if (!isInt<32>(Offset))
3079 // If we don't have a symbolic displacement - we don't have any extra
3081 if (!hasSymbolicDisplacement)
3084 // FIXME: Some tweaks might be needed for medium code model.
3085 if (M != CodeModel::Small && M != CodeModel::Kernel)
3088 // For small code model we assume that latest object is 16MB before end of 31
3089 // bits boundary. We may also accept pretty large negative constants knowing
3090 // that all objects are in the positive half of address space.
3091 if (M == CodeModel::Small && Offset < 16*1024*1024)
3094 // For kernel code model we know that all object resist in the negative half
3095 // of 32bits address space. We may not accept negative offsets, since they may
3096 // be just off and we may accept pretty large positive ones.
3097 if (M == CodeModel::Kernel && Offset > 0)
3103 /// isCalleePop - Determines whether the callee is required to pop its
3104 /// own arguments. Callee pop is necessary to support tail calls.
3105 bool X86::isCalleePop(CallingConv::ID CallingConv,
3106 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3110 switch (CallingConv) {
3113 case CallingConv::X86_StdCall:
3115 case CallingConv::X86_FastCall:
3117 case CallingConv::X86_ThisCall:
3119 case CallingConv::Fast:
3121 case CallingConv::GHC:
3123 case CallingConv::HiPE:
3128 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3129 /// specific condition code, returning the condition code and the LHS/RHS of the
3130 /// comparison to make.
3131 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3132 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3134 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3135 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3136 // X > -1 -> X == 0, jump !sign.
3137 RHS = DAG.getConstant(0, RHS.getValueType());
3138 return X86::COND_NS;
3140 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3141 // X < 0 -> X == 0, jump on sign.
3144 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3146 RHS = DAG.getConstant(0, RHS.getValueType());
3147 return X86::COND_LE;
3151 switch (SetCCOpcode) {
3152 default: llvm_unreachable("Invalid integer condition!");
3153 case ISD::SETEQ: return X86::COND_E;
3154 case ISD::SETGT: return X86::COND_G;
3155 case ISD::SETGE: return X86::COND_GE;
3156 case ISD::SETLT: return X86::COND_L;
3157 case ISD::SETLE: return X86::COND_LE;
3158 case ISD::SETNE: return X86::COND_NE;
3159 case ISD::SETULT: return X86::COND_B;
3160 case ISD::SETUGT: return X86::COND_A;
3161 case ISD::SETULE: return X86::COND_BE;
3162 case ISD::SETUGE: return X86::COND_AE;
3166 // First determine if it is required or is profitable to flip the operands.
3168 // If LHS is a foldable load, but RHS is not, flip the condition.
3169 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3170 !ISD::isNON_EXTLoad(RHS.getNode())) {
3171 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3172 std::swap(LHS, RHS);
3175 switch (SetCCOpcode) {
3181 std::swap(LHS, RHS);
3185 // On a floating point condition, the flags are set as follows:
3187 // 0 | 0 | 0 | X > Y
3188 // 0 | 0 | 1 | X < Y
3189 // 1 | 0 | 0 | X == Y
3190 // 1 | 1 | 1 | unordered
3191 switch (SetCCOpcode) {
3192 default: llvm_unreachable("Condcode should be pre-legalized away");
3194 case ISD::SETEQ: return X86::COND_E;
3195 case ISD::SETOLT: // flipped
3197 case ISD::SETGT: return X86::COND_A;
3198 case ISD::SETOLE: // flipped
3200 case ISD::SETGE: return X86::COND_AE;
3201 case ISD::SETUGT: // flipped
3203 case ISD::SETLT: return X86::COND_B;
3204 case ISD::SETUGE: // flipped
3206 case ISD::SETLE: return X86::COND_BE;
3208 case ISD::SETNE: return X86::COND_NE;
3209 case ISD::SETUO: return X86::COND_P;
3210 case ISD::SETO: return X86::COND_NP;
3212 case ISD::SETUNE: return X86::COND_INVALID;
3216 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3217 /// code. Current x86 isa includes the following FP cmov instructions:
3218 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3219 static bool hasFPCMov(unsigned X86CC) {
3235 /// isFPImmLegal - Returns true if the target can instruction select the
3236 /// specified FP immediate natively. If false, the legalizer will
3237 /// materialize the FP immediate as a load from a constant pool.
3238 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3239 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3240 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3246 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3247 /// the specified range (L, H].
3248 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3249 return (Val < 0) || (Val >= Low && Val < Hi);
3252 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3253 /// specified value.
3254 static bool isUndefOrEqual(int Val, int CmpVal) {
3255 return (Val < 0 || Val == CmpVal);
3258 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3259 /// from position Pos and ending in Pos+Size, falls within the specified
3260 /// sequential range (L, L+Pos]. or is undef.
3261 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3262 unsigned Pos, unsigned Size, int Low) {
3263 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3264 if (!isUndefOrEqual(Mask[i], Low))
3269 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3270 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3271 /// the second operand.
3272 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3273 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3274 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3275 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3276 return (Mask[0] < 2 && Mask[1] < 2);
3280 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3281 /// is suitable for input to PSHUFHW.
3282 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3283 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3286 // Lower quadword copied in order or undef.
3287 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3290 // Upper quadword shuffled.
3291 for (unsigned i = 4; i != 8; ++i)
3292 if (!isUndefOrInRange(Mask[i], 4, 8))
3295 if (VT == MVT::v16i16) {
3296 // Lower quadword copied in order or undef.
3297 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3300 // Upper quadword shuffled.
3301 for (unsigned i = 12; i != 16; ++i)
3302 if (!isUndefOrInRange(Mask[i], 12, 16))
3309 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3310 /// is suitable for input to PSHUFLW.
3311 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3312 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3315 // Upper quadword copied in order.
3316 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3319 // Lower quadword shuffled.
3320 for (unsigned i = 0; i != 4; ++i)
3321 if (!isUndefOrInRange(Mask[i], 0, 4))
3324 if (VT == MVT::v16i16) {
3325 // Upper quadword copied in order.
3326 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3329 // Lower quadword shuffled.
3330 for (unsigned i = 8; i != 12; ++i)
3331 if (!isUndefOrInRange(Mask[i], 8, 12))
3338 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3339 /// is suitable for input to PALIGNR.
3340 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3341 const X86Subtarget *Subtarget) {
3342 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3343 (VT.getSizeInBits() == 256 && !Subtarget->hasInt256()))
3346 unsigned NumElts = VT.getVectorNumElements();
3347 unsigned NumLanes = VT.getSizeInBits()/128;
3348 unsigned NumLaneElts = NumElts/NumLanes;
3350 // Do not handle 64-bit element shuffles with palignr.
3351 if (NumLaneElts == 2)
3354 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3356 for (i = 0; i != NumLaneElts; ++i) {
3361 // Lane is all undef, go to next lane
3362 if (i == NumLaneElts)
3365 int Start = Mask[i+l];
3367 // Make sure its in this lane in one of the sources
3368 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3369 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3372 // If not lane 0, then we must match lane 0
3373 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3376 // Correct second source to be contiguous with first source
3377 if (Start >= (int)NumElts)
3378 Start -= NumElts - NumLaneElts;
3380 // Make sure we're shifting in the right direction.
3381 if (Start <= (int)(i+l))
3386 // Check the rest of the elements to see if they are consecutive.
3387 for (++i; i != NumLaneElts; ++i) {
3388 int Idx = Mask[i+l];
3390 // Make sure its in this lane
3391 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3392 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3395 // If not lane 0, then we must match lane 0
3396 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3399 if (Idx >= (int)NumElts)
3400 Idx -= NumElts - NumLaneElts;
3402 if (!isUndefOrEqual(Idx, Start+i))
3411 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3412 /// the two vector operands have swapped position.
3413 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3414 unsigned NumElems) {
3415 for (unsigned i = 0; i != NumElems; ++i) {
3419 else if (idx < (int)NumElems)
3420 Mask[i] = idx + NumElems;
3422 Mask[i] = idx - NumElems;
3426 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3427 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3428 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3429 /// reverse of what x86 shuffles want.
3430 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3431 bool Commuted = false) {
3432 if (!HasFp256 && VT.getSizeInBits() == 256)
3435 unsigned NumElems = VT.getVectorNumElements();
3436 unsigned NumLanes = VT.getSizeInBits()/128;
3437 unsigned NumLaneElems = NumElems/NumLanes;
3439 if (NumLaneElems != 2 && NumLaneElems != 4)
3442 // VSHUFPSY divides the resulting vector into 4 chunks.
3443 // The sources are also splitted into 4 chunks, and each destination
3444 // chunk must come from a different source chunk.
3446 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3447 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3449 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3450 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3452 // VSHUFPDY divides the resulting vector into 4 chunks.
3453 // The sources are also splitted into 4 chunks, and each destination
3454 // chunk must come from a different source chunk.
3456 // SRC1 => X3 X2 X1 X0
3457 // SRC2 => Y3 Y2 Y1 Y0
3459 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3461 unsigned HalfLaneElems = NumLaneElems/2;
3462 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3463 for (unsigned i = 0; i != NumLaneElems; ++i) {
3464 int Idx = Mask[i+l];
3465 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3466 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3468 // For VSHUFPSY, the mask of the second half must be the same as the
3469 // first but with the appropriate offsets. This works in the same way as
3470 // VPERMILPS works with masks.
3471 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3473 if (!isUndefOrEqual(Idx, Mask[i]+l))
3481 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3482 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3483 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3484 if (!VT.is128BitVector())
3487 unsigned NumElems = VT.getVectorNumElements();
3492 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3493 return isUndefOrEqual(Mask[0], 6) &&
3494 isUndefOrEqual(Mask[1], 7) &&
3495 isUndefOrEqual(Mask[2], 2) &&
3496 isUndefOrEqual(Mask[3], 3);
3499 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3500 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3502 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3503 if (!VT.is128BitVector())
3506 unsigned NumElems = VT.getVectorNumElements();
3511 return isUndefOrEqual(Mask[0], 2) &&
3512 isUndefOrEqual(Mask[1], 3) &&
3513 isUndefOrEqual(Mask[2], 2) &&
3514 isUndefOrEqual(Mask[3], 3);
3517 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3518 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3519 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3520 if (!VT.is128BitVector())
3523 unsigned NumElems = VT.getVectorNumElements();
3525 if (NumElems != 2 && NumElems != 4)
3528 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3529 if (!isUndefOrEqual(Mask[i], i + NumElems))
3532 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3533 if (!isUndefOrEqual(Mask[i], i))
3539 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3540 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3541 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3542 if (!VT.is128BitVector())
3545 unsigned NumElems = VT.getVectorNumElements();
3547 if (NumElems != 2 && NumElems != 4)
3550 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3551 if (!isUndefOrEqual(Mask[i], i))
3554 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3555 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3562 // Some special combinations that can be optimized.
3565 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3566 SelectionDAG &DAG) {
3567 EVT VT = SVOp->getValueType(0);
3568 DebugLoc dl = SVOp->getDebugLoc();
3570 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3573 ArrayRef<int> Mask = SVOp->getMask();
3575 // These are the special masks that may be optimized.
3576 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3577 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3578 bool MatchEvenMask = true;
3579 bool MatchOddMask = true;
3580 for (int i=0; i<8; ++i) {
3581 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3582 MatchEvenMask = false;
3583 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3584 MatchOddMask = false;
3587 if (!MatchEvenMask && !MatchOddMask)
3590 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3592 SDValue Op0 = SVOp->getOperand(0);
3593 SDValue Op1 = SVOp->getOperand(1);
3595 if (MatchEvenMask) {
3596 // Shift the second operand right to 32 bits.
3597 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3598 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3600 // Shift the first operand left to 32 bits.
3601 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3602 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3604 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3605 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3608 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3609 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3610 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3611 bool HasInt256, bool V2IsSplat = false) {
3612 unsigned NumElts = VT.getVectorNumElements();
3614 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3615 "Unsupported vector type for unpckh");
3617 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3618 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3621 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3622 // independently on 128-bit lanes.
3623 unsigned NumLanes = VT.getSizeInBits()/128;
3624 unsigned NumLaneElts = NumElts/NumLanes;
3626 for (unsigned l = 0; l != NumLanes; ++l) {
3627 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3628 i != (l+1)*NumLaneElts;
3631 int BitI1 = Mask[i+1];
3632 if (!isUndefOrEqual(BitI, j))
3635 if (!isUndefOrEqual(BitI1, NumElts))
3638 if (!isUndefOrEqual(BitI1, j + NumElts))
3647 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3648 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3649 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3650 bool HasInt256, bool V2IsSplat = false) {
3651 unsigned NumElts = VT.getVectorNumElements();
3653 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3654 "Unsupported vector type for unpckh");
3656 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3657 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3660 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3661 // independently on 128-bit lanes.
3662 unsigned NumLanes = VT.getSizeInBits()/128;
3663 unsigned NumLaneElts = NumElts/NumLanes;
3665 for (unsigned l = 0; l != NumLanes; ++l) {
3666 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3667 i != (l+1)*NumLaneElts; i += 2, ++j) {
3669 int BitI1 = Mask[i+1];
3670 if (!isUndefOrEqual(BitI, j))
3673 if (isUndefOrEqual(BitI1, NumElts))
3676 if (!isUndefOrEqual(BitI1, j+NumElts))
3684 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3685 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3687 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3689 unsigned NumElts = VT.getVectorNumElements();
3691 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3692 "Unsupported vector type for unpckh");
3694 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3695 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3698 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3699 // FIXME: Need a better way to get rid of this, there's no latency difference
3700 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3701 // the former later. We should also remove the "_undef" special mask.
3702 if (NumElts == 4 && VT.getSizeInBits() == 256)
3705 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3706 // independently on 128-bit lanes.
3707 unsigned NumLanes = VT.getSizeInBits()/128;
3708 unsigned NumLaneElts = NumElts/NumLanes;
3710 for (unsigned l = 0; l != NumLanes; ++l) {
3711 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3712 i != (l+1)*NumLaneElts;
3715 int BitI1 = Mask[i+1];
3717 if (!isUndefOrEqual(BitI, j))
3719 if (!isUndefOrEqual(BitI1, j))
3727 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3728 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3730 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3731 unsigned NumElts = VT.getVectorNumElements();
3733 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3734 "Unsupported vector type for unpckh");
3736 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3737 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3740 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3741 // independently on 128-bit lanes.
3742 unsigned NumLanes = VT.getSizeInBits()/128;
3743 unsigned NumLaneElts = NumElts/NumLanes;
3745 for (unsigned l = 0; l != NumLanes; ++l) {
3746 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3747 i != (l+1)*NumLaneElts; i += 2, ++j) {
3749 int BitI1 = Mask[i+1];
3750 if (!isUndefOrEqual(BitI, j))
3752 if (!isUndefOrEqual(BitI1, j))
3759 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3760 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3761 /// MOVSD, and MOVD, i.e. setting the lowest element.
3762 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3763 if (VT.getVectorElementType().getSizeInBits() < 32)
3765 if (!VT.is128BitVector())
3768 unsigned NumElts = VT.getVectorNumElements();
3770 if (!isUndefOrEqual(Mask[0], NumElts))
3773 for (unsigned i = 1; i != NumElts; ++i)
3774 if (!isUndefOrEqual(Mask[i], i))
3780 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3781 /// as permutations between 128-bit chunks or halves. As an example: this
3783 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3784 /// The first half comes from the second half of V1 and the second half from the
3785 /// the second half of V2.
3786 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3787 if (!HasFp256 || !VT.is256BitVector())
3790 // The shuffle result is divided into half A and half B. In total the two
3791 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3792 // B must come from C, D, E or F.
3793 unsigned HalfSize = VT.getVectorNumElements()/2;
3794 bool MatchA = false, MatchB = false;
3796 // Check if A comes from one of C, D, E, F.
3797 for (unsigned Half = 0; Half != 4; ++Half) {
3798 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3804 // Check if B comes from one of C, D, E, F.
3805 for (unsigned Half = 0; Half != 4; ++Half) {
3806 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3812 return MatchA && MatchB;
3815 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3816 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3817 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3818 EVT VT = SVOp->getValueType(0);
3820 unsigned HalfSize = VT.getVectorNumElements()/2;
3822 unsigned FstHalf = 0, SndHalf = 0;
3823 for (unsigned i = 0; i < HalfSize; ++i) {
3824 if (SVOp->getMaskElt(i) > 0) {
3825 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3829 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3830 if (SVOp->getMaskElt(i) > 0) {
3831 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3836 return (FstHalf | (SndHalf << 4));
3839 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3840 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3841 /// Note that VPERMIL mask matching is different depending whether theunderlying
3842 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3843 /// to the same elements of the low, but to the higher half of the source.
3844 /// In VPERMILPD the two lanes could be shuffled independently of each other
3845 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3846 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3850 unsigned NumElts = VT.getVectorNumElements();
3851 // Only match 256-bit with 32/64-bit types
3852 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3855 unsigned NumLanes = VT.getSizeInBits()/128;
3856 unsigned LaneSize = NumElts/NumLanes;
3857 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3858 for (unsigned i = 0; i != LaneSize; ++i) {
3859 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3861 if (NumElts != 8 || l == 0)
3863 // VPERMILPS handling
3866 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3874 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3875 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3876 /// element of vector 2 and the other elements to come from vector 1 in order.
3877 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3878 bool V2IsSplat = false, bool V2IsUndef = false) {
3879 if (!VT.is128BitVector())
3882 unsigned NumOps = VT.getVectorNumElements();
3883 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3886 if (!isUndefOrEqual(Mask[0], 0))
3889 for (unsigned i = 1; i != NumOps; ++i)
3890 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3891 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3892 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3898 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3900 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3901 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3902 const X86Subtarget *Subtarget) {
3903 if (!Subtarget->hasSSE3())
3906 unsigned NumElems = VT.getVectorNumElements();
3908 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3909 (VT.getSizeInBits() == 256 && NumElems != 8))
3912 // "i+1" is the value the indexed mask element must have
3913 for (unsigned i = 0; i != NumElems; i += 2)
3914 if (!isUndefOrEqual(Mask[i], i+1) ||
3915 !isUndefOrEqual(Mask[i+1], i+1))
3921 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3922 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3923 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3924 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3925 const X86Subtarget *Subtarget) {
3926 if (!Subtarget->hasSSE3())
3929 unsigned NumElems = VT.getVectorNumElements();
3931 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3932 (VT.getSizeInBits() == 256 && NumElems != 8))
3935 // "i" is the value the indexed mask element must have
3936 for (unsigned i = 0; i != NumElems; i += 2)
3937 if (!isUndefOrEqual(Mask[i], i) ||
3938 !isUndefOrEqual(Mask[i+1], i))
3944 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3945 /// specifies a shuffle of elements that is suitable for input to 256-bit
3946 /// version of MOVDDUP.
3947 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3948 if (!HasFp256 || !VT.is256BitVector())
3951 unsigned NumElts = VT.getVectorNumElements();
3955 for (unsigned i = 0; i != NumElts/2; ++i)
3956 if (!isUndefOrEqual(Mask[i], 0))
3958 for (unsigned i = NumElts/2; i != NumElts; ++i)
3959 if (!isUndefOrEqual(Mask[i], NumElts/2))
3964 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3965 /// specifies a shuffle of elements that is suitable for input to 128-bit
3966 /// version of MOVDDUP.
3967 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3968 if (!VT.is128BitVector())
3971 unsigned e = VT.getVectorNumElements() / 2;
3972 for (unsigned i = 0; i != e; ++i)
3973 if (!isUndefOrEqual(Mask[i], i))
3975 for (unsigned i = 0; i != e; ++i)
3976 if (!isUndefOrEqual(Mask[e+i], i))
3981 /// isVEXTRACTF128Index - Return true if the specified
3982 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3983 /// suitable for input to VEXTRACTF128.
3984 bool X86::isVEXTRACTF128Index(SDNode *N) {
3985 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3988 // The index should be aligned on a 128-bit boundary.
3990 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3992 unsigned VL = N->getValueType(0).getVectorNumElements();
3993 unsigned VBits = N->getValueType(0).getSizeInBits();
3994 unsigned ElSize = VBits / VL;
3995 bool Result = (Index * ElSize) % 128 == 0;
4000 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4001 /// operand specifies a subvector insert that is suitable for input to
4003 bool X86::isVINSERTF128Index(SDNode *N) {
4004 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4007 // The index should be aligned on a 128-bit boundary.
4009 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4011 unsigned VL = N->getValueType(0).getVectorNumElements();
4012 unsigned VBits = N->getValueType(0).getSizeInBits();
4013 unsigned ElSize = VBits / VL;
4014 bool Result = (Index * ElSize) % 128 == 0;
4019 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4020 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4021 /// Handles 128-bit and 256-bit.
4022 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4023 EVT VT = N->getValueType(0);
4025 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4026 "Unsupported vector type for PSHUF/SHUFP");
4028 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4029 // independently on 128-bit lanes.
4030 unsigned NumElts = VT.getVectorNumElements();
4031 unsigned NumLanes = VT.getSizeInBits()/128;
4032 unsigned NumLaneElts = NumElts/NumLanes;
4034 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4035 "Only supports 2 or 4 elements per lane");
4037 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4039 for (unsigned i = 0; i != NumElts; ++i) {
4040 int Elt = N->getMaskElt(i);
4041 if (Elt < 0) continue;
4042 Elt &= NumLaneElts - 1;
4043 unsigned ShAmt = (i << Shift) % 8;
4044 Mask |= Elt << ShAmt;
4050 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4051 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4052 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4053 EVT VT = N->getValueType(0);
4055 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4056 "Unsupported vector type for PSHUFHW");
4058 unsigned NumElts = VT.getVectorNumElements();
4061 for (unsigned l = 0; l != NumElts; l += 8) {
4062 // 8 nodes per lane, but we only care about the last 4.
4063 for (unsigned i = 0; i < 4; ++i) {
4064 int Elt = N->getMaskElt(l+i+4);
4065 if (Elt < 0) continue;
4066 Elt &= 0x3; // only 2-bits.
4067 Mask |= Elt << (i * 2);
4074 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4075 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4076 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4077 EVT VT = N->getValueType(0);
4079 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4080 "Unsupported vector type for PSHUFHW");
4082 unsigned NumElts = VT.getVectorNumElements();
4085 for (unsigned l = 0; l != NumElts; l += 8) {
4086 // 8 nodes per lane, but we only care about the first 4.
4087 for (unsigned i = 0; i < 4; ++i) {
4088 int Elt = N->getMaskElt(l+i);
4089 if (Elt < 0) continue;
4090 Elt &= 0x3; // only 2-bits
4091 Mask |= Elt << (i * 2);
4098 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4099 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4100 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4101 EVT VT = SVOp->getValueType(0);
4102 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4104 unsigned NumElts = VT.getVectorNumElements();
4105 unsigned NumLanes = VT.getSizeInBits()/128;
4106 unsigned NumLaneElts = NumElts/NumLanes;
4110 for (i = 0; i != NumElts; ++i) {
4111 Val = SVOp->getMaskElt(i);
4115 if (Val >= (int)NumElts)
4116 Val -= NumElts - NumLaneElts;
4118 assert(Val - i > 0 && "PALIGNR imm should be positive");
4119 return (Val - i) * EltSize;
4122 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4123 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4125 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4126 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4127 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4130 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4132 EVT VecVT = N->getOperand(0).getValueType();
4133 EVT ElVT = VecVT.getVectorElementType();
4135 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4136 return Index / NumElemsPerChunk;
4139 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4140 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4142 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4143 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4144 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4147 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4149 EVT VecVT = N->getValueType(0);
4150 EVT ElVT = VecVT.getVectorElementType();
4152 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4153 return Index / NumElemsPerChunk;
4156 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4157 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4158 /// Handles 256-bit.
4159 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4160 EVT VT = N->getValueType(0);
4162 unsigned NumElts = VT.getVectorNumElements();
4164 assert((VT.is256BitVector() && NumElts == 4) &&
4165 "Unsupported vector type for VPERMQ/VPERMPD");
4168 for (unsigned i = 0; i != NumElts; ++i) {
4169 int Elt = N->getMaskElt(i);
4172 Mask |= Elt << (i*2);
4177 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4179 bool X86::isZeroNode(SDValue Elt) {
4180 return ((isa<ConstantSDNode>(Elt) &&
4181 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4182 (isa<ConstantFPSDNode>(Elt) &&
4183 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4186 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4187 /// their permute mask.
4188 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4189 SelectionDAG &DAG) {
4190 EVT VT = SVOp->getValueType(0);
4191 unsigned NumElems = VT.getVectorNumElements();
4192 SmallVector<int, 8> MaskVec;
4194 for (unsigned i = 0; i != NumElems; ++i) {
4195 int Idx = SVOp->getMaskElt(i);
4197 if (Idx < (int)NumElems)
4202 MaskVec.push_back(Idx);
4204 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4205 SVOp->getOperand(0), &MaskVec[0]);
4208 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4209 /// match movhlps. The lower half elements should come from upper half of
4210 /// V1 (and in order), and the upper half elements should come from the upper
4211 /// half of V2 (and in order).
4212 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4213 if (!VT.is128BitVector())
4215 if (VT.getVectorNumElements() != 4)
4217 for (unsigned i = 0, e = 2; i != e; ++i)
4218 if (!isUndefOrEqual(Mask[i], i+2))
4220 for (unsigned i = 2; i != 4; ++i)
4221 if (!isUndefOrEqual(Mask[i], i+4))
4226 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4227 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4229 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4230 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4232 N = N->getOperand(0).getNode();
4233 if (!ISD::isNON_EXTLoad(N))
4236 *LD = cast<LoadSDNode>(N);
4240 // Test whether the given value is a vector value which will be legalized
4242 static bool WillBeConstantPoolLoad(SDNode *N) {
4243 if (N->getOpcode() != ISD::BUILD_VECTOR)
4246 // Check for any non-constant elements.
4247 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4248 switch (N->getOperand(i).getNode()->getOpcode()) {
4250 case ISD::ConstantFP:
4257 // Vectors of all-zeros and all-ones are materialized with special
4258 // instructions rather than being loaded.
4259 return !ISD::isBuildVectorAllZeros(N) &&
4260 !ISD::isBuildVectorAllOnes(N);
4263 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4264 /// match movlp{s|d}. The lower half elements should come from lower half of
4265 /// V1 (and in order), and the upper half elements should come from the upper
4266 /// half of V2 (and in order). And since V1 will become the source of the
4267 /// MOVLP, it must be either a vector load or a scalar load to vector.
4268 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4269 ArrayRef<int> Mask, EVT VT) {
4270 if (!VT.is128BitVector())
4273 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4275 // Is V2 is a vector load, don't do this transformation. We will try to use
4276 // load folding shufps op.
4277 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4280 unsigned NumElems = VT.getVectorNumElements();
4282 if (NumElems != 2 && NumElems != 4)
4284 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4285 if (!isUndefOrEqual(Mask[i], i))
4287 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4288 if (!isUndefOrEqual(Mask[i], i+NumElems))
4293 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4295 static bool isSplatVector(SDNode *N) {
4296 if (N->getOpcode() != ISD::BUILD_VECTOR)
4299 SDValue SplatValue = N->getOperand(0);
4300 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4301 if (N->getOperand(i) != SplatValue)
4306 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4307 /// to an zero vector.
4308 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4309 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4310 SDValue V1 = N->getOperand(0);
4311 SDValue V2 = N->getOperand(1);
4312 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4313 for (unsigned i = 0; i != NumElems; ++i) {
4314 int Idx = N->getMaskElt(i);
4315 if (Idx >= (int)NumElems) {
4316 unsigned Opc = V2.getOpcode();
4317 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4319 if (Opc != ISD::BUILD_VECTOR ||
4320 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4322 } else if (Idx >= 0) {
4323 unsigned Opc = V1.getOpcode();
4324 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4326 if (Opc != ISD::BUILD_VECTOR ||
4327 !X86::isZeroNode(V1.getOperand(Idx)))
4334 /// getZeroVector - Returns a vector of specified type with all zero elements.
4336 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4337 SelectionDAG &DAG, DebugLoc dl) {
4338 assert(VT.isVector() && "Expected a vector type");
4339 unsigned Size = VT.getSizeInBits();
4341 // Always build SSE zero vectors as <4 x i32> bitcasted
4342 // to their dest type. This ensures they get CSE'd.
4344 if (Size == 128) { // SSE
4345 if (Subtarget->hasSSE2()) { // SSE2
4346 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4347 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4349 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4350 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4352 } else if (Size == 256) { // AVX
4353 if (Subtarget->hasInt256()) { // AVX2
4354 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4355 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4356 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4358 // 256-bit logic and arithmetic instructions in AVX are all
4359 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4360 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4361 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4362 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4365 llvm_unreachable("Unexpected vector type");
4367 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4370 /// getOnesVector - Returns a vector of specified type with all bits set.
4371 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4372 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4373 /// Then bitcast to their original type, ensuring they get CSE'd.
4374 static SDValue getOnesVector(EVT VT, bool HasInt256, SelectionDAG &DAG,
4376 assert(VT.isVector() && "Expected a vector type");
4377 unsigned Size = VT.getSizeInBits();
4379 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4382 if (HasInt256) { // AVX2
4383 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4386 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4387 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4389 } else if (Size == 128) {
4390 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4392 llvm_unreachable("Unexpected vector type");
4394 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4397 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4398 /// that point to V2 points to its first element.
4399 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4400 for (unsigned i = 0; i != NumElems; ++i) {
4401 if (Mask[i] > (int)NumElems) {
4407 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4408 /// operation of specified width.
4409 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4411 unsigned NumElems = VT.getVectorNumElements();
4412 SmallVector<int, 8> Mask;
4413 Mask.push_back(NumElems);
4414 for (unsigned i = 1; i != NumElems; ++i)
4416 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4419 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4420 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4422 unsigned NumElems = VT.getVectorNumElements();
4423 SmallVector<int, 8> Mask;
4424 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4426 Mask.push_back(i + NumElems);
4428 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4431 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4432 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4434 unsigned NumElems = VT.getVectorNumElements();
4435 SmallVector<int, 8> Mask;
4436 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4437 Mask.push_back(i + Half);
4438 Mask.push_back(i + NumElems + Half);
4440 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4443 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4444 // a generic shuffle instruction because the target has no such instructions.
4445 // Generate shuffles which repeat i16 and i8 several times until they can be
4446 // represented by v4f32 and then be manipulated by target suported shuffles.
4447 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4448 EVT VT = V.getValueType();
4449 int NumElems = VT.getVectorNumElements();
4450 DebugLoc dl = V.getDebugLoc();
4452 while (NumElems > 4) {
4453 if (EltNo < NumElems/2) {
4454 V = getUnpackl(DAG, dl, VT, V, V);
4456 V = getUnpackh(DAG, dl, VT, V, V);
4457 EltNo -= NumElems/2;
4464 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4465 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4466 EVT VT = V.getValueType();
4467 DebugLoc dl = V.getDebugLoc();
4468 unsigned Size = VT.getSizeInBits();
4471 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4472 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4473 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4475 } else if (Size == 256) {
4476 // To use VPERMILPS to splat scalars, the second half of indicies must
4477 // refer to the higher part, which is a duplication of the lower one,
4478 // because VPERMILPS can only handle in-lane permutations.
4479 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4480 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4482 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4483 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4486 llvm_unreachable("Vector size not supported");
4488 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4491 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4492 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4493 EVT SrcVT = SV->getValueType(0);
4494 SDValue V1 = SV->getOperand(0);
4495 DebugLoc dl = SV->getDebugLoc();
4497 int EltNo = SV->getSplatIndex();
4498 int NumElems = SrcVT.getVectorNumElements();
4499 unsigned Size = SrcVT.getSizeInBits();
4501 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4502 "Unknown how to promote splat for type");
4504 // Extract the 128-bit part containing the splat element and update
4505 // the splat element index when it refers to the higher register.
4507 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4508 if (EltNo >= NumElems/2)
4509 EltNo -= NumElems/2;
4512 // All i16 and i8 vector types can't be used directly by a generic shuffle
4513 // instruction because the target has no such instruction. Generate shuffles
4514 // which repeat i16 and i8 several times until they fit in i32, and then can
4515 // be manipulated by target suported shuffles.
4516 EVT EltVT = SrcVT.getVectorElementType();
4517 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4518 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4520 // Recreate the 256-bit vector and place the same 128-bit vector
4521 // into the low and high part. This is necessary because we want
4522 // to use VPERM* to shuffle the vectors
4524 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4527 return getLegalSplat(DAG, V1, EltNo);
4530 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4531 /// vector of zero or undef vector. This produces a shuffle where the low
4532 /// element of V2 is swizzled into the zero/undef vector, landing at element
4533 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4534 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4536 const X86Subtarget *Subtarget,
4537 SelectionDAG &DAG) {
4538 EVT VT = V2.getValueType();
4540 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4541 unsigned NumElems = VT.getVectorNumElements();
4542 SmallVector<int, 16> MaskVec;
4543 for (unsigned i = 0; i != NumElems; ++i)
4544 // If this is the insertion idx, put the low elt of V2 here.
4545 MaskVec.push_back(i == Idx ? NumElems : i);
4546 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4549 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4550 /// target specific opcode. Returns true if the Mask could be calculated.
4551 /// Sets IsUnary to true if only uses one source.
4552 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4553 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4554 unsigned NumElems = VT.getVectorNumElements();
4558 switch(N->getOpcode()) {
4560 ImmN = N->getOperand(N->getNumOperands()-1);
4561 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563 case X86ISD::UNPCKH:
4564 DecodeUNPCKHMask(VT, Mask);
4566 case X86ISD::UNPCKL:
4567 DecodeUNPCKLMask(VT, Mask);
4569 case X86ISD::MOVHLPS:
4570 DecodeMOVHLPSMask(NumElems, Mask);
4572 case X86ISD::MOVLHPS:
4573 DecodeMOVLHPSMask(NumElems, Mask);
4575 case X86ISD::PSHUFD:
4576 case X86ISD::VPERMILP:
4577 ImmN = N->getOperand(N->getNumOperands()-1);
4578 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4581 case X86ISD::PSHUFHW:
4582 ImmN = N->getOperand(N->getNumOperands()-1);
4583 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4586 case X86ISD::PSHUFLW:
4587 ImmN = N->getOperand(N->getNumOperands()-1);
4588 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4591 case X86ISD::VPERMI:
4592 ImmN = N->getOperand(N->getNumOperands()-1);
4593 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4597 case X86ISD::MOVSD: {
4598 // The index 0 always comes from the first element of the second source,
4599 // this is why MOVSS and MOVSD are used in the first place. The other
4600 // elements come from the other positions of the first source vector
4601 Mask.push_back(NumElems);
4602 for (unsigned i = 1; i != NumElems; ++i) {
4607 case X86ISD::VPERM2X128:
4608 ImmN = N->getOperand(N->getNumOperands()-1);
4609 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4610 if (Mask.empty()) return false;
4612 case X86ISD::MOVDDUP:
4613 case X86ISD::MOVLHPD:
4614 case X86ISD::MOVLPD:
4615 case X86ISD::MOVLPS:
4616 case X86ISD::MOVSHDUP:
4617 case X86ISD::MOVSLDUP:
4618 case X86ISD::PALIGN:
4619 // Not yet implemented
4621 default: llvm_unreachable("unknown target shuffle node");
4627 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4628 /// element of the result of the vector shuffle.
4629 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4632 return SDValue(); // Limit search depth.
4634 SDValue V = SDValue(N, 0);
4635 EVT VT = V.getValueType();
4636 unsigned Opcode = V.getOpcode();
4638 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4639 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4640 int Elt = SV->getMaskElt(Index);
4643 return DAG.getUNDEF(VT.getVectorElementType());
4645 unsigned NumElems = VT.getVectorNumElements();
4646 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4647 : SV->getOperand(1);
4648 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4651 // Recurse into target specific vector shuffles to find scalars.
4652 if (isTargetShuffle(Opcode)) {
4653 MVT ShufVT = V.getValueType().getSimpleVT();
4654 unsigned NumElems = ShufVT.getVectorNumElements();
4655 SmallVector<int, 16> ShuffleMask;
4658 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4661 int Elt = ShuffleMask[Index];
4663 return DAG.getUNDEF(ShufVT.getVectorElementType());
4665 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4667 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4671 // Actual nodes that may contain scalar elements
4672 if (Opcode == ISD::BITCAST) {
4673 V = V.getOperand(0);
4674 EVT SrcVT = V.getValueType();
4675 unsigned NumElems = VT.getVectorNumElements();
4677 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4681 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4682 return (Index == 0) ? V.getOperand(0)
4683 : DAG.getUNDEF(VT.getVectorElementType());
4685 if (V.getOpcode() == ISD::BUILD_VECTOR)
4686 return V.getOperand(Index);
4691 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4692 /// shuffle operation which come from a consecutively from a zero. The
4693 /// search can start in two different directions, from left or right.
4695 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4696 bool ZerosFromLeft, SelectionDAG &DAG) {
4698 for (i = 0; i != NumElems; ++i) {
4699 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4700 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4701 if (!(Elt.getNode() &&
4702 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4709 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4710 /// correspond consecutively to elements from one of the vector operands,
4711 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4713 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4714 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4715 unsigned NumElems, unsigned &OpNum) {
4716 bool SeenV1 = false;
4717 bool SeenV2 = false;
4719 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4720 int Idx = SVOp->getMaskElt(i);
4721 // Ignore undef indicies
4725 if (Idx < (int)NumElems)
4730 // Only accept consecutive elements from the same vector
4731 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4735 OpNum = SeenV1 ? 0 : 1;
4739 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4740 /// logical left shift of a vector.
4741 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4742 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4743 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4744 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4745 false /* check zeros from right */, DAG);
4751 // Considering the elements in the mask that are not consecutive zeros,
4752 // check if they consecutively come from only one of the source vectors.
4754 // V1 = {X, A, B, C} 0
4756 // vector_shuffle V1, V2 <1, 2, 3, X>
4758 if (!isShuffleMaskConsecutive(SVOp,
4759 0, // Mask Start Index
4760 NumElems-NumZeros, // Mask End Index(exclusive)
4761 NumZeros, // Where to start looking in the src vector
4762 NumElems, // Number of elements in vector
4763 OpSrc)) // Which source operand ?
4768 ShVal = SVOp->getOperand(OpSrc);
4772 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4773 /// logical left shift of a vector.
4774 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4775 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4776 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4777 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4778 true /* check zeros from left */, DAG);
4784 // Considering the elements in the mask that are not consecutive zeros,
4785 // check if they consecutively come from only one of the source vectors.
4787 // 0 { A, B, X, X } = V2
4789 // vector_shuffle V1, V2 <X, X, 4, 5>
4791 if (!isShuffleMaskConsecutive(SVOp,
4792 NumZeros, // Mask Start Index
4793 NumElems, // Mask End Index(exclusive)
4794 0, // Where to start looking in the src vector
4795 NumElems, // Number of elements in vector
4796 OpSrc)) // Which source operand ?
4801 ShVal = SVOp->getOperand(OpSrc);
4805 /// isVectorShift - Returns true if the shuffle can be implemented as a
4806 /// logical left or right shift of a vector.
4807 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4808 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4809 // Although the logic below support any bitwidth size, there are no
4810 // shift instructions which handle more than 128-bit vectors.
4811 if (!SVOp->getValueType(0).is128BitVector())
4814 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4815 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4821 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4823 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4824 unsigned NumNonZero, unsigned NumZero,
4826 const X86Subtarget* Subtarget,
4827 const TargetLowering &TLI) {
4831 DebugLoc dl = Op.getDebugLoc();
4834 for (unsigned i = 0; i < 16; ++i) {
4835 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4836 if (ThisIsNonZero && First) {
4838 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4840 V = DAG.getUNDEF(MVT::v8i16);
4845 SDValue ThisElt(0, 0), LastElt(0, 0);
4846 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4847 if (LastIsNonZero) {
4848 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4849 MVT::i16, Op.getOperand(i-1));
4851 if (ThisIsNonZero) {
4852 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4853 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4854 ThisElt, DAG.getConstant(8, MVT::i8));
4856 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4860 if (ThisElt.getNode())
4861 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4862 DAG.getIntPtrConstant(i/2));
4866 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4869 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4871 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4872 unsigned NumNonZero, unsigned NumZero,
4874 const X86Subtarget* Subtarget,
4875 const TargetLowering &TLI) {
4879 DebugLoc dl = Op.getDebugLoc();
4882 for (unsigned i = 0; i < 8; ++i) {
4883 bool isNonZero = (NonZeros & (1 << i)) != 0;
4887 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4889 V = DAG.getUNDEF(MVT::v8i16);
4892 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4893 MVT::v8i16, V, Op.getOperand(i),
4894 DAG.getIntPtrConstant(i));
4901 /// getVShift - Return a vector logical shift node.
4903 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4904 unsigned NumBits, SelectionDAG &DAG,
4905 const TargetLowering &TLI, DebugLoc dl) {
4906 assert(VT.is128BitVector() && "Unknown type for VShift");
4907 EVT ShVT = MVT::v2i64;
4908 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4909 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4910 return DAG.getNode(ISD::BITCAST, dl, VT,
4911 DAG.getNode(Opc, dl, ShVT, SrcOp,
4912 DAG.getConstant(NumBits,
4913 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4917 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4918 SelectionDAG &DAG) const {
4920 // Check if the scalar load can be widened into a vector load. And if
4921 // the address is "base + cst" see if the cst can be "absorbed" into
4922 // the shuffle mask.
4923 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4924 SDValue Ptr = LD->getBasePtr();
4925 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4927 EVT PVT = LD->getValueType(0);
4928 if (PVT != MVT::i32 && PVT != MVT::f32)
4933 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4934 FI = FINode->getIndex();
4936 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4937 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4938 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4939 Offset = Ptr.getConstantOperandVal(1);
4940 Ptr = Ptr.getOperand(0);
4945 // FIXME: 256-bit vector instructions don't require a strict alignment,
4946 // improve this code to support it better.
4947 unsigned RequiredAlign = VT.getSizeInBits()/8;
4948 SDValue Chain = LD->getChain();
4949 // Make sure the stack object alignment is at least 16 or 32.
4950 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4951 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4952 if (MFI->isFixedObjectIndex(FI)) {
4953 // Can't change the alignment. FIXME: It's possible to compute
4954 // the exact stack offset and reference FI + adjust offset instead.
4955 // If someone *really* cares about this. That's the way to implement it.
4958 MFI->setObjectAlignment(FI, RequiredAlign);
4962 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4963 // Ptr + (Offset & ~15).
4966 if ((Offset % RequiredAlign) & 3)
4968 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4970 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4971 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4973 int EltNo = (Offset - StartOffset) >> 2;
4974 unsigned NumElems = VT.getVectorNumElements();
4976 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4977 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4978 LD->getPointerInfo().getWithOffset(StartOffset),
4979 false, false, false, 0);
4981 SmallVector<int, 8> Mask;
4982 for (unsigned i = 0; i != NumElems; ++i)
4983 Mask.push_back(EltNo);
4985 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4991 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4992 /// vector of type 'VT', see if the elements can be replaced by a single large
4993 /// load which has the same value as a build_vector whose operands are 'elts'.
4995 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4997 /// FIXME: we'd also like to handle the case where the last elements are zero
4998 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4999 /// There's even a handy isZeroNode for that purpose.
5000 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5001 DebugLoc &DL, SelectionDAG &DAG) {
5002 EVT EltVT = VT.getVectorElementType();
5003 unsigned NumElems = Elts.size();
5005 LoadSDNode *LDBase = NULL;
5006 unsigned LastLoadedElt = -1U;
5008 // For each element in the initializer, see if we've found a load or an undef.
5009 // If we don't find an initial load element, or later load elements are
5010 // non-consecutive, bail out.
5011 for (unsigned i = 0; i < NumElems; ++i) {
5012 SDValue Elt = Elts[i];
5014 if (!Elt.getNode() ||
5015 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5018 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5020 LDBase = cast<LoadSDNode>(Elt.getNode());
5024 if (Elt.getOpcode() == ISD::UNDEF)
5027 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5028 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5033 // If we have found an entire vector of loads and undefs, then return a large
5034 // load of the entire vector width starting at the base pointer. If we found
5035 // consecutive loads for the low half, generate a vzext_load node.
5036 if (LastLoadedElt == NumElems - 1) {
5037 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5038 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5039 LDBase->getPointerInfo(),
5040 LDBase->isVolatile(), LDBase->isNonTemporal(),
5041 LDBase->isInvariant(), 0);
5042 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5043 LDBase->getPointerInfo(),
5044 LDBase->isVolatile(), LDBase->isNonTemporal(),
5045 LDBase->isInvariant(), LDBase->getAlignment());
5047 if (NumElems == 4 && LastLoadedElt == 1 &&
5048 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5049 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5050 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5052 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5053 LDBase->getPointerInfo(),
5054 LDBase->getAlignment(),
5055 false/*isVolatile*/, true/*ReadMem*/,
5058 // Make sure the newly-created LOAD is in the same position as LDBase in
5059 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5060 // update uses of LDBase's output chain to use the TokenFactor.
5061 if (LDBase->hasAnyUseOfValue(1)) {
5062 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5063 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5064 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5065 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5066 SDValue(ResNode.getNode(), 1));
5069 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5074 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5075 /// to generate a splat value for the following cases:
5076 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5077 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5078 /// a scalar load, or a constant.
5079 /// The VBROADCAST node is returned when a pattern is found,
5080 /// or SDValue() otherwise.
5082 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5083 if (!Subtarget->hasFp256())
5086 EVT VT = Op.getValueType();
5087 DebugLoc dl = Op.getDebugLoc();
5089 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5090 "Unsupported vector type for broadcast.");
5095 switch (Op.getOpcode()) {
5097 // Unknown pattern found.
5100 case ISD::BUILD_VECTOR: {
5101 // The BUILD_VECTOR node must be a splat.
5102 if (!isSplatVector(Op.getNode()))
5105 Ld = Op.getOperand(0);
5106 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5107 Ld.getOpcode() == ISD::ConstantFP);
5109 // The suspected load node has several users. Make sure that all
5110 // of its users are from the BUILD_VECTOR node.
5111 // Constants may have multiple users.
5112 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5117 case ISD::VECTOR_SHUFFLE: {
5118 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5120 // Shuffles must have a splat mask where the first element is
5122 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5125 SDValue Sc = Op.getOperand(0);
5126 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5127 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5129 if (!Subtarget->hasInt256())
5132 // Use the register form of the broadcast instruction available on AVX2.
5133 if (VT.is256BitVector())
5134 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5135 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5138 Ld = Sc.getOperand(0);
5139 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5140 Ld.getOpcode() == ISD::ConstantFP);
5142 // The scalar_to_vector node and the suspected
5143 // load node must have exactly one user.
5144 // Constants may have multiple users.
5145 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5151 bool Is256 = VT.is256BitVector();
5153 // Handle the broadcasting a single constant scalar from the constant pool
5154 // into a vector. On Sandybridge it is still better to load a constant vector
5155 // from the constant pool and not to broadcast it from a scalar.
5156 if (ConstSplatVal && Subtarget->hasInt256()) {
5157 EVT CVT = Ld.getValueType();
5158 assert(!CVT.isVector() && "Must not broadcast a vector type");
5159 unsigned ScalarSize = CVT.getSizeInBits();
5161 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5162 const Constant *C = 0;
5163 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5164 C = CI->getConstantIntValue();
5165 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5166 C = CF->getConstantFPValue();
5168 assert(C && "Invalid constant type");
5170 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5171 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5172 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5173 MachinePointerInfo::getConstantPool(),
5174 false, false, false, Alignment);
5176 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5180 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5181 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5183 // Handle AVX2 in-register broadcasts.
5184 if (!IsLoad && Subtarget->hasInt256() &&
5185 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5186 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5188 // The scalar source must be a normal load.
5192 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5193 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5195 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5196 // double since there is no vbroadcastsd xmm
5197 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5198 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5199 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5202 // Unsupported broadcast.
5207 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5208 EVT VT = Op.getValueType();
5210 // Skip if insert_vec_elt is not supported.
5211 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5214 DebugLoc DL = Op.getDebugLoc();
5215 unsigned NumElems = Op.getNumOperands();
5219 SmallVector<unsigned, 4> InsertIndices;
5220 SmallVector<int, 8> Mask(NumElems, -1);
5222 for (unsigned i = 0; i != NumElems; ++i) {
5223 unsigned Opc = Op.getOperand(i).getOpcode();
5225 if (Opc == ISD::UNDEF)
5228 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5229 // Quit if more than 1 elements need inserting.
5230 if (InsertIndices.size() > 1)
5233 InsertIndices.push_back(i);
5237 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5238 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5240 // Quit if extracted from vector of different type.
5241 if (ExtractedFromVec.getValueType() != VT)
5244 // Quit if non-constant index.
5245 if (!isa<ConstantSDNode>(ExtIdx))
5248 if (VecIn1.getNode() == 0)
5249 VecIn1 = ExtractedFromVec;
5250 else if (VecIn1 != ExtractedFromVec) {
5251 if (VecIn2.getNode() == 0)
5252 VecIn2 = ExtractedFromVec;
5253 else if (VecIn2 != ExtractedFromVec)
5254 // Quit if more than 2 vectors to shuffle
5258 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5260 if (ExtractedFromVec == VecIn1)
5262 else if (ExtractedFromVec == VecIn2)
5263 Mask[i] = Idx + NumElems;
5266 if (VecIn1.getNode() == 0)
5269 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5270 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5271 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5272 unsigned Idx = InsertIndices[i];
5273 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5274 DAG.getIntPtrConstant(Idx));
5281 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5282 DebugLoc dl = Op.getDebugLoc();
5284 EVT VT = Op.getValueType();
5285 EVT ExtVT = VT.getVectorElementType();
5286 unsigned NumElems = Op.getNumOperands();
5288 // Vectors containing all zeros can be matched by pxor and xorps later
5289 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5290 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5291 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5292 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5295 return getZeroVector(VT, Subtarget, DAG, dl);
5298 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5299 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5300 // vpcmpeqd on 256-bit vectors.
5301 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5302 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5305 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5308 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5309 if (Broadcast.getNode())
5312 unsigned EVTBits = ExtVT.getSizeInBits();
5314 unsigned NumZero = 0;
5315 unsigned NumNonZero = 0;
5316 unsigned NonZeros = 0;
5317 bool IsAllConstants = true;
5318 SmallSet<SDValue, 8> Values;
5319 for (unsigned i = 0; i < NumElems; ++i) {
5320 SDValue Elt = Op.getOperand(i);
5321 if (Elt.getOpcode() == ISD::UNDEF)
5324 if (Elt.getOpcode() != ISD::Constant &&
5325 Elt.getOpcode() != ISD::ConstantFP)
5326 IsAllConstants = false;
5327 if (X86::isZeroNode(Elt))
5330 NonZeros |= (1 << i);
5335 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5336 if (NumNonZero == 0)
5337 return DAG.getUNDEF(VT);
5339 // Special case for single non-zero, non-undef, element.
5340 if (NumNonZero == 1) {
5341 unsigned Idx = CountTrailingZeros_32(NonZeros);
5342 SDValue Item = Op.getOperand(Idx);
5344 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5345 // the value are obviously zero, truncate the value to i32 and do the
5346 // insertion that way. Only do this if the value is non-constant or if the
5347 // value is a constant being inserted into element 0. It is cheaper to do
5348 // a constant pool load than it is to do a movd + shuffle.
5349 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5350 (!IsAllConstants || Idx == 0)) {
5351 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5353 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5354 EVT VecVT = MVT::v4i32;
5355 unsigned VecElts = 4;
5357 // Truncate the value (which may itself be a constant) to i32, and
5358 // convert it to a vector with movd (S2V+shuffle to zero extend).
5359 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5360 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5361 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5363 // Now we have our 32-bit value zero extended in the low element of
5364 // a vector. If Idx != 0, swizzle it into place.
5366 SmallVector<int, 4> Mask;
5367 Mask.push_back(Idx);
5368 for (unsigned i = 1; i != VecElts; ++i)
5370 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5373 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5377 // If we have a constant or non-constant insertion into the low element of
5378 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5379 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5380 // depending on what the source datatype is.
5383 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5385 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5386 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5387 if (VT.is256BitVector()) {
5388 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5389 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5390 Item, DAG.getIntPtrConstant(0));
5392 assert(VT.is128BitVector() && "Expected an SSE value type!");
5393 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5394 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5395 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5398 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5399 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5400 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5401 if (VT.is256BitVector()) {
5402 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5403 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5405 assert(VT.is128BitVector() && "Expected an SSE value type!");
5406 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5408 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5412 // Is it a vector logical left shift?
5413 if (NumElems == 2 && Idx == 1 &&
5414 X86::isZeroNode(Op.getOperand(0)) &&
5415 !X86::isZeroNode(Op.getOperand(1))) {
5416 unsigned NumBits = VT.getSizeInBits();
5417 return getVShift(true, VT,
5418 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5419 VT, Op.getOperand(1)),
5420 NumBits/2, DAG, *this, dl);
5423 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5426 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5427 // is a non-constant being inserted into an element other than the low one,
5428 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5429 // movd/movss) to move this into the low element, then shuffle it into
5431 if (EVTBits == 32) {
5432 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5434 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5435 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5436 SmallVector<int, 8> MaskVec;
5437 for (unsigned i = 0; i != NumElems; ++i)
5438 MaskVec.push_back(i == Idx ? 0 : 1);
5439 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5443 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5444 if (Values.size() == 1) {
5445 if (EVTBits == 32) {
5446 // Instead of a shuffle like this:
5447 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5448 // Check if it's possible to issue this instead.
5449 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5450 unsigned Idx = CountTrailingZeros_32(NonZeros);
5451 SDValue Item = Op.getOperand(Idx);
5452 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5453 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5458 // A vector full of immediates; various special cases are already
5459 // handled, so this is best done with a single constant-pool load.
5463 // For AVX-length vectors, build the individual 128-bit pieces and use
5464 // shuffles to put them in place.
5465 if (VT.is256BitVector()) {
5466 SmallVector<SDValue, 32> V;
5467 for (unsigned i = 0; i != NumElems; ++i)
5468 V.push_back(Op.getOperand(i));
5470 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5472 // Build both the lower and upper subvector.
5473 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5474 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5477 // Recreate the wider vector with the lower and upper part.
5478 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5481 // Let legalizer expand 2-wide build_vectors.
5482 if (EVTBits == 64) {
5483 if (NumNonZero == 1) {
5484 // One half is zero or undef.
5485 unsigned Idx = CountTrailingZeros_32(NonZeros);
5486 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5487 Op.getOperand(Idx));
5488 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5493 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5494 if (EVTBits == 8 && NumElems == 16) {
5495 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5497 if (V.getNode()) return V;
5500 if (EVTBits == 16 && NumElems == 8) {
5501 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5503 if (V.getNode()) return V;
5506 // If element VT is == 32 bits, turn it into a number of shuffles.
5507 SmallVector<SDValue, 8> V(NumElems);
5508 if (NumElems == 4 && NumZero > 0) {
5509 for (unsigned i = 0; i < 4; ++i) {
5510 bool isZero = !(NonZeros & (1 << i));
5512 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5514 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5517 for (unsigned i = 0; i < 2; ++i) {
5518 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5521 V[i] = V[i*2]; // Must be a zero vector.
5524 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5527 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5530 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5535 bool Reverse1 = (NonZeros & 0x3) == 2;
5536 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5540 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5541 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5543 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5546 if (Values.size() > 1 && VT.is128BitVector()) {
5547 // Check for a build vector of consecutive loads.
5548 for (unsigned i = 0; i < NumElems; ++i)
5549 V[i] = Op.getOperand(i);
5551 // Check for elements which are consecutive loads.
5552 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5556 // Check for a build vector from mostly shuffle plus few inserting.
5557 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5561 // For SSE 4.1, use insertps to put the high elements into the low element.
5562 if (getSubtarget()->hasSSE41()) {
5564 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5565 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5567 Result = DAG.getUNDEF(VT);
5569 for (unsigned i = 1; i < NumElems; ++i) {
5570 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5571 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5572 Op.getOperand(i), DAG.getIntPtrConstant(i));
5577 // Otherwise, expand into a number of unpckl*, start by extending each of
5578 // our (non-undef) elements to the full vector width with the element in the
5579 // bottom slot of the vector (which generates no code for SSE).
5580 for (unsigned i = 0; i < NumElems; ++i) {
5581 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5582 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5584 V[i] = DAG.getUNDEF(VT);
5587 // Next, we iteratively mix elements, e.g. for v4f32:
5588 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5589 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5590 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5591 unsigned EltStride = NumElems >> 1;
5592 while (EltStride != 0) {
5593 for (unsigned i = 0; i < EltStride; ++i) {
5594 // If V[i+EltStride] is undef and this is the first round of mixing,
5595 // then it is safe to just drop this shuffle: V[i] is already in the
5596 // right place, the one element (since it's the first round) being
5597 // inserted as undef can be dropped. This isn't safe for successive
5598 // rounds because they will permute elements within both vectors.
5599 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5600 EltStride == NumElems/2)
5603 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5612 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5613 // to create 256-bit vectors from two other 128-bit ones.
5614 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5615 DebugLoc dl = Op.getDebugLoc();
5616 EVT ResVT = Op.getValueType();
5618 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5620 SDValue V1 = Op.getOperand(0);
5621 SDValue V2 = Op.getOperand(1);
5622 unsigned NumElems = ResVT.getVectorNumElements();
5624 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5627 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5628 assert(Op.getNumOperands() == 2);
5630 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5631 // from two other 128-bit ones.
5632 return LowerAVXCONCAT_VECTORS(Op, DAG);
5635 // Try to lower a shuffle node into a simple blend instruction.
5637 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5638 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5639 SDValue V1 = SVOp->getOperand(0);
5640 SDValue V2 = SVOp->getOperand(1);
5641 DebugLoc dl = SVOp->getDebugLoc();
5642 EVT VT = SVOp->getValueType(0);
5643 EVT EltVT = VT.getVectorElementType();
5644 unsigned NumElems = VT.getVectorNumElements();
5646 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5648 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5651 // Check the mask for BLEND and build the value.
5652 unsigned MaskValue = 0;
5653 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5654 unsigned NumLanes = (NumElems-1)/8 + 1;
5655 unsigned NumElemsInLane = NumElems / NumLanes;
5657 // Blend for v16i16 should be symetric for the both lanes.
5658 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5660 int SndLaneEltIdx = (NumLanes == 2) ?
5661 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5662 int EltIdx = SVOp->getMaskElt(i);
5664 if ((EltIdx == -1 || EltIdx == (int)i) &&
5665 (SndLaneEltIdx == -1 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5668 if (((unsigned)EltIdx == (i + NumElems)) &&
5669 (SndLaneEltIdx == -1 ||
5670 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5671 MaskValue |= (1<<i);
5676 // Convert i32 vectors to floating point if it is not AVX2.
5677 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5679 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5680 BlendVT = EVT::getVectorVT(*DAG.getContext(),
5681 EVT::getFloatingPointVT(EltVT.getSizeInBits()),
5683 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5684 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5687 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5688 DAG.getConstant(MaskValue, MVT::i32));
5689 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5692 // v8i16 shuffles - Prefer shuffles in the following order:
5693 // 1. [all] pshuflw, pshufhw, optional move
5694 // 2. [ssse3] 1 x pshufb
5695 // 3. [ssse3] 2 x pshufb + 1 x por
5696 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5698 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5699 SelectionDAG &DAG) {
5700 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5701 SDValue V1 = SVOp->getOperand(0);
5702 SDValue V2 = SVOp->getOperand(1);
5703 DebugLoc dl = SVOp->getDebugLoc();
5704 SmallVector<int, 8> MaskVals;
5706 // Determine if more than 1 of the words in each of the low and high quadwords
5707 // of the result come from the same quadword of one of the two inputs. Undef
5708 // mask values count as coming from any quadword, for better codegen.
5709 unsigned LoQuad[] = { 0, 0, 0, 0 };
5710 unsigned HiQuad[] = { 0, 0, 0, 0 };
5711 std::bitset<4> InputQuads;
5712 for (unsigned i = 0; i < 8; ++i) {
5713 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5714 int EltIdx = SVOp->getMaskElt(i);
5715 MaskVals.push_back(EltIdx);
5724 InputQuads.set(EltIdx / 4);
5727 int BestLoQuad = -1;
5728 unsigned MaxQuad = 1;
5729 for (unsigned i = 0; i < 4; ++i) {
5730 if (LoQuad[i] > MaxQuad) {
5732 MaxQuad = LoQuad[i];
5736 int BestHiQuad = -1;
5738 for (unsigned i = 0; i < 4; ++i) {
5739 if (HiQuad[i] > MaxQuad) {
5741 MaxQuad = HiQuad[i];
5745 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5746 // of the two input vectors, shuffle them into one input vector so only a
5747 // single pshufb instruction is necessary. If There are more than 2 input
5748 // quads, disable the next transformation since it does not help SSSE3.
5749 bool V1Used = InputQuads[0] || InputQuads[1];
5750 bool V2Used = InputQuads[2] || InputQuads[3];
5751 if (Subtarget->hasSSSE3()) {
5752 if (InputQuads.count() == 2 && V1Used && V2Used) {
5753 BestLoQuad = InputQuads[0] ? 0 : 1;
5754 BestHiQuad = InputQuads[2] ? 2 : 3;
5756 if (InputQuads.count() > 2) {
5762 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5763 // the shuffle mask. If a quad is scored as -1, that means that it contains
5764 // words from all 4 input quadwords.
5766 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5768 BestLoQuad < 0 ? 0 : BestLoQuad,
5769 BestHiQuad < 0 ? 1 : BestHiQuad
5771 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5772 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5773 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5774 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5776 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5777 // source words for the shuffle, to aid later transformations.
5778 bool AllWordsInNewV = true;
5779 bool InOrder[2] = { true, true };
5780 for (unsigned i = 0; i != 8; ++i) {
5781 int idx = MaskVals[i];
5783 InOrder[i/4] = false;
5784 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5786 AllWordsInNewV = false;
5790 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5791 if (AllWordsInNewV) {
5792 for (int i = 0; i != 8; ++i) {
5793 int idx = MaskVals[i];
5796 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5797 if ((idx != i) && idx < 4)
5799 if ((idx != i) && idx > 3)
5808 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5809 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5810 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5811 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5812 unsigned TargetMask = 0;
5813 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5814 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5815 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5816 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5817 getShufflePSHUFLWImmediate(SVOp);
5818 V1 = NewV.getOperand(0);
5819 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5823 // If we have SSSE3, and all words of the result are from 1 input vector,
5824 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5825 // is present, fall back to case 4.
5826 if (Subtarget->hasSSSE3()) {
5827 SmallVector<SDValue,16> pshufbMask;
5829 // If we have elements from both input vectors, set the high bit of the
5830 // shuffle mask element to zero out elements that come from V2 in the V1
5831 // mask, and elements that come from V1 in the V2 mask, so that the two
5832 // results can be OR'd together.
5833 bool TwoInputs = V1Used && V2Used;
5834 for (unsigned i = 0; i != 8; ++i) {
5835 int EltIdx = MaskVals[i] * 2;
5836 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5837 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5838 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5839 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5841 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5842 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5843 DAG.getNode(ISD::BUILD_VECTOR, dl,
5844 MVT::v16i8, &pshufbMask[0], 16));
5846 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5848 // Calculate the shuffle mask for the second input, shuffle it, and
5849 // OR it with the first shuffled input.
5851 for (unsigned i = 0; i != 8; ++i) {
5852 int EltIdx = MaskVals[i] * 2;
5853 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5854 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5855 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5856 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5858 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5859 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5860 DAG.getNode(ISD::BUILD_VECTOR, dl,
5861 MVT::v16i8, &pshufbMask[0], 16));
5862 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5863 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5866 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5867 // and update MaskVals with new element order.
5868 std::bitset<8> InOrder;
5869 if (BestLoQuad >= 0) {
5870 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5871 for (int i = 0; i != 4; ++i) {
5872 int idx = MaskVals[i];
5875 } else if ((idx / 4) == BestLoQuad) {
5880 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5883 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5885 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5887 getShufflePSHUFLWImmediate(SVOp), DAG);
5891 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5892 // and update MaskVals with the new element order.
5893 if (BestHiQuad >= 0) {
5894 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5895 for (unsigned i = 4; i != 8; ++i) {
5896 int idx = MaskVals[i];
5899 } else if ((idx / 4) == BestHiQuad) {
5900 MaskV[i] = (idx & 3) + 4;
5904 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5907 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5908 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5909 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5911 getShufflePSHUFHWImmediate(SVOp), DAG);
5915 // In case BestHi & BestLo were both -1, which means each quadword has a word
5916 // from each of the four input quadwords, calculate the InOrder bitvector now
5917 // before falling through to the insert/extract cleanup.
5918 if (BestLoQuad == -1 && BestHiQuad == -1) {
5920 for (int i = 0; i != 8; ++i)
5921 if (MaskVals[i] < 0 || MaskVals[i] == i)
5925 // The other elements are put in the right place using pextrw and pinsrw.
5926 for (unsigned i = 0; i != 8; ++i) {
5929 int EltIdx = MaskVals[i];
5932 SDValue ExtOp = (EltIdx < 8) ?
5933 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5934 DAG.getIntPtrConstant(EltIdx)) :
5935 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5936 DAG.getIntPtrConstant(EltIdx - 8));
5937 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5938 DAG.getIntPtrConstant(i));
5943 // v16i8 shuffles - Prefer shuffles in the following order:
5944 // 1. [ssse3] 1 x pshufb
5945 // 2. [ssse3] 2 x pshufb + 1 x por
5946 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5948 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5950 const X86TargetLowering &TLI) {
5951 SDValue V1 = SVOp->getOperand(0);
5952 SDValue V2 = SVOp->getOperand(1);
5953 DebugLoc dl = SVOp->getDebugLoc();
5954 ArrayRef<int> MaskVals = SVOp->getMask();
5956 // If we have SSSE3, case 1 is generated when all result bytes come from
5957 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5958 // present, fall back to case 3.
5960 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5961 if (TLI.getSubtarget()->hasSSSE3()) {
5962 SmallVector<SDValue,16> pshufbMask;
5964 // If all result elements are from one input vector, then only translate
5965 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5967 // Otherwise, we have elements from both input vectors, and must zero out
5968 // elements that come from V2 in the first mask, and V1 in the second mask
5969 // so that we can OR them together.
5970 for (unsigned i = 0; i != 16; ++i) {
5971 int EltIdx = MaskVals[i];
5972 if (EltIdx < 0 || EltIdx >= 16)
5974 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5976 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5977 DAG.getNode(ISD::BUILD_VECTOR, dl,
5978 MVT::v16i8, &pshufbMask[0], 16));
5980 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5981 // the 2nd operand if it's undefined or zero.
5982 if (V2.getOpcode() == ISD::UNDEF ||
5983 ISD::isBuildVectorAllZeros(V2.getNode()))
5986 // Calculate the shuffle mask for the second input, shuffle it, and
5987 // OR it with the first shuffled input.
5989 for (unsigned i = 0; i != 16; ++i) {
5990 int EltIdx = MaskVals[i];
5991 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5992 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5994 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5995 DAG.getNode(ISD::BUILD_VECTOR, dl,
5996 MVT::v16i8, &pshufbMask[0], 16));
5997 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6000 // No SSSE3 - Calculate in place words and then fix all out of place words
6001 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6002 // the 16 different words that comprise the two doublequadword input vectors.
6003 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6004 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6006 for (int i = 0; i != 8; ++i) {
6007 int Elt0 = MaskVals[i*2];
6008 int Elt1 = MaskVals[i*2+1];
6010 // This word of the result is all undef, skip it.
6011 if (Elt0 < 0 && Elt1 < 0)
6014 // This word of the result is already in the correct place, skip it.
6015 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6018 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6019 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6022 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6023 // using a single extract together, load it and store it.
6024 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6025 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6026 DAG.getIntPtrConstant(Elt1 / 2));
6027 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6028 DAG.getIntPtrConstant(i));
6032 // If Elt1 is defined, extract it from the appropriate source. If the
6033 // source byte is not also odd, shift the extracted word left 8 bits
6034 // otherwise clear the bottom 8 bits if we need to do an or.
6036 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6037 DAG.getIntPtrConstant(Elt1 / 2));
6038 if ((Elt1 & 1) == 0)
6039 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6041 TLI.getShiftAmountTy(InsElt.getValueType())));
6043 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6044 DAG.getConstant(0xFF00, MVT::i16));
6046 // If Elt0 is defined, extract it from the appropriate source. If the
6047 // source byte is not also even, shift the extracted word right 8 bits. If
6048 // Elt1 was also defined, OR the extracted values together before
6049 // inserting them in the result.
6051 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6052 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6053 if ((Elt0 & 1) != 0)
6054 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6056 TLI.getShiftAmountTy(InsElt0.getValueType())));
6058 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6059 DAG.getConstant(0x00FF, MVT::i16));
6060 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6063 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6064 DAG.getIntPtrConstant(i));
6066 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6069 // v32i8 shuffles - Translate to VPSHUFB if possible.
6071 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6072 const X86Subtarget *Subtarget,
6073 SelectionDAG &DAG) {
6074 EVT VT = SVOp->getValueType(0);
6075 SDValue V1 = SVOp->getOperand(0);
6076 SDValue V2 = SVOp->getOperand(1);
6077 DebugLoc dl = SVOp->getDebugLoc();
6078 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6080 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6081 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6082 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6084 // VPSHUFB may be generated if
6085 // (1) one of input vector is undefined or zeroinitializer.
6086 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6087 // And (2) the mask indexes don't cross the 128-bit lane.
6088 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6089 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6092 if (V1IsAllZero && !V2IsAllZero) {
6093 CommuteVectorShuffleMask(MaskVals, 32);
6096 SmallVector<SDValue, 32> pshufbMask;
6097 for (unsigned i = 0; i != 32; i++) {
6098 int EltIdx = MaskVals[i];
6099 if (EltIdx < 0 || EltIdx >= 32)
6102 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6103 // Cross lane is not allowed.
6107 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6109 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6110 DAG.getNode(ISD::BUILD_VECTOR, dl,
6111 MVT::v32i8, &pshufbMask[0], 32));
6114 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6115 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6116 /// done when every pair / quad of shuffle mask elements point to elements in
6117 /// the right sequence. e.g.
6118 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6120 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6121 SelectionDAG &DAG, DebugLoc dl) {
6122 MVT VT = SVOp->getValueType(0).getSimpleVT();
6123 unsigned NumElems = VT.getVectorNumElements();
6126 switch (VT.SimpleTy) {
6127 default: llvm_unreachable("Unexpected!");
6128 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6129 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6130 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6131 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6132 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6133 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6136 SmallVector<int, 8> MaskVec;
6137 for (unsigned i = 0; i != NumElems; i += Scale) {
6139 for (unsigned j = 0; j != Scale; ++j) {
6140 int EltIdx = SVOp->getMaskElt(i+j);
6144 StartIdx = (EltIdx / Scale);
6145 if (EltIdx != (int)(StartIdx*Scale + j))
6148 MaskVec.push_back(StartIdx);
6151 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6152 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6153 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6156 /// getVZextMovL - Return a zero-extending vector move low node.
6158 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6159 SDValue SrcOp, SelectionDAG &DAG,
6160 const X86Subtarget *Subtarget, DebugLoc dl) {
6161 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6162 LoadSDNode *LD = NULL;
6163 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6164 LD = dyn_cast<LoadSDNode>(SrcOp);
6166 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6168 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6169 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6170 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6171 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6172 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6174 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6175 return DAG.getNode(ISD::BITCAST, dl, VT,
6176 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6177 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6185 return DAG.getNode(ISD::BITCAST, dl, VT,
6186 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6187 DAG.getNode(ISD::BITCAST, dl,
6191 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6192 /// which could not be matched by any known target speficic shuffle
6194 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6196 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6197 if (NewOp.getNode())
6200 EVT VT = SVOp->getValueType(0);
6202 unsigned NumElems = VT.getVectorNumElements();
6203 unsigned NumLaneElems = NumElems / 2;
6205 DebugLoc dl = SVOp->getDebugLoc();
6206 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6207 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6210 SmallVector<int, 16> Mask;
6211 for (unsigned l = 0; l < 2; ++l) {
6212 // Build a shuffle mask for the output, discovering on the fly which
6213 // input vectors to use as shuffle operands (recorded in InputUsed).
6214 // If building a suitable shuffle vector proves too hard, then bail
6215 // out with UseBuildVector set.
6216 bool UseBuildVector = false;
6217 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6218 unsigned LaneStart = l * NumLaneElems;
6219 for (unsigned i = 0; i != NumLaneElems; ++i) {
6220 // The mask element. This indexes into the input.
6221 int Idx = SVOp->getMaskElt(i+LaneStart);
6223 // the mask element does not index into any input vector.
6228 // The input vector this mask element indexes into.
6229 int Input = Idx / NumLaneElems;
6231 // Turn the index into an offset from the start of the input vector.
6232 Idx -= Input * NumLaneElems;
6234 // Find or create a shuffle vector operand to hold this input.
6236 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6237 if (InputUsed[OpNo] == Input)
6238 // This input vector is already an operand.
6240 if (InputUsed[OpNo] < 0) {
6241 // Create a new operand for this input vector.
6242 InputUsed[OpNo] = Input;
6247 if (OpNo >= array_lengthof(InputUsed)) {
6248 // More than two input vectors used! Give up on trying to create a
6249 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6250 UseBuildVector = true;
6254 // Add the mask index for the new shuffle vector.
6255 Mask.push_back(Idx + OpNo * NumLaneElems);
6258 if (UseBuildVector) {
6259 SmallVector<SDValue, 16> SVOps;
6260 for (unsigned i = 0; i != NumLaneElems; ++i) {
6261 // The mask element. This indexes into the input.
6262 int Idx = SVOp->getMaskElt(i+LaneStart);
6264 SVOps.push_back(DAG.getUNDEF(EltVT));
6268 // The input vector this mask element indexes into.
6269 int Input = Idx / NumElems;
6271 // Turn the index into an offset from the start of the input vector.
6272 Idx -= Input * NumElems;
6274 // Extract the vector element by hand.
6275 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6276 SVOp->getOperand(Input),
6277 DAG.getIntPtrConstant(Idx)));
6280 // Construct the output using a BUILD_VECTOR.
6281 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6283 } else if (InputUsed[0] < 0) {
6284 // No input vectors were used! The result is undefined.
6285 Output[l] = DAG.getUNDEF(NVT);
6287 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6288 (InputUsed[0] % 2) * NumLaneElems,
6290 // If only one input was used, use an undefined vector for the other.
6291 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6292 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6293 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6294 // At least one input vector was used. Create a new shuffle vector.
6295 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6301 // Concatenate the result back
6302 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6305 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6306 /// 4 elements, and match them with several different shuffle types.
6308 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6309 SDValue V1 = SVOp->getOperand(0);
6310 SDValue V2 = SVOp->getOperand(1);
6311 DebugLoc dl = SVOp->getDebugLoc();
6312 EVT VT = SVOp->getValueType(0);
6314 assert(VT.is128BitVector() && "Unsupported vector size");
6316 std::pair<int, int> Locs[4];
6317 int Mask1[] = { -1, -1, -1, -1 };
6318 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6322 for (unsigned i = 0; i != 4; ++i) {
6323 int Idx = PermMask[i];
6325 Locs[i] = std::make_pair(-1, -1);
6327 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6329 Locs[i] = std::make_pair(0, NumLo);
6333 Locs[i] = std::make_pair(1, NumHi);
6335 Mask1[2+NumHi] = Idx;
6341 if (NumLo <= 2 && NumHi <= 2) {
6342 // If no more than two elements come from either vector. This can be
6343 // implemented with two shuffles. First shuffle gather the elements.
6344 // The second shuffle, which takes the first shuffle as both of its
6345 // vector operands, put the elements into the right order.
6346 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6348 int Mask2[] = { -1, -1, -1, -1 };
6350 for (unsigned i = 0; i != 4; ++i)
6351 if (Locs[i].first != -1) {
6352 unsigned Idx = (i < 2) ? 0 : 4;
6353 Idx += Locs[i].first * 2 + Locs[i].second;
6357 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6360 if (NumLo == 3 || NumHi == 3) {
6361 // Otherwise, we must have three elements from one vector, call it X, and
6362 // one element from the other, call it Y. First, use a shufps to build an
6363 // intermediate vector with the one element from Y and the element from X
6364 // that will be in the same half in the final destination (the indexes don't
6365 // matter). Then, use a shufps to build the final vector, taking the half
6366 // containing the element from Y from the intermediate, and the other half
6369 // Normalize it so the 3 elements come from V1.
6370 CommuteVectorShuffleMask(PermMask, 4);
6374 // Find the element from V2.
6376 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6377 int Val = PermMask[HiIndex];
6384 Mask1[0] = PermMask[HiIndex];
6386 Mask1[2] = PermMask[HiIndex^1];
6388 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6391 Mask1[0] = PermMask[0];
6392 Mask1[1] = PermMask[1];
6393 Mask1[2] = HiIndex & 1 ? 6 : 4;
6394 Mask1[3] = HiIndex & 1 ? 4 : 6;
6395 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6398 Mask1[0] = HiIndex & 1 ? 2 : 0;
6399 Mask1[1] = HiIndex & 1 ? 0 : 2;
6400 Mask1[2] = PermMask[2];
6401 Mask1[3] = PermMask[3];
6406 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6409 // Break it into (shuffle shuffle_hi, shuffle_lo).
6410 int LoMask[] = { -1, -1, -1, -1 };
6411 int HiMask[] = { -1, -1, -1, -1 };
6413 int *MaskPtr = LoMask;
6414 unsigned MaskIdx = 0;
6417 for (unsigned i = 0; i != 4; ++i) {
6424 int Idx = PermMask[i];
6426 Locs[i] = std::make_pair(-1, -1);
6427 } else if (Idx < 4) {
6428 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6429 MaskPtr[LoIdx] = Idx;
6432 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6433 MaskPtr[HiIdx] = Idx;
6438 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6439 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6440 int MaskOps[] = { -1, -1, -1, -1 };
6441 for (unsigned i = 0; i != 4; ++i)
6442 if (Locs[i].first != -1)
6443 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6444 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6447 static bool MayFoldVectorLoad(SDValue V) {
6448 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6449 V = V.getOperand(0);
6451 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6452 V = V.getOperand(0);
6453 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6454 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6455 // BUILD_VECTOR (load), undef
6456 V = V.getOperand(0);
6458 return MayFoldLoad(V);
6462 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6463 EVT VT = Op.getValueType();
6465 // Canonizalize to v2f64.
6466 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6467 return DAG.getNode(ISD::BITCAST, dl, VT,
6468 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6473 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6475 SDValue V1 = Op.getOperand(0);
6476 SDValue V2 = Op.getOperand(1);
6477 EVT VT = Op.getValueType();
6479 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6481 if (HasSSE2 && VT == MVT::v2f64)
6482 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6484 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6485 return DAG.getNode(ISD::BITCAST, dl, VT,
6486 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6487 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6488 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6492 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6493 SDValue V1 = Op.getOperand(0);
6494 SDValue V2 = Op.getOperand(1);
6495 EVT VT = Op.getValueType();
6497 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6498 "unsupported shuffle type");
6500 if (V2.getOpcode() == ISD::UNDEF)
6504 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6508 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6509 SDValue V1 = Op.getOperand(0);
6510 SDValue V2 = Op.getOperand(1);
6511 EVT VT = Op.getValueType();
6512 unsigned NumElems = VT.getVectorNumElements();
6514 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6515 // operand of these instructions is only memory, so check if there's a
6516 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6518 bool CanFoldLoad = false;
6520 // Trivial case, when V2 comes from a load.
6521 if (MayFoldVectorLoad(V2))
6524 // When V1 is a load, it can be folded later into a store in isel, example:
6525 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6527 // (MOVLPSmr addr:$src1, VR128:$src2)
6528 // So, recognize this potential and also use MOVLPS or MOVLPD
6529 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6532 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6534 if (HasSSE2 && NumElems == 2)
6535 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6538 // If we don't care about the second element, proceed to use movss.
6539 if (SVOp->getMaskElt(1) != -1)
6540 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6543 // movl and movlp will both match v2i64, but v2i64 is never matched by
6544 // movl earlier because we make it strict to avoid messing with the movlp load
6545 // folding logic (see the code above getMOVLP call). Match it here then,
6546 // this is horrible, but will stay like this until we move all shuffle
6547 // matching to x86 specific nodes. Note that for the 1st condition all
6548 // types are matched with movsd.
6550 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6551 // as to remove this logic from here, as much as possible
6552 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6553 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6554 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6557 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6559 // Invert the operand order and use SHUFPS to match it.
6560 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6561 getShuffleSHUFImmediate(SVOp), DAG);
6564 // Reduce a vector shuffle to zext.
6566 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6567 // PMOVZX is only available from SSE41.
6568 if (!Subtarget->hasSSE41())
6571 EVT VT = Op.getValueType();
6573 // Only AVX2 support 256-bit vector integer extending.
6574 if (!Subtarget->hasInt256() && VT.is256BitVector())
6577 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6578 DebugLoc DL = Op.getDebugLoc();
6579 SDValue V1 = Op.getOperand(0);
6580 SDValue V2 = Op.getOperand(1);
6581 unsigned NumElems = VT.getVectorNumElements();
6583 // Extending is an unary operation and the element type of the source vector
6584 // won't be equal to or larger than i64.
6585 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6586 VT.getVectorElementType() == MVT::i64)
6589 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6590 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6591 while ((1U << Shift) < NumElems) {
6592 if (SVOp->getMaskElt(1U << Shift) == 1)
6595 // The maximal ratio is 8, i.e. from i8 to i64.
6600 // Check the shuffle mask.
6601 unsigned Mask = (1U << Shift) - 1;
6602 for (unsigned i = 0; i != NumElems; ++i) {
6603 int EltIdx = SVOp->getMaskElt(i);
6604 if ((i & Mask) != 0 && EltIdx != -1)
6606 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6610 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6611 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6612 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6614 if (!isTypeLegal(NVT))
6617 // Simplify the operand as it's prepared to be fed into shuffle.
6618 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6619 if (V1.getOpcode() == ISD::BITCAST &&
6620 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6621 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6623 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6624 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6625 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6626 ConstantSDNode *CIdx =
6627 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6628 // If it's foldable, i.e. normal load with single use, we will let code
6629 // selection to fold it. Otherwise, we will short the conversion sequence.
6630 if (CIdx && CIdx->getZExtValue() == 0 &&
6631 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6632 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6635 return DAG.getNode(ISD::BITCAST, DL, VT,
6636 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6640 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6641 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6642 EVT VT = Op.getValueType();
6643 DebugLoc dl = Op.getDebugLoc();
6644 SDValue V1 = Op.getOperand(0);
6645 SDValue V2 = Op.getOperand(1);
6647 if (isZeroShuffle(SVOp))
6648 return getZeroVector(VT, Subtarget, DAG, dl);
6650 // Handle splat operations
6651 if (SVOp->isSplat()) {
6652 unsigned NumElem = VT.getVectorNumElements();
6653 int Size = VT.getSizeInBits();
6655 // Use vbroadcast whenever the splat comes from a foldable load
6656 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6657 if (Broadcast.getNode())
6660 // Handle splats by matching through known shuffle masks
6661 if ((Size == 128 && NumElem <= 4) ||
6662 (Size == 256 && NumElem <= 8))
6665 // All remaning splats are promoted to target supported vector shuffles.
6666 return PromoteSplat(SVOp, DAG);
6669 // Check integer expanding shuffles.
6670 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6671 if (NewOp.getNode())
6674 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6676 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6677 VT == MVT::v16i16 || VT == MVT::v32i8) {
6678 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6679 if (NewOp.getNode())
6680 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6681 } else if ((VT == MVT::v4i32 ||
6682 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6683 // FIXME: Figure out a cleaner way to do this.
6684 // Try to make use of movq to zero out the top part.
6685 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6686 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6687 if (NewOp.getNode()) {
6688 EVT NewVT = NewOp.getValueType();
6689 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6690 NewVT, true, false))
6691 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6692 DAG, Subtarget, dl);
6694 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6695 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6696 if (NewOp.getNode()) {
6697 EVT NewVT = NewOp.getValueType();
6698 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6699 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6700 DAG, Subtarget, dl);
6708 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6710 SDValue V1 = Op.getOperand(0);
6711 SDValue V2 = Op.getOperand(1);
6712 EVT VT = Op.getValueType();
6713 DebugLoc dl = Op.getDebugLoc();
6714 unsigned NumElems = VT.getVectorNumElements();
6715 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6716 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6717 bool V1IsSplat = false;
6718 bool V2IsSplat = false;
6719 bool HasSSE2 = Subtarget->hasSSE2();
6720 bool HasFp256 = Subtarget->hasFp256();
6721 bool HasInt256 = Subtarget->hasInt256();
6722 MachineFunction &MF = DAG.getMachineFunction();
6723 bool OptForSize = MF.getFunction()->getFnAttributes().
6724 hasAttribute(Attributes::OptimizeForSize);
6726 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6728 if (V1IsUndef && V2IsUndef)
6729 return DAG.getUNDEF(VT);
6731 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6733 // Vector shuffle lowering takes 3 steps:
6735 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6736 // narrowing and commutation of operands should be handled.
6737 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6739 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6740 // so the shuffle can be broken into other shuffles and the legalizer can
6741 // try the lowering again.
6743 // The general idea is that no vector_shuffle operation should be left to
6744 // be matched during isel, all of them must be converted to a target specific
6747 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6748 // narrowing and commutation of operands should be handled. The actual code
6749 // doesn't include all of those, work in progress...
6750 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6751 if (NewOp.getNode())
6754 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6756 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6757 // unpckh_undef). Only use pshufd if speed is more important than size.
6758 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6759 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6760 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6761 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6763 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6764 V2IsUndef && MayFoldVectorLoad(V1))
6765 return getMOVDDup(Op, dl, V1, DAG);
6767 if (isMOVHLPS_v_undef_Mask(M, VT))
6768 return getMOVHighToLow(Op, dl, DAG);
6770 // Use to match splats
6771 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6772 (VT == MVT::v2f64 || VT == MVT::v2i64))
6773 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6775 if (isPSHUFDMask(M, VT)) {
6776 // The actual implementation will match the mask in the if above and then
6777 // during isel it can match several different instructions, not only pshufd
6778 // as its name says, sad but true, emulate the behavior for now...
6779 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6780 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6782 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6784 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6785 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6787 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6788 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6791 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6795 // Check if this can be converted into a logical shift.
6796 bool isLeft = false;
6799 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6800 if (isShift && ShVal.hasOneUse()) {
6801 // If the shifted value has multiple uses, it may be cheaper to use
6802 // v_set0 + movlhps or movhlps, etc.
6803 EVT EltVT = VT.getVectorElementType();
6804 ShAmt *= EltVT.getSizeInBits();
6805 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6808 if (isMOVLMask(M, VT)) {
6809 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6810 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6811 if (!isMOVLPMask(M, VT)) {
6812 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6813 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6815 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6816 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6820 // FIXME: fold these into legal mask.
6821 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6822 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6824 if (isMOVHLPSMask(M, VT))
6825 return getMOVHighToLow(Op, dl, DAG);
6827 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6828 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6830 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6831 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6833 if (isMOVLPMask(M, VT))
6834 return getMOVLP(Op, dl, DAG, HasSSE2);
6836 if (ShouldXformToMOVHLPS(M, VT) ||
6837 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6838 return CommuteVectorShuffle(SVOp, DAG);
6841 // No better options. Use a vshldq / vsrldq.
6842 EVT EltVT = VT.getVectorElementType();
6843 ShAmt *= EltVT.getSizeInBits();
6844 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6847 bool Commuted = false;
6848 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6849 // 1,1,1,1 -> v8i16 though.
6850 V1IsSplat = isSplatVector(V1.getNode());
6851 V2IsSplat = isSplatVector(V2.getNode());
6853 // Canonicalize the splat or undef, if present, to be on the RHS.
6854 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6855 CommuteVectorShuffleMask(M, NumElems);
6857 std::swap(V1IsSplat, V2IsSplat);
6861 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6862 // Shuffling low element of v1 into undef, just return v1.
6865 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6866 // the instruction selector will not match, so get a canonical MOVL with
6867 // swapped operands to undo the commute.
6868 return getMOVL(DAG, dl, VT, V2, V1);
6871 if (isUNPCKLMask(M, VT, HasInt256))
6872 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6874 if (isUNPCKHMask(M, VT, HasInt256))
6875 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6878 // Normalize mask so all entries that point to V2 points to its first
6879 // element then try to match unpck{h|l} again. If match, return a
6880 // new vector_shuffle with the corrected mask.p
6881 SmallVector<int, 8> NewMask(M.begin(), M.end());
6882 NormalizeMask(NewMask, NumElems);
6883 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6884 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6885 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6886 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6890 // Commute is back and try unpck* again.
6891 // FIXME: this seems wrong.
6892 CommuteVectorShuffleMask(M, NumElems);
6894 std::swap(V1IsSplat, V2IsSplat);
6897 if (isUNPCKLMask(M, VT, HasInt256))
6898 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6900 if (isUNPCKHMask(M, VT, HasInt256))
6901 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6904 // Normalize the node to match x86 shuffle ops if needed
6905 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6906 return CommuteVectorShuffle(SVOp, DAG);
6908 // The checks below are all present in isShuffleMaskLegal, but they are
6909 // inlined here right now to enable us to directly emit target specific
6910 // nodes, and remove one by one until they don't return Op anymore.
6912 if (isPALIGNRMask(M, VT, Subtarget))
6913 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6914 getShufflePALIGNRImmediate(SVOp),
6917 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6918 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6919 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6920 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6923 if (isPSHUFHWMask(M, VT, HasInt256))
6924 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6925 getShufflePSHUFHWImmediate(SVOp),
6928 if (isPSHUFLWMask(M, VT, HasInt256))
6929 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6930 getShufflePSHUFLWImmediate(SVOp),
6933 if (isSHUFPMask(M, VT, HasFp256))
6934 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6935 getShuffleSHUFImmediate(SVOp), DAG);
6937 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6938 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6939 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6940 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6942 //===--------------------------------------------------------------------===//
6943 // Generate target specific nodes for 128 or 256-bit shuffles only
6944 // supported in the AVX instruction set.
6947 // Handle VMOVDDUPY permutations
6948 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6949 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6951 // Handle VPERMILPS/D* permutations
6952 if (isVPERMILPMask(M, VT, HasFp256)) {
6953 if (HasInt256 && VT == MVT::v8i32)
6954 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6955 getShuffleSHUFImmediate(SVOp), DAG);
6956 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6957 getShuffleSHUFImmediate(SVOp), DAG);
6960 // Handle VPERM2F128/VPERM2I128 permutations
6961 if (isVPERM2X128Mask(M, VT, HasFp256))
6962 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6963 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6965 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6966 if (BlendOp.getNode())
6969 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6970 SmallVector<SDValue, 8> permclMask;
6971 for (unsigned i = 0; i != 8; ++i) {
6972 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6974 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6976 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6977 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6978 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6981 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6982 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6983 getShuffleCLImmediate(SVOp), DAG);
6986 //===--------------------------------------------------------------------===//
6987 // Since no target specific shuffle was selected for this generic one,
6988 // lower it into other known shuffles. FIXME: this isn't true yet, but
6989 // this is the plan.
6992 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6993 if (VT == MVT::v8i16) {
6994 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
6995 if (NewOp.getNode())
6999 if (VT == MVT::v16i8) {
7000 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7001 if (NewOp.getNode())
7005 if (VT == MVT::v32i8) {
7006 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7007 if (NewOp.getNode())
7011 // Handle all 128-bit wide vectors with 4 elements, and match them with
7012 // several different shuffle types.
7013 if (NumElems == 4 && VT.is128BitVector())
7014 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7016 // Handle general 256-bit shuffles
7017 if (VT.is256BitVector())
7018 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7024 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7025 SelectionDAG &DAG) const {
7026 EVT VT = Op.getValueType();
7027 DebugLoc dl = Op.getDebugLoc();
7029 if (!Op.getOperand(0).getValueType().is128BitVector())
7032 if (VT.getSizeInBits() == 8) {
7033 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7034 Op.getOperand(0), Op.getOperand(1));
7035 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7036 DAG.getValueType(VT));
7037 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7040 if (VT.getSizeInBits() == 16) {
7041 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7042 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7044 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7045 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7046 DAG.getNode(ISD::BITCAST, dl,
7050 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7051 Op.getOperand(0), Op.getOperand(1));
7052 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7053 DAG.getValueType(VT));
7054 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7057 if (VT == MVT::f32) {
7058 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7059 // the result back to FR32 register. It's only worth matching if the
7060 // result has a single use which is a store or a bitcast to i32. And in
7061 // the case of a store, it's not worth it if the index is a constant 0,
7062 // because a MOVSSmr can be used instead, which is smaller and faster.
7063 if (!Op.hasOneUse())
7065 SDNode *User = *Op.getNode()->use_begin();
7066 if ((User->getOpcode() != ISD::STORE ||
7067 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7068 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7069 (User->getOpcode() != ISD::BITCAST ||
7070 User->getValueType(0) != MVT::i32))
7072 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7073 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7076 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7079 if (VT == MVT::i32 || VT == MVT::i64) {
7080 // ExtractPS/pextrq works with constant index.
7081 if (isa<ConstantSDNode>(Op.getOperand(1)))
7089 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7090 SelectionDAG &DAG) const {
7091 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7094 SDValue Vec = Op.getOperand(0);
7095 EVT VecVT = Vec.getValueType();
7097 // If this is a 256-bit vector result, first extract the 128-bit vector and
7098 // then extract the element from the 128-bit vector.
7099 if (VecVT.is256BitVector()) {
7100 DebugLoc dl = Op.getNode()->getDebugLoc();
7101 unsigned NumElems = VecVT.getVectorNumElements();
7102 SDValue Idx = Op.getOperand(1);
7103 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7105 // Get the 128-bit vector.
7106 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7108 if (IdxVal >= NumElems/2)
7109 IdxVal -= NumElems/2;
7110 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7111 DAG.getConstant(IdxVal, MVT::i32));
7114 assert(VecVT.is128BitVector() && "Unexpected vector length");
7116 if (Subtarget->hasSSE41()) {
7117 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7122 EVT VT = Op.getValueType();
7123 DebugLoc dl = Op.getDebugLoc();
7124 // TODO: handle v16i8.
7125 if (VT.getSizeInBits() == 16) {
7126 SDValue Vec = Op.getOperand(0);
7127 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7129 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7130 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7131 DAG.getNode(ISD::BITCAST, dl,
7134 // Transform it so it match pextrw which produces a 32-bit result.
7135 EVT EltVT = MVT::i32;
7136 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7137 Op.getOperand(0), Op.getOperand(1));
7138 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7139 DAG.getValueType(VT));
7140 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7143 if (VT.getSizeInBits() == 32) {
7144 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7148 // SHUFPS the element to the lowest double word, then movss.
7149 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7150 EVT VVT = Op.getOperand(0).getValueType();
7151 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7152 DAG.getUNDEF(VVT), Mask);
7153 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7154 DAG.getIntPtrConstant(0));
7157 if (VT.getSizeInBits() == 64) {
7158 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7159 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7160 // to match extract_elt for f64.
7161 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7165 // UNPCKHPD the element to the lowest double word, then movsd.
7166 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7167 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7168 int Mask[2] = { 1, -1 };
7169 EVT VVT = Op.getOperand(0).getValueType();
7170 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7171 DAG.getUNDEF(VVT), Mask);
7172 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7173 DAG.getIntPtrConstant(0));
7180 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7181 SelectionDAG &DAG) const {
7182 EVT VT = Op.getValueType();
7183 EVT EltVT = VT.getVectorElementType();
7184 DebugLoc dl = Op.getDebugLoc();
7186 SDValue N0 = Op.getOperand(0);
7187 SDValue N1 = Op.getOperand(1);
7188 SDValue N2 = Op.getOperand(2);
7190 if (!VT.is128BitVector())
7193 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7194 isa<ConstantSDNode>(N2)) {
7196 if (VT == MVT::v8i16)
7197 Opc = X86ISD::PINSRW;
7198 else if (VT == MVT::v16i8)
7199 Opc = X86ISD::PINSRB;
7201 Opc = X86ISD::PINSRB;
7203 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7205 if (N1.getValueType() != MVT::i32)
7206 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7207 if (N2.getValueType() != MVT::i32)
7208 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7209 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7212 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7213 // Bits [7:6] of the constant are the source select. This will always be
7214 // zero here. The DAG Combiner may combine an extract_elt index into these
7215 // bits. For example (insert (extract, 3), 2) could be matched by putting
7216 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7217 // Bits [5:4] of the constant are the destination select. This is the
7218 // value of the incoming immediate.
7219 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7220 // combine either bitwise AND or insert of float 0.0 to set these bits.
7221 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7222 // Create this as a scalar to vector..
7223 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7224 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7227 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7228 // PINSR* works with constant index.
7235 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7236 EVT VT = Op.getValueType();
7237 EVT EltVT = VT.getVectorElementType();
7239 DebugLoc dl = Op.getDebugLoc();
7240 SDValue N0 = Op.getOperand(0);
7241 SDValue N1 = Op.getOperand(1);
7242 SDValue N2 = Op.getOperand(2);
7244 // If this is a 256-bit vector result, first extract the 128-bit vector,
7245 // insert the element into the extracted half and then place it back.
7246 if (VT.is256BitVector()) {
7247 if (!isa<ConstantSDNode>(N2))
7250 // Get the desired 128-bit vector half.
7251 unsigned NumElems = VT.getVectorNumElements();
7252 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7253 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7255 // Insert the element into the desired half.
7256 bool Upper = IdxVal >= NumElems/2;
7257 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7258 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7260 // Insert the changed part back to the 256-bit vector
7261 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7264 if (Subtarget->hasSSE41())
7265 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7267 if (EltVT == MVT::i8)
7270 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7271 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7272 // as its second argument.
7273 if (N1.getValueType() != MVT::i32)
7274 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7275 if (N2.getValueType() != MVT::i32)
7276 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7277 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7282 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7283 LLVMContext *Context = DAG.getContext();
7284 DebugLoc dl = Op.getDebugLoc();
7285 EVT OpVT = Op.getValueType();
7287 // If this is a 256-bit vector result, first insert into a 128-bit
7288 // vector and then insert into the 256-bit vector.
7289 if (!OpVT.is128BitVector()) {
7290 // Insert into a 128-bit vector.
7291 EVT VT128 = EVT::getVectorVT(*Context,
7292 OpVT.getVectorElementType(),
7293 OpVT.getVectorNumElements() / 2);
7295 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7297 // Insert the 128-bit vector.
7298 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7301 if (OpVT == MVT::v1i64 &&
7302 Op.getOperand(0).getValueType() == MVT::i64)
7303 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7305 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7306 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7307 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7308 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7311 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7312 // a simple subregister reference or explicit instructions to grab
7313 // upper bits of a vector.
7314 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7315 SelectionDAG &DAG) {
7316 if (Subtarget->hasFp256()) {
7317 DebugLoc dl = Op.getNode()->getDebugLoc();
7318 SDValue Vec = Op.getNode()->getOperand(0);
7319 SDValue Idx = Op.getNode()->getOperand(1);
7321 if (Op.getNode()->getValueType(0).is128BitVector() &&
7322 Vec.getNode()->getValueType(0).is256BitVector() &&
7323 isa<ConstantSDNode>(Idx)) {
7324 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7325 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7331 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7332 // simple superregister reference or explicit instructions to insert
7333 // the upper bits of a vector.
7334 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7335 SelectionDAG &DAG) {
7336 if (Subtarget->hasFp256()) {
7337 DebugLoc dl = Op.getNode()->getDebugLoc();
7338 SDValue Vec = Op.getNode()->getOperand(0);
7339 SDValue SubVec = Op.getNode()->getOperand(1);
7340 SDValue Idx = Op.getNode()->getOperand(2);
7342 if (Op.getNode()->getValueType(0).is256BitVector() &&
7343 SubVec.getNode()->getValueType(0).is128BitVector() &&
7344 isa<ConstantSDNode>(Idx)) {
7345 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7346 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7352 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7353 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7354 // one of the above mentioned nodes. It has to be wrapped because otherwise
7355 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7356 // be used to form addressing mode. These wrapped nodes will be selected
7359 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7360 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7362 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7364 unsigned char OpFlag = 0;
7365 unsigned WrapperKind = X86ISD::Wrapper;
7366 CodeModel::Model M = getTargetMachine().getCodeModel();
7368 if (Subtarget->isPICStyleRIPRel() &&
7369 (M == CodeModel::Small || M == CodeModel::Kernel))
7370 WrapperKind = X86ISD::WrapperRIP;
7371 else if (Subtarget->isPICStyleGOT())
7372 OpFlag = X86II::MO_GOTOFF;
7373 else if (Subtarget->isPICStyleStubPIC())
7374 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7376 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7378 CP->getOffset(), OpFlag);
7379 DebugLoc DL = CP->getDebugLoc();
7380 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7381 // With PIC, the address is actually $g + Offset.
7383 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7384 DAG.getNode(X86ISD::GlobalBaseReg,
7385 DebugLoc(), getPointerTy()),
7392 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7393 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7395 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7397 unsigned char OpFlag = 0;
7398 unsigned WrapperKind = X86ISD::Wrapper;
7399 CodeModel::Model M = getTargetMachine().getCodeModel();
7401 if (Subtarget->isPICStyleRIPRel() &&
7402 (M == CodeModel::Small || M == CodeModel::Kernel))
7403 WrapperKind = X86ISD::WrapperRIP;
7404 else if (Subtarget->isPICStyleGOT())
7405 OpFlag = X86II::MO_GOTOFF;
7406 else if (Subtarget->isPICStyleStubPIC())
7407 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7409 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7411 DebugLoc DL = JT->getDebugLoc();
7412 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7414 // With PIC, the address is actually $g + Offset.
7416 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7417 DAG.getNode(X86ISD::GlobalBaseReg,
7418 DebugLoc(), getPointerTy()),
7425 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7426 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7428 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7430 unsigned char OpFlag = 0;
7431 unsigned WrapperKind = X86ISD::Wrapper;
7432 CodeModel::Model M = getTargetMachine().getCodeModel();
7434 if (Subtarget->isPICStyleRIPRel() &&
7435 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7436 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7437 OpFlag = X86II::MO_GOTPCREL;
7438 WrapperKind = X86ISD::WrapperRIP;
7439 } else if (Subtarget->isPICStyleGOT()) {
7440 OpFlag = X86II::MO_GOT;
7441 } else if (Subtarget->isPICStyleStubPIC()) {
7442 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7443 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7444 OpFlag = X86II::MO_DARWIN_NONLAZY;
7447 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7449 DebugLoc DL = Op.getDebugLoc();
7450 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7453 // With PIC, the address is actually $g + Offset.
7454 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7455 !Subtarget->is64Bit()) {
7456 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7457 DAG.getNode(X86ISD::GlobalBaseReg,
7458 DebugLoc(), getPointerTy()),
7462 // For symbols that require a load from a stub to get the address, emit the
7464 if (isGlobalStubReference(OpFlag))
7465 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7466 MachinePointerInfo::getGOT(), false, false, false, 0);
7472 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7473 // Create the TargetBlockAddressAddress node.
7474 unsigned char OpFlags =
7475 Subtarget->ClassifyBlockAddressReference();
7476 CodeModel::Model M = getTargetMachine().getCodeModel();
7477 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7478 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7479 DebugLoc dl = Op.getDebugLoc();
7480 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7483 if (Subtarget->isPICStyleRIPRel() &&
7484 (M == CodeModel::Small || M == CodeModel::Kernel))
7485 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7487 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7489 // With PIC, the address is actually $g + Offset.
7490 if (isGlobalRelativeToPICBase(OpFlags)) {
7491 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7492 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7500 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7502 SelectionDAG &DAG) const {
7503 // Create the TargetGlobalAddress node, folding in the constant
7504 // offset if it is legal.
7505 unsigned char OpFlags =
7506 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7507 CodeModel::Model M = getTargetMachine().getCodeModel();
7509 if (OpFlags == X86II::MO_NO_FLAG &&
7510 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7511 // A direct static reference to a global.
7512 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7515 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7518 if (Subtarget->isPICStyleRIPRel() &&
7519 (M == CodeModel::Small || M == CodeModel::Kernel))
7520 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7522 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7524 // With PIC, the address is actually $g + Offset.
7525 if (isGlobalRelativeToPICBase(OpFlags)) {
7526 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7527 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7531 // For globals that require a load from a stub to get the address, emit the
7533 if (isGlobalStubReference(OpFlags))
7534 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7535 MachinePointerInfo::getGOT(), false, false, false, 0);
7537 // If there was a non-zero offset that we didn't fold, create an explicit
7540 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7541 DAG.getConstant(Offset, getPointerTy()));
7547 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7548 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7549 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7550 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7554 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7555 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7556 unsigned char OperandFlags, bool LocalDynamic = false) {
7557 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7558 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7559 DebugLoc dl = GA->getDebugLoc();
7560 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7561 GA->getValueType(0),
7565 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7569 SDValue Ops[] = { Chain, TGA, *InFlag };
7570 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7572 SDValue Ops[] = { Chain, TGA };
7573 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7576 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7577 MFI->setAdjustsStack(true);
7579 SDValue Flag = Chain.getValue(1);
7580 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7583 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7585 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7588 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7589 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7590 DAG.getNode(X86ISD::GlobalBaseReg,
7591 DebugLoc(), PtrVT), InFlag);
7592 InFlag = Chain.getValue(1);
7594 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7597 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7599 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7601 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7602 X86::RAX, X86II::MO_TLSGD);
7605 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7609 DebugLoc dl = GA->getDebugLoc();
7611 // Get the start address of the TLS block for this module.
7612 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7613 .getInfo<X86MachineFunctionInfo>();
7614 MFI->incNumLocalDynamicTLSAccesses();
7618 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7619 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7622 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7623 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7624 InFlag = Chain.getValue(1);
7625 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7626 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7629 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7633 unsigned char OperandFlags = X86II::MO_DTPOFF;
7634 unsigned WrapperKind = X86ISD::Wrapper;
7635 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7636 GA->getValueType(0),
7637 GA->getOffset(), OperandFlags);
7638 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7640 // Add x@dtpoff with the base.
7641 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7644 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7645 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7646 const EVT PtrVT, TLSModel::Model model,
7647 bool is64Bit, bool isPIC) {
7648 DebugLoc dl = GA->getDebugLoc();
7650 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7651 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7652 is64Bit ? 257 : 256));
7654 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7655 DAG.getIntPtrConstant(0),
7656 MachinePointerInfo(Ptr),
7657 false, false, false, 0);
7659 unsigned char OperandFlags = 0;
7660 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7662 unsigned WrapperKind = X86ISD::Wrapper;
7663 if (model == TLSModel::LocalExec) {
7664 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7665 } else if (model == TLSModel::InitialExec) {
7667 OperandFlags = X86II::MO_GOTTPOFF;
7668 WrapperKind = X86ISD::WrapperRIP;
7670 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7673 llvm_unreachable("Unexpected model");
7676 // emit "addl x@ntpoff,%eax" (local exec)
7677 // or "addl x@indntpoff,%eax" (initial exec)
7678 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7679 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7680 GA->getValueType(0),
7681 GA->getOffset(), OperandFlags);
7682 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7684 if (model == TLSModel::InitialExec) {
7685 if (isPIC && !is64Bit) {
7686 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7687 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7691 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7692 MachinePointerInfo::getGOT(), false, false, false,
7696 // The address of the thread local variable is the add of the thread
7697 // pointer with the offset of the variable.
7698 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7702 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7704 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7705 const GlobalValue *GV = GA->getGlobal();
7707 if (Subtarget->isTargetELF()) {
7708 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7711 case TLSModel::GeneralDynamic:
7712 if (Subtarget->is64Bit())
7713 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7714 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7715 case TLSModel::LocalDynamic:
7716 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7717 Subtarget->is64Bit());
7718 case TLSModel::InitialExec:
7719 case TLSModel::LocalExec:
7720 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7721 Subtarget->is64Bit(),
7722 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7724 llvm_unreachable("Unknown TLS model.");
7727 if (Subtarget->isTargetDarwin()) {
7728 // Darwin only has one model of TLS. Lower to that.
7729 unsigned char OpFlag = 0;
7730 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7731 X86ISD::WrapperRIP : X86ISD::Wrapper;
7733 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7735 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7736 !Subtarget->is64Bit();
7738 OpFlag = X86II::MO_TLVP_PIC_BASE;
7740 OpFlag = X86II::MO_TLVP;
7741 DebugLoc DL = Op.getDebugLoc();
7742 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7743 GA->getValueType(0),
7744 GA->getOffset(), OpFlag);
7745 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7747 // With PIC32, the address is actually $g + Offset.
7749 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7750 DAG.getNode(X86ISD::GlobalBaseReg,
7751 DebugLoc(), getPointerTy()),
7754 // Lowering the machine isd will make sure everything is in the right
7756 SDValue Chain = DAG.getEntryNode();
7757 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7758 SDValue Args[] = { Chain, Offset };
7759 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7761 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7762 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7763 MFI->setAdjustsStack(true);
7765 // And our return value (tls address) is in the standard call return value
7767 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7768 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7772 if (Subtarget->isTargetWindows()) {
7773 // Just use the implicit TLS architecture
7774 // Need to generate someting similar to:
7775 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7777 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7778 // mov rcx, qword [rdx+rcx*8]
7779 // mov eax, .tls$:tlsvar
7780 // [rax+rcx] contains the address
7781 // Windows 64bit: gs:0x58
7782 // Windows 32bit: fs:__tls_array
7784 // If GV is an alias then use the aliasee for determining
7785 // thread-localness.
7786 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7787 GV = GA->resolveAliasedGlobal(false);
7788 DebugLoc dl = GA->getDebugLoc();
7789 SDValue Chain = DAG.getEntryNode();
7791 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7792 // %gs:0x58 (64-bit).
7793 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7794 ? Type::getInt8PtrTy(*DAG.getContext(),
7796 : Type::getInt32PtrTy(*DAG.getContext(),
7799 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7800 Subtarget->is64Bit()
7801 ? DAG.getIntPtrConstant(0x58)
7802 : DAG.getExternalSymbol("_tls_array",
7804 MachinePointerInfo(Ptr),
7805 false, false, false, 0);
7807 // Load the _tls_index variable
7808 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7809 if (Subtarget->is64Bit())
7810 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7811 IDX, MachinePointerInfo(), MVT::i32,
7814 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7815 false, false, false, 0);
7817 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7819 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7821 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7822 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7823 false, false, false, 0);
7825 // Get the offset of start of .tls section
7826 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7827 GA->getValueType(0),
7828 GA->getOffset(), X86II::MO_SECREL);
7829 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7831 // The address of the thread local variable is the add of the thread
7832 // pointer with the offset of the variable.
7833 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7836 llvm_unreachable("TLS not implemented for this target.");
7840 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7841 /// and take a 2 x i32 value to shift plus a shift amount.
7842 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7843 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7844 EVT VT = Op.getValueType();
7845 unsigned VTBits = VT.getSizeInBits();
7846 DebugLoc dl = Op.getDebugLoc();
7847 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7848 SDValue ShOpLo = Op.getOperand(0);
7849 SDValue ShOpHi = Op.getOperand(1);
7850 SDValue ShAmt = Op.getOperand(2);
7851 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7852 DAG.getConstant(VTBits - 1, MVT::i8))
7853 : DAG.getConstant(0, VT);
7856 if (Op.getOpcode() == ISD::SHL_PARTS) {
7857 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7858 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7860 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7861 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7864 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7865 DAG.getConstant(VTBits, MVT::i8));
7866 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7867 AndNode, DAG.getConstant(0, MVT::i8));
7870 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7871 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7872 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7874 if (Op.getOpcode() == ISD::SHL_PARTS) {
7875 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7876 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7878 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7879 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7882 SDValue Ops[2] = { Lo, Hi };
7883 return DAG.getMergeValues(Ops, 2, dl);
7886 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7887 SelectionDAG &DAG) const {
7888 EVT SrcVT = Op.getOperand(0).getValueType();
7890 if (SrcVT.isVector())
7893 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7894 "Unknown SINT_TO_FP to lower!");
7896 // These are really Legal; return the operand so the caller accepts it as
7898 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7900 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7901 Subtarget->is64Bit()) {
7905 DebugLoc dl = Op.getDebugLoc();
7906 unsigned Size = SrcVT.getSizeInBits()/8;
7907 MachineFunction &MF = DAG.getMachineFunction();
7908 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7909 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7910 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7912 MachinePointerInfo::getFixedStack(SSFI),
7914 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7917 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7919 SelectionDAG &DAG) const {
7921 DebugLoc DL = Op.getDebugLoc();
7923 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7925 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7927 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7929 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7931 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7932 MachineMemOperand *MMO;
7934 int SSFI = FI->getIndex();
7936 DAG.getMachineFunction()
7937 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7938 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7940 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7941 StackSlot = StackSlot.getOperand(1);
7943 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7944 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7946 Tys, Ops, array_lengthof(Ops),
7950 Chain = Result.getValue(1);
7951 SDValue InFlag = Result.getValue(2);
7953 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7954 // shouldn't be necessary except that RFP cannot be live across
7955 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7956 MachineFunction &MF = DAG.getMachineFunction();
7957 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7958 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7959 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7960 Tys = DAG.getVTList(MVT::Other);
7962 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7964 MachineMemOperand *MMO =
7965 DAG.getMachineFunction()
7966 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7967 MachineMemOperand::MOStore, SSFISize, SSFISize);
7969 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7970 Ops, array_lengthof(Ops),
7971 Op.getValueType(), MMO);
7972 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7973 MachinePointerInfo::getFixedStack(SSFI),
7974 false, false, false, 0);
7980 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7981 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7982 SelectionDAG &DAG) const {
7983 // This algorithm is not obvious. Here it is what we're trying to output:
7986 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7987 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7991 pshufd $0x4e, %xmm0, %xmm1
7996 DebugLoc dl = Op.getDebugLoc();
7997 LLVMContext *Context = DAG.getContext();
7999 // Build some magic constants.
8000 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8001 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8002 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8004 SmallVector<Constant*,2> CV1;
8006 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8008 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8009 Constant *C1 = ConstantVector::get(CV1);
8010 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8012 // Load the 64-bit value into an XMM register.
8013 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8015 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8016 MachinePointerInfo::getConstantPool(),
8017 false, false, false, 16);
8018 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8019 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8022 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8023 MachinePointerInfo::getConstantPool(),
8024 false, false, false, 16);
8025 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8026 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8029 if (Subtarget->hasSSE3()) {
8030 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8031 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8033 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8034 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8036 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8037 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8041 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8042 DAG.getIntPtrConstant(0));
8045 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8046 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8047 SelectionDAG &DAG) const {
8048 DebugLoc dl = Op.getDebugLoc();
8049 // FP constant to bias correct the final result.
8050 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8053 // Load the 32-bit value into an XMM register.
8054 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8057 // Zero out the upper parts of the register.
8058 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8060 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8061 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8062 DAG.getIntPtrConstant(0));
8064 // Or the load with the bias.
8065 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8066 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8067 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8069 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8070 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8071 MVT::v2f64, Bias)));
8072 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8073 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8074 DAG.getIntPtrConstant(0));
8076 // Subtract the bias.
8077 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8079 // Handle final rounding.
8080 EVT DestVT = Op.getValueType();
8082 if (DestVT.bitsLT(MVT::f64))
8083 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8084 DAG.getIntPtrConstant(0));
8085 if (DestVT.bitsGT(MVT::f64))
8086 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8088 // Handle final rounding.
8092 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8093 SelectionDAG &DAG) const {
8094 SDValue N0 = Op.getOperand(0);
8095 EVT SVT = N0.getValueType();
8096 DebugLoc dl = Op.getDebugLoc();
8098 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8099 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8100 "Custom UINT_TO_FP is not supported!");
8102 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8103 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8104 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8107 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8108 SelectionDAG &DAG) const {
8109 SDValue N0 = Op.getOperand(0);
8110 DebugLoc dl = Op.getDebugLoc();
8112 if (Op.getValueType().isVector())
8113 return lowerUINT_TO_FP_vec(Op, DAG);
8115 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8116 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8117 // the optimization here.
8118 if (DAG.SignBitIsZero(N0))
8119 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8121 EVT SrcVT = N0.getValueType();
8122 EVT DstVT = Op.getValueType();
8123 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8124 return LowerUINT_TO_FP_i64(Op, DAG);
8125 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8126 return LowerUINT_TO_FP_i32(Op, DAG);
8127 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8130 // Make a 64-bit buffer, and use it to build an FILD.
8131 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8132 if (SrcVT == MVT::i32) {
8133 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8134 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8135 getPointerTy(), StackSlot, WordOff);
8136 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8137 StackSlot, MachinePointerInfo(),
8139 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8140 OffsetSlot, MachinePointerInfo(),
8142 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8146 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8147 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8148 StackSlot, MachinePointerInfo(),
8150 // For i64 source, we need to add the appropriate power of 2 if the input
8151 // was negative. This is the same as the optimization in
8152 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8153 // we must be careful to do the computation in x87 extended precision, not
8154 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8155 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8156 MachineMemOperand *MMO =
8157 DAG.getMachineFunction()
8158 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8159 MachineMemOperand::MOLoad, 8, 8);
8161 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8162 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8163 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8166 APInt FF(32, 0x5F800000ULL);
8168 // Check whether the sign bit is set.
8169 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8170 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8173 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8174 SDValue FudgePtr = DAG.getConstantPool(
8175 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8178 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8179 SDValue Zero = DAG.getIntPtrConstant(0);
8180 SDValue Four = DAG.getIntPtrConstant(4);
8181 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8183 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8185 // Load the value out, extending it from f32 to f80.
8186 // FIXME: Avoid the extend by constructing the right constant pool?
8187 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8188 FudgePtr, MachinePointerInfo::getConstantPool(),
8189 MVT::f32, false, false, 4);
8190 // Extend everything to 80 bits to force it to be done on x87.
8191 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8192 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8195 std::pair<SDValue,SDValue> X86TargetLowering::
8196 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8197 DebugLoc DL = Op.getDebugLoc();
8199 EVT DstTy = Op.getValueType();
8201 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8202 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8206 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8207 DstTy.getSimpleVT() >= MVT::i16 &&
8208 "Unknown FP_TO_INT to lower!");
8210 // These are really Legal.
8211 if (DstTy == MVT::i32 &&
8212 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8213 return std::make_pair(SDValue(), SDValue());
8214 if (Subtarget->is64Bit() &&
8215 DstTy == MVT::i64 &&
8216 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8217 return std::make_pair(SDValue(), SDValue());
8219 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8220 // stack slot, or into the FTOL runtime function.
8221 MachineFunction &MF = DAG.getMachineFunction();
8222 unsigned MemSize = DstTy.getSizeInBits()/8;
8223 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8224 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8227 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8228 Opc = X86ISD::WIN_FTOL;
8230 switch (DstTy.getSimpleVT().SimpleTy) {
8231 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8232 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8233 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8234 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8237 SDValue Chain = DAG.getEntryNode();
8238 SDValue Value = Op.getOperand(0);
8239 EVT TheVT = Op.getOperand(0).getValueType();
8240 // FIXME This causes a redundant load/store if the SSE-class value is already
8241 // in memory, such as if it is on the callstack.
8242 if (isScalarFPTypeInSSEReg(TheVT)) {
8243 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8244 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8245 MachinePointerInfo::getFixedStack(SSFI),
8247 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8249 Chain, StackSlot, DAG.getValueType(TheVT)
8252 MachineMemOperand *MMO =
8253 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8254 MachineMemOperand::MOLoad, MemSize, MemSize);
8255 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8257 Chain = Value.getValue(1);
8258 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8259 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8262 MachineMemOperand *MMO =
8263 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8264 MachineMemOperand::MOStore, MemSize, MemSize);
8266 if (Opc != X86ISD::WIN_FTOL) {
8267 // Build the FP_TO_INT*_IN_MEM
8268 SDValue Ops[] = { Chain, Value, StackSlot };
8269 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8270 Ops, 3, DstTy, MMO);
8271 return std::make_pair(FIST, StackSlot);
8273 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8274 DAG.getVTList(MVT::Other, MVT::Glue),
8276 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8277 MVT::i32, ftol.getValue(1));
8278 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8279 MVT::i32, eax.getValue(2));
8280 SDValue Ops[] = { eax, edx };
8281 SDValue pair = IsReplace
8282 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8283 : DAG.getMergeValues(Ops, 2, DL);
8284 return std::make_pair(pair, SDValue());
8288 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8289 DebugLoc DL = Op.getDebugLoc();
8290 EVT VT = Op.getValueType();
8291 SDValue In = Op.getOperand(0);
8292 EVT SVT = In.getValueType();
8294 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8295 VT.getVectorNumElements() != SVT.getVectorNumElements())
8298 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8300 // AVX2 has better support of integer extending.
8301 if (Subtarget->hasInt256())
8302 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8304 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8305 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8306 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8307 DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8309 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8312 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8313 DebugLoc DL = Op.getDebugLoc();
8314 EVT VT = Op.getValueType();
8315 EVT SVT = Op.getOperand(0).getValueType();
8317 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8318 VT.getVectorNumElements() != SVT.getVectorNumElements())
8321 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8323 unsigned NumElems = VT.getVectorNumElements();
8324 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8327 SDValue In = Op.getOperand(0);
8328 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8329 // Prepare truncation shuffle mask
8330 for (unsigned i = 0; i != NumElems; ++i)
8332 SDValue V = DAG.getVectorShuffle(NVT, DL,
8333 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8334 DAG.getUNDEF(NVT), &MaskVec[0]);
8335 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8336 DAG.getIntPtrConstant(0));
8339 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8340 SelectionDAG &DAG) const {
8341 if (Op.getValueType().isVector()) {
8342 if (Op.getValueType() == MVT::v8i16)
8343 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8344 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8345 MVT::v8i32, Op.getOperand(0)));
8349 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8350 /*IsSigned=*/ true, /*IsReplace=*/ false);
8351 SDValue FIST = Vals.first, StackSlot = Vals.second;
8352 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8353 if (FIST.getNode() == 0) return Op;
8355 if (StackSlot.getNode())
8357 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8358 FIST, StackSlot, MachinePointerInfo(),
8359 false, false, false, 0);
8361 // The node is the result.
8365 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8366 SelectionDAG &DAG) const {
8367 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8368 /*IsSigned=*/ false, /*IsReplace=*/ false);
8369 SDValue FIST = Vals.first, StackSlot = Vals.second;
8370 assert(FIST.getNode() && "Unexpected failure");
8372 if (StackSlot.getNode())
8374 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8375 FIST, StackSlot, MachinePointerInfo(),
8376 false, false, false, 0);
8378 // The node is the result.
8382 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8383 SelectionDAG &DAG) const {
8384 DebugLoc DL = Op.getDebugLoc();
8385 EVT VT = Op.getValueType();
8386 SDValue In = Op.getOperand(0);
8387 EVT SVT = In.getValueType();
8389 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8391 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8392 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8393 In, DAG.getUNDEF(SVT)));
8396 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8397 LLVMContext *Context = DAG.getContext();
8398 DebugLoc dl = Op.getDebugLoc();
8399 EVT VT = Op.getValueType();
8401 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8402 if (VT.isVector()) {
8403 EltVT = VT.getVectorElementType();
8404 NumElts = VT.getVectorNumElements();
8407 if (EltVT == MVT::f64)
8408 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8410 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8411 C = ConstantVector::getSplat(NumElts, C);
8412 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8413 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8414 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8415 MachinePointerInfo::getConstantPool(),
8416 false, false, false, Alignment);
8417 if (VT.isVector()) {
8418 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8419 return DAG.getNode(ISD::BITCAST, dl, VT,
8420 DAG.getNode(ISD::AND, dl, ANDVT,
8421 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8423 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8425 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8428 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8429 LLVMContext *Context = DAG.getContext();
8430 DebugLoc dl = Op.getDebugLoc();
8431 EVT VT = Op.getValueType();
8433 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8434 if (VT.isVector()) {
8435 EltVT = VT.getVectorElementType();
8436 NumElts = VT.getVectorNumElements();
8439 if (EltVT == MVT::f64)
8440 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8442 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8443 C = ConstantVector::getSplat(NumElts, C);
8444 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8445 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8446 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8447 MachinePointerInfo::getConstantPool(),
8448 false, false, false, Alignment);
8449 if (VT.isVector()) {
8450 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8451 return DAG.getNode(ISD::BITCAST, dl, VT,
8452 DAG.getNode(ISD::XOR, dl, XORVT,
8453 DAG.getNode(ISD::BITCAST, dl, XORVT,
8455 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8458 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8461 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8462 LLVMContext *Context = DAG.getContext();
8463 SDValue Op0 = Op.getOperand(0);
8464 SDValue Op1 = Op.getOperand(1);
8465 DebugLoc dl = Op.getDebugLoc();
8466 EVT VT = Op.getValueType();
8467 EVT SrcVT = Op1.getValueType();
8469 // If second operand is smaller, extend it first.
8470 if (SrcVT.bitsLT(VT)) {
8471 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8474 // And if it is bigger, shrink it first.
8475 if (SrcVT.bitsGT(VT)) {
8476 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8480 // At this point the operands and the result should have the same
8481 // type, and that won't be f80 since that is not custom lowered.
8483 // First get the sign bit of second operand.
8484 SmallVector<Constant*,4> CV;
8485 if (SrcVT == MVT::f64) {
8486 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8487 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8489 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8490 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8491 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8492 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8494 Constant *C = ConstantVector::get(CV);
8495 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8496 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8497 MachinePointerInfo::getConstantPool(),
8498 false, false, false, 16);
8499 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8501 // Shift sign bit right or left if the two operands have different types.
8502 if (SrcVT.bitsGT(VT)) {
8503 // Op0 is MVT::f32, Op1 is MVT::f64.
8504 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8505 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8506 DAG.getConstant(32, MVT::i32));
8507 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8508 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8509 DAG.getIntPtrConstant(0));
8512 // Clear first operand sign bit.
8514 if (VT == MVT::f64) {
8515 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8516 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8518 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8519 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8520 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8521 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8523 C = ConstantVector::get(CV);
8524 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8525 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8526 MachinePointerInfo::getConstantPool(),
8527 false, false, false, 16);
8528 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8530 // Or the value with the sign bit.
8531 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8534 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8535 SDValue N0 = Op.getOperand(0);
8536 DebugLoc dl = Op.getDebugLoc();
8537 EVT VT = Op.getValueType();
8539 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8540 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8541 DAG.getConstant(1, VT));
8542 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8545 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8547 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8548 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8550 if (!Subtarget->hasSSE41())
8553 if (!Op->hasOneUse())
8556 SDNode *N = Op.getNode();
8557 DebugLoc DL = N->getDebugLoc();
8559 SmallVector<SDValue, 8> Opnds;
8560 DenseMap<SDValue, unsigned> VecInMap;
8561 EVT VT = MVT::Other;
8563 // Recognize a special case where a vector is casted into wide integer to
8565 Opnds.push_back(N->getOperand(0));
8566 Opnds.push_back(N->getOperand(1));
8568 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8569 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8570 // BFS traverse all OR'd operands.
8571 if (I->getOpcode() == ISD::OR) {
8572 Opnds.push_back(I->getOperand(0));
8573 Opnds.push_back(I->getOperand(1));
8574 // Re-evaluate the number of nodes to be traversed.
8575 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8579 // Quit if a non-EXTRACT_VECTOR_ELT
8580 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8583 // Quit if without a constant index.
8584 SDValue Idx = I->getOperand(1);
8585 if (!isa<ConstantSDNode>(Idx))
8588 SDValue ExtractedFromVec = I->getOperand(0);
8589 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8590 if (M == VecInMap.end()) {
8591 VT = ExtractedFromVec.getValueType();
8592 // Quit if not 128/256-bit vector.
8593 if (!VT.is128BitVector() && !VT.is256BitVector())
8595 // Quit if not the same type.
8596 if (VecInMap.begin() != VecInMap.end() &&
8597 VT != VecInMap.begin()->first.getValueType())
8599 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8601 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8604 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8605 "Not extracted from 128-/256-bit vector.");
8607 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8608 SmallVector<SDValue, 8> VecIns;
8610 for (DenseMap<SDValue, unsigned>::const_iterator
8611 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8612 // Quit if not all elements are used.
8613 if (I->second != FullMask)
8615 VecIns.push_back(I->first);
8618 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8620 // Cast all vectors into TestVT for PTEST.
8621 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8622 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8624 // If more than one full vectors are evaluated, OR them first before PTEST.
8625 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8626 // Each iteration will OR 2 nodes and append the result until there is only
8627 // 1 node left, i.e. the final OR'd value of all vectors.
8628 SDValue LHS = VecIns[Slot];
8629 SDValue RHS = VecIns[Slot + 1];
8630 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8633 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8634 VecIns.back(), VecIns.back());
8637 /// Emit nodes that will be selected as "test Op0,Op0", or something
8639 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8640 SelectionDAG &DAG) const {
8641 DebugLoc dl = Op.getDebugLoc();
8643 // CF and OF aren't always set the way we want. Determine which
8644 // of these we need.
8645 bool NeedCF = false;
8646 bool NeedOF = false;
8649 case X86::COND_A: case X86::COND_AE:
8650 case X86::COND_B: case X86::COND_BE:
8653 case X86::COND_G: case X86::COND_GE:
8654 case X86::COND_L: case X86::COND_LE:
8655 case X86::COND_O: case X86::COND_NO:
8660 // See if we can use the EFLAGS value from the operand instead of
8661 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8662 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8663 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8664 // Emit a CMP with 0, which is the TEST pattern.
8665 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8666 DAG.getConstant(0, Op.getValueType()));
8668 unsigned Opcode = 0;
8669 unsigned NumOperands = 0;
8671 // Truncate operations may prevent the merge of the SETCC instruction
8672 // and the arithmetic intruction before it. Attempt to truncate the operands
8673 // of the arithmetic instruction and use a reduced bit-width instruction.
8674 bool NeedTruncation = false;
8675 SDValue ArithOp = Op;
8676 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8677 SDValue Arith = Op->getOperand(0);
8678 // Both the trunc and the arithmetic op need to have one user each.
8679 if (Arith->hasOneUse())
8680 switch (Arith.getOpcode()) {
8687 NeedTruncation = true;
8693 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8694 // which may be the result of a CAST. We use the variable 'Op', which is the
8695 // non-casted variable when we check for possible users.
8696 switch (ArithOp.getOpcode()) {
8698 // Due to an isel shortcoming, be conservative if this add is likely to be
8699 // selected as part of a load-modify-store instruction. When the root node
8700 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8701 // uses of other nodes in the match, such as the ADD in this case. This
8702 // leads to the ADD being left around and reselected, with the result being
8703 // two adds in the output. Alas, even if none our users are stores, that
8704 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8705 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8706 // climbing the DAG back to the root, and it doesn't seem to be worth the
8708 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8709 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8710 if (UI->getOpcode() != ISD::CopyToReg &&
8711 UI->getOpcode() != ISD::SETCC &&
8712 UI->getOpcode() != ISD::STORE)
8715 if (ConstantSDNode *C =
8716 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8717 // An add of one will be selected as an INC.
8718 if (C->getAPIntValue() == 1) {
8719 Opcode = X86ISD::INC;
8724 // An add of negative one (subtract of one) will be selected as a DEC.
8725 if (C->getAPIntValue().isAllOnesValue()) {
8726 Opcode = X86ISD::DEC;
8732 // Otherwise use a regular EFLAGS-setting add.
8733 Opcode = X86ISD::ADD;
8737 // If the primary and result isn't used, don't bother using X86ISD::AND,
8738 // because a TEST instruction will be better.
8739 bool NonFlagUse = false;
8740 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8741 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8743 unsigned UOpNo = UI.getOperandNo();
8744 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8745 // Look pass truncate.
8746 UOpNo = User->use_begin().getOperandNo();
8747 User = *User->use_begin();
8750 if (User->getOpcode() != ISD::BRCOND &&
8751 User->getOpcode() != ISD::SETCC &&
8752 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8765 // Due to the ISEL shortcoming noted above, be conservative if this op is
8766 // likely to be selected as part of a load-modify-store instruction.
8767 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8768 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8769 if (UI->getOpcode() == ISD::STORE)
8772 // Otherwise use a regular EFLAGS-setting instruction.
8773 switch (ArithOp.getOpcode()) {
8774 default: llvm_unreachable("unexpected operator!");
8775 case ISD::SUB: Opcode = X86ISD::SUB; break;
8776 case ISD::XOR: Opcode = X86ISD::XOR; break;
8777 case ISD::AND: Opcode = X86ISD::AND; break;
8779 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8780 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8781 if (EFLAGS.getNode())
8784 Opcode = X86ISD::OR;
8798 return SDValue(Op.getNode(), 1);
8804 // If we found that truncation is beneficial, perform the truncation and
8806 if (NeedTruncation) {
8807 EVT VT = Op.getValueType();
8808 SDValue WideVal = Op->getOperand(0);
8809 EVT WideVT = WideVal.getValueType();
8810 unsigned ConvertedOp = 0;
8811 // Use a target machine opcode to prevent further DAGCombine
8812 // optimizations that may separate the arithmetic operations
8813 // from the setcc node.
8814 switch (WideVal.getOpcode()) {
8816 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8817 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8818 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8819 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8820 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8825 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8826 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8827 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8828 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8834 // Emit a CMP with 0, which is the TEST pattern.
8835 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8836 DAG.getConstant(0, Op.getValueType()));
8838 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8839 SmallVector<SDValue, 4> Ops;
8840 for (unsigned i = 0; i != NumOperands; ++i)
8841 Ops.push_back(Op.getOperand(i));
8843 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8844 DAG.ReplaceAllUsesWith(Op, New);
8845 return SDValue(New.getNode(), 1);
8848 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8850 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8851 SelectionDAG &DAG) const {
8852 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8853 if (C->getAPIntValue() == 0)
8854 return EmitTest(Op0, X86CC, DAG);
8856 DebugLoc dl = Op0.getDebugLoc();
8857 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8858 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8859 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8860 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8861 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8863 return SDValue(Sub.getNode(), 1);
8865 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8868 /// Convert a comparison if required by the subtarget.
8869 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8870 SelectionDAG &DAG) const {
8871 // If the subtarget does not support the FUCOMI instruction, floating-point
8872 // comparisons have to be converted.
8873 if (Subtarget->hasCMov() ||
8874 Cmp.getOpcode() != X86ISD::CMP ||
8875 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8876 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8879 // The instruction selector will select an FUCOM instruction instead of
8880 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8881 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8882 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8883 DebugLoc dl = Cmp.getDebugLoc();
8884 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8885 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8886 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8887 DAG.getConstant(8, MVT::i8));
8888 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8889 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8892 static bool isAllOnes(SDValue V) {
8893 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8894 return C && C->isAllOnesValue();
8897 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8898 /// if it's possible.
8899 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8900 DebugLoc dl, SelectionDAG &DAG) const {
8901 SDValue Op0 = And.getOperand(0);
8902 SDValue Op1 = And.getOperand(1);
8903 if (Op0.getOpcode() == ISD::TRUNCATE)
8904 Op0 = Op0.getOperand(0);
8905 if (Op1.getOpcode() == ISD::TRUNCATE)
8906 Op1 = Op1.getOperand(0);
8909 if (Op1.getOpcode() == ISD::SHL)
8910 std::swap(Op0, Op1);
8911 if (Op0.getOpcode() == ISD::SHL) {
8912 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8913 if (And00C->getZExtValue() == 1) {
8914 // If we looked past a truncate, check that it's only truncating away
8916 unsigned BitWidth = Op0.getValueSizeInBits();
8917 unsigned AndBitWidth = And.getValueSizeInBits();
8918 if (BitWidth > AndBitWidth) {
8920 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8921 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8925 RHS = Op0.getOperand(1);
8927 } else if (Op1.getOpcode() == ISD::Constant) {
8928 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8929 uint64_t AndRHSVal = AndRHS->getZExtValue();
8930 SDValue AndLHS = Op0;
8932 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8933 LHS = AndLHS.getOperand(0);
8934 RHS = AndLHS.getOperand(1);
8937 // Use BT if the immediate can't be encoded in a TEST instruction.
8938 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8940 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8944 if (LHS.getNode()) {
8945 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
8946 // the condition code later.
8947 bool Invert = false;
8948 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
8950 LHS = LHS.getOperand(0);
8953 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8954 // instruction. Since the shift amount is in-range-or-undefined, we know
8955 // that doing a bittest on the i32 value is ok. We extend to i32 because
8956 // the encoding for the i16 version is larger than the i32 version.
8957 // Also promote i16 to i32 for performance / code size reason.
8958 if (LHS.getValueType() == MVT::i8 ||
8959 LHS.getValueType() == MVT::i16)
8960 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8962 // If the operand types disagree, extend the shift amount to match. Since
8963 // BT ignores high bits (like shifts) we can use anyextend.
8964 if (LHS.getValueType() != RHS.getValueType())
8965 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8967 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8968 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8969 // Flip the condition if the LHS was a not instruction
8971 Cond = X86::GetOppositeBranchCondition(Cond);
8972 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8973 DAG.getConstant(Cond, MVT::i8), BT);
8979 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8981 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8983 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8984 SDValue Op0 = Op.getOperand(0);
8985 SDValue Op1 = Op.getOperand(1);
8986 DebugLoc dl = Op.getDebugLoc();
8987 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8989 // Optimize to BT if possible.
8990 // Lower (X & (1 << N)) == 0 to BT(X, N).
8991 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8992 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8993 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8994 Op1.getOpcode() == ISD::Constant &&
8995 cast<ConstantSDNode>(Op1)->isNullValue() &&
8996 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8997 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8998 if (NewSetCC.getNode())
9002 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9004 if (Op1.getOpcode() == ISD::Constant &&
9005 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9006 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9007 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9009 // If the input is a setcc, then reuse the input setcc or use a new one with
9010 // the inverted condition.
9011 if (Op0.getOpcode() == X86ISD::SETCC) {
9012 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9013 bool Invert = (CC == ISD::SETNE) ^
9014 cast<ConstantSDNode>(Op1)->isNullValue();
9015 if (!Invert) return Op0;
9017 CCode = X86::GetOppositeBranchCondition(CCode);
9018 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9019 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9023 bool isFP = Op1.getValueType().isFloatingPoint();
9024 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9025 if (X86CC == X86::COND_INVALID)
9028 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9029 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9030 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9031 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9034 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9035 // ones, and then concatenate the result back.
9036 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9037 EVT VT = Op.getValueType();
9039 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9040 "Unsupported value type for operation");
9042 unsigned NumElems = VT.getVectorNumElements();
9043 DebugLoc dl = Op.getDebugLoc();
9044 SDValue CC = Op.getOperand(2);
9046 // Extract the LHS vectors
9047 SDValue LHS = Op.getOperand(0);
9048 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9049 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9051 // Extract the RHS vectors
9052 SDValue RHS = Op.getOperand(1);
9053 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9054 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9056 // Issue the operation on the smaller types and concatenate the result back
9057 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9058 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9059 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9060 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9061 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9065 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9067 SDValue Op0 = Op.getOperand(0);
9068 SDValue Op1 = Op.getOperand(1);
9069 SDValue CC = Op.getOperand(2);
9070 EVT VT = Op.getValueType();
9071 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9072 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9073 DebugLoc dl = Op.getDebugLoc();
9077 EVT EltVT = Op0.getValueType().getVectorElementType();
9078 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9084 // SSE Condition code mapping:
9093 switch (SetCCOpcode) {
9094 default: llvm_unreachable("Unexpected SETCC condition");
9096 case ISD::SETEQ: SSECC = 0; break;
9098 case ISD::SETGT: Swap = true; // Fallthrough
9100 case ISD::SETOLT: SSECC = 1; break;
9102 case ISD::SETGE: Swap = true; // Fallthrough
9104 case ISD::SETOLE: SSECC = 2; break;
9105 case ISD::SETUO: SSECC = 3; break;
9107 case ISD::SETNE: SSECC = 4; break;
9108 case ISD::SETULE: Swap = true; // Fallthrough
9109 case ISD::SETUGE: SSECC = 5; break;
9110 case ISD::SETULT: Swap = true; // Fallthrough
9111 case ISD::SETUGT: SSECC = 6; break;
9112 case ISD::SETO: SSECC = 7; break;
9114 case ISD::SETONE: SSECC = 8; break;
9117 std::swap(Op0, Op1);
9119 // In the two special cases we can't handle, emit two comparisons.
9122 unsigned CombineOpc;
9123 if (SetCCOpcode == ISD::SETUEQ) {
9124 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9126 assert(SetCCOpcode == ISD::SETONE);
9127 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9130 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9131 DAG.getConstant(CC0, MVT::i8));
9132 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9133 DAG.getConstant(CC1, MVT::i8));
9134 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9136 // Handle all other FP comparisons here.
9137 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9138 DAG.getConstant(SSECC, MVT::i8));
9141 // Break 256-bit integer vector compare into smaller ones.
9142 if (VT.is256BitVector() && !Subtarget->hasInt256())
9143 return Lower256IntVSETCC(Op, DAG);
9145 // We are handling one of the integer comparisons here. Since SSE only has
9146 // GT and EQ comparisons for integer, swapping operands and multiple
9147 // operations may be required for some comparisons.
9149 bool Swap = false, Invert = false, FlipSigns = false;
9151 switch (SetCCOpcode) {
9152 default: llvm_unreachable("Unexpected SETCC condition");
9153 case ISD::SETNE: Invert = true;
9154 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9155 case ISD::SETLT: Swap = true;
9156 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9157 case ISD::SETGE: Swap = true;
9158 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9159 case ISD::SETULT: Swap = true;
9160 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9161 case ISD::SETUGE: Swap = true;
9162 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9165 std::swap(Op0, Op1);
9167 // Check that the operation in question is available (most are plain SSE2,
9168 // but PCMPGTQ and PCMPEQQ have different requirements).
9169 if (VT == MVT::v2i64) {
9170 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9172 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9176 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9177 // bits of the inputs before performing those operations.
9179 EVT EltVT = VT.getVectorElementType();
9180 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9182 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9183 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9185 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9186 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9189 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9191 // If the logical-not of the result is required, perform that now.
9193 Result = DAG.getNOT(dl, Result, VT);
9198 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9199 static bool isX86LogicalCmp(SDValue Op) {
9200 unsigned Opc = Op.getNode()->getOpcode();
9201 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9202 Opc == X86ISD::SAHF)
9204 if (Op.getResNo() == 1 &&
9205 (Opc == X86ISD::ADD ||
9206 Opc == X86ISD::SUB ||
9207 Opc == X86ISD::ADC ||
9208 Opc == X86ISD::SBB ||
9209 Opc == X86ISD::SMUL ||
9210 Opc == X86ISD::UMUL ||
9211 Opc == X86ISD::INC ||
9212 Opc == X86ISD::DEC ||
9213 Opc == X86ISD::OR ||
9214 Opc == X86ISD::XOR ||
9215 Opc == X86ISD::AND))
9218 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9224 static bool isZero(SDValue V) {
9225 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9226 return C && C->isNullValue();
9229 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9230 if (V.getOpcode() != ISD::TRUNCATE)
9233 SDValue VOp0 = V.getOperand(0);
9234 unsigned InBits = VOp0.getValueSizeInBits();
9235 unsigned Bits = V.getValueSizeInBits();
9236 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9239 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9240 bool addTest = true;
9241 SDValue Cond = Op.getOperand(0);
9242 SDValue Op1 = Op.getOperand(1);
9243 SDValue Op2 = Op.getOperand(2);
9244 DebugLoc DL = Op.getDebugLoc();
9247 if (Cond.getOpcode() == ISD::SETCC) {
9248 SDValue NewCond = LowerSETCC(Cond, DAG);
9249 if (NewCond.getNode())
9253 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9254 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9255 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9256 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9257 if (Cond.getOpcode() == X86ISD::SETCC &&
9258 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9259 isZero(Cond.getOperand(1).getOperand(1))) {
9260 SDValue Cmp = Cond.getOperand(1);
9262 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9264 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9265 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9266 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9268 SDValue CmpOp0 = Cmp.getOperand(0);
9269 // Apply further optimizations for special cases
9270 // (select (x != 0), -1, 0) -> neg & sbb
9271 // (select (x == 0), 0, -1) -> neg & sbb
9272 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9273 if (YC->isNullValue() &&
9274 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9275 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9276 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9277 DAG.getConstant(0, CmpOp0.getValueType()),
9279 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9280 DAG.getConstant(X86::COND_B, MVT::i8),
9281 SDValue(Neg.getNode(), 1));
9285 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9286 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9287 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9289 SDValue Res = // Res = 0 or -1.
9290 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9291 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9293 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9294 Res = DAG.getNOT(DL, Res, Res.getValueType());
9296 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9297 if (N2C == 0 || !N2C->isNullValue())
9298 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9303 // Look past (and (setcc_carry (cmp ...)), 1).
9304 if (Cond.getOpcode() == ISD::AND &&
9305 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9307 if (C && C->getAPIntValue() == 1)
9308 Cond = Cond.getOperand(0);
9311 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9312 // setting operand in place of the X86ISD::SETCC.
9313 unsigned CondOpcode = Cond.getOpcode();
9314 if (CondOpcode == X86ISD::SETCC ||
9315 CondOpcode == X86ISD::SETCC_CARRY) {
9316 CC = Cond.getOperand(0);
9318 SDValue Cmp = Cond.getOperand(1);
9319 unsigned Opc = Cmp.getOpcode();
9320 EVT VT = Op.getValueType();
9322 bool IllegalFPCMov = false;
9323 if (VT.isFloatingPoint() && !VT.isVector() &&
9324 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9325 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9327 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9328 Opc == X86ISD::BT) { // FIXME
9332 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9333 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9334 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9335 Cond.getOperand(0).getValueType() != MVT::i8)) {
9336 SDValue LHS = Cond.getOperand(0);
9337 SDValue RHS = Cond.getOperand(1);
9341 switch (CondOpcode) {
9342 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9343 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9344 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9345 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9346 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9347 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9348 default: llvm_unreachable("unexpected overflowing operator");
9350 if (CondOpcode == ISD::UMULO)
9351 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9354 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9356 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9358 if (CondOpcode == ISD::UMULO)
9359 Cond = X86Op.getValue(2);
9361 Cond = X86Op.getValue(1);
9363 CC = DAG.getConstant(X86Cond, MVT::i8);
9368 // Look pass the truncate if the high bits are known zero.
9369 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9370 Cond = Cond.getOperand(0);
9372 // We know the result of AND is compared against zero. Try to match
9374 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9375 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9376 if (NewSetCC.getNode()) {
9377 CC = NewSetCC.getOperand(0);
9378 Cond = NewSetCC.getOperand(1);
9385 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9386 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9389 // a < b ? -1 : 0 -> RES = ~setcc_carry
9390 // a < b ? 0 : -1 -> RES = setcc_carry
9391 // a >= b ? -1 : 0 -> RES = setcc_carry
9392 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9393 if (Cond.getOpcode() == X86ISD::SUB) {
9394 Cond = ConvertCmpIfNecessary(Cond, DAG);
9395 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9397 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9398 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9399 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9400 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9401 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9402 return DAG.getNOT(DL, Res, Res.getValueType());
9407 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9408 // widen the cmov and push the truncate through. This avoids introducing a new
9409 // branch during isel and doesn't add any extensions.
9410 if (Op.getValueType() == MVT::i8 &&
9411 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9412 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9413 if (T1.getValueType() == T2.getValueType() &&
9414 // Blacklist CopyFromReg to avoid partial register stalls.
9415 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9416 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9417 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9418 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9422 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9423 // condition is true.
9424 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9425 SDValue Ops[] = { Op2, Op1, CC, Cond };
9426 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9429 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9430 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9431 // from the AND / OR.
9432 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9433 Opc = Op.getOpcode();
9434 if (Opc != ISD::OR && Opc != ISD::AND)
9436 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9437 Op.getOperand(0).hasOneUse() &&
9438 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9439 Op.getOperand(1).hasOneUse());
9442 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9443 // 1 and that the SETCC node has a single use.
9444 static bool isXor1OfSetCC(SDValue Op) {
9445 if (Op.getOpcode() != ISD::XOR)
9447 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9448 if (N1C && N1C->getAPIntValue() == 1) {
9449 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9450 Op.getOperand(0).hasOneUse();
9455 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9456 bool addTest = true;
9457 SDValue Chain = Op.getOperand(0);
9458 SDValue Cond = Op.getOperand(1);
9459 SDValue Dest = Op.getOperand(2);
9460 DebugLoc dl = Op.getDebugLoc();
9462 bool Inverted = false;
9464 if (Cond.getOpcode() == ISD::SETCC) {
9465 // Check for setcc([su]{add,sub,mul}o == 0).
9466 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9467 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9468 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9469 Cond.getOperand(0).getResNo() == 1 &&
9470 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9471 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9472 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9473 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9474 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9475 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9477 Cond = Cond.getOperand(0);
9479 SDValue NewCond = LowerSETCC(Cond, DAG);
9480 if (NewCond.getNode())
9485 // FIXME: LowerXALUO doesn't handle these!!
9486 else if (Cond.getOpcode() == X86ISD::ADD ||
9487 Cond.getOpcode() == X86ISD::SUB ||
9488 Cond.getOpcode() == X86ISD::SMUL ||
9489 Cond.getOpcode() == X86ISD::UMUL)
9490 Cond = LowerXALUO(Cond, DAG);
9493 // Look pass (and (setcc_carry (cmp ...)), 1).
9494 if (Cond.getOpcode() == ISD::AND &&
9495 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9496 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9497 if (C && C->getAPIntValue() == 1)
9498 Cond = Cond.getOperand(0);
9501 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9502 // setting operand in place of the X86ISD::SETCC.
9503 unsigned CondOpcode = Cond.getOpcode();
9504 if (CondOpcode == X86ISD::SETCC ||
9505 CondOpcode == X86ISD::SETCC_CARRY) {
9506 CC = Cond.getOperand(0);
9508 SDValue Cmp = Cond.getOperand(1);
9509 unsigned Opc = Cmp.getOpcode();
9510 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9511 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9515 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9519 // These can only come from an arithmetic instruction with overflow,
9520 // e.g. SADDO, UADDO.
9521 Cond = Cond.getNode()->getOperand(1);
9527 CondOpcode = Cond.getOpcode();
9528 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9529 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9530 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9531 Cond.getOperand(0).getValueType() != MVT::i8)) {
9532 SDValue LHS = Cond.getOperand(0);
9533 SDValue RHS = Cond.getOperand(1);
9537 switch (CondOpcode) {
9538 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9539 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9540 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9541 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9542 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9543 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9544 default: llvm_unreachable("unexpected overflowing operator");
9547 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9548 if (CondOpcode == ISD::UMULO)
9549 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9552 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9554 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9556 if (CondOpcode == ISD::UMULO)
9557 Cond = X86Op.getValue(2);
9559 Cond = X86Op.getValue(1);
9561 CC = DAG.getConstant(X86Cond, MVT::i8);
9565 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9566 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9567 if (CondOpc == ISD::OR) {
9568 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9569 // two branches instead of an explicit OR instruction with a
9571 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9572 isX86LogicalCmp(Cmp)) {
9573 CC = Cond.getOperand(0).getOperand(0);
9574 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9575 Chain, Dest, CC, Cmp);
9576 CC = Cond.getOperand(1).getOperand(0);
9580 } else { // ISD::AND
9581 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9582 // two branches instead of an explicit AND instruction with a
9583 // separate test. However, we only do this if this block doesn't
9584 // have a fall-through edge, because this requires an explicit
9585 // jmp when the condition is false.
9586 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9587 isX86LogicalCmp(Cmp) &&
9588 Op.getNode()->hasOneUse()) {
9589 X86::CondCode CCode =
9590 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9591 CCode = X86::GetOppositeBranchCondition(CCode);
9592 CC = DAG.getConstant(CCode, MVT::i8);
9593 SDNode *User = *Op.getNode()->use_begin();
9594 // Look for an unconditional branch following this conditional branch.
9595 // We need this because we need to reverse the successors in order
9596 // to implement FCMP_OEQ.
9597 if (User->getOpcode() == ISD::BR) {
9598 SDValue FalseBB = User->getOperand(1);
9600 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9601 assert(NewBR == User);
9605 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9606 Chain, Dest, CC, Cmp);
9607 X86::CondCode CCode =
9608 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9609 CCode = X86::GetOppositeBranchCondition(CCode);
9610 CC = DAG.getConstant(CCode, MVT::i8);
9616 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9617 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9618 // It should be transformed during dag combiner except when the condition
9619 // is set by a arithmetics with overflow node.
9620 X86::CondCode CCode =
9621 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9622 CCode = X86::GetOppositeBranchCondition(CCode);
9623 CC = DAG.getConstant(CCode, MVT::i8);
9624 Cond = Cond.getOperand(0).getOperand(1);
9626 } else if (Cond.getOpcode() == ISD::SETCC &&
9627 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9628 // For FCMP_OEQ, we can emit
9629 // two branches instead of an explicit AND instruction with a
9630 // separate test. However, we only do this if this block doesn't
9631 // have a fall-through edge, because this requires an explicit
9632 // jmp when the condition is false.
9633 if (Op.getNode()->hasOneUse()) {
9634 SDNode *User = *Op.getNode()->use_begin();
9635 // Look for an unconditional branch following this conditional branch.
9636 // We need this because we need to reverse the successors in order
9637 // to implement FCMP_OEQ.
9638 if (User->getOpcode() == ISD::BR) {
9639 SDValue FalseBB = User->getOperand(1);
9641 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9642 assert(NewBR == User);
9646 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9647 Cond.getOperand(0), Cond.getOperand(1));
9648 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9649 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9650 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9651 Chain, Dest, CC, Cmp);
9652 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9657 } else if (Cond.getOpcode() == ISD::SETCC &&
9658 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9659 // For FCMP_UNE, we can emit
9660 // two branches instead of an explicit AND instruction with a
9661 // separate test. However, we only do this if this block doesn't
9662 // have a fall-through edge, because this requires an explicit
9663 // jmp when the condition is false.
9664 if (Op.getNode()->hasOneUse()) {
9665 SDNode *User = *Op.getNode()->use_begin();
9666 // Look for an unconditional branch following this conditional branch.
9667 // We need this because we need to reverse the successors in order
9668 // to implement FCMP_UNE.
9669 if (User->getOpcode() == ISD::BR) {
9670 SDValue FalseBB = User->getOperand(1);
9672 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9673 assert(NewBR == User);
9676 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9677 Cond.getOperand(0), Cond.getOperand(1));
9678 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9679 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9680 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9681 Chain, Dest, CC, Cmp);
9682 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9692 // Look pass the truncate if the high bits are known zero.
9693 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9694 Cond = Cond.getOperand(0);
9696 // We know the result of AND is compared against zero. Try to match
9698 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9699 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9700 if (NewSetCC.getNode()) {
9701 CC = NewSetCC.getOperand(0);
9702 Cond = NewSetCC.getOperand(1);
9709 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9710 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9712 Cond = ConvertCmpIfNecessary(Cond, DAG);
9713 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9714 Chain, Dest, CC, Cond);
9718 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9719 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9720 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9721 // that the guard pages used by the OS virtual memory manager are allocated in
9722 // correct sequence.
9724 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9725 SelectionDAG &DAG) const {
9726 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9727 getTargetMachine().Options.EnableSegmentedStacks) &&
9728 "This should be used only on Windows targets or when segmented stacks "
9730 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9731 DebugLoc dl = Op.getDebugLoc();
9734 SDValue Chain = Op.getOperand(0);
9735 SDValue Size = Op.getOperand(1);
9736 // FIXME: Ensure alignment here
9738 bool Is64Bit = Subtarget->is64Bit();
9739 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9741 if (getTargetMachine().Options.EnableSegmentedStacks) {
9742 MachineFunction &MF = DAG.getMachineFunction();
9743 MachineRegisterInfo &MRI = MF.getRegInfo();
9746 // The 64 bit implementation of segmented stacks needs to clobber both r10
9747 // r11. This makes it impossible to use it along with nested parameters.
9748 const Function *F = MF.getFunction();
9750 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9752 if (I->hasNestAttr())
9753 report_fatal_error("Cannot use segmented stacks with functions that "
9754 "have nested arguments.");
9757 const TargetRegisterClass *AddrRegClass =
9758 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9759 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9760 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9761 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9762 DAG.getRegister(Vreg, SPTy));
9763 SDValue Ops1[2] = { Value, Chain };
9764 return DAG.getMergeValues(Ops1, 2, dl);
9767 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9769 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9770 Flag = Chain.getValue(1);
9771 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9773 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9774 Flag = Chain.getValue(1);
9776 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
9779 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9780 return DAG.getMergeValues(Ops1, 2, dl);
9784 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9785 MachineFunction &MF = DAG.getMachineFunction();
9786 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9788 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9789 DebugLoc DL = Op.getDebugLoc();
9791 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9792 // vastart just stores the address of the VarArgsFrameIndex slot into the
9793 // memory location argument.
9794 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9796 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9797 MachinePointerInfo(SV), false, false, 0);
9801 // gp_offset (0 - 6 * 8)
9802 // fp_offset (48 - 48 + 8 * 16)
9803 // overflow_arg_area (point to parameters coming in memory).
9805 SmallVector<SDValue, 8> MemOps;
9806 SDValue FIN = Op.getOperand(1);
9808 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9809 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9811 FIN, MachinePointerInfo(SV), false, false, 0);
9812 MemOps.push_back(Store);
9815 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9816 FIN, DAG.getIntPtrConstant(4));
9817 Store = DAG.getStore(Op.getOperand(0), DL,
9818 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9820 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9821 MemOps.push_back(Store);
9823 // Store ptr to overflow_arg_area
9824 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9825 FIN, DAG.getIntPtrConstant(4));
9826 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9828 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9829 MachinePointerInfo(SV, 8),
9831 MemOps.push_back(Store);
9833 // Store ptr to reg_save_area.
9834 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9835 FIN, DAG.getIntPtrConstant(8));
9836 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9838 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9839 MachinePointerInfo(SV, 16), false, false, 0);
9840 MemOps.push_back(Store);
9841 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9842 &MemOps[0], MemOps.size());
9845 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9846 assert(Subtarget->is64Bit() &&
9847 "LowerVAARG only handles 64-bit va_arg!");
9848 assert((Subtarget->isTargetLinux() ||
9849 Subtarget->isTargetDarwin()) &&
9850 "Unhandled target in LowerVAARG");
9851 assert(Op.getNode()->getNumOperands() == 4);
9852 SDValue Chain = Op.getOperand(0);
9853 SDValue SrcPtr = Op.getOperand(1);
9854 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9855 unsigned Align = Op.getConstantOperandVal(3);
9856 DebugLoc dl = Op.getDebugLoc();
9858 EVT ArgVT = Op.getNode()->getValueType(0);
9859 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9860 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9863 // Decide which area this value should be read from.
9864 // TODO: Implement the AMD64 ABI in its entirety. This simple
9865 // selection mechanism works only for the basic types.
9866 if (ArgVT == MVT::f80) {
9867 llvm_unreachable("va_arg for f80 not yet implemented");
9868 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9869 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9870 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9871 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9873 llvm_unreachable("Unhandled argument type in LowerVAARG");
9877 // Sanity Check: Make sure using fp_offset makes sense.
9878 assert(!getTargetMachine().Options.UseSoftFloat &&
9879 !(DAG.getMachineFunction()
9880 .getFunction()->getFnAttributes()
9881 .hasAttribute(Attributes::NoImplicitFloat)) &&
9882 Subtarget->hasSSE1());
9885 // Insert VAARG_64 node into the DAG
9886 // VAARG_64 returns two values: Variable Argument Address, Chain
9887 SmallVector<SDValue, 11> InstOps;
9888 InstOps.push_back(Chain);
9889 InstOps.push_back(SrcPtr);
9890 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9891 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9892 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9893 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9894 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9895 VTs, &InstOps[0], InstOps.size(),
9897 MachinePointerInfo(SV),
9902 Chain = VAARG.getValue(1);
9904 // Load the next argument and return it
9905 return DAG.getLoad(ArgVT, dl,
9908 MachinePointerInfo(),
9909 false, false, false, 0);
9912 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9913 SelectionDAG &DAG) {
9914 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9915 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9916 SDValue Chain = Op.getOperand(0);
9917 SDValue DstPtr = Op.getOperand(1);
9918 SDValue SrcPtr = Op.getOperand(2);
9919 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9920 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9921 DebugLoc DL = Op.getDebugLoc();
9923 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9924 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9926 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9929 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9930 // may or may not be a constant. Takes immediate version of shift as input.
9931 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9932 SDValue SrcOp, SDValue ShAmt,
9933 SelectionDAG &DAG) {
9934 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9936 if (isa<ConstantSDNode>(ShAmt)) {
9937 // Constant may be a TargetConstant. Use a regular constant.
9938 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9940 default: llvm_unreachable("Unknown target vector shift node");
9944 return DAG.getNode(Opc, dl, VT, SrcOp,
9945 DAG.getConstant(ShiftAmt, MVT::i32));
9949 // Change opcode to non-immediate version
9951 default: llvm_unreachable("Unknown target vector shift node");
9952 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9953 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9954 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9957 // Need to build a vector containing shift amount
9958 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9961 ShOps[1] = DAG.getConstant(0, MVT::i32);
9962 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9963 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9965 // The return type has to be a 128-bit type with the same element
9966 // type as the input type.
9967 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9968 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9970 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9971 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9974 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9975 DebugLoc dl = Op.getDebugLoc();
9976 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9978 default: return SDValue(); // Don't custom lower most intrinsics.
9979 // Comparison intrinsics.
9980 case Intrinsic::x86_sse_comieq_ss:
9981 case Intrinsic::x86_sse_comilt_ss:
9982 case Intrinsic::x86_sse_comile_ss:
9983 case Intrinsic::x86_sse_comigt_ss:
9984 case Intrinsic::x86_sse_comige_ss:
9985 case Intrinsic::x86_sse_comineq_ss:
9986 case Intrinsic::x86_sse_ucomieq_ss:
9987 case Intrinsic::x86_sse_ucomilt_ss:
9988 case Intrinsic::x86_sse_ucomile_ss:
9989 case Intrinsic::x86_sse_ucomigt_ss:
9990 case Intrinsic::x86_sse_ucomige_ss:
9991 case Intrinsic::x86_sse_ucomineq_ss:
9992 case Intrinsic::x86_sse2_comieq_sd:
9993 case Intrinsic::x86_sse2_comilt_sd:
9994 case Intrinsic::x86_sse2_comile_sd:
9995 case Intrinsic::x86_sse2_comigt_sd:
9996 case Intrinsic::x86_sse2_comige_sd:
9997 case Intrinsic::x86_sse2_comineq_sd:
9998 case Intrinsic::x86_sse2_ucomieq_sd:
9999 case Intrinsic::x86_sse2_ucomilt_sd:
10000 case Intrinsic::x86_sse2_ucomile_sd:
10001 case Intrinsic::x86_sse2_ucomigt_sd:
10002 case Intrinsic::x86_sse2_ucomige_sd:
10003 case Intrinsic::x86_sse2_ucomineq_sd: {
10007 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10008 case Intrinsic::x86_sse_comieq_ss:
10009 case Intrinsic::x86_sse2_comieq_sd:
10010 Opc = X86ISD::COMI;
10013 case Intrinsic::x86_sse_comilt_ss:
10014 case Intrinsic::x86_sse2_comilt_sd:
10015 Opc = X86ISD::COMI;
10018 case Intrinsic::x86_sse_comile_ss:
10019 case Intrinsic::x86_sse2_comile_sd:
10020 Opc = X86ISD::COMI;
10023 case Intrinsic::x86_sse_comigt_ss:
10024 case Intrinsic::x86_sse2_comigt_sd:
10025 Opc = X86ISD::COMI;
10028 case Intrinsic::x86_sse_comige_ss:
10029 case Intrinsic::x86_sse2_comige_sd:
10030 Opc = X86ISD::COMI;
10033 case Intrinsic::x86_sse_comineq_ss:
10034 case Intrinsic::x86_sse2_comineq_sd:
10035 Opc = X86ISD::COMI;
10038 case Intrinsic::x86_sse_ucomieq_ss:
10039 case Intrinsic::x86_sse2_ucomieq_sd:
10040 Opc = X86ISD::UCOMI;
10043 case Intrinsic::x86_sse_ucomilt_ss:
10044 case Intrinsic::x86_sse2_ucomilt_sd:
10045 Opc = X86ISD::UCOMI;
10048 case Intrinsic::x86_sse_ucomile_ss:
10049 case Intrinsic::x86_sse2_ucomile_sd:
10050 Opc = X86ISD::UCOMI;
10053 case Intrinsic::x86_sse_ucomigt_ss:
10054 case Intrinsic::x86_sse2_ucomigt_sd:
10055 Opc = X86ISD::UCOMI;
10058 case Intrinsic::x86_sse_ucomige_ss:
10059 case Intrinsic::x86_sse2_ucomige_sd:
10060 Opc = X86ISD::UCOMI;
10063 case Intrinsic::x86_sse_ucomineq_ss:
10064 case Intrinsic::x86_sse2_ucomineq_sd:
10065 Opc = X86ISD::UCOMI;
10070 SDValue LHS = Op.getOperand(1);
10071 SDValue RHS = Op.getOperand(2);
10072 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10073 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10074 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10075 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10076 DAG.getConstant(X86CC, MVT::i8), Cond);
10077 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10080 // Arithmetic intrinsics.
10081 case Intrinsic::x86_sse2_pmulu_dq:
10082 case Intrinsic::x86_avx2_pmulu_dq:
10083 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10084 Op.getOperand(1), Op.getOperand(2));
10086 // SSE3/AVX horizontal add/sub intrinsics
10087 case Intrinsic::x86_sse3_hadd_ps:
10088 case Intrinsic::x86_sse3_hadd_pd:
10089 case Intrinsic::x86_avx_hadd_ps_256:
10090 case Intrinsic::x86_avx_hadd_pd_256:
10091 case Intrinsic::x86_sse3_hsub_ps:
10092 case Intrinsic::x86_sse3_hsub_pd:
10093 case Intrinsic::x86_avx_hsub_ps_256:
10094 case Intrinsic::x86_avx_hsub_pd_256:
10095 case Intrinsic::x86_ssse3_phadd_w_128:
10096 case Intrinsic::x86_ssse3_phadd_d_128:
10097 case Intrinsic::x86_avx2_phadd_w:
10098 case Intrinsic::x86_avx2_phadd_d:
10099 case Intrinsic::x86_ssse3_phsub_w_128:
10100 case Intrinsic::x86_ssse3_phsub_d_128:
10101 case Intrinsic::x86_avx2_phsub_w:
10102 case Intrinsic::x86_avx2_phsub_d: {
10105 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10106 case Intrinsic::x86_sse3_hadd_ps:
10107 case Intrinsic::x86_sse3_hadd_pd:
10108 case Intrinsic::x86_avx_hadd_ps_256:
10109 case Intrinsic::x86_avx_hadd_pd_256:
10110 Opcode = X86ISD::FHADD;
10112 case Intrinsic::x86_sse3_hsub_ps:
10113 case Intrinsic::x86_sse3_hsub_pd:
10114 case Intrinsic::x86_avx_hsub_ps_256:
10115 case Intrinsic::x86_avx_hsub_pd_256:
10116 Opcode = X86ISD::FHSUB;
10118 case Intrinsic::x86_ssse3_phadd_w_128:
10119 case Intrinsic::x86_ssse3_phadd_d_128:
10120 case Intrinsic::x86_avx2_phadd_w:
10121 case Intrinsic::x86_avx2_phadd_d:
10122 Opcode = X86ISD::HADD;
10124 case Intrinsic::x86_ssse3_phsub_w_128:
10125 case Intrinsic::x86_ssse3_phsub_d_128:
10126 case Intrinsic::x86_avx2_phsub_w:
10127 case Intrinsic::x86_avx2_phsub_d:
10128 Opcode = X86ISD::HSUB;
10131 return DAG.getNode(Opcode, dl, Op.getValueType(),
10132 Op.getOperand(1), Op.getOperand(2));
10135 // AVX2 variable shift intrinsics
10136 case Intrinsic::x86_avx2_psllv_d:
10137 case Intrinsic::x86_avx2_psllv_q:
10138 case Intrinsic::x86_avx2_psllv_d_256:
10139 case Intrinsic::x86_avx2_psllv_q_256:
10140 case Intrinsic::x86_avx2_psrlv_d:
10141 case Intrinsic::x86_avx2_psrlv_q:
10142 case Intrinsic::x86_avx2_psrlv_d_256:
10143 case Intrinsic::x86_avx2_psrlv_q_256:
10144 case Intrinsic::x86_avx2_psrav_d:
10145 case Intrinsic::x86_avx2_psrav_d_256: {
10148 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10149 case Intrinsic::x86_avx2_psllv_d:
10150 case Intrinsic::x86_avx2_psllv_q:
10151 case Intrinsic::x86_avx2_psllv_d_256:
10152 case Intrinsic::x86_avx2_psllv_q_256:
10155 case Intrinsic::x86_avx2_psrlv_d:
10156 case Intrinsic::x86_avx2_psrlv_q:
10157 case Intrinsic::x86_avx2_psrlv_d_256:
10158 case Intrinsic::x86_avx2_psrlv_q_256:
10161 case Intrinsic::x86_avx2_psrav_d:
10162 case Intrinsic::x86_avx2_psrav_d_256:
10166 return DAG.getNode(Opcode, dl, Op.getValueType(),
10167 Op.getOperand(1), Op.getOperand(2));
10170 case Intrinsic::x86_ssse3_pshuf_b_128:
10171 case Intrinsic::x86_avx2_pshuf_b:
10172 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10173 Op.getOperand(1), Op.getOperand(2));
10175 case Intrinsic::x86_ssse3_psign_b_128:
10176 case Intrinsic::x86_ssse3_psign_w_128:
10177 case Intrinsic::x86_ssse3_psign_d_128:
10178 case Intrinsic::x86_avx2_psign_b:
10179 case Intrinsic::x86_avx2_psign_w:
10180 case Intrinsic::x86_avx2_psign_d:
10181 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10182 Op.getOperand(1), Op.getOperand(2));
10184 case Intrinsic::x86_sse41_insertps:
10185 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10186 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10188 case Intrinsic::x86_avx_vperm2f128_ps_256:
10189 case Intrinsic::x86_avx_vperm2f128_pd_256:
10190 case Intrinsic::x86_avx_vperm2f128_si_256:
10191 case Intrinsic::x86_avx2_vperm2i128:
10192 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10193 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10195 case Intrinsic::x86_avx2_permd:
10196 case Intrinsic::x86_avx2_permps:
10197 // Operands intentionally swapped. Mask is last operand to intrinsic,
10198 // but second operand for node/intruction.
10199 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10200 Op.getOperand(2), Op.getOperand(1));
10202 // ptest and testp intrinsics. The intrinsic these come from are designed to
10203 // return an integer value, not just an instruction so lower it to the ptest
10204 // or testp pattern and a setcc for the result.
10205 case Intrinsic::x86_sse41_ptestz:
10206 case Intrinsic::x86_sse41_ptestc:
10207 case Intrinsic::x86_sse41_ptestnzc:
10208 case Intrinsic::x86_avx_ptestz_256:
10209 case Intrinsic::x86_avx_ptestc_256:
10210 case Intrinsic::x86_avx_ptestnzc_256:
10211 case Intrinsic::x86_avx_vtestz_ps:
10212 case Intrinsic::x86_avx_vtestc_ps:
10213 case Intrinsic::x86_avx_vtestnzc_ps:
10214 case Intrinsic::x86_avx_vtestz_pd:
10215 case Intrinsic::x86_avx_vtestc_pd:
10216 case Intrinsic::x86_avx_vtestnzc_pd:
10217 case Intrinsic::x86_avx_vtestz_ps_256:
10218 case Intrinsic::x86_avx_vtestc_ps_256:
10219 case Intrinsic::x86_avx_vtestnzc_ps_256:
10220 case Intrinsic::x86_avx_vtestz_pd_256:
10221 case Intrinsic::x86_avx_vtestc_pd_256:
10222 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10223 bool IsTestPacked = false;
10226 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10227 case Intrinsic::x86_avx_vtestz_ps:
10228 case Intrinsic::x86_avx_vtestz_pd:
10229 case Intrinsic::x86_avx_vtestz_ps_256:
10230 case Intrinsic::x86_avx_vtestz_pd_256:
10231 IsTestPacked = true; // Fallthrough
10232 case Intrinsic::x86_sse41_ptestz:
10233 case Intrinsic::x86_avx_ptestz_256:
10235 X86CC = X86::COND_E;
10237 case Intrinsic::x86_avx_vtestc_ps:
10238 case Intrinsic::x86_avx_vtestc_pd:
10239 case Intrinsic::x86_avx_vtestc_ps_256:
10240 case Intrinsic::x86_avx_vtestc_pd_256:
10241 IsTestPacked = true; // Fallthrough
10242 case Intrinsic::x86_sse41_ptestc:
10243 case Intrinsic::x86_avx_ptestc_256:
10245 X86CC = X86::COND_B;
10247 case Intrinsic::x86_avx_vtestnzc_ps:
10248 case Intrinsic::x86_avx_vtestnzc_pd:
10249 case Intrinsic::x86_avx_vtestnzc_ps_256:
10250 case Intrinsic::x86_avx_vtestnzc_pd_256:
10251 IsTestPacked = true; // Fallthrough
10252 case Intrinsic::x86_sse41_ptestnzc:
10253 case Intrinsic::x86_avx_ptestnzc_256:
10255 X86CC = X86::COND_A;
10259 SDValue LHS = Op.getOperand(1);
10260 SDValue RHS = Op.getOperand(2);
10261 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10262 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10263 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10264 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10265 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10268 // SSE/AVX shift intrinsics
10269 case Intrinsic::x86_sse2_psll_w:
10270 case Intrinsic::x86_sse2_psll_d:
10271 case Intrinsic::x86_sse2_psll_q:
10272 case Intrinsic::x86_avx2_psll_w:
10273 case Intrinsic::x86_avx2_psll_d:
10274 case Intrinsic::x86_avx2_psll_q:
10275 case Intrinsic::x86_sse2_psrl_w:
10276 case Intrinsic::x86_sse2_psrl_d:
10277 case Intrinsic::x86_sse2_psrl_q:
10278 case Intrinsic::x86_avx2_psrl_w:
10279 case Intrinsic::x86_avx2_psrl_d:
10280 case Intrinsic::x86_avx2_psrl_q:
10281 case Intrinsic::x86_sse2_psra_w:
10282 case Intrinsic::x86_sse2_psra_d:
10283 case Intrinsic::x86_avx2_psra_w:
10284 case Intrinsic::x86_avx2_psra_d: {
10287 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10288 case Intrinsic::x86_sse2_psll_w:
10289 case Intrinsic::x86_sse2_psll_d:
10290 case Intrinsic::x86_sse2_psll_q:
10291 case Intrinsic::x86_avx2_psll_w:
10292 case Intrinsic::x86_avx2_psll_d:
10293 case Intrinsic::x86_avx2_psll_q:
10294 Opcode = X86ISD::VSHL;
10296 case Intrinsic::x86_sse2_psrl_w:
10297 case Intrinsic::x86_sse2_psrl_d:
10298 case Intrinsic::x86_sse2_psrl_q:
10299 case Intrinsic::x86_avx2_psrl_w:
10300 case Intrinsic::x86_avx2_psrl_d:
10301 case Intrinsic::x86_avx2_psrl_q:
10302 Opcode = X86ISD::VSRL;
10304 case Intrinsic::x86_sse2_psra_w:
10305 case Intrinsic::x86_sse2_psra_d:
10306 case Intrinsic::x86_avx2_psra_w:
10307 case Intrinsic::x86_avx2_psra_d:
10308 Opcode = X86ISD::VSRA;
10311 return DAG.getNode(Opcode, dl, Op.getValueType(),
10312 Op.getOperand(1), Op.getOperand(2));
10315 // SSE/AVX immediate shift intrinsics
10316 case Intrinsic::x86_sse2_pslli_w:
10317 case Intrinsic::x86_sse2_pslli_d:
10318 case Intrinsic::x86_sse2_pslli_q:
10319 case Intrinsic::x86_avx2_pslli_w:
10320 case Intrinsic::x86_avx2_pslli_d:
10321 case Intrinsic::x86_avx2_pslli_q:
10322 case Intrinsic::x86_sse2_psrli_w:
10323 case Intrinsic::x86_sse2_psrli_d:
10324 case Intrinsic::x86_sse2_psrli_q:
10325 case Intrinsic::x86_avx2_psrli_w:
10326 case Intrinsic::x86_avx2_psrli_d:
10327 case Intrinsic::x86_avx2_psrli_q:
10328 case Intrinsic::x86_sse2_psrai_w:
10329 case Intrinsic::x86_sse2_psrai_d:
10330 case Intrinsic::x86_avx2_psrai_w:
10331 case Intrinsic::x86_avx2_psrai_d: {
10334 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10335 case Intrinsic::x86_sse2_pslli_w:
10336 case Intrinsic::x86_sse2_pslli_d:
10337 case Intrinsic::x86_sse2_pslli_q:
10338 case Intrinsic::x86_avx2_pslli_w:
10339 case Intrinsic::x86_avx2_pslli_d:
10340 case Intrinsic::x86_avx2_pslli_q:
10341 Opcode = X86ISD::VSHLI;
10343 case Intrinsic::x86_sse2_psrli_w:
10344 case Intrinsic::x86_sse2_psrli_d:
10345 case Intrinsic::x86_sse2_psrli_q:
10346 case Intrinsic::x86_avx2_psrli_w:
10347 case Intrinsic::x86_avx2_psrli_d:
10348 case Intrinsic::x86_avx2_psrli_q:
10349 Opcode = X86ISD::VSRLI;
10351 case Intrinsic::x86_sse2_psrai_w:
10352 case Intrinsic::x86_sse2_psrai_d:
10353 case Intrinsic::x86_avx2_psrai_w:
10354 case Intrinsic::x86_avx2_psrai_d:
10355 Opcode = X86ISD::VSRAI;
10358 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10359 Op.getOperand(1), Op.getOperand(2), DAG);
10362 case Intrinsic::x86_sse42_pcmpistria128:
10363 case Intrinsic::x86_sse42_pcmpestria128:
10364 case Intrinsic::x86_sse42_pcmpistric128:
10365 case Intrinsic::x86_sse42_pcmpestric128:
10366 case Intrinsic::x86_sse42_pcmpistrio128:
10367 case Intrinsic::x86_sse42_pcmpestrio128:
10368 case Intrinsic::x86_sse42_pcmpistris128:
10369 case Intrinsic::x86_sse42_pcmpestris128:
10370 case Intrinsic::x86_sse42_pcmpistriz128:
10371 case Intrinsic::x86_sse42_pcmpestriz128: {
10375 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10376 case Intrinsic::x86_sse42_pcmpistria128:
10377 Opcode = X86ISD::PCMPISTRI;
10378 X86CC = X86::COND_A;
10380 case Intrinsic::x86_sse42_pcmpestria128:
10381 Opcode = X86ISD::PCMPESTRI;
10382 X86CC = X86::COND_A;
10384 case Intrinsic::x86_sse42_pcmpistric128:
10385 Opcode = X86ISD::PCMPISTRI;
10386 X86CC = X86::COND_B;
10388 case Intrinsic::x86_sse42_pcmpestric128:
10389 Opcode = X86ISD::PCMPESTRI;
10390 X86CC = X86::COND_B;
10392 case Intrinsic::x86_sse42_pcmpistrio128:
10393 Opcode = X86ISD::PCMPISTRI;
10394 X86CC = X86::COND_O;
10396 case Intrinsic::x86_sse42_pcmpestrio128:
10397 Opcode = X86ISD::PCMPESTRI;
10398 X86CC = X86::COND_O;
10400 case Intrinsic::x86_sse42_pcmpistris128:
10401 Opcode = X86ISD::PCMPISTRI;
10402 X86CC = X86::COND_S;
10404 case Intrinsic::x86_sse42_pcmpestris128:
10405 Opcode = X86ISD::PCMPESTRI;
10406 X86CC = X86::COND_S;
10408 case Intrinsic::x86_sse42_pcmpistriz128:
10409 Opcode = X86ISD::PCMPISTRI;
10410 X86CC = X86::COND_E;
10412 case Intrinsic::x86_sse42_pcmpestriz128:
10413 Opcode = X86ISD::PCMPESTRI;
10414 X86CC = X86::COND_E;
10417 SmallVector<SDValue, 5> NewOps;
10418 NewOps.append(Op->op_begin()+1, Op->op_end());
10419 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10420 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10421 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10422 DAG.getConstant(X86CC, MVT::i8),
10423 SDValue(PCMP.getNode(), 1));
10424 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10427 case Intrinsic::x86_sse42_pcmpistri128:
10428 case Intrinsic::x86_sse42_pcmpestri128: {
10430 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10431 Opcode = X86ISD::PCMPISTRI;
10433 Opcode = X86ISD::PCMPESTRI;
10435 SmallVector<SDValue, 5> NewOps;
10436 NewOps.append(Op->op_begin()+1, Op->op_end());
10437 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10438 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10440 case Intrinsic::x86_fma_vfmadd_ps:
10441 case Intrinsic::x86_fma_vfmadd_pd:
10442 case Intrinsic::x86_fma_vfmsub_ps:
10443 case Intrinsic::x86_fma_vfmsub_pd:
10444 case Intrinsic::x86_fma_vfnmadd_ps:
10445 case Intrinsic::x86_fma_vfnmadd_pd:
10446 case Intrinsic::x86_fma_vfnmsub_ps:
10447 case Intrinsic::x86_fma_vfnmsub_pd:
10448 case Intrinsic::x86_fma_vfmaddsub_ps:
10449 case Intrinsic::x86_fma_vfmaddsub_pd:
10450 case Intrinsic::x86_fma_vfmsubadd_ps:
10451 case Intrinsic::x86_fma_vfmsubadd_pd:
10452 case Intrinsic::x86_fma_vfmadd_ps_256:
10453 case Intrinsic::x86_fma_vfmadd_pd_256:
10454 case Intrinsic::x86_fma_vfmsub_ps_256:
10455 case Intrinsic::x86_fma_vfmsub_pd_256:
10456 case Intrinsic::x86_fma_vfnmadd_ps_256:
10457 case Intrinsic::x86_fma_vfnmadd_pd_256:
10458 case Intrinsic::x86_fma_vfnmsub_ps_256:
10459 case Intrinsic::x86_fma_vfnmsub_pd_256:
10460 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10461 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10462 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10463 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10466 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10467 case Intrinsic::x86_fma_vfmadd_ps:
10468 case Intrinsic::x86_fma_vfmadd_pd:
10469 case Intrinsic::x86_fma_vfmadd_ps_256:
10470 case Intrinsic::x86_fma_vfmadd_pd_256:
10471 Opc = X86ISD::FMADD;
10473 case Intrinsic::x86_fma_vfmsub_ps:
10474 case Intrinsic::x86_fma_vfmsub_pd:
10475 case Intrinsic::x86_fma_vfmsub_ps_256:
10476 case Intrinsic::x86_fma_vfmsub_pd_256:
10477 Opc = X86ISD::FMSUB;
10479 case Intrinsic::x86_fma_vfnmadd_ps:
10480 case Intrinsic::x86_fma_vfnmadd_pd:
10481 case Intrinsic::x86_fma_vfnmadd_ps_256:
10482 case Intrinsic::x86_fma_vfnmadd_pd_256:
10483 Opc = X86ISD::FNMADD;
10485 case Intrinsic::x86_fma_vfnmsub_ps:
10486 case Intrinsic::x86_fma_vfnmsub_pd:
10487 case Intrinsic::x86_fma_vfnmsub_ps_256:
10488 case Intrinsic::x86_fma_vfnmsub_pd_256:
10489 Opc = X86ISD::FNMSUB;
10491 case Intrinsic::x86_fma_vfmaddsub_ps:
10492 case Intrinsic::x86_fma_vfmaddsub_pd:
10493 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10494 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10495 Opc = X86ISD::FMADDSUB;
10497 case Intrinsic::x86_fma_vfmsubadd_ps:
10498 case Intrinsic::x86_fma_vfmsubadd_pd:
10499 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10500 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10501 Opc = X86ISD::FMSUBADD;
10505 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10506 Op.getOperand(2), Op.getOperand(3));
10511 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10512 DebugLoc dl = Op.getDebugLoc();
10513 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10515 default: return SDValue(); // Don't custom lower most intrinsics.
10517 // RDRAND intrinsics.
10518 case Intrinsic::x86_rdrand_16:
10519 case Intrinsic::x86_rdrand_32:
10520 case Intrinsic::x86_rdrand_64: {
10521 // Emit the node with the right value type.
10522 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10523 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10525 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10526 // return the value from Rand, which is always 0, casted to i32.
10527 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10528 DAG.getConstant(1, Op->getValueType(1)),
10529 DAG.getConstant(X86::COND_B, MVT::i32),
10530 SDValue(Result.getNode(), 1) };
10531 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10532 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10535 // Return { result, isValid, chain }.
10536 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10537 SDValue(Result.getNode(), 2));
10542 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10543 SelectionDAG &DAG) const {
10544 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10545 MFI->setReturnAddressIsTaken(true);
10547 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10548 DebugLoc dl = Op.getDebugLoc();
10549 EVT PtrVT = getPointerTy();
10552 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10554 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10555 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10556 DAG.getNode(ISD::ADD, dl, PtrVT,
10557 FrameAddr, Offset),
10558 MachinePointerInfo(), false, false, false, 0);
10561 // Just load the return address.
10562 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10563 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10564 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10567 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10568 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10569 MFI->setFrameAddressIsTaken(true);
10571 EVT VT = Op.getValueType();
10572 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10573 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10574 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10575 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10577 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10578 MachinePointerInfo(),
10579 false, false, false, 0);
10583 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10584 SelectionDAG &DAG) const {
10585 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10588 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10589 SDValue Chain = Op.getOperand(0);
10590 SDValue Offset = Op.getOperand(1);
10591 SDValue Handler = Op.getOperand(2);
10592 DebugLoc dl = Op.getDebugLoc();
10594 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10595 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10597 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10599 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10600 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10601 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10602 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10604 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10606 return DAG.getNode(X86ISD::EH_RETURN, dl,
10608 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10611 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10612 SelectionDAG &DAG) const {
10613 DebugLoc DL = Op.getDebugLoc();
10614 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10615 DAG.getVTList(MVT::i32, MVT::Other),
10616 Op.getOperand(0), Op.getOperand(1));
10619 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10620 SelectionDAG &DAG) const {
10621 DebugLoc DL = Op.getDebugLoc();
10622 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10623 Op.getOperand(0), Op.getOperand(1));
10626 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10627 return Op.getOperand(0);
10630 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10631 SelectionDAG &DAG) const {
10632 SDValue Root = Op.getOperand(0);
10633 SDValue Trmp = Op.getOperand(1); // trampoline
10634 SDValue FPtr = Op.getOperand(2); // nested function
10635 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10636 DebugLoc dl = Op.getDebugLoc();
10638 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10639 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10641 if (Subtarget->is64Bit()) {
10642 SDValue OutChains[6];
10644 // Large code-model.
10645 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10646 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10648 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10649 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10651 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10653 // Load the pointer to the nested function into R11.
10654 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10655 SDValue Addr = Trmp;
10656 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10657 Addr, MachinePointerInfo(TrmpAddr),
10660 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10661 DAG.getConstant(2, MVT::i64));
10662 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10663 MachinePointerInfo(TrmpAddr, 2),
10666 // Load the 'nest' parameter value into R10.
10667 // R10 is specified in X86CallingConv.td
10668 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10669 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10670 DAG.getConstant(10, MVT::i64));
10671 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10672 Addr, MachinePointerInfo(TrmpAddr, 10),
10675 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10676 DAG.getConstant(12, MVT::i64));
10677 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10678 MachinePointerInfo(TrmpAddr, 12),
10681 // Jump to the nested function.
10682 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10683 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10684 DAG.getConstant(20, MVT::i64));
10685 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10686 Addr, MachinePointerInfo(TrmpAddr, 20),
10689 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10690 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10691 DAG.getConstant(22, MVT::i64));
10692 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10693 MachinePointerInfo(TrmpAddr, 22),
10696 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10698 const Function *Func =
10699 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10700 CallingConv::ID CC = Func->getCallingConv();
10705 llvm_unreachable("Unsupported calling convention");
10706 case CallingConv::C:
10707 case CallingConv::X86_StdCall: {
10708 // Pass 'nest' parameter in ECX.
10709 // Must be kept in sync with X86CallingConv.td
10710 NestReg = X86::ECX;
10712 // Check that ECX wasn't needed by an 'inreg' parameter.
10713 FunctionType *FTy = Func->getFunctionType();
10714 const AttributeSet &Attrs = Func->getAttributes();
10716 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10717 unsigned InRegCount = 0;
10720 for (FunctionType::param_iterator I = FTy->param_begin(),
10721 E = FTy->param_end(); I != E; ++I, ++Idx)
10722 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10723 // FIXME: should only count parameters that are lowered to integers.
10724 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10726 if (InRegCount > 2) {
10727 report_fatal_error("Nest register in use - reduce number of inreg"
10733 case CallingConv::X86_FastCall:
10734 case CallingConv::X86_ThisCall:
10735 case CallingConv::Fast:
10736 // Pass 'nest' parameter in EAX.
10737 // Must be kept in sync with X86CallingConv.td
10738 NestReg = X86::EAX;
10742 SDValue OutChains[4];
10743 SDValue Addr, Disp;
10745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10746 DAG.getConstant(10, MVT::i32));
10747 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10749 // This is storing the opcode for MOV32ri.
10750 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10751 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10752 OutChains[0] = DAG.getStore(Root, dl,
10753 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10754 Trmp, MachinePointerInfo(TrmpAddr),
10757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10758 DAG.getConstant(1, MVT::i32));
10759 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10760 MachinePointerInfo(TrmpAddr, 1),
10763 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10764 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10765 DAG.getConstant(5, MVT::i32));
10766 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10767 MachinePointerInfo(TrmpAddr, 5),
10770 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10771 DAG.getConstant(6, MVT::i32));
10772 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10773 MachinePointerInfo(TrmpAddr, 6),
10776 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10780 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10781 SelectionDAG &DAG) const {
10783 The rounding mode is in bits 11:10 of FPSR, and has the following
10785 00 Round to nearest
10790 FLT_ROUNDS, on the other hand, expects the following:
10797 To perform the conversion, we do:
10798 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10801 MachineFunction &MF = DAG.getMachineFunction();
10802 const TargetMachine &TM = MF.getTarget();
10803 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10804 unsigned StackAlignment = TFI.getStackAlignment();
10805 EVT VT = Op.getValueType();
10806 DebugLoc DL = Op.getDebugLoc();
10808 // Save FP Control Word to stack slot
10809 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10810 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10813 MachineMemOperand *MMO =
10814 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10815 MachineMemOperand::MOStore, 2, 2);
10817 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10818 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10819 DAG.getVTList(MVT::Other),
10820 Ops, 2, MVT::i16, MMO);
10822 // Load FP Control Word from stack slot
10823 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10824 MachinePointerInfo(), false, false, false, 0);
10826 // Transform as necessary
10828 DAG.getNode(ISD::SRL, DL, MVT::i16,
10829 DAG.getNode(ISD::AND, DL, MVT::i16,
10830 CWD, DAG.getConstant(0x800, MVT::i16)),
10831 DAG.getConstant(11, MVT::i8));
10833 DAG.getNode(ISD::SRL, DL, MVT::i16,
10834 DAG.getNode(ISD::AND, DL, MVT::i16,
10835 CWD, DAG.getConstant(0x400, MVT::i16)),
10836 DAG.getConstant(9, MVT::i8));
10839 DAG.getNode(ISD::AND, DL, MVT::i16,
10840 DAG.getNode(ISD::ADD, DL, MVT::i16,
10841 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10842 DAG.getConstant(1, MVT::i16)),
10843 DAG.getConstant(3, MVT::i16));
10846 return DAG.getNode((VT.getSizeInBits() < 16 ?
10847 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10850 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10851 EVT VT = Op.getValueType();
10853 unsigned NumBits = VT.getSizeInBits();
10854 DebugLoc dl = Op.getDebugLoc();
10856 Op = Op.getOperand(0);
10857 if (VT == MVT::i8) {
10858 // Zero extend to i32 since there is not an i8 bsr.
10860 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10863 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10864 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10865 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10867 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10870 DAG.getConstant(NumBits+NumBits-1, OpVT),
10871 DAG.getConstant(X86::COND_E, MVT::i8),
10874 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10876 // Finally xor with NumBits-1.
10877 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10880 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10884 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10885 EVT VT = Op.getValueType();
10887 unsigned NumBits = VT.getSizeInBits();
10888 DebugLoc dl = Op.getDebugLoc();
10890 Op = Op.getOperand(0);
10891 if (VT == MVT::i8) {
10892 // Zero extend to i32 since there is not an i8 bsr.
10894 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10897 // Issue a bsr (scan bits in reverse).
10898 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10899 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10901 // And xor with NumBits-1.
10902 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10905 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10909 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10910 EVT VT = Op.getValueType();
10911 unsigned NumBits = VT.getSizeInBits();
10912 DebugLoc dl = Op.getDebugLoc();
10913 Op = Op.getOperand(0);
10915 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10916 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10917 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10919 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10922 DAG.getConstant(NumBits, VT),
10923 DAG.getConstant(X86::COND_E, MVT::i8),
10926 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10929 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10930 // ones, and then concatenate the result back.
10931 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10932 EVT VT = Op.getValueType();
10934 assert(VT.is256BitVector() && VT.isInteger() &&
10935 "Unsupported value type for operation");
10937 unsigned NumElems = VT.getVectorNumElements();
10938 DebugLoc dl = Op.getDebugLoc();
10940 // Extract the LHS vectors
10941 SDValue LHS = Op.getOperand(0);
10942 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10943 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10945 // Extract the RHS vectors
10946 SDValue RHS = Op.getOperand(1);
10947 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10948 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10950 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10951 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10953 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10954 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10955 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10958 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10959 assert(Op.getValueType().is256BitVector() &&
10960 Op.getValueType().isInteger() &&
10961 "Only handle AVX 256-bit vector integer operation");
10962 return Lower256IntArith(Op, DAG);
10965 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10966 assert(Op.getValueType().is256BitVector() &&
10967 Op.getValueType().isInteger() &&
10968 "Only handle AVX 256-bit vector integer operation");
10969 return Lower256IntArith(Op, DAG);
10972 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10973 SelectionDAG &DAG) {
10974 EVT VT = Op.getValueType();
10976 // Decompose 256-bit ops into smaller 128-bit ops.
10977 if (VT.is256BitVector() && !Subtarget->hasInt256())
10978 return Lower256IntArith(Op, DAG);
10980 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10981 "Only know how to lower V2I64/V4I64 multiply");
10983 DebugLoc dl = Op.getDebugLoc();
10985 // Ahi = psrlqi(a, 32);
10986 // Bhi = psrlqi(b, 32);
10988 // AloBlo = pmuludq(a, b);
10989 // AloBhi = pmuludq(a, Bhi);
10990 // AhiBlo = pmuludq(Ahi, b);
10992 // AloBhi = psllqi(AloBhi, 32);
10993 // AhiBlo = psllqi(AhiBlo, 32);
10994 // return AloBlo + AloBhi + AhiBlo;
10996 SDValue A = Op.getOperand(0);
10997 SDValue B = Op.getOperand(1);
10999 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11001 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11002 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11004 // Bit cast to 32-bit vectors for MULUDQ
11005 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11006 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11007 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11008 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11009 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11011 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11012 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11013 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11015 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11016 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11018 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11019 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11022 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11024 EVT VT = Op.getValueType();
11025 DebugLoc dl = Op.getDebugLoc();
11026 SDValue R = Op.getOperand(0);
11027 SDValue Amt = Op.getOperand(1);
11028 LLVMContext *Context = DAG.getContext();
11030 if (!Subtarget->hasSSE2())
11033 // Optimize shl/srl/sra with constant shift amount.
11034 if (isSplatVector(Amt.getNode())) {
11035 SDValue SclrAmt = Amt->getOperand(0);
11036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11037 uint64_t ShiftAmt = C->getZExtValue();
11039 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11040 (Subtarget->hasInt256() &&
11041 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11042 if (Op.getOpcode() == ISD::SHL)
11043 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11044 DAG.getConstant(ShiftAmt, MVT::i32));
11045 if (Op.getOpcode() == ISD::SRL)
11046 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11047 DAG.getConstant(ShiftAmt, MVT::i32));
11048 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11049 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11050 DAG.getConstant(ShiftAmt, MVT::i32));
11053 if (VT == MVT::v16i8) {
11054 if (Op.getOpcode() == ISD::SHL) {
11055 // Make a large shift.
11056 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11057 DAG.getConstant(ShiftAmt, MVT::i32));
11058 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11059 // Zero out the rightmost bits.
11060 SmallVector<SDValue, 16> V(16,
11061 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11063 return DAG.getNode(ISD::AND, dl, VT, SHL,
11064 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11066 if (Op.getOpcode() == ISD::SRL) {
11067 // Make a large shift.
11068 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11069 DAG.getConstant(ShiftAmt, MVT::i32));
11070 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11071 // Zero out the leftmost bits.
11072 SmallVector<SDValue, 16> V(16,
11073 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11075 return DAG.getNode(ISD::AND, dl, VT, SRL,
11076 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11078 if (Op.getOpcode() == ISD::SRA) {
11079 if (ShiftAmt == 7) {
11080 // R s>> 7 === R s< 0
11081 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11082 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11085 // R s>> a === ((R u>> a) ^ m) - m
11086 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11087 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11089 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11090 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11091 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11094 llvm_unreachable("Unknown shift opcode.");
11097 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11098 if (Op.getOpcode() == ISD::SHL) {
11099 // Make a large shift.
11100 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11101 DAG.getConstant(ShiftAmt, MVT::i32));
11102 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11103 // Zero out the rightmost bits.
11104 SmallVector<SDValue, 32> V(32,
11105 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11107 return DAG.getNode(ISD::AND, dl, VT, SHL,
11108 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11110 if (Op.getOpcode() == ISD::SRL) {
11111 // Make a large shift.
11112 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11113 DAG.getConstant(ShiftAmt, MVT::i32));
11114 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11115 // Zero out the leftmost bits.
11116 SmallVector<SDValue, 32> V(32,
11117 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11119 return DAG.getNode(ISD::AND, dl, VT, SRL,
11120 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11122 if (Op.getOpcode() == ISD::SRA) {
11123 if (ShiftAmt == 7) {
11124 // R s>> 7 === R s< 0
11125 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11126 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11129 // R s>> a === ((R u>> a) ^ m) - m
11130 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11131 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11133 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11134 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11135 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11138 llvm_unreachable("Unknown shift opcode.");
11143 // Lower SHL with variable shift amount.
11144 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11145 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11146 DAG.getConstant(23, MVT::i32));
11148 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11149 Constant *C = ConstantDataVector::get(*Context, CV);
11150 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11151 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11152 MachinePointerInfo::getConstantPool(),
11153 false, false, false, 16);
11155 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11156 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11157 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11158 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11160 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11161 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11164 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11165 DAG.getConstant(5, MVT::i32));
11166 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11168 // Turn 'a' into a mask suitable for VSELECT
11169 SDValue VSelM = DAG.getConstant(0x80, VT);
11170 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11171 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11173 SDValue CM1 = DAG.getConstant(0x0f, VT);
11174 SDValue CM2 = DAG.getConstant(0x3f, VT);
11176 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11177 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11178 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11179 DAG.getConstant(4, MVT::i32), DAG);
11180 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11181 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11184 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11185 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11186 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11188 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11189 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11190 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11191 DAG.getConstant(2, MVT::i32), DAG);
11192 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11193 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11196 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11197 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11198 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11200 // return VSELECT(r, r+r, a);
11201 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11202 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11206 // Decompose 256-bit shifts into smaller 128-bit shifts.
11207 if (VT.is256BitVector()) {
11208 unsigned NumElems = VT.getVectorNumElements();
11209 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11210 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11212 // Extract the two vectors
11213 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11214 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11216 // Recreate the shift amount vectors
11217 SDValue Amt1, Amt2;
11218 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11219 // Constant shift amount
11220 SmallVector<SDValue, 4> Amt1Csts;
11221 SmallVector<SDValue, 4> Amt2Csts;
11222 for (unsigned i = 0; i != NumElems/2; ++i)
11223 Amt1Csts.push_back(Amt->getOperand(i));
11224 for (unsigned i = NumElems/2; i != NumElems; ++i)
11225 Amt2Csts.push_back(Amt->getOperand(i));
11227 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11228 &Amt1Csts[0], NumElems/2);
11229 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11230 &Amt2Csts[0], NumElems/2);
11232 // Variable shift amount
11233 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11234 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11237 // Issue new vector shifts for the smaller types
11238 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11239 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11241 // Concatenate the result back
11242 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11248 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11249 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11250 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11251 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11252 // has only one use.
11253 SDNode *N = Op.getNode();
11254 SDValue LHS = N->getOperand(0);
11255 SDValue RHS = N->getOperand(1);
11256 unsigned BaseOp = 0;
11258 DebugLoc DL = Op.getDebugLoc();
11259 switch (Op.getOpcode()) {
11260 default: llvm_unreachable("Unknown ovf instruction!");
11262 // A subtract of one will be selected as a INC. Note that INC doesn't
11263 // set CF, so we can't do this for UADDO.
11264 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11266 BaseOp = X86ISD::INC;
11267 Cond = X86::COND_O;
11270 BaseOp = X86ISD::ADD;
11271 Cond = X86::COND_O;
11274 BaseOp = X86ISD::ADD;
11275 Cond = X86::COND_B;
11278 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11279 // set CF, so we can't do this for USUBO.
11280 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11282 BaseOp = X86ISD::DEC;
11283 Cond = X86::COND_O;
11286 BaseOp = X86ISD::SUB;
11287 Cond = X86::COND_O;
11290 BaseOp = X86ISD::SUB;
11291 Cond = X86::COND_B;
11294 BaseOp = X86ISD::SMUL;
11295 Cond = X86::COND_O;
11297 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11298 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11300 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11303 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11304 DAG.getConstant(X86::COND_O, MVT::i32),
11305 SDValue(Sum.getNode(), 2));
11307 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11311 // Also sets EFLAGS.
11312 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11313 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11316 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11317 DAG.getConstant(Cond, MVT::i32),
11318 SDValue(Sum.getNode(), 1));
11320 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11323 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11324 SelectionDAG &DAG) const {
11325 DebugLoc dl = Op.getDebugLoc();
11326 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11327 EVT VT = Op.getValueType();
11329 if (!Subtarget->hasSSE2() || !VT.isVector())
11332 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11333 ExtraVT.getScalarType().getSizeInBits();
11334 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11336 switch (VT.getSimpleVT().SimpleTy) {
11337 default: return SDValue();
11340 if (!Subtarget->hasFp256())
11342 if (!Subtarget->hasInt256()) {
11343 // needs to be split
11344 unsigned NumElems = VT.getVectorNumElements();
11346 // Extract the LHS vectors
11347 SDValue LHS = Op.getOperand(0);
11348 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11349 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11351 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11352 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11354 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11355 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11356 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11358 SDValue Extra = DAG.getValueType(ExtraVT);
11360 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11361 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11363 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11368 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11369 Op.getOperand(0), ShAmt, DAG);
11370 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11376 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11377 SelectionDAG &DAG) {
11378 DebugLoc dl = Op.getDebugLoc();
11380 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11381 // There isn't any reason to disable it if the target processor supports it.
11382 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11383 SDValue Chain = Op.getOperand(0);
11384 SDValue Zero = DAG.getConstant(0, MVT::i32);
11386 DAG.getRegister(X86::ESP, MVT::i32), // Base
11387 DAG.getTargetConstant(1, MVT::i8), // Scale
11388 DAG.getRegister(0, MVT::i32), // Index
11389 DAG.getTargetConstant(0, MVT::i32), // Disp
11390 DAG.getRegister(0, MVT::i32), // Segment.
11395 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11396 array_lengthof(Ops));
11397 return SDValue(Res, 0);
11400 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11402 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11404 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11405 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11406 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11407 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11409 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11410 if (!Op1 && !Op2 && !Op3 && Op4)
11411 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11413 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11414 if (Op1 && !Op2 && !Op3 && !Op4)
11415 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11417 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11419 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11422 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11423 SelectionDAG &DAG) {
11424 DebugLoc dl = Op.getDebugLoc();
11425 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11426 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11427 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11428 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11430 // The only fence that needs an instruction is a sequentially-consistent
11431 // cross-thread fence.
11432 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11433 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11434 // no-sse2). There isn't any reason to disable it if the target processor
11436 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11437 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11439 SDValue Chain = Op.getOperand(0);
11440 SDValue Zero = DAG.getConstant(0, MVT::i32);
11442 DAG.getRegister(X86::ESP, MVT::i32), // Base
11443 DAG.getTargetConstant(1, MVT::i8), // Scale
11444 DAG.getRegister(0, MVT::i32), // Index
11445 DAG.getTargetConstant(0, MVT::i32), // Disp
11446 DAG.getRegister(0, MVT::i32), // Segment.
11451 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11452 array_lengthof(Ops));
11453 return SDValue(Res, 0);
11456 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11457 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11461 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11462 SelectionDAG &DAG) {
11463 EVT T = Op.getValueType();
11464 DebugLoc DL = Op.getDebugLoc();
11467 switch(T.getSimpleVT().SimpleTy) {
11468 default: llvm_unreachable("Invalid value type!");
11469 case MVT::i8: Reg = X86::AL; size = 1; break;
11470 case MVT::i16: Reg = X86::AX; size = 2; break;
11471 case MVT::i32: Reg = X86::EAX; size = 4; break;
11473 assert(Subtarget->is64Bit() && "Node not type legal!");
11474 Reg = X86::RAX; size = 8;
11477 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11478 Op.getOperand(2), SDValue());
11479 SDValue Ops[] = { cpIn.getValue(0),
11482 DAG.getTargetConstant(size, MVT::i8),
11483 cpIn.getValue(1) };
11484 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11485 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11486 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11489 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11493 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11494 SelectionDAG &DAG) {
11495 assert(Subtarget->is64Bit() && "Result not type legalized?");
11496 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11497 SDValue TheChain = Op.getOperand(0);
11498 DebugLoc dl = Op.getDebugLoc();
11499 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11500 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11501 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11503 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11504 DAG.getConstant(32, MVT::i8));
11506 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11509 return DAG.getMergeValues(Ops, 2, dl);
11512 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11513 EVT SrcVT = Op.getOperand(0).getValueType();
11514 EVT DstVT = Op.getValueType();
11515 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11516 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11517 assert((DstVT == MVT::i64 ||
11518 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11519 "Unexpected custom BITCAST");
11520 // i64 <=> MMX conversions are Legal.
11521 if (SrcVT==MVT::i64 && DstVT.isVector())
11523 if (DstVT==MVT::i64 && SrcVT.isVector())
11525 // MMX <=> MMX conversions are Legal.
11526 if (SrcVT.isVector() && DstVT.isVector())
11528 // All other conversions need to be expanded.
11532 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11533 SDNode *Node = Op.getNode();
11534 DebugLoc dl = Node->getDebugLoc();
11535 EVT T = Node->getValueType(0);
11536 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11537 DAG.getConstant(0, T), Node->getOperand(2));
11538 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11539 cast<AtomicSDNode>(Node)->getMemoryVT(),
11540 Node->getOperand(0),
11541 Node->getOperand(1), negOp,
11542 cast<AtomicSDNode>(Node)->getSrcValue(),
11543 cast<AtomicSDNode>(Node)->getAlignment(),
11544 cast<AtomicSDNode>(Node)->getOrdering(),
11545 cast<AtomicSDNode>(Node)->getSynchScope());
11548 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11549 SDNode *Node = Op.getNode();
11550 DebugLoc dl = Node->getDebugLoc();
11551 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11553 // Convert seq_cst store -> xchg
11554 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11555 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11556 // (The only way to get a 16-byte store is cmpxchg16b)
11557 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11558 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11559 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11560 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11561 cast<AtomicSDNode>(Node)->getMemoryVT(),
11562 Node->getOperand(0),
11563 Node->getOperand(1), Node->getOperand(2),
11564 cast<AtomicSDNode>(Node)->getMemOperand(),
11565 cast<AtomicSDNode>(Node)->getOrdering(),
11566 cast<AtomicSDNode>(Node)->getSynchScope());
11567 return Swap.getValue(1);
11569 // Other atomic stores have a simple pattern.
11573 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11574 EVT VT = Op.getNode()->getValueType(0);
11576 // Let legalize expand this if it isn't a legal type yet.
11577 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11580 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11583 bool ExtraOp = false;
11584 switch (Op.getOpcode()) {
11585 default: llvm_unreachable("Invalid code");
11586 case ISD::ADDC: Opc = X86ISD::ADD; break;
11587 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11588 case ISD::SUBC: Opc = X86ISD::SUB; break;
11589 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11593 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11595 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11596 Op.getOperand(1), Op.getOperand(2));
11599 /// LowerOperation - Provide custom lowering hooks for some operations.
11601 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11602 switch (Op.getOpcode()) {
11603 default: llvm_unreachable("Should not custom lower this!");
11604 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11605 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11606 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11607 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11608 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11609 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11610 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11611 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11612 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11613 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11614 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11615 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11616 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11617 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11618 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11619 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11620 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11621 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11622 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11623 case ISD::SHL_PARTS:
11624 case ISD::SRA_PARTS:
11625 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11626 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11627 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11628 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11629 case ISD::ZERO_EXTEND: return lowerZERO_EXTEND(Op, DAG);
11630 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11631 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11632 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11633 case ISD::FABS: return LowerFABS(Op, DAG);
11634 case ISD::FNEG: return LowerFNEG(Op, DAG);
11635 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11636 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11637 case ISD::SETCC: return LowerSETCC(Op, DAG);
11638 case ISD::SELECT: return LowerSELECT(Op, DAG);
11639 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11640 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11641 case ISD::VASTART: return LowerVASTART(Op, DAG);
11642 case ISD::VAARG: return LowerVAARG(Op, DAG);
11643 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11644 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11645 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11646 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11647 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11648 case ISD::FRAME_TO_ARGS_OFFSET:
11649 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11650 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11651 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11652 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11653 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11654 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11655 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11656 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11657 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11658 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11659 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11660 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11663 case ISD::SHL: return LowerShift(Op, DAG);
11669 case ISD::UMULO: return LowerXALUO(Op, DAG);
11670 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11671 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11675 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11676 case ISD::ADD: return LowerADD(Op, DAG);
11677 case ISD::SUB: return LowerSUB(Op, DAG);
11681 static void ReplaceATOMIC_LOAD(SDNode *Node,
11682 SmallVectorImpl<SDValue> &Results,
11683 SelectionDAG &DAG) {
11684 DebugLoc dl = Node->getDebugLoc();
11685 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11687 // Convert wide load -> cmpxchg8b/cmpxchg16b
11688 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11689 // (The only way to get a 16-byte load is cmpxchg16b)
11690 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11691 SDValue Zero = DAG.getConstant(0, VT);
11692 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11693 Node->getOperand(0),
11694 Node->getOperand(1), Zero, Zero,
11695 cast<AtomicSDNode>(Node)->getMemOperand(),
11696 cast<AtomicSDNode>(Node)->getOrdering(),
11697 cast<AtomicSDNode>(Node)->getSynchScope());
11698 Results.push_back(Swap.getValue(0));
11699 Results.push_back(Swap.getValue(1));
11703 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11704 SelectionDAG &DAG, unsigned NewOp) {
11705 DebugLoc dl = Node->getDebugLoc();
11706 assert (Node->getValueType(0) == MVT::i64 &&
11707 "Only know how to expand i64 atomics");
11709 SDValue Chain = Node->getOperand(0);
11710 SDValue In1 = Node->getOperand(1);
11711 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11712 Node->getOperand(2), DAG.getIntPtrConstant(0));
11713 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11714 Node->getOperand(2), DAG.getIntPtrConstant(1));
11715 SDValue Ops[] = { Chain, In1, In2L, In2H };
11716 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11718 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11719 cast<MemSDNode>(Node)->getMemOperand());
11720 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11721 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11722 Results.push_back(Result.getValue(2));
11725 /// ReplaceNodeResults - Replace a node with an illegal result type
11726 /// with a new node built out of custom code.
11727 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11728 SmallVectorImpl<SDValue>&Results,
11729 SelectionDAG &DAG) const {
11730 DebugLoc dl = N->getDebugLoc();
11731 switch (N->getOpcode()) {
11733 llvm_unreachable("Do not know how to custom type legalize this operation!");
11734 case ISD::SIGN_EXTEND_INREG:
11739 // We don't want to expand or promote these.
11741 case ISD::FP_TO_SINT:
11742 case ISD::FP_TO_UINT: {
11743 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11745 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11748 std::pair<SDValue,SDValue> Vals =
11749 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11750 SDValue FIST = Vals.first, StackSlot = Vals.second;
11751 if (FIST.getNode() != 0) {
11752 EVT VT = N->getValueType(0);
11753 // Return a load from the stack slot.
11754 if (StackSlot.getNode() != 0)
11755 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11756 MachinePointerInfo(),
11757 false, false, false, 0));
11759 Results.push_back(FIST);
11763 case ISD::UINT_TO_FP: {
11764 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11765 N->getValueType(0) != MVT::v2f32)
11767 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11769 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11771 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11772 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11773 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11774 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11775 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11776 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11779 case ISD::FP_ROUND: {
11780 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11781 Results.push_back(V);
11784 case ISD::READCYCLECOUNTER: {
11785 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11786 SDValue TheChain = N->getOperand(0);
11787 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11788 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11790 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11792 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11793 SDValue Ops[] = { eax, edx };
11794 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11795 Results.push_back(edx.getValue(1));
11798 case ISD::ATOMIC_CMP_SWAP: {
11799 EVT T = N->getValueType(0);
11800 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11801 bool Regs64bit = T == MVT::i128;
11802 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11803 SDValue cpInL, cpInH;
11804 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11805 DAG.getConstant(0, HalfT));
11806 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11807 DAG.getConstant(1, HalfT));
11808 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11809 Regs64bit ? X86::RAX : X86::EAX,
11811 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11812 Regs64bit ? X86::RDX : X86::EDX,
11813 cpInH, cpInL.getValue(1));
11814 SDValue swapInL, swapInH;
11815 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11816 DAG.getConstant(0, HalfT));
11817 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11818 DAG.getConstant(1, HalfT));
11819 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11820 Regs64bit ? X86::RBX : X86::EBX,
11821 swapInL, cpInH.getValue(1));
11822 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11823 Regs64bit ? X86::RCX : X86::ECX,
11824 swapInH, swapInL.getValue(1));
11825 SDValue Ops[] = { swapInH.getValue(0),
11827 swapInH.getValue(1) };
11828 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11829 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11830 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11831 X86ISD::LCMPXCHG8_DAG;
11832 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11834 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11835 Regs64bit ? X86::RAX : X86::EAX,
11836 HalfT, Result.getValue(1));
11837 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11838 Regs64bit ? X86::RDX : X86::EDX,
11839 HalfT, cpOutL.getValue(2));
11840 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11841 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11842 Results.push_back(cpOutH.getValue(1));
11845 case ISD::ATOMIC_LOAD_ADD:
11846 case ISD::ATOMIC_LOAD_AND:
11847 case ISD::ATOMIC_LOAD_NAND:
11848 case ISD::ATOMIC_LOAD_OR:
11849 case ISD::ATOMIC_LOAD_SUB:
11850 case ISD::ATOMIC_LOAD_XOR:
11851 case ISD::ATOMIC_LOAD_MAX:
11852 case ISD::ATOMIC_LOAD_MIN:
11853 case ISD::ATOMIC_LOAD_UMAX:
11854 case ISD::ATOMIC_LOAD_UMIN:
11855 case ISD::ATOMIC_SWAP: {
11857 switch (N->getOpcode()) {
11858 default: llvm_unreachable("Unexpected opcode");
11859 case ISD::ATOMIC_LOAD_ADD:
11860 Opc = X86ISD::ATOMADD64_DAG;
11862 case ISD::ATOMIC_LOAD_AND:
11863 Opc = X86ISD::ATOMAND64_DAG;
11865 case ISD::ATOMIC_LOAD_NAND:
11866 Opc = X86ISD::ATOMNAND64_DAG;
11868 case ISD::ATOMIC_LOAD_OR:
11869 Opc = X86ISD::ATOMOR64_DAG;
11871 case ISD::ATOMIC_LOAD_SUB:
11872 Opc = X86ISD::ATOMSUB64_DAG;
11874 case ISD::ATOMIC_LOAD_XOR:
11875 Opc = X86ISD::ATOMXOR64_DAG;
11877 case ISD::ATOMIC_LOAD_MAX:
11878 Opc = X86ISD::ATOMMAX64_DAG;
11880 case ISD::ATOMIC_LOAD_MIN:
11881 Opc = X86ISD::ATOMMIN64_DAG;
11883 case ISD::ATOMIC_LOAD_UMAX:
11884 Opc = X86ISD::ATOMUMAX64_DAG;
11886 case ISD::ATOMIC_LOAD_UMIN:
11887 Opc = X86ISD::ATOMUMIN64_DAG;
11889 case ISD::ATOMIC_SWAP:
11890 Opc = X86ISD::ATOMSWAP64_DAG;
11893 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11896 case ISD::ATOMIC_LOAD:
11897 ReplaceATOMIC_LOAD(N, Results, DAG);
11901 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11903 default: return NULL;
11904 case X86ISD::BSF: return "X86ISD::BSF";
11905 case X86ISD::BSR: return "X86ISD::BSR";
11906 case X86ISD::SHLD: return "X86ISD::SHLD";
11907 case X86ISD::SHRD: return "X86ISD::SHRD";
11908 case X86ISD::FAND: return "X86ISD::FAND";
11909 case X86ISD::FOR: return "X86ISD::FOR";
11910 case X86ISD::FXOR: return "X86ISD::FXOR";
11911 case X86ISD::FSRL: return "X86ISD::FSRL";
11912 case X86ISD::FILD: return "X86ISD::FILD";
11913 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11914 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11915 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11916 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11917 case X86ISD::FLD: return "X86ISD::FLD";
11918 case X86ISD::FST: return "X86ISD::FST";
11919 case X86ISD::CALL: return "X86ISD::CALL";
11920 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11921 case X86ISD::BT: return "X86ISD::BT";
11922 case X86ISD::CMP: return "X86ISD::CMP";
11923 case X86ISD::COMI: return "X86ISD::COMI";
11924 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11925 case X86ISD::SETCC: return "X86ISD::SETCC";
11926 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11927 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11928 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11929 case X86ISD::CMOV: return "X86ISD::CMOV";
11930 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11931 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11932 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11933 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11934 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11935 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11936 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11937 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11938 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11939 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11940 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11941 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11942 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11943 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11944 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11945 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11946 case X86ISD::BLENDI: return "X86ISD::BLENDI";
11947 case X86ISD::HADD: return "X86ISD::HADD";
11948 case X86ISD::HSUB: return "X86ISD::HSUB";
11949 case X86ISD::FHADD: return "X86ISD::FHADD";
11950 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11951 case X86ISD::FMAX: return "X86ISD::FMAX";
11952 case X86ISD::FMIN: return "X86ISD::FMIN";
11953 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11954 case X86ISD::FMINC: return "X86ISD::FMINC";
11955 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11956 case X86ISD::FRCP: return "X86ISD::FRCP";
11957 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11958 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11959 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11960 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11961 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11962 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11963 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11964 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11965 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11966 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11967 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11968 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11969 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11970 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11971 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11972 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11973 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11974 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11975 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11976 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11977 case X86ISD::VZEXT: return "X86ISD::VZEXT";
11978 case X86ISD::VSEXT: return "X86ISD::VSEXT";
11979 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11980 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11981 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11982 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11983 case X86ISD::VSHL: return "X86ISD::VSHL";
11984 case X86ISD::VSRL: return "X86ISD::VSRL";
11985 case X86ISD::VSRA: return "X86ISD::VSRA";
11986 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11987 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11988 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11989 case X86ISD::CMPP: return "X86ISD::CMPP";
11990 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11991 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11992 case X86ISD::ADD: return "X86ISD::ADD";
11993 case X86ISD::SUB: return "X86ISD::SUB";
11994 case X86ISD::ADC: return "X86ISD::ADC";
11995 case X86ISD::SBB: return "X86ISD::SBB";
11996 case X86ISD::SMUL: return "X86ISD::SMUL";
11997 case X86ISD::UMUL: return "X86ISD::UMUL";
11998 case X86ISD::INC: return "X86ISD::INC";
11999 case X86ISD::DEC: return "X86ISD::DEC";
12000 case X86ISD::OR: return "X86ISD::OR";
12001 case X86ISD::XOR: return "X86ISD::XOR";
12002 case X86ISD::AND: return "X86ISD::AND";
12003 case X86ISD::ANDN: return "X86ISD::ANDN";
12004 case X86ISD::BLSI: return "X86ISD::BLSI";
12005 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12006 case X86ISD::BLSR: return "X86ISD::BLSR";
12007 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12008 case X86ISD::PTEST: return "X86ISD::PTEST";
12009 case X86ISD::TESTP: return "X86ISD::TESTP";
12010 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12011 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12012 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12013 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12014 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12015 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12016 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12017 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12018 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12019 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12020 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12021 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12022 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12023 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12024 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12025 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12026 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12027 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12028 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12029 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12030 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12031 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12032 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12033 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12034 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12035 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12036 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12037 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12038 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12039 case X86ISD::SAHF: return "X86ISD::SAHF";
12040 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12041 case X86ISD::FMADD: return "X86ISD::FMADD";
12042 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12043 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12044 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12045 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12046 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12047 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12048 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12052 // isLegalAddressingMode - Return true if the addressing mode represented
12053 // by AM is legal for this target, for a load/store of the specified type.
12054 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12056 // X86 supports extremely general addressing modes.
12057 CodeModel::Model M = getTargetMachine().getCodeModel();
12058 Reloc::Model R = getTargetMachine().getRelocationModel();
12060 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12061 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12066 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12068 // If a reference to this global requires an extra load, we can't fold it.
12069 if (isGlobalStubReference(GVFlags))
12072 // If BaseGV requires a register for the PIC base, we cannot also have a
12073 // BaseReg specified.
12074 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12077 // If lower 4G is not available, then we must use rip-relative addressing.
12078 if ((M != CodeModel::Small || R != Reloc::Static) &&
12079 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12083 switch (AM.Scale) {
12089 // These scales always work.
12094 // These scales are formed with basereg+scalereg. Only accept if there is
12099 default: // Other stuff never works.
12107 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12108 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12110 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12111 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12112 if (NumBits1 <= NumBits2)
12117 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12118 return Imm == (int32_t)Imm;
12121 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12122 // Can also use sub to handle negated immediates.
12123 return Imm == (int32_t)Imm;
12126 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12127 if (!VT1.isInteger() || !VT2.isInteger())
12129 unsigned NumBits1 = VT1.getSizeInBits();
12130 unsigned NumBits2 = VT2.getSizeInBits();
12131 if (NumBits1 <= NumBits2)
12136 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12137 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12138 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12141 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12142 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12143 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12146 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12147 EVT VT1 = Val.getValueType();
12148 if (isZExtFree(VT1, VT2))
12151 if (Val.getOpcode() != ISD::LOAD)
12154 if (!VT1.isSimple() || !VT1.isInteger() ||
12155 !VT2.isSimple() || !VT2.isInteger())
12158 switch (VT1.getSimpleVT().SimpleTy) {
12163 // X86 has 8, 16, and 32-bit zero-extending loads.
12170 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12171 // i16 instructions are longer (0x66 prefix) and potentially slower.
12172 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12175 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12176 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12177 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12178 /// are assumed to be legal.
12180 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12182 // Very little shuffling can be done for 64-bit vectors right now.
12183 if (VT.getSizeInBits() == 64)
12186 // FIXME: pshufb, blends, shifts.
12187 return (VT.getVectorNumElements() == 2 ||
12188 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12189 isMOVLMask(M, VT) ||
12190 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12191 isPSHUFDMask(M, VT) ||
12192 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12193 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12194 isPALIGNRMask(M, VT, Subtarget) ||
12195 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12196 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12197 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12198 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12202 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12204 unsigned NumElts = VT.getVectorNumElements();
12205 // FIXME: This collection of masks seems suspect.
12208 if (NumElts == 4 && VT.is128BitVector()) {
12209 return (isMOVLMask(Mask, VT) ||
12210 isCommutedMOVLMask(Mask, VT, true) ||
12211 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12212 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12217 //===----------------------------------------------------------------------===//
12218 // X86 Scheduler Hooks
12219 //===----------------------------------------------------------------------===//
12221 /// Utility function to emit xbegin specifying the start of an RTM region.
12222 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12223 const TargetInstrInfo *TII) {
12224 DebugLoc DL = MI->getDebugLoc();
12226 const BasicBlock *BB = MBB->getBasicBlock();
12227 MachineFunction::iterator I = MBB;
12230 // For the v = xbegin(), we generate
12241 MachineBasicBlock *thisMBB = MBB;
12242 MachineFunction *MF = MBB->getParent();
12243 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12244 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12245 MF->insert(I, mainMBB);
12246 MF->insert(I, sinkMBB);
12248 // Transfer the remainder of BB and its successor edges to sinkMBB.
12249 sinkMBB->splice(sinkMBB->begin(), MBB,
12250 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12251 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12255 // # fallthrough to mainMBB
12256 // # abortion to sinkMBB
12257 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12258 thisMBB->addSuccessor(mainMBB);
12259 thisMBB->addSuccessor(sinkMBB);
12263 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12264 mainMBB->addSuccessor(sinkMBB);
12267 // EAX is live into the sinkMBB
12268 sinkMBB->addLiveIn(X86::EAX);
12269 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12270 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12273 MI->eraseFromParent();
12277 // Get CMPXCHG opcode for the specified data type.
12278 static unsigned getCmpXChgOpcode(EVT VT) {
12279 switch (VT.getSimpleVT().SimpleTy) {
12280 case MVT::i8: return X86::LCMPXCHG8;
12281 case MVT::i16: return X86::LCMPXCHG16;
12282 case MVT::i32: return X86::LCMPXCHG32;
12283 case MVT::i64: return X86::LCMPXCHG64;
12287 llvm_unreachable("Invalid operand size!");
12290 // Get LOAD opcode for the specified data type.
12291 static unsigned getLoadOpcode(EVT VT) {
12292 switch (VT.getSimpleVT().SimpleTy) {
12293 case MVT::i8: return X86::MOV8rm;
12294 case MVT::i16: return X86::MOV16rm;
12295 case MVT::i32: return X86::MOV32rm;
12296 case MVT::i64: return X86::MOV64rm;
12300 llvm_unreachable("Invalid operand size!");
12303 // Get opcode of the non-atomic one from the specified atomic instruction.
12304 static unsigned getNonAtomicOpcode(unsigned Opc) {
12306 case X86::ATOMAND8: return X86::AND8rr;
12307 case X86::ATOMAND16: return X86::AND16rr;
12308 case X86::ATOMAND32: return X86::AND32rr;
12309 case X86::ATOMAND64: return X86::AND64rr;
12310 case X86::ATOMOR8: return X86::OR8rr;
12311 case X86::ATOMOR16: return X86::OR16rr;
12312 case X86::ATOMOR32: return X86::OR32rr;
12313 case X86::ATOMOR64: return X86::OR64rr;
12314 case X86::ATOMXOR8: return X86::XOR8rr;
12315 case X86::ATOMXOR16: return X86::XOR16rr;
12316 case X86::ATOMXOR32: return X86::XOR32rr;
12317 case X86::ATOMXOR64: return X86::XOR64rr;
12319 llvm_unreachable("Unhandled atomic-load-op opcode!");
12322 // Get opcode of the non-atomic one from the specified atomic instruction with
12324 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12325 unsigned &ExtraOpc) {
12327 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12328 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12329 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12330 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12331 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12332 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12333 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12334 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12335 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12336 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12337 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12338 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12339 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12340 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12341 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12342 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12343 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12344 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12345 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12346 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12348 llvm_unreachable("Unhandled atomic-load-op opcode!");
12351 // Get opcode of the non-atomic one from the specified atomic instruction for
12352 // 64-bit data type on 32-bit target.
12353 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12355 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12356 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12357 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12358 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12359 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12360 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12361 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12362 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12363 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12364 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12366 llvm_unreachable("Unhandled atomic-load-op opcode!");
12369 // Get opcode of the non-atomic one from the specified atomic instruction for
12370 // 64-bit data type on 32-bit target with extra opcode.
12371 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12373 unsigned &ExtraOpc) {
12375 case X86::ATOMNAND6432:
12376 ExtraOpc = X86::NOT32r;
12377 HiOpc = X86::AND32rr;
12378 return X86::AND32rr;
12380 llvm_unreachable("Unhandled atomic-load-op opcode!");
12383 // Get pseudo CMOV opcode from the specified data type.
12384 static unsigned getPseudoCMOVOpc(EVT VT) {
12385 switch (VT.getSimpleVT().SimpleTy) {
12386 case MVT::i8: return X86::CMOV_GR8;
12387 case MVT::i16: return X86::CMOV_GR16;
12388 case MVT::i32: return X86::CMOV_GR32;
12392 llvm_unreachable("Unknown CMOV opcode!");
12395 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12396 // They will be translated into a spin-loop or compare-exchange loop from
12399 // dst = atomic-fetch-op MI.addr, MI.val
12405 // EAX = LOAD MI.addr
12407 // t1 = OP MI.val, EAX
12408 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12413 MachineBasicBlock *
12414 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12415 MachineBasicBlock *MBB) const {
12416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12417 DebugLoc DL = MI->getDebugLoc();
12419 MachineFunction *MF = MBB->getParent();
12420 MachineRegisterInfo &MRI = MF->getRegInfo();
12422 const BasicBlock *BB = MBB->getBasicBlock();
12423 MachineFunction::iterator I = MBB;
12426 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12427 "Unexpected number of operands");
12429 assert(MI->hasOneMemOperand() &&
12430 "Expected atomic-load-op to have one memoperand");
12432 // Memory Reference
12433 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12434 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12436 unsigned DstReg, SrcReg;
12437 unsigned MemOpndSlot;
12439 unsigned CurOp = 0;
12441 DstReg = MI->getOperand(CurOp++).getReg();
12442 MemOpndSlot = CurOp;
12443 CurOp += X86::AddrNumOperands;
12444 SrcReg = MI->getOperand(CurOp++).getReg();
12446 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12447 MVT::SimpleValueType VT = *RC->vt_begin();
12448 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12450 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12451 unsigned LOADOpc = getLoadOpcode(VT);
12453 // For the atomic load-arith operator, we generate
12456 // EAX = LOAD [MI.addr]
12458 // t1 = OP MI.val, EAX
12459 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12463 MachineBasicBlock *thisMBB = MBB;
12464 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12465 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12466 MF->insert(I, mainMBB);
12467 MF->insert(I, sinkMBB);
12469 MachineInstrBuilder MIB;
12471 // Transfer the remainder of BB and its successor edges to sinkMBB.
12472 sinkMBB->splice(sinkMBB->begin(), MBB,
12473 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12474 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12477 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12478 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12479 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12480 MIB.setMemRefs(MMOBegin, MMOEnd);
12482 thisMBB->addSuccessor(mainMBB);
12485 MachineBasicBlock *origMainMBB = mainMBB;
12486 mainMBB->addLiveIn(AccPhyReg);
12488 // Copy AccPhyReg as it is used more than once.
12489 unsigned AccReg = MRI.createVirtualRegister(RC);
12490 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12491 .addReg(AccPhyReg);
12493 unsigned t1 = MRI.createVirtualRegister(RC);
12494 unsigned Opc = MI->getOpcode();
12497 llvm_unreachable("Unhandled atomic-load-op opcode!");
12498 case X86::ATOMAND8:
12499 case X86::ATOMAND16:
12500 case X86::ATOMAND32:
12501 case X86::ATOMAND64:
12503 case X86::ATOMOR16:
12504 case X86::ATOMOR32:
12505 case X86::ATOMOR64:
12506 case X86::ATOMXOR8:
12507 case X86::ATOMXOR16:
12508 case X86::ATOMXOR32:
12509 case X86::ATOMXOR64: {
12510 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12511 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12515 case X86::ATOMNAND8:
12516 case X86::ATOMNAND16:
12517 case X86::ATOMNAND32:
12518 case X86::ATOMNAND64: {
12519 unsigned t2 = MRI.createVirtualRegister(RC);
12521 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12522 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12524 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12527 case X86::ATOMMAX8:
12528 case X86::ATOMMAX16:
12529 case X86::ATOMMAX32:
12530 case X86::ATOMMAX64:
12531 case X86::ATOMMIN8:
12532 case X86::ATOMMIN16:
12533 case X86::ATOMMIN32:
12534 case X86::ATOMMIN64:
12535 case X86::ATOMUMAX8:
12536 case X86::ATOMUMAX16:
12537 case X86::ATOMUMAX32:
12538 case X86::ATOMUMAX64:
12539 case X86::ATOMUMIN8:
12540 case X86::ATOMUMIN16:
12541 case X86::ATOMUMIN32:
12542 case X86::ATOMUMIN64: {
12544 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12546 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12550 if (Subtarget->hasCMov()) {
12551 if (VT != MVT::i8) {
12553 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12557 // Promote i8 to i32 to use CMOV32
12558 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12559 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12560 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12561 unsigned t2 = MRI.createVirtualRegister(RC32);
12563 unsigned Undef = MRI.createVirtualRegister(RC32);
12564 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12566 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12569 .addImm(X86::sub_8bit);
12570 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12573 .addImm(X86::sub_8bit);
12575 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12579 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12580 .addReg(t2, 0, X86::sub_8bit);
12583 // Use pseudo select and lower them.
12584 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12585 "Invalid atomic-load-op transformation!");
12586 unsigned SelOpc = getPseudoCMOVOpc(VT);
12587 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12588 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12589 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12590 .addReg(SrcReg).addReg(AccReg)
12592 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12598 // Copy AccPhyReg back from virtual register.
12599 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12602 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12603 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12604 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12606 MIB.setMemRefs(MMOBegin, MMOEnd);
12608 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12610 mainMBB->addSuccessor(origMainMBB);
12611 mainMBB->addSuccessor(sinkMBB);
12614 sinkMBB->addLiveIn(AccPhyReg);
12616 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12617 TII->get(TargetOpcode::COPY), DstReg)
12618 .addReg(AccPhyReg);
12620 MI->eraseFromParent();
12624 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12625 // instructions. They will be translated into a spin-loop or compare-exchange
12629 // dst = atomic-fetch-op MI.addr, MI.val
12635 // EAX = LOAD [MI.addr + 0]
12636 // EDX = LOAD [MI.addr + 4]
12638 // EBX = OP MI.val.lo, EAX
12639 // ECX = OP MI.val.hi, EDX
12640 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12645 MachineBasicBlock *
12646 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12647 MachineBasicBlock *MBB) const {
12648 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12649 DebugLoc DL = MI->getDebugLoc();
12651 MachineFunction *MF = MBB->getParent();
12652 MachineRegisterInfo &MRI = MF->getRegInfo();
12654 const BasicBlock *BB = MBB->getBasicBlock();
12655 MachineFunction::iterator I = MBB;
12658 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12659 "Unexpected number of operands");
12661 assert(MI->hasOneMemOperand() &&
12662 "Expected atomic-load-op32 to have one memoperand");
12664 // Memory Reference
12665 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12666 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12668 unsigned DstLoReg, DstHiReg;
12669 unsigned SrcLoReg, SrcHiReg;
12670 unsigned MemOpndSlot;
12672 unsigned CurOp = 0;
12674 DstLoReg = MI->getOperand(CurOp++).getReg();
12675 DstHiReg = MI->getOperand(CurOp++).getReg();
12676 MemOpndSlot = CurOp;
12677 CurOp += X86::AddrNumOperands;
12678 SrcLoReg = MI->getOperand(CurOp++).getReg();
12679 SrcHiReg = MI->getOperand(CurOp++).getReg();
12681 const TargetRegisterClass *RC = &X86::GR32RegClass;
12682 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12684 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12685 unsigned LOADOpc = X86::MOV32rm;
12687 // For the atomic load-arith operator, we generate
12690 // EAX = LOAD [MI.addr + 0]
12691 // EDX = LOAD [MI.addr + 4]
12693 // EBX = OP MI.vallo, EAX
12694 // ECX = OP MI.valhi, EDX
12695 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12699 MachineBasicBlock *thisMBB = MBB;
12700 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12701 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12702 MF->insert(I, mainMBB);
12703 MF->insert(I, sinkMBB);
12705 MachineInstrBuilder MIB;
12707 // Transfer the remainder of BB and its successor edges to sinkMBB.
12708 sinkMBB->splice(sinkMBB->begin(), MBB,
12709 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12710 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12714 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12715 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12716 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12717 MIB.setMemRefs(MMOBegin, MMOEnd);
12719 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12720 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12721 if (i == X86::AddrDisp)
12722 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12724 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12726 MIB.setMemRefs(MMOBegin, MMOEnd);
12728 thisMBB->addSuccessor(mainMBB);
12731 MachineBasicBlock *origMainMBB = mainMBB;
12732 mainMBB->addLiveIn(X86::EAX);
12733 mainMBB->addLiveIn(X86::EDX);
12735 // Copy EDX:EAX as they are used more than once.
12736 unsigned LoReg = MRI.createVirtualRegister(RC);
12737 unsigned HiReg = MRI.createVirtualRegister(RC);
12738 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12739 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12741 unsigned t1L = MRI.createVirtualRegister(RC);
12742 unsigned t1H = MRI.createVirtualRegister(RC);
12744 unsigned Opc = MI->getOpcode();
12747 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12748 case X86::ATOMAND6432:
12749 case X86::ATOMOR6432:
12750 case X86::ATOMXOR6432:
12751 case X86::ATOMADD6432:
12752 case X86::ATOMSUB6432: {
12754 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12755 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
12756 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
12759 case X86::ATOMNAND6432: {
12760 unsigned HiOpc, NOTOpc;
12761 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12762 unsigned t2L = MRI.createVirtualRegister(RC);
12763 unsigned t2H = MRI.createVirtualRegister(RC);
12764 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12765 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12766 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12767 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12770 case X86::ATOMMAX6432:
12771 case X86::ATOMMIN6432:
12772 case X86::ATOMUMAX6432:
12773 case X86::ATOMUMIN6432: {
12775 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12776 unsigned cL = MRI.createVirtualRegister(RC8);
12777 unsigned cH = MRI.createVirtualRegister(RC8);
12778 unsigned cL32 = MRI.createVirtualRegister(RC);
12779 unsigned cH32 = MRI.createVirtualRegister(RC);
12780 unsigned cc = MRI.createVirtualRegister(RC);
12781 // cl := cmp src_lo, lo
12782 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12783 .addReg(SrcLoReg).addReg(LoReg);
12784 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12785 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12786 // ch := cmp src_hi, hi
12787 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12788 .addReg(SrcHiReg).addReg(HiReg);
12789 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12790 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12791 // cc := if (src_hi == hi) ? cl : ch;
12792 if (Subtarget->hasCMov()) {
12793 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12794 .addReg(cH32).addReg(cL32);
12796 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12797 .addReg(cH32).addReg(cL32)
12798 .addImm(X86::COND_E);
12799 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12801 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12802 if (Subtarget->hasCMov()) {
12803 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12804 .addReg(SrcLoReg).addReg(LoReg);
12805 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12806 .addReg(SrcHiReg).addReg(HiReg);
12808 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12809 .addReg(SrcLoReg).addReg(LoReg)
12810 .addImm(X86::COND_NE);
12811 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12812 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12813 .addReg(SrcHiReg).addReg(HiReg)
12814 .addImm(X86::COND_NE);
12815 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12819 case X86::ATOMSWAP6432: {
12821 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12822 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12823 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12828 // Copy EDX:EAX back from HiReg:LoReg
12829 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12830 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12831 // Copy ECX:EBX from t1H:t1L
12832 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12833 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12835 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12836 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12837 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12838 MIB.setMemRefs(MMOBegin, MMOEnd);
12840 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12842 mainMBB->addSuccessor(origMainMBB);
12843 mainMBB->addSuccessor(sinkMBB);
12846 sinkMBB->addLiveIn(X86::EAX);
12847 sinkMBB->addLiveIn(X86::EDX);
12849 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12850 TII->get(TargetOpcode::COPY), DstLoReg)
12852 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12853 TII->get(TargetOpcode::COPY), DstHiReg)
12856 MI->eraseFromParent();
12860 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12861 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12862 // in the .td file.
12863 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
12864 const TargetInstrInfo *TII) {
12866 switch (MI->getOpcode()) {
12867 default: llvm_unreachable("illegal opcode!");
12868 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
12869 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
12870 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
12871 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
12872 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
12873 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
12874 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
12875 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
12878 DebugLoc dl = MI->getDebugLoc();
12879 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12881 unsigned NumArgs = MI->getNumOperands();
12882 for (unsigned i = 1; i < NumArgs; ++i) {
12883 MachineOperand &Op = MI->getOperand(i);
12884 if (!(Op.isReg() && Op.isImplicit()))
12885 MIB.addOperand(Op);
12887 if (MI->hasOneMemOperand())
12888 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12890 BuildMI(*BB, MI, dl,
12891 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12892 .addReg(X86::XMM0);
12894 MI->eraseFromParent();
12898 // FIXME: Custom handling because TableGen doesn't support multiple implicit
12899 // defs in an instruction pattern
12900 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
12901 const TargetInstrInfo *TII) {
12903 switch (MI->getOpcode()) {
12904 default: llvm_unreachable("illegal opcode!");
12905 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
12906 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
12907 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
12908 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
12909 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
12910 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
12911 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
12912 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
12915 DebugLoc dl = MI->getDebugLoc();
12916 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12918 unsigned NumArgs = MI->getNumOperands(); // remove the results
12919 for (unsigned i = 1; i < NumArgs; ++i) {
12920 MachineOperand &Op = MI->getOperand(i);
12921 if (!(Op.isReg() && Op.isImplicit()))
12922 MIB.addOperand(Op);
12924 if (MI->hasOneMemOperand())
12925 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
12927 BuildMI(*BB, MI, dl,
12928 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12931 MI->eraseFromParent();
12935 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
12936 const TargetInstrInfo *TII,
12937 const X86Subtarget* Subtarget) {
12938 DebugLoc dl = MI->getDebugLoc();
12940 // Address into RAX/EAX, other two args into ECX, EDX.
12941 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12942 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12943 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12944 for (int i = 0; i < X86::AddrNumOperands; ++i)
12945 MIB.addOperand(MI->getOperand(i));
12947 unsigned ValOps = X86::AddrNumOperands;
12948 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12949 .addReg(MI->getOperand(ValOps).getReg());
12950 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12951 .addReg(MI->getOperand(ValOps+1).getReg());
12953 // The instruction doesn't actually take any operands though.
12954 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12956 MI->eraseFromParent(); // The pseudo is gone now.
12960 MachineBasicBlock *
12961 X86TargetLowering::EmitVAARG64WithCustomInserter(
12963 MachineBasicBlock *MBB) const {
12964 // Emit va_arg instruction on X86-64.
12966 // Operands to this pseudo-instruction:
12967 // 0 ) Output : destination address (reg)
12968 // 1-5) Input : va_list address (addr, i64mem)
12969 // 6 ) ArgSize : Size (in bytes) of vararg type
12970 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12971 // 8 ) Align : Alignment of type
12972 // 9 ) EFLAGS (implicit-def)
12974 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12975 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12977 unsigned DestReg = MI->getOperand(0).getReg();
12978 MachineOperand &Base = MI->getOperand(1);
12979 MachineOperand &Scale = MI->getOperand(2);
12980 MachineOperand &Index = MI->getOperand(3);
12981 MachineOperand &Disp = MI->getOperand(4);
12982 MachineOperand &Segment = MI->getOperand(5);
12983 unsigned ArgSize = MI->getOperand(6).getImm();
12984 unsigned ArgMode = MI->getOperand(7).getImm();
12985 unsigned Align = MI->getOperand(8).getImm();
12987 // Memory Reference
12988 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12989 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12990 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12992 // Machine Information
12993 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12994 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12995 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12996 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12997 DebugLoc DL = MI->getDebugLoc();
12999 // struct va_list {
13002 // i64 overflow_area (address)
13003 // i64 reg_save_area (address)
13005 // sizeof(va_list) = 24
13006 // alignment(va_list) = 8
13008 unsigned TotalNumIntRegs = 6;
13009 unsigned TotalNumXMMRegs = 8;
13010 bool UseGPOffset = (ArgMode == 1);
13011 bool UseFPOffset = (ArgMode == 2);
13012 unsigned MaxOffset = TotalNumIntRegs * 8 +
13013 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13015 /* Align ArgSize to a multiple of 8 */
13016 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13017 bool NeedsAlign = (Align > 8);
13019 MachineBasicBlock *thisMBB = MBB;
13020 MachineBasicBlock *overflowMBB;
13021 MachineBasicBlock *offsetMBB;
13022 MachineBasicBlock *endMBB;
13024 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13025 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13026 unsigned OffsetReg = 0;
13028 if (!UseGPOffset && !UseFPOffset) {
13029 // If we only pull from the overflow region, we don't create a branch.
13030 // We don't need to alter control flow.
13031 OffsetDestReg = 0; // unused
13032 OverflowDestReg = DestReg;
13035 overflowMBB = thisMBB;
13038 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13039 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13040 // If not, pull from overflow_area. (branch to overflowMBB)
13045 // offsetMBB overflowMBB
13050 // Registers for the PHI in endMBB
13051 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13052 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13054 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13055 MachineFunction *MF = MBB->getParent();
13056 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13057 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13058 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13060 MachineFunction::iterator MBBIter = MBB;
13063 // Insert the new basic blocks
13064 MF->insert(MBBIter, offsetMBB);
13065 MF->insert(MBBIter, overflowMBB);
13066 MF->insert(MBBIter, endMBB);
13068 // Transfer the remainder of MBB and its successor edges to endMBB.
13069 endMBB->splice(endMBB->begin(), thisMBB,
13070 llvm::next(MachineBasicBlock::iterator(MI)),
13072 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13074 // Make offsetMBB and overflowMBB successors of thisMBB
13075 thisMBB->addSuccessor(offsetMBB);
13076 thisMBB->addSuccessor(overflowMBB);
13078 // endMBB is a successor of both offsetMBB and overflowMBB
13079 offsetMBB->addSuccessor(endMBB);
13080 overflowMBB->addSuccessor(endMBB);
13082 // Load the offset value into a register
13083 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13084 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13088 .addDisp(Disp, UseFPOffset ? 4 : 0)
13089 .addOperand(Segment)
13090 .setMemRefs(MMOBegin, MMOEnd);
13092 // Check if there is enough room left to pull this argument.
13093 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13095 .addImm(MaxOffset + 8 - ArgSizeA8);
13097 // Branch to "overflowMBB" if offset >= max
13098 // Fall through to "offsetMBB" otherwise
13099 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13100 .addMBB(overflowMBB);
13103 // In offsetMBB, emit code to use the reg_save_area.
13105 assert(OffsetReg != 0);
13107 // Read the reg_save_area address.
13108 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13109 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13114 .addOperand(Segment)
13115 .setMemRefs(MMOBegin, MMOEnd);
13117 // Zero-extend the offset
13118 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13119 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13122 .addImm(X86::sub_32bit);
13124 // Add the offset to the reg_save_area to get the final address.
13125 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13126 .addReg(OffsetReg64)
13127 .addReg(RegSaveReg);
13129 // Compute the offset for the next argument
13130 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13131 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13133 .addImm(UseFPOffset ? 16 : 8);
13135 // Store it back into the va_list.
13136 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13140 .addDisp(Disp, UseFPOffset ? 4 : 0)
13141 .addOperand(Segment)
13142 .addReg(NextOffsetReg)
13143 .setMemRefs(MMOBegin, MMOEnd);
13146 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13151 // Emit code to use overflow area
13154 // Load the overflow_area address into a register.
13155 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13156 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13161 .addOperand(Segment)
13162 .setMemRefs(MMOBegin, MMOEnd);
13164 // If we need to align it, do so. Otherwise, just copy the address
13165 // to OverflowDestReg.
13167 // Align the overflow address
13168 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13169 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13171 // aligned_addr = (addr + (align-1)) & ~(align-1)
13172 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13173 .addReg(OverflowAddrReg)
13176 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13178 .addImm(~(uint64_t)(Align-1));
13180 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13181 .addReg(OverflowAddrReg);
13184 // Compute the next overflow address after this argument.
13185 // (the overflow address should be kept 8-byte aligned)
13186 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13187 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13188 .addReg(OverflowDestReg)
13189 .addImm(ArgSizeA8);
13191 // Store the new overflow address.
13192 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13197 .addOperand(Segment)
13198 .addReg(NextAddrReg)
13199 .setMemRefs(MMOBegin, MMOEnd);
13201 // If we branched, emit the PHI to the front of endMBB.
13203 BuildMI(*endMBB, endMBB->begin(), DL,
13204 TII->get(X86::PHI), DestReg)
13205 .addReg(OffsetDestReg).addMBB(offsetMBB)
13206 .addReg(OverflowDestReg).addMBB(overflowMBB);
13209 // Erase the pseudo instruction
13210 MI->eraseFromParent();
13215 MachineBasicBlock *
13216 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13218 MachineBasicBlock *MBB) const {
13219 // Emit code to save XMM registers to the stack. The ABI says that the
13220 // number of registers to save is given in %al, so it's theoretically
13221 // possible to do an indirect jump trick to avoid saving all of them,
13222 // however this code takes a simpler approach and just executes all
13223 // of the stores if %al is non-zero. It's less code, and it's probably
13224 // easier on the hardware branch predictor, and stores aren't all that
13225 // expensive anyway.
13227 // Create the new basic blocks. One block contains all the XMM stores,
13228 // and one block is the final destination regardless of whether any
13229 // stores were performed.
13230 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13231 MachineFunction *F = MBB->getParent();
13232 MachineFunction::iterator MBBIter = MBB;
13234 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13235 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13236 F->insert(MBBIter, XMMSaveMBB);
13237 F->insert(MBBIter, EndMBB);
13239 // Transfer the remainder of MBB and its successor edges to EndMBB.
13240 EndMBB->splice(EndMBB->begin(), MBB,
13241 llvm::next(MachineBasicBlock::iterator(MI)),
13243 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13245 // The original block will now fall through to the XMM save block.
13246 MBB->addSuccessor(XMMSaveMBB);
13247 // The XMMSaveMBB will fall through to the end block.
13248 XMMSaveMBB->addSuccessor(EndMBB);
13250 // Now add the instructions.
13251 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13252 DebugLoc DL = MI->getDebugLoc();
13254 unsigned CountReg = MI->getOperand(0).getReg();
13255 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13256 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13258 if (!Subtarget->isTargetWin64()) {
13259 // If %al is 0, branch around the XMM save block.
13260 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13261 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13262 MBB->addSuccessor(EndMBB);
13265 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13266 // In the XMM save block, save all the XMM argument registers.
13267 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13268 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13269 MachineMemOperand *MMO =
13270 F->getMachineMemOperand(
13271 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13272 MachineMemOperand::MOStore,
13273 /*Size=*/16, /*Align=*/16);
13274 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13275 .addFrameIndex(RegSaveFrameIndex)
13276 .addImm(/*Scale=*/1)
13277 .addReg(/*IndexReg=*/0)
13278 .addImm(/*Disp=*/Offset)
13279 .addReg(/*Segment=*/0)
13280 .addReg(MI->getOperand(i).getReg())
13281 .addMemOperand(MMO);
13284 MI->eraseFromParent(); // The pseudo instruction is gone now.
13289 // The EFLAGS operand of SelectItr might be missing a kill marker
13290 // because there were multiple uses of EFLAGS, and ISel didn't know
13291 // which to mark. Figure out whether SelectItr should have had a
13292 // kill marker, and set it if it should. Returns the correct kill
13294 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13295 MachineBasicBlock* BB,
13296 const TargetRegisterInfo* TRI) {
13297 // Scan forward through BB for a use/def of EFLAGS.
13298 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13299 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13300 const MachineInstr& mi = *miI;
13301 if (mi.readsRegister(X86::EFLAGS))
13303 if (mi.definesRegister(X86::EFLAGS))
13304 break; // Should have kill-flag - update below.
13307 // If we hit the end of the block, check whether EFLAGS is live into a
13309 if (miI == BB->end()) {
13310 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13311 sEnd = BB->succ_end();
13312 sItr != sEnd; ++sItr) {
13313 MachineBasicBlock* succ = *sItr;
13314 if (succ->isLiveIn(X86::EFLAGS))
13319 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13320 // out. SelectMI should have a kill flag on EFLAGS.
13321 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13325 MachineBasicBlock *
13326 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13327 MachineBasicBlock *BB) const {
13328 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13329 DebugLoc DL = MI->getDebugLoc();
13331 // To "insert" a SELECT_CC instruction, we actually have to insert the
13332 // diamond control-flow pattern. The incoming instruction knows the
13333 // destination vreg to set, the condition code register to branch on, the
13334 // true/false values to select between, and a branch opcode to use.
13335 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13336 MachineFunction::iterator It = BB;
13342 // cmpTY ccX, r1, r2
13344 // fallthrough --> copy0MBB
13345 MachineBasicBlock *thisMBB = BB;
13346 MachineFunction *F = BB->getParent();
13347 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13348 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13349 F->insert(It, copy0MBB);
13350 F->insert(It, sinkMBB);
13352 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13353 // live into the sink and copy blocks.
13354 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13355 if (!MI->killsRegister(X86::EFLAGS) &&
13356 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13357 copy0MBB->addLiveIn(X86::EFLAGS);
13358 sinkMBB->addLiveIn(X86::EFLAGS);
13361 // Transfer the remainder of BB and its successor edges to sinkMBB.
13362 sinkMBB->splice(sinkMBB->begin(), BB,
13363 llvm::next(MachineBasicBlock::iterator(MI)),
13365 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13367 // Add the true and fallthrough blocks as its successors.
13368 BB->addSuccessor(copy0MBB);
13369 BB->addSuccessor(sinkMBB);
13371 // Create the conditional branch instruction.
13373 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13374 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13377 // %FalseValue = ...
13378 // # fallthrough to sinkMBB
13379 copy0MBB->addSuccessor(sinkMBB);
13382 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13384 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13385 TII->get(X86::PHI), MI->getOperand(0).getReg())
13386 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13387 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13389 MI->eraseFromParent(); // The pseudo instruction is gone now.
13393 MachineBasicBlock *
13394 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13395 bool Is64Bit) const {
13396 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13397 DebugLoc DL = MI->getDebugLoc();
13398 MachineFunction *MF = BB->getParent();
13399 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13401 assert(getTargetMachine().Options.EnableSegmentedStacks);
13403 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13404 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13407 // ... [Till the alloca]
13408 // If stacklet is not large enough, jump to mallocMBB
13411 // Allocate by subtracting from RSP
13412 // Jump to continueMBB
13415 // Allocate by call to runtime
13419 // [rest of original BB]
13422 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13423 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13424 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13426 MachineRegisterInfo &MRI = MF->getRegInfo();
13427 const TargetRegisterClass *AddrRegClass =
13428 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13430 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13431 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13432 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13433 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13434 sizeVReg = MI->getOperand(1).getReg(),
13435 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13437 MachineFunction::iterator MBBIter = BB;
13440 MF->insert(MBBIter, bumpMBB);
13441 MF->insert(MBBIter, mallocMBB);
13442 MF->insert(MBBIter, continueMBB);
13444 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13445 (MachineBasicBlock::iterator(MI)), BB->end());
13446 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13448 // Add code to the main basic block to check if the stack limit has been hit,
13449 // and if so, jump to mallocMBB otherwise to bumpMBB.
13450 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13451 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13452 .addReg(tmpSPVReg).addReg(sizeVReg);
13453 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13454 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13455 .addReg(SPLimitVReg);
13456 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13458 // bumpMBB simply decreases the stack pointer, since we know the current
13459 // stacklet has enough space.
13460 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13461 .addReg(SPLimitVReg);
13462 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13463 .addReg(SPLimitVReg);
13464 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13466 // Calls into a routine in libgcc to allocate more space from the heap.
13467 const uint32_t *RegMask =
13468 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13470 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13472 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13473 .addExternalSymbol("__morestack_allocate_stack_space")
13474 .addRegMask(RegMask)
13475 .addReg(X86::RDI, RegState::Implicit)
13476 .addReg(X86::RAX, RegState::ImplicitDefine);
13478 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13480 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13481 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13482 .addExternalSymbol("__morestack_allocate_stack_space")
13483 .addRegMask(RegMask)
13484 .addReg(X86::EAX, RegState::ImplicitDefine);
13488 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13491 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13492 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13493 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13495 // Set up the CFG correctly.
13496 BB->addSuccessor(bumpMBB);
13497 BB->addSuccessor(mallocMBB);
13498 mallocMBB->addSuccessor(continueMBB);
13499 bumpMBB->addSuccessor(continueMBB);
13501 // Take care of the PHI nodes.
13502 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13503 MI->getOperand(0).getReg())
13504 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13505 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13507 // Delete the original pseudo instruction.
13508 MI->eraseFromParent();
13511 return continueMBB;
13514 MachineBasicBlock *
13515 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13516 MachineBasicBlock *BB) const {
13517 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13518 DebugLoc DL = MI->getDebugLoc();
13520 assert(!Subtarget->isTargetEnvMacho());
13522 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13523 // non-trivial part is impdef of ESP.
13525 if (Subtarget->isTargetWin64()) {
13526 if (Subtarget->isTargetCygMing()) {
13527 // ___chkstk(Mingw64):
13528 // Clobbers R10, R11, RAX and EFLAGS.
13530 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13531 .addExternalSymbol("___chkstk")
13532 .addReg(X86::RAX, RegState::Implicit)
13533 .addReg(X86::RSP, RegState::Implicit)
13534 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13535 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13536 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13538 // __chkstk(MSVCRT): does not update stack pointer.
13539 // Clobbers R10, R11 and EFLAGS.
13540 // FIXME: RAX(allocated size) might be reused and not killed.
13541 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13542 .addExternalSymbol("__chkstk")
13543 .addReg(X86::RAX, RegState::Implicit)
13544 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13545 // RAX has the offset to subtracted from RSP.
13546 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13551 const char *StackProbeSymbol =
13552 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13554 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13555 .addExternalSymbol(StackProbeSymbol)
13556 .addReg(X86::EAX, RegState::Implicit)
13557 .addReg(X86::ESP, RegState::Implicit)
13558 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13559 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13560 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13563 MI->eraseFromParent(); // The pseudo instruction is gone now.
13567 MachineBasicBlock *
13568 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13569 MachineBasicBlock *BB) const {
13570 // This is pretty easy. We're taking the value that we received from
13571 // our load from the relocation, sticking it in either RDI (x86-64)
13572 // or EAX and doing an indirect call. The return value will then
13573 // be in the normal return register.
13574 const X86InstrInfo *TII
13575 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13576 DebugLoc DL = MI->getDebugLoc();
13577 MachineFunction *F = BB->getParent();
13579 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13580 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13582 // Get a register mask for the lowered call.
13583 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13584 // proper register mask.
13585 const uint32_t *RegMask =
13586 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13587 if (Subtarget->is64Bit()) {
13588 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13589 TII->get(X86::MOV64rm), X86::RDI)
13591 .addImm(0).addReg(0)
13592 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13593 MI->getOperand(3).getTargetFlags())
13595 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13596 addDirectMem(MIB, X86::RDI);
13597 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13598 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13599 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13600 TII->get(X86::MOV32rm), X86::EAX)
13602 .addImm(0).addReg(0)
13603 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13604 MI->getOperand(3).getTargetFlags())
13606 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13607 addDirectMem(MIB, X86::EAX);
13608 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13610 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13611 TII->get(X86::MOV32rm), X86::EAX)
13612 .addReg(TII->getGlobalBaseReg(F))
13613 .addImm(0).addReg(0)
13614 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13615 MI->getOperand(3).getTargetFlags())
13617 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13618 addDirectMem(MIB, X86::EAX);
13619 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13622 MI->eraseFromParent(); // The pseudo instruction is gone now.
13626 MachineBasicBlock *
13627 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13628 MachineBasicBlock *MBB) const {
13629 DebugLoc DL = MI->getDebugLoc();
13630 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13632 MachineFunction *MF = MBB->getParent();
13633 MachineRegisterInfo &MRI = MF->getRegInfo();
13635 const BasicBlock *BB = MBB->getBasicBlock();
13636 MachineFunction::iterator I = MBB;
13639 // Memory Reference
13640 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13641 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13644 unsigned MemOpndSlot = 0;
13646 unsigned CurOp = 0;
13648 DstReg = MI->getOperand(CurOp++).getReg();
13649 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13650 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13651 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13652 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13654 MemOpndSlot = CurOp;
13656 MVT PVT = getPointerTy();
13657 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13658 "Invalid Pointer Size!");
13660 // For v = setjmp(buf), we generate
13663 // buf[LabelOffset] = restoreMBB
13664 // SjLjSetup restoreMBB
13670 // v = phi(main, restore)
13675 MachineBasicBlock *thisMBB = MBB;
13676 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13677 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13678 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13679 MF->insert(I, mainMBB);
13680 MF->insert(I, sinkMBB);
13681 MF->push_back(restoreMBB);
13683 MachineInstrBuilder MIB;
13685 // Transfer the remainder of BB and its successor edges to sinkMBB.
13686 sinkMBB->splice(sinkMBB->begin(), MBB,
13687 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13688 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13691 unsigned PtrStoreOpc = 0;
13692 unsigned LabelReg = 0;
13693 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13694 Reloc::Model RM = getTargetMachine().getRelocationModel();
13695 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13696 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13698 // Prepare IP either in reg or imm.
13699 if (!UseImmLabel) {
13700 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13701 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13702 LabelReg = MRI.createVirtualRegister(PtrRC);
13703 if (Subtarget->is64Bit()) {
13704 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13708 .addMBB(restoreMBB)
13711 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13712 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13713 .addReg(XII->getGlobalBaseReg(MF))
13716 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13720 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13722 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13723 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13724 if (i == X86::AddrDisp)
13725 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13727 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13730 MIB.addReg(LabelReg);
13732 MIB.addMBB(restoreMBB);
13733 MIB.setMemRefs(MMOBegin, MMOEnd);
13735 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13736 .addMBB(restoreMBB);
13737 MIB.addRegMask(RegInfo->getNoPreservedMask());
13738 thisMBB->addSuccessor(mainMBB);
13739 thisMBB->addSuccessor(restoreMBB);
13743 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13744 mainMBB->addSuccessor(sinkMBB);
13747 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13748 TII->get(X86::PHI), DstReg)
13749 .addReg(mainDstReg).addMBB(mainMBB)
13750 .addReg(restoreDstReg).addMBB(restoreMBB);
13753 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13754 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13755 restoreMBB->addSuccessor(sinkMBB);
13757 MI->eraseFromParent();
13761 MachineBasicBlock *
13762 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13763 MachineBasicBlock *MBB) const {
13764 DebugLoc DL = MI->getDebugLoc();
13765 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13767 MachineFunction *MF = MBB->getParent();
13768 MachineRegisterInfo &MRI = MF->getRegInfo();
13770 // Memory Reference
13771 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13772 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13774 MVT PVT = getPointerTy();
13775 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13776 "Invalid Pointer Size!");
13778 const TargetRegisterClass *RC =
13779 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13780 unsigned Tmp = MRI.createVirtualRegister(RC);
13781 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13782 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13783 unsigned SP = RegInfo->getStackRegister();
13785 MachineInstrBuilder MIB;
13787 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13788 const int64_t SPOffset = 2 * PVT.getStoreSize();
13790 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13791 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13794 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13795 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13796 MIB.addOperand(MI->getOperand(i));
13797 MIB.setMemRefs(MMOBegin, MMOEnd);
13799 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13800 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13801 if (i == X86::AddrDisp)
13802 MIB.addDisp(MI->getOperand(i), LabelOffset);
13804 MIB.addOperand(MI->getOperand(i));
13806 MIB.setMemRefs(MMOBegin, MMOEnd);
13808 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13809 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13810 if (i == X86::AddrDisp)
13811 MIB.addDisp(MI->getOperand(i), SPOffset);
13813 MIB.addOperand(MI->getOperand(i));
13815 MIB.setMemRefs(MMOBegin, MMOEnd);
13817 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13819 MI->eraseFromParent();
13823 MachineBasicBlock *
13824 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13825 MachineBasicBlock *BB) const {
13826 switch (MI->getOpcode()) {
13827 default: llvm_unreachable("Unexpected instr type to insert");
13828 case X86::TAILJMPd64:
13829 case X86::TAILJMPr64:
13830 case X86::TAILJMPm64:
13831 llvm_unreachable("TAILJMP64 would not be touched here.");
13832 case X86::TCRETURNdi64:
13833 case X86::TCRETURNri64:
13834 case X86::TCRETURNmi64:
13836 case X86::WIN_ALLOCA:
13837 return EmitLoweredWinAlloca(MI, BB);
13838 case X86::SEG_ALLOCA_32:
13839 return EmitLoweredSegAlloca(MI, BB, false);
13840 case X86::SEG_ALLOCA_64:
13841 return EmitLoweredSegAlloca(MI, BB, true);
13842 case X86::TLSCall_32:
13843 case X86::TLSCall_64:
13844 return EmitLoweredTLSCall(MI, BB);
13845 case X86::CMOV_GR8:
13846 case X86::CMOV_FR32:
13847 case X86::CMOV_FR64:
13848 case X86::CMOV_V4F32:
13849 case X86::CMOV_V2F64:
13850 case X86::CMOV_V2I64:
13851 case X86::CMOV_V8F32:
13852 case X86::CMOV_V4F64:
13853 case X86::CMOV_V4I64:
13854 case X86::CMOV_GR16:
13855 case X86::CMOV_GR32:
13856 case X86::CMOV_RFP32:
13857 case X86::CMOV_RFP64:
13858 case X86::CMOV_RFP80:
13859 return EmitLoweredSelect(MI, BB);
13861 case X86::FP32_TO_INT16_IN_MEM:
13862 case X86::FP32_TO_INT32_IN_MEM:
13863 case X86::FP32_TO_INT64_IN_MEM:
13864 case X86::FP64_TO_INT16_IN_MEM:
13865 case X86::FP64_TO_INT32_IN_MEM:
13866 case X86::FP64_TO_INT64_IN_MEM:
13867 case X86::FP80_TO_INT16_IN_MEM:
13868 case X86::FP80_TO_INT32_IN_MEM:
13869 case X86::FP80_TO_INT64_IN_MEM: {
13870 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13871 DebugLoc DL = MI->getDebugLoc();
13873 // Change the floating point control register to use "round towards zero"
13874 // mode when truncating to an integer value.
13875 MachineFunction *F = BB->getParent();
13876 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13877 addFrameReference(BuildMI(*BB, MI, DL,
13878 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13880 // Load the old value of the high byte of the control word...
13882 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13883 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13886 // Set the high part to be round to zero...
13887 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13890 // Reload the modified control word now...
13891 addFrameReference(BuildMI(*BB, MI, DL,
13892 TII->get(X86::FLDCW16m)), CWFrameIdx);
13894 // Restore the memory image of control word to original value
13895 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13898 // Get the X86 opcode to use.
13900 switch (MI->getOpcode()) {
13901 default: llvm_unreachable("illegal opcode!");
13902 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13903 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13904 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13905 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13906 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13907 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13908 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13909 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13910 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13914 MachineOperand &Op = MI->getOperand(0);
13916 AM.BaseType = X86AddressMode::RegBase;
13917 AM.Base.Reg = Op.getReg();
13919 AM.BaseType = X86AddressMode::FrameIndexBase;
13920 AM.Base.FrameIndex = Op.getIndex();
13922 Op = MI->getOperand(1);
13924 AM.Scale = Op.getImm();
13925 Op = MI->getOperand(2);
13927 AM.IndexReg = Op.getImm();
13928 Op = MI->getOperand(3);
13929 if (Op.isGlobal()) {
13930 AM.GV = Op.getGlobal();
13932 AM.Disp = Op.getImm();
13934 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13935 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13937 // Reload the original control word now.
13938 addFrameReference(BuildMI(*BB, MI, DL,
13939 TII->get(X86::FLDCW16m)), CWFrameIdx);
13941 MI->eraseFromParent(); // The pseudo instruction is gone now.
13944 // String/text processing lowering.
13945 case X86::PCMPISTRM128REG:
13946 case X86::VPCMPISTRM128REG:
13947 case X86::PCMPISTRM128MEM:
13948 case X86::VPCMPISTRM128MEM:
13949 case X86::PCMPESTRM128REG:
13950 case X86::VPCMPESTRM128REG:
13951 case X86::PCMPESTRM128MEM:
13952 case X86::VPCMPESTRM128MEM:
13953 assert(Subtarget->hasSSE42() &&
13954 "Target must have SSE4.2 or AVX features enabled");
13955 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
13957 // String/text processing lowering.
13958 case X86::PCMPISTRIREG:
13959 case X86::VPCMPISTRIREG:
13960 case X86::PCMPISTRIMEM:
13961 case X86::VPCMPISTRIMEM:
13962 case X86::PCMPESTRIREG:
13963 case X86::VPCMPESTRIREG:
13964 case X86::PCMPESTRIMEM:
13965 case X86::VPCMPESTRIMEM:
13966 assert(Subtarget->hasSSE42() &&
13967 "Target must have SSE4.2 or AVX features enabled");
13968 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
13970 // Thread synchronization.
13972 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
13976 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
13978 // Atomic Lowering.
13979 case X86::ATOMAND8:
13980 case X86::ATOMAND16:
13981 case X86::ATOMAND32:
13982 case X86::ATOMAND64:
13985 case X86::ATOMOR16:
13986 case X86::ATOMOR32:
13987 case X86::ATOMOR64:
13989 case X86::ATOMXOR16:
13990 case X86::ATOMXOR8:
13991 case X86::ATOMXOR32:
13992 case X86::ATOMXOR64:
13994 case X86::ATOMNAND8:
13995 case X86::ATOMNAND16:
13996 case X86::ATOMNAND32:
13997 case X86::ATOMNAND64:
13999 case X86::ATOMMAX8:
14000 case X86::ATOMMAX16:
14001 case X86::ATOMMAX32:
14002 case X86::ATOMMAX64:
14004 case X86::ATOMMIN8:
14005 case X86::ATOMMIN16:
14006 case X86::ATOMMIN32:
14007 case X86::ATOMMIN64:
14009 case X86::ATOMUMAX8:
14010 case X86::ATOMUMAX16:
14011 case X86::ATOMUMAX32:
14012 case X86::ATOMUMAX64:
14014 case X86::ATOMUMIN8:
14015 case X86::ATOMUMIN16:
14016 case X86::ATOMUMIN32:
14017 case X86::ATOMUMIN64:
14018 return EmitAtomicLoadArith(MI, BB);
14020 // This group does 64-bit operations on a 32-bit host.
14021 case X86::ATOMAND6432:
14022 case X86::ATOMOR6432:
14023 case X86::ATOMXOR6432:
14024 case X86::ATOMNAND6432:
14025 case X86::ATOMADD6432:
14026 case X86::ATOMSUB6432:
14027 case X86::ATOMMAX6432:
14028 case X86::ATOMMIN6432:
14029 case X86::ATOMUMAX6432:
14030 case X86::ATOMUMIN6432:
14031 case X86::ATOMSWAP6432:
14032 return EmitAtomicLoadArith6432(MI, BB);
14034 case X86::VASTART_SAVE_XMM_REGS:
14035 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14037 case X86::VAARG_64:
14038 return EmitVAARG64WithCustomInserter(MI, BB);
14040 case X86::EH_SjLj_SetJmp32:
14041 case X86::EH_SjLj_SetJmp64:
14042 return emitEHSjLjSetJmp(MI, BB);
14044 case X86::EH_SjLj_LongJmp32:
14045 case X86::EH_SjLj_LongJmp64:
14046 return emitEHSjLjLongJmp(MI, BB);
14050 //===----------------------------------------------------------------------===//
14051 // X86 Optimization Hooks
14052 //===----------------------------------------------------------------------===//
14054 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14057 const SelectionDAG &DAG,
14058 unsigned Depth) const {
14059 unsigned BitWidth = KnownZero.getBitWidth();
14060 unsigned Opc = Op.getOpcode();
14061 assert((Opc >= ISD::BUILTIN_OP_END ||
14062 Opc == ISD::INTRINSIC_WO_CHAIN ||
14063 Opc == ISD::INTRINSIC_W_CHAIN ||
14064 Opc == ISD::INTRINSIC_VOID) &&
14065 "Should use MaskedValueIsZero if you don't know whether Op"
14066 " is a target node!");
14068 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14082 // These nodes' second result is a boolean.
14083 if (Op.getResNo() == 0)
14086 case X86ISD::SETCC:
14087 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14089 case ISD::INTRINSIC_WO_CHAIN: {
14090 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14091 unsigned NumLoBits = 0;
14094 case Intrinsic::x86_sse_movmsk_ps:
14095 case Intrinsic::x86_avx_movmsk_ps_256:
14096 case Intrinsic::x86_sse2_movmsk_pd:
14097 case Intrinsic::x86_avx_movmsk_pd_256:
14098 case Intrinsic::x86_mmx_pmovmskb:
14099 case Intrinsic::x86_sse2_pmovmskb_128:
14100 case Intrinsic::x86_avx2_pmovmskb: {
14101 // High bits of movmskp{s|d}, pmovmskb are known zero.
14103 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14104 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14105 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14106 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14107 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14108 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14109 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14110 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14112 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14121 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14122 unsigned Depth) const {
14123 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14124 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14125 return Op.getValueType().getScalarType().getSizeInBits();
14131 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14132 /// node is a GlobalAddress + offset.
14133 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14134 const GlobalValue* &GA,
14135 int64_t &Offset) const {
14136 if (N->getOpcode() == X86ISD::Wrapper) {
14137 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14138 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14139 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14143 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14146 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14147 /// same as extracting the high 128-bit part of 256-bit vector and then
14148 /// inserting the result into the low part of a new 256-bit vector
14149 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14150 EVT VT = SVOp->getValueType(0);
14151 unsigned NumElems = VT.getVectorNumElements();
14153 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14154 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14155 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14156 SVOp->getMaskElt(j) >= 0)
14162 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14163 /// same as extracting the low 128-bit part of 256-bit vector and then
14164 /// inserting the result into the high part of a new 256-bit vector
14165 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14166 EVT VT = SVOp->getValueType(0);
14167 unsigned NumElems = VT.getVectorNumElements();
14169 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14170 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14171 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14172 SVOp->getMaskElt(j) >= 0)
14178 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14179 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14180 TargetLowering::DAGCombinerInfo &DCI,
14181 const X86Subtarget* Subtarget) {
14182 DebugLoc dl = N->getDebugLoc();
14183 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14184 SDValue V1 = SVOp->getOperand(0);
14185 SDValue V2 = SVOp->getOperand(1);
14186 EVT VT = SVOp->getValueType(0);
14187 unsigned NumElems = VT.getVectorNumElements();
14189 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14190 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14194 // V UNDEF BUILD_VECTOR UNDEF
14196 // CONCAT_VECTOR CONCAT_VECTOR
14199 // RESULT: V + zero extended
14201 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14202 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14203 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14206 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14209 // To match the shuffle mask, the first half of the mask should
14210 // be exactly the first vector, and all the rest a splat with the
14211 // first element of the second one.
14212 for (unsigned i = 0; i != NumElems/2; ++i)
14213 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14214 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14217 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14218 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14219 if (Ld->hasNUsesOfValue(1, 0)) {
14220 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14221 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14223 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14225 Ld->getPointerInfo(),
14226 Ld->getAlignment(),
14227 false/*isVolatile*/, true/*ReadMem*/,
14228 false/*WriteMem*/);
14230 // Make sure the newly-created LOAD is in the same position as Ld in
14231 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14232 // and update uses of Ld's output chain to use the TokenFactor.
14233 if (Ld->hasAnyUseOfValue(1)) {
14234 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14235 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14236 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14237 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14238 SDValue(ResNode.getNode(), 1));
14241 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14245 // Emit a zeroed vector and insert the desired subvector on its
14247 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14248 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14249 return DCI.CombineTo(N, InsV);
14252 //===--------------------------------------------------------------------===//
14253 // Combine some shuffles into subvector extracts and inserts:
14256 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14257 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14258 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14259 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14260 return DCI.CombineTo(N, InsV);
14263 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14264 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14265 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14266 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14267 return DCI.CombineTo(N, InsV);
14273 /// PerformShuffleCombine - Performs several different shuffle combines.
14274 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14275 TargetLowering::DAGCombinerInfo &DCI,
14276 const X86Subtarget *Subtarget) {
14277 DebugLoc dl = N->getDebugLoc();
14278 EVT VT = N->getValueType(0);
14280 // Don't create instructions with illegal types after legalize types has run.
14281 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14282 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14285 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14286 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14287 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14288 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14290 // Only handle 128 wide vector from here on.
14291 if (!VT.is128BitVector())
14294 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14295 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14296 // consecutive, non-overlapping, and in the right order.
14297 SmallVector<SDValue, 16> Elts;
14298 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14299 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14301 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14305 /// PerformTruncateCombine - Converts truncate operation to
14306 /// a sequence of vector shuffle operations.
14307 /// It is possible when we truncate 256-bit vector to 128-bit vector
14308 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14309 TargetLowering::DAGCombinerInfo &DCI,
14310 const X86Subtarget *Subtarget) {
14311 if (!DCI.isBeforeLegalizeOps())
14314 if (!Subtarget->hasFp256())
14317 EVT VT = N->getValueType(0);
14318 SDValue Op = N->getOperand(0);
14319 EVT OpVT = Op.getValueType();
14320 DebugLoc dl = N->getDebugLoc();
14322 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14324 if (Subtarget->hasInt256()) {
14325 // AVX2: v4i64 -> v4i32
14328 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14330 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14331 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14334 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14335 DAG.getIntPtrConstant(0));
14338 // AVX: v4i64 -> v4i32
14339 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14340 DAG.getIntPtrConstant(0));
14342 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14343 DAG.getIntPtrConstant(2));
14345 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14346 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14349 static const int ShufMask1[] = {0, 2, 0, 0};
14351 SDValue Undef = DAG.getUNDEF(VT);
14352 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14353 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14356 static const int ShufMask2[] = {0, 1, 4, 5};
14358 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14361 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14363 if (Subtarget->hasInt256()) {
14364 // AVX2: v8i32 -> v8i16
14366 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14369 SmallVector<SDValue,32> pshufbMask;
14370 for (unsigned i = 0; i < 2; ++i) {
14371 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14372 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14373 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14374 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14375 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14376 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14377 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14378 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14379 for (unsigned j = 0; j < 8; ++j)
14380 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14382 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14383 &pshufbMask[0], 32);
14384 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14386 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14388 static const int ShufMask[] = {0, 2, -1, -1};
14389 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14392 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14393 DAG.getIntPtrConstant(0));
14395 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14398 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14399 DAG.getIntPtrConstant(0));
14401 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14402 DAG.getIntPtrConstant(4));
14404 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14405 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14408 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14409 -1, -1, -1, -1, -1, -1, -1, -1};
14411 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14412 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14413 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14415 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14416 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14419 static const int ShufMask2[] = {0, 1, 4, 5};
14421 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14422 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14428 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14429 /// specific shuffle of a load can be folded into a single element load.
14430 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14431 /// shuffles have been customed lowered so we need to handle those here.
14432 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14433 TargetLowering::DAGCombinerInfo &DCI) {
14434 if (DCI.isBeforeLegalizeOps())
14437 SDValue InVec = N->getOperand(0);
14438 SDValue EltNo = N->getOperand(1);
14440 if (!isa<ConstantSDNode>(EltNo))
14443 EVT VT = InVec.getValueType();
14445 bool HasShuffleIntoBitcast = false;
14446 if (InVec.getOpcode() == ISD::BITCAST) {
14447 // Don't duplicate a load with other uses.
14448 if (!InVec.hasOneUse())
14450 EVT BCVT = InVec.getOperand(0).getValueType();
14451 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14453 InVec = InVec.getOperand(0);
14454 HasShuffleIntoBitcast = true;
14457 if (!isTargetShuffle(InVec.getOpcode()))
14460 // Don't duplicate a load with other uses.
14461 if (!InVec.hasOneUse())
14464 SmallVector<int, 16> ShuffleMask;
14466 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14470 // Select the input vector, guarding against out of range extract vector.
14471 unsigned NumElems = VT.getVectorNumElements();
14472 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14473 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14474 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14475 : InVec.getOperand(1);
14477 // If inputs to shuffle are the same for both ops, then allow 2 uses
14478 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14480 if (LdNode.getOpcode() == ISD::BITCAST) {
14481 // Don't duplicate a load with other uses.
14482 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14485 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14486 LdNode = LdNode.getOperand(0);
14489 if (!ISD::isNormalLoad(LdNode.getNode()))
14492 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14494 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14497 if (HasShuffleIntoBitcast) {
14498 // If there's a bitcast before the shuffle, check if the load type and
14499 // alignment is valid.
14500 unsigned Align = LN0->getAlignment();
14501 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14502 unsigned NewAlign = TLI.getDataLayout()->
14503 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14505 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14509 // All checks match so transform back to vector_shuffle so that DAG combiner
14510 // can finish the job
14511 DebugLoc dl = N->getDebugLoc();
14513 // Create shuffle node taking into account the case that its a unary shuffle
14514 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14515 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14516 InVec.getOperand(0), Shuffle,
14518 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14519 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14523 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14524 /// generation and convert it from being a bunch of shuffles and extracts
14525 /// to a simple store and scalar loads to extract the elements.
14526 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14527 TargetLowering::DAGCombinerInfo &DCI) {
14528 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14529 if (NewOp.getNode())
14532 SDValue InputVector = N->getOperand(0);
14533 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14534 // from mmx to v2i32 has a single usage.
14535 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14536 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14537 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14538 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14539 N->getValueType(0),
14540 InputVector.getNode()->getOperand(0));
14542 // Only operate on vectors of 4 elements, where the alternative shuffling
14543 // gets to be more expensive.
14544 if (InputVector.getValueType() != MVT::v4i32)
14547 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14548 // single use which is a sign-extend or zero-extend, and all elements are
14550 SmallVector<SDNode *, 4> Uses;
14551 unsigned ExtractedElements = 0;
14552 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14553 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14554 if (UI.getUse().getResNo() != InputVector.getResNo())
14557 SDNode *Extract = *UI;
14558 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14561 if (Extract->getValueType(0) != MVT::i32)
14563 if (!Extract->hasOneUse())
14565 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14566 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14568 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14571 // Record which element was extracted.
14572 ExtractedElements |=
14573 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14575 Uses.push_back(Extract);
14578 // If not all the elements were used, this may not be worthwhile.
14579 if (ExtractedElements != 15)
14582 // Ok, we've now decided to do the transformation.
14583 DebugLoc dl = InputVector.getDebugLoc();
14585 // Store the value to a temporary stack slot.
14586 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14587 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14588 MachinePointerInfo(), false, false, 0);
14590 // Replace each use (extract) with a load of the appropriate element.
14591 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14592 UE = Uses.end(); UI != UE; ++UI) {
14593 SDNode *Extract = *UI;
14595 // cOMpute the element's address.
14596 SDValue Idx = Extract->getOperand(1);
14598 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14599 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14600 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14601 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14603 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14604 StackPtr, OffsetVal);
14606 // Load the scalar.
14607 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14608 ScalarAddr, MachinePointerInfo(),
14609 false, false, false, 0);
14611 // Replace the exact with the load.
14612 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14615 // The replacement was made in place; don't return anything.
14619 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14621 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14622 TargetLowering::DAGCombinerInfo &DCI,
14623 const X86Subtarget *Subtarget) {
14624 DebugLoc DL = N->getDebugLoc();
14625 SDValue Cond = N->getOperand(0);
14626 // Get the LHS/RHS of the select.
14627 SDValue LHS = N->getOperand(1);
14628 SDValue RHS = N->getOperand(2);
14629 EVT VT = LHS.getValueType();
14631 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14632 // instructions match the semantics of the common C idiom x<y?x:y but not
14633 // x<=y?x:y, because of how they handle negative zero (which can be
14634 // ignored in unsafe-math mode).
14635 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14636 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14637 (Subtarget->hasSSE2() ||
14638 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14639 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14641 unsigned Opcode = 0;
14642 // Check for x CC y ? x : y.
14643 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14644 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14648 // Converting this to a min would handle NaNs incorrectly, and swapping
14649 // the operands would cause it to handle comparisons between positive
14650 // and negative zero incorrectly.
14651 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14652 if (!DAG.getTarget().Options.UnsafeFPMath &&
14653 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14655 std::swap(LHS, RHS);
14657 Opcode = X86ISD::FMIN;
14660 // Converting this to a min would handle comparisons between positive
14661 // and negative zero incorrectly.
14662 if (!DAG.getTarget().Options.UnsafeFPMath &&
14663 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14665 Opcode = X86ISD::FMIN;
14668 // Converting this to a min would handle both negative zeros and NaNs
14669 // incorrectly, but we can swap the operands to fix both.
14670 std::swap(LHS, RHS);
14674 Opcode = X86ISD::FMIN;
14678 // Converting this to a max would handle comparisons between positive
14679 // and negative zero incorrectly.
14680 if (!DAG.getTarget().Options.UnsafeFPMath &&
14681 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14683 Opcode = X86ISD::FMAX;
14686 // Converting this to a max would handle NaNs incorrectly, and swapping
14687 // the operands would cause it to handle comparisons between positive
14688 // and negative zero incorrectly.
14689 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14690 if (!DAG.getTarget().Options.UnsafeFPMath &&
14691 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14693 std::swap(LHS, RHS);
14695 Opcode = X86ISD::FMAX;
14698 // Converting this to a max would handle both negative zeros and NaNs
14699 // incorrectly, but we can swap the operands to fix both.
14700 std::swap(LHS, RHS);
14704 Opcode = X86ISD::FMAX;
14707 // Check for x CC y ? y : x -- a min/max with reversed arms.
14708 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14709 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14713 // Converting this to a min would handle comparisons between positive
14714 // and negative zero incorrectly, and swapping the operands would
14715 // cause it to handle NaNs incorrectly.
14716 if (!DAG.getTarget().Options.UnsafeFPMath &&
14717 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14718 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14720 std::swap(LHS, RHS);
14722 Opcode = X86ISD::FMIN;
14725 // Converting this to a min would handle NaNs incorrectly.
14726 if (!DAG.getTarget().Options.UnsafeFPMath &&
14727 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14729 Opcode = X86ISD::FMIN;
14732 // Converting this to a min would handle both negative zeros and NaNs
14733 // incorrectly, but we can swap the operands to fix both.
14734 std::swap(LHS, RHS);
14738 Opcode = X86ISD::FMIN;
14742 // Converting this to a max would handle NaNs incorrectly.
14743 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14745 Opcode = X86ISD::FMAX;
14748 // Converting this to a max would handle comparisons between positive
14749 // and negative zero incorrectly, and swapping the operands would
14750 // cause it to handle NaNs incorrectly.
14751 if (!DAG.getTarget().Options.UnsafeFPMath &&
14752 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14753 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14755 std::swap(LHS, RHS);
14757 Opcode = X86ISD::FMAX;
14760 // Converting this to a max would handle both negative zeros and NaNs
14761 // incorrectly, but we can swap the operands to fix both.
14762 std::swap(LHS, RHS);
14766 Opcode = X86ISD::FMAX;
14772 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14775 // If this is a select between two integer constants, try to do some
14777 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14778 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14779 // Don't do this for crazy integer types.
14780 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14781 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14782 // so that TrueC (the true value) is larger than FalseC.
14783 bool NeedsCondInvert = false;
14785 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14786 // Efficiently invertible.
14787 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14788 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14789 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14790 NeedsCondInvert = true;
14791 std::swap(TrueC, FalseC);
14794 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14795 if (FalseC->getAPIntValue() == 0 &&
14796 TrueC->getAPIntValue().isPowerOf2()) {
14797 if (NeedsCondInvert) // Invert the condition if needed.
14798 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14799 DAG.getConstant(1, Cond.getValueType()));
14801 // Zero extend the condition if needed.
14802 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14804 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14805 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14806 DAG.getConstant(ShAmt, MVT::i8));
14809 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14810 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14811 if (NeedsCondInvert) // Invert the condition if needed.
14812 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14813 DAG.getConstant(1, Cond.getValueType()));
14815 // Zero extend the condition if needed.
14816 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14817 FalseC->getValueType(0), Cond);
14818 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14819 SDValue(FalseC, 0));
14822 // Optimize cases that will turn into an LEA instruction. This requires
14823 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14824 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14825 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14826 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14828 bool isFastMultiplier = false;
14830 switch ((unsigned char)Diff) {
14832 case 1: // result = add base, cond
14833 case 2: // result = lea base( , cond*2)
14834 case 3: // result = lea base(cond, cond*2)
14835 case 4: // result = lea base( , cond*4)
14836 case 5: // result = lea base(cond, cond*4)
14837 case 8: // result = lea base( , cond*8)
14838 case 9: // result = lea base(cond, cond*8)
14839 isFastMultiplier = true;
14844 if (isFastMultiplier) {
14845 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14846 if (NeedsCondInvert) // Invert the condition if needed.
14847 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14848 DAG.getConstant(1, Cond.getValueType()));
14850 // Zero extend the condition if needed.
14851 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14853 // Scale the condition by the difference.
14855 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14856 DAG.getConstant(Diff, Cond.getValueType()));
14858 // Add the base if non-zero.
14859 if (FalseC->getAPIntValue() != 0)
14860 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14861 SDValue(FalseC, 0));
14868 // Canonicalize max and min:
14869 // (x > y) ? x : y -> (x >= y) ? x : y
14870 // (x < y) ? x : y -> (x <= y) ? x : y
14871 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14872 // the need for an extra compare
14873 // against zero. e.g.
14874 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14876 // testl %edi, %edi
14878 // cmovgl %edi, %eax
14882 // cmovsl %eax, %edi
14883 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14884 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14885 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14886 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14891 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14892 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14893 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14894 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14899 // If we know that this node is legal then we know that it is going to be
14900 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14901 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14902 // to simplify previous instructions.
14903 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14904 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14905 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14906 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14908 // Don't optimize vector selects that map to mask-registers.
14912 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14913 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14915 APInt KnownZero, KnownOne;
14916 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14917 DCI.isBeforeLegalizeOps());
14918 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14919 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14920 DCI.CommitTargetLoweringOpt(TLO);
14926 // Check whether a boolean test is testing a boolean value generated by
14927 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14930 // Simplify the following patterns:
14931 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14932 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14933 // to (Op EFLAGS Cond)
14935 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14936 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14937 // to (Op EFLAGS !Cond)
14939 // where Op could be BRCOND or CMOV.
14941 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14942 // Quit if not CMP and SUB with its value result used.
14943 if (Cmp.getOpcode() != X86ISD::CMP &&
14944 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14947 // Quit if not used as a boolean value.
14948 if (CC != X86::COND_E && CC != X86::COND_NE)
14951 // Check CMP operands. One of them should be 0 or 1 and the other should be
14952 // an SetCC or extended from it.
14953 SDValue Op1 = Cmp.getOperand(0);
14954 SDValue Op2 = Cmp.getOperand(1);
14957 const ConstantSDNode* C = 0;
14958 bool needOppositeCond = (CC == X86::COND_E);
14960 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14962 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14964 else // Quit if all operands are not constants.
14967 if (C->getZExtValue() == 1)
14968 needOppositeCond = !needOppositeCond;
14969 else if (C->getZExtValue() != 0)
14970 // Quit if the constant is neither 0 or 1.
14973 // Skip 'zext' node.
14974 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14975 SetCC = SetCC.getOperand(0);
14977 switch (SetCC.getOpcode()) {
14978 case X86ISD::SETCC:
14979 // Set the condition code or opposite one if necessary.
14980 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14981 if (needOppositeCond)
14982 CC = X86::GetOppositeBranchCondition(CC);
14983 return SetCC.getOperand(1);
14984 case X86ISD::CMOV: {
14985 // Check whether false/true value has canonical one, i.e. 0 or 1.
14986 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14987 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14988 // Quit if true value is not a constant.
14991 // Quit if false value is not a constant.
14993 // A special case for rdrand, where 0 is set if false cond is found.
14994 SDValue Op = SetCC.getOperand(0);
14995 if (Op.getOpcode() != X86ISD::RDRAND)
14998 // Quit if false value is not the constant 0 or 1.
14999 bool FValIsFalse = true;
15000 if (FVal && FVal->getZExtValue() != 0) {
15001 if (FVal->getZExtValue() != 1)
15003 // If FVal is 1, opposite cond is needed.
15004 needOppositeCond = !needOppositeCond;
15005 FValIsFalse = false;
15007 // Quit if TVal is not the constant opposite of FVal.
15008 if (FValIsFalse && TVal->getZExtValue() != 1)
15010 if (!FValIsFalse && TVal->getZExtValue() != 0)
15012 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15013 if (needOppositeCond)
15014 CC = X86::GetOppositeBranchCondition(CC);
15015 return SetCC.getOperand(3);
15022 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15023 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15024 TargetLowering::DAGCombinerInfo &DCI,
15025 const X86Subtarget *Subtarget) {
15026 DebugLoc DL = N->getDebugLoc();
15028 // If the flag operand isn't dead, don't touch this CMOV.
15029 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15032 SDValue FalseOp = N->getOperand(0);
15033 SDValue TrueOp = N->getOperand(1);
15034 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15035 SDValue Cond = N->getOperand(3);
15037 if (CC == X86::COND_E || CC == X86::COND_NE) {
15038 switch (Cond.getOpcode()) {
15042 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15043 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15044 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15050 Flags = checkBoolTestSetCCCombine(Cond, CC);
15051 if (Flags.getNode() &&
15052 // Extra check as FCMOV only supports a subset of X86 cond.
15053 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15054 SDValue Ops[] = { FalseOp, TrueOp,
15055 DAG.getConstant(CC, MVT::i8), Flags };
15056 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15057 Ops, array_lengthof(Ops));
15060 // If this is a select between two integer constants, try to do some
15061 // optimizations. Note that the operands are ordered the opposite of SELECT
15063 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15064 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15065 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15066 // larger than FalseC (the false value).
15067 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15068 CC = X86::GetOppositeBranchCondition(CC);
15069 std::swap(TrueC, FalseC);
15070 std::swap(TrueOp, FalseOp);
15073 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15074 // This is efficient for any integer data type (including i8/i16) and
15076 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15077 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15078 DAG.getConstant(CC, MVT::i8), Cond);
15080 // Zero extend the condition if needed.
15081 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15083 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15084 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15085 DAG.getConstant(ShAmt, MVT::i8));
15086 if (N->getNumValues() == 2) // Dead flag value?
15087 return DCI.CombineTo(N, Cond, SDValue());
15091 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15092 // for any integer data type, including i8/i16.
15093 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15094 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15095 DAG.getConstant(CC, MVT::i8), Cond);
15097 // Zero extend the condition if needed.
15098 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15099 FalseC->getValueType(0), Cond);
15100 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15101 SDValue(FalseC, 0));
15103 if (N->getNumValues() == 2) // Dead flag value?
15104 return DCI.CombineTo(N, Cond, SDValue());
15108 // Optimize cases that will turn into an LEA instruction. This requires
15109 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15110 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15111 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15112 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15114 bool isFastMultiplier = false;
15116 switch ((unsigned char)Diff) {
15118 case 1: // result = add base, cond
15119 case 2: // result = lea base( , cond*2)
15120 case 3: // result = lea base(cond, cond*2)
15121 case 4: // result = lea base( , cond*4)
15122 case 5: // result = lea base(cond, cond*4)
15123 case 8: // result = lea base( , cond*8)
15124 case 9: // result = lea base(cond, cond*8)
15125 isFastMultiplier = true;
15130 if (isFastMultiplier) {
15131 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15132 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15133 DAG.getConstant(CC, MVT::i8), Cond);
15134 // Zero extend the condition if needed.
15135 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15137 // Scale the condition by the difference.
15139 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15140 DAG.getConstant(Diff, Cond.getValueType()));
15142 // Add the base if non-zero.
15143 if (FalseC->getAPIntValue() != 0)
15144 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15145 SDValue(FalseC, 0));
15146 if (N->getNumValues() == 2) // Dead flag value?
15147 return DCI.CombineTo(N, Cond, SDValue());
15154 // Handle these cases:
15155 // (select (x != c), e, c) -> select (x != c), e, x),
15156 // (select (x == c), c, e) -> select (x == c), x, e)
15157 // where the c is an integer constant, and the "select" is the combination
15158 // of CMOV and CMP.
15160 // The rationale for this change is that the conditional-move from a constant
15161 // needs two instructions, however, conditional-move from a register needs
15162 // only one instruction.
15164 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15165 // some instruction-combining opportunities. This opt needs to be
15166 // postponed as late as possible.
15168 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15169 // the DCI.xxxx conditions are provided to postpone the optimization as
15170 // late as possible.
15172 ConstantSDNode *CmpAgainst = 0;
15173 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15174 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15175 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15177 if (CC == X86::COND_NE &&
15178 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15179 CC = X86::GetOppositeBranchCondition(CC);
15180 std::swap(TrueOp, FalseOp);
15183 if (CC == X86::COND_E &&
15184 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15185 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15186 DAG.getConstant(CC, MVT::i8), Cond };
15187 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15188 array_lengthof(Ops));
15197 /// PerformMulCombine - Optimize a single multiply with constant into two
15198 /// in order to implement it with two cheaper instructions, e.g.
15199 /// LEA + SHL, LEA + LEA.
15200 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15201 TargetLowering::DAGCombinerInfo &DCI) {
15202 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15205 EVT VT = N->getValueType(0);
15206 if (VT != MVT::i64)
15209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15212 uint64_t MulAmt = C->getZExtValue();
15213 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15216 uint64_t MulAmt1 = 0;
15217 uint64_t MulAmt2 = 0;
15218 if ((MulAmt % 9) == 0) {
15220 MulAmt2 = MulAmt / 9;
15221 } else if ((MulAmt % 5) == 0) {
15223 MulAmt2 = MulAmt / 5;
15224 } else if ((MulAmt % 3) == 0) {
15226 MulAmt2 = MulAmt / 3;
15229 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15230 DebugLoc DL = N->getDebugLoc();
15232 if (isPowerOf2_64(MulAmt2) &&
15233 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15234 // If second multiplifer is pow2, issue it first. We want the multiply by
15235 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15237 std::swap(MulAmt1, MulAmt2);
15240 if (isPowerOf2_64(MulAmt1))
15241 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15242 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15244 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15245 DAG.getConstant(MulAmt1, VT));
15247 if (isPowerOf2_64(MulAmt2))
15248 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15249 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15251 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15252 DAG.getConstant(MulAmt2, VT));
15254 // Do not add new nodes to DAG combiner worklist.
15255 DCI.CombineTo(N, NewMul, false);
15260 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15261 SDValue N0 = N->getOperand(0);
15262 SDValue N1 = N->getOperand(1);
15263 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15264 EVT VT = N0.getValueType();
15266 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15267 // since the result of setcc_c is all zero's or all ones.
15268 if (VT.isInteger() && !VT.isVector() &&
15269 N1C && N0.getOpcode() == ISD::AND &&
15270 N0.getOperand(1).getOpcode() == ISD::Constant) {
15271 SDValue N00 = N0.getOperand(0);
15272 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15273 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15274 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15275 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15276 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15277 APInt ShAmt = N1C->getAPIntValue();
15278 Mask = Mask.shl(ShAmt);
15280 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15281 N00, DAG.getConstant(Mask, VT));
15286 // Hardware support for vector shifts is sparse which makes us scalarize the
15287 // vector operations in many cases. Also, on sandybridge ADD is faster than
15289 // (shl V, 1) -> add V,V
15290 if (isSplatVector(N1.getNode())) {
15291 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15293 // We shift all of the values by one. In many cases we do not have
15294 // hardware support for this operation. This is better expressed as an ADD
15296 if (N1C && (1 == N1C->getZExtValue())) {
15297 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15304 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15306 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15307 TargetLowering::DAGCombinerInfo &DCI,
15308 const X86Subtarget *Subtarget) {
15309 EVT VT = N->getValueType(0);
15310 if (N->getOpcode() == ISD::SHL) {
15311 SDValue V = PerformSHLCombine(N, DAG);
15312 if (V.getNode()) return V;
15315 // On X86 with SSE2 support, we can transform this to a vector shift if
15316 // all elements are shifted by the same amount. We can't do this in legalize
15317 // because the a constant vector is typically transformed to a constant pool
15318 // so we have no knowledge of the shift amount.
15319 if (!Subtarget->hasSSE2())
15322 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15323 (!Subtarget->hasInt256() ||
15324 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15327 SDValue ShAmtOp = N->getOperand(1);
15328 EVT EltVT = VT.getVectorElementType();
15329 DebugLoc DL = N->getDebugLoc();
15330 SDValue BaseShAmt = SDValue();
15331 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15332 unsigned NumElts = VT.getVectorNumElements();
15334 for (; i != NumElts; ++i) {
15335 SDValue Arg = ShAmtOp.getOperand(i);
15336 if (Arg.getOpcode() == ISD::UNDEF) continue;
15340 // Handle the case where the build_vector is all undef
15341 // FIXME: Should DAG allow this?
15345 for (; i != NumElts; ++i) {
15346 SDValue Arg = ShAmtOp.getOperand(i);
15347 if (Arg.getOpcode() == ISD::UNDEF) continue;
15348 if (Arg != BaseShAmt) {
15352 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15353 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15354 SDValue InVec = ShAmtOp.getOperand(0);
15355 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15356 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15358 for (; i != NumElts; ++i) {
15359 SDValue Arg = InVec.getOperand(i);
15360 if (Arg.getOpcode() == ISD::UNDEF) continue;
15364 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15366 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15367 if (C->getZExtValue() == SplatIdx)
15368 BaseShAmt = InVec.getOperand(1);
15371 if (BaseShAmt.getNode() == 0) {
15372 // Don't create instructions with illegal types after legalize
15374 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15375 !DCI.isBeforeLegalize())
15378 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15379 DAG.getIntPtrConstant(0));
15384 // The shift amount is an i32.
15385 if (EltVT.bitsGT(MVT::i32))
15386 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15387 else if (EltVT.bitsLT(MVT::i32))
15388 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15390 // The shift amount is identical so we can do a vector shift.
15391 SDValue ValOp = N->getOperand(0);
15392 switch (N->getOpcode()) {
15394 llvm_unreachable("Unknown shift opcode!");
15396 switch (VT.getSimpleVT().SimpleTy) {
15397 default: return SDValue();
15404 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15407 switch (VT.getSimpleVT().SimpleTy) {
15408 default: return SDValue();
15413 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15416 switch (VT.getSimpleVT().SimpleTy) {
15417 default: return SDValue();
15424 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15430 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15431 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15432 // and friends. Likewise for OR -> CMPNEQSS.
15433 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15434 TargetLowering::DAGCombinerInfo &DCI,
15435 const X86Subtarget *Subtarget) {
15438 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15439 // we're requiring SSE2 for both.
15440 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15441 SDValue N0 = N->getOperand(0);
15442 SDValue N1 = N->getOperand(1);
15443 SDValue CMP0 = N0->getOperand(1);
15444 SDValue CMP1 = N1->getOperand(1);
15445 DebugLoc DL = N->getDebugLoc();
15447 // The SETCCs should both refer to the same CMP.
15448 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15451 SDValue CMP00 = CMP0->getOperand(0);
15452 SDValue CMP01 = CMP0->getOperand(1);
15453 EVT VT = CMP00.getValueType();
15455 if (VT == MVT::f32 || VT == MVT::f64) {
15456 bool ExpectingFlags = false;
15457 // Check for any users that want flags:
15458 for (SDNode::use_iterator UI = N->use_begin(),
15460 !ExpectingFlags && UI != UE; ++UI)
15461 switch (UI->getOpcode()) {
15466 ExpectingFlags = true;
15468 case ISD::CopyToReg:
15469 case ISD::SIGN_EXTEND:
15470 case ISD::ZERO_EXTEND:
15471 case ISD::ANY_EXTEND:
15475 if (!ExpectingFlags) {
15476 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15477 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15479 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15480 X86::CondCode tmp = cc0;
15485 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15486 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15487 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15488 X86ISD::NodeType NTOperator = is64BitFP ?
15489 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15490 // FIXME: need symbolic constants for these magic numbers.
15491 // See X86ATTInstPrinter.cpp:printSSECC().
15492 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15493 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15494 DAG.getConstant(x86cc, MVT::i8));
15495 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15497 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15498 DAG.getConstant(1, MVT::i32));
15499 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15500 return OneBitOfTruth;
15508 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15509 /// so it can be folded inside ANDNP.
15510 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15511 EVT VT = N->getValueType(0);
15513 // Match direct AllOnes for 128 and 256-bit vectors
15514 if (ISD::isBuildVectorAllOnes(N))
15517 // Look through a bit convert.
15518 if (N->getOpcode() == ISD::BITCAST)
15519 N = N->getOperand(0).getNode();
15521 // Sometimes the operand may come from a insert_subvector building a 256-bit
15523 if (VT.is256BitVector() &&
15524 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15525 SDValue V1 = N->getOperand(0);
15526 SDValue V2 = N->getOperand(1);
15528 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15529 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15530 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15531 ISD::isBuildVectorAllOnes(V2.getNode()))
15538 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15539 TargetLowering::DAGCombinerInfo &DCI,
15540 const X86Subtarget *Subtarget) {
15541 if (DCI.isBeforeLegalizeOps())
15544 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15548 EVT VT = N->getValueType(0);
15550 // Create ANDN, BLSI, and BLSR instructions
15551 // BLSI is X & (-X)
15552 // BLSR is X & (X-1)
15553 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15554 SDValue N0 = N->getOperand(0);
15555 SDValue N1 = N->getOperand(1);
15556 DebugLoc DL = N->getDebugLoc();
15558 // Check LHS for not
15559 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15560 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15561 // Check RHS for not
15562 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15563 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15565 // Check LHS for neg
15566 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15567 isZero(N0.getOperand(0)))
15568 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15570 // Check RHS for neg
15571 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15572 isZero(N1.getOperand(0)))
15573 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15575 // Check LHS for X-1
15576 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15577 isAllOnes(N0.getOperand(1)))
15578 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15580 // Check RHS for X-1
15581 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15582 isAllOnes(N1.getOperand(1)))
15583 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15588 // Want to form ANDNP nodes:
15589 // 1) In the hopes of then easily combining them with OR and AND nodes
15590 // to form PBLEND/PSIGN.
15591 // 2) To match ANDN packed intrinsics
15592 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15595 SDValue N0 = N->getOperand(0);
15596 SDValue N1 = N->getOperand(1);
15597 DebugLoc DL = N->getDebugLoc();
15599 // Check LHS for vnot
15600 if (N0.getOpcode() == ISD::XOR &&
15601 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15602 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15603 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15605 // Check RHS for vnot
15606 if (N1.getOpcode() == ISD::XOR &&
15607 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15608 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15609 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15614 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15615 TargetLowering::DAGCombinerInfo &DCI,
15616 const X86Subtarget *Subtarget) {
15617 if (DCI.isBeforeLegalizeOps())
15620 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15624 EVT VT = N->getValueType(0);
15626 SDValue N0 = N->getOperand(0);
15627 SDValue N1 = N->getOperand(1);
15629 // look for psign/blend
15630 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15631 if (!Subtarget->hasSSSE3() ||
15632 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
15635 // Canonicalize pandn to RHS
15636 if (N0.getOpcode() == X86ISD::ANDNP)
15638 // or (and (m, y), (pandn m, x))
15639 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15640 SDValue Mask = N1.getOperand(0);
15641 SDValue X = N1.getOperand(1);
15643 if (N0.getOperand(0) == Mask)
15644 Y = N0.getOperand(1);
15645 if (N0.getOperand(1) == Mask)
15646 Y = N0.getOperand(0);
15648 // Check to see if the mask appeared in both the AND and ANDNP and
15652 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15653 // Look through mask bitcast.
15654 if (Mask.getOpcode() == ISD::BITCAST)
15655 Mask = Mask.getOperand(0);
15656 if (X.getOpcode() == ISD::BITCAST)
15657 X = X.getOperand(0);
15658 if (Y.getOpcode() == ISD::BITCAST)
15659 Y = Y.getOperand(0);
15661 EVT MaskVT = Mask.getValueType();
15663 // Validate that the Mask operand is a vector sra node.
15664 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15665 // there is no psrai.b
15666 if (Mask.getOpcode() != X86ISD::VSRAI)
15669 // Check that the SRA is all signbits.
15670 SDValue SraC = Mask.getOperand(1);
15671 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15672 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15673 if ((SraAmt + 1) != EltBits)
15676 DebugLoc DL = N->getDebugLoc();
15678 // We are going to replace the AND, OR, NAND with either BLEND
15679 // or PSIGN, which only look at the MSB. The VSRAI instruction
15680 // does not affect the highest bit, so we can get rid of it.
15681 Mask = Mask.getOperand(0);
15683 // Now we know we at least have a plendvb with the mask val. See if
15684 // we can form a psignb/w/d.
15685 // psign = x.type == y.type == mask.type && y = sub(0, x);
15686 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15687 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15688 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15689 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15690 "Unsupported VT for PSIGN");
15691 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
15692 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15694 // PBLENDVB only available on SSE 4.1
15695 if (!Subtarget->hasSSE41())
15698 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15700 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15701 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15702 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15703 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15704 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15708 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15711 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15712 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15714 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15716 if (!N0.hasOneUse() || !N1.hasOneUse())
15719 SDValue ShAmt0 = N0.getOperand(1);
15720 if (ShAmt0.getValueType() != MVT::i8)
15722 SDValue ShAmt1 = N1.getOperand(1);
15723 if (ShAmt1.getValueType() != MVT::i8)
15725 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15726 ShAmt0 = ShAmt0.getOperand(0);
15727 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15728 ShAmt1 = ShAmt1.getOperand(0);
15730 DebugLoc DL = N->getDebugLoc();
15731 unsigned Opc = X86ISD::SHLD;
15732 SDValue Op0 = N0.getOperand(0);
15733 SDValue Op1 = N1.getOperand(0);
15734 if (ShAmt0.getOpcode() == ISD::SUB) {
15735 Opc = X86ISD::SHRD;
15736 std::swap(Op0, Op1);
15737 std::swap(ShAmt0, ShAmt1);
15740 unsigned Bits = VT.getSizeInBits();
15741 if (ShAmt1.getOpcode() == ISD::SUB) {
15742 SDValue Sum = ShAmt1.getOperand(0);
15743 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15744 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15745 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15746 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15747 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15748 return DAG.getNode(Opc, DL, VT,
15750 DAG.getNode(ISD::TRUNCATE, DL,
15753 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15754 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15756 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15757 return DAG.getNode(Opc, DL, VT,
15758 N0.getOperand(0), N1.getOperand(0),
15759 DAG.getNode(ISD::TRUNCATE, DL,
15766 // Generate NEG and CMOV for integer abs.
15767 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15768 EVT VT = N->getValueType(0);
15770 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15771 // 8-bit integer abs to NEG and CMOV.
15772 if (VT.isInteger() && VT.getSizeInBits() == 8)
15775 SDValue N0 = N->getOperand(0);
15776 SDValue N1 = N->getOperand(1);
15777 DebugLoc DL = N->getDebugLoc();
15779 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15780 // and change it to SUB and CMOV.
15781 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15782 N0.getOpcode() == ISD::ADD &&
15783 N0.getOperand(1) == N1 &&
15784 N1.getOpcode() == ISD::SRA &&
15785 N1.getOperand(0) == N0.getOperand(0))
15786 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15787 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15788 // Generate SUB & CMOV.
15789 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15790 DAG.getConstant(0, VT), N0.getOperand(0));
15792 SDValue Ops[] = { N0.getOperand(0), Neg,
15793 DAG.getConstant(X86::COND_GE, MVT::i8),
15794 SDValue(Neg.getNode(), 1) };
15795 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15796 Ops, array_lengthof(Ops));
15801 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15802 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15803 TargetLowering::DAGCombinerInfo &DCI,
15804 const X86Subtarget *Subtarget) {
15805 if (DCI.isBeforeLegalizeOps())
15808 if (Subtarget->hasCMov()) {
15809 SDValue RV = performIntegerAbsCombine(N, DAG);
15814 // Try forming BMI if it is available.
15815 if (!Subtarget->hasBMI())
15818 EVT VT = N->getValueType(0);
15820 if (VT != MVT::i32 && VT != MVT::i64)
15823 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15825 // Create BLSMSK instructions by finding X ^ (X-1)
15826 SDValue N0 = N->getOperand(0);
15827 SDValue N1 = N->getOperand(1);
15828 DebugLoc DL = N->getDebugLoc();
15830 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15831 isAllOnes(N0.getOperand(1)))
15832 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15834 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15835 isAllOnes(N1.getOperand(1)))
15836 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15841 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15842 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15843 TargetLowering::DAGCombinerInfo &DCI,
15844 const X86Subtarget *Subtarget) {
15845 LoadSDNode *Ld = cast<LoadSDNode>(N);
15846 EVT RegVT = Ld->getValueType(0);
15847 EVT MemVT = Ld->getMemoryVT();
15848 DebugLoc dl = Ld->getDebugLoc();
15849 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15851 ISD::LoadExtType Ext = Ld->getExtensionType();
15853 // If this is a vector EXT Load then attempt to optimize it using a
15854 // shuffle. We need SSSE3 shuffles.
15855 // TODO: It is possible to support ZExt by zeroing the undef values
15856 // during the shuffle phase or after the shuffle.
15857 if (RegVT.isVector() && RegVT.isInteger() &&
15858 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15859 assert(MemVT != RegVT && "Cannot extend to the same type");
15860 assert(MemVT.isVector() && "Must load a vector from memory");
15862 unsigned NumElems = RegVT.getVectorNumElements();
15863 unsigned RegSz = RegVT.getSizeInBits();
15864 unsigned MemSz = MemVT.getSizeInBits();
15865 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15867 // All sizes must be a power of two.
15868 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15871 // Attempt to load the original value using scalar loads.
15872 // Find the largest scalar type that divides the total loaded size.
15873 MVT SclrLoadTy = MVT::i8;
15874 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15875 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15876 MVT Tp = (MVT::SimpleValueType)tp;
15877 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15882 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15883 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15885 SclrLoadTy = MVT::f64;
15887 // Calculate the number of scalar loads that we need to perform
15888 // in order to load our vector from memory.
15889 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15891 // Represent our vector as a sequence of elements which are the
15892 // largest scalar that we can load.
15893 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15894 RegSz/SclrLoadTy.getSizeInBits());
15896 // Represent the data using the same element type that is stored in
15897 // memory. In practice, we ''widen'' MemVT.
15898 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15899 RegSz/MemVT.getScalarType().getSizeInBits());
15901 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15902 "Invalid vector type");
15904 // We can't shuffle using an illegal type.
15905 if (!TLI.isTypeLegal(WideVecVT))
15908 SmallVector<SDValue, 8> Chains;
15909 SDValue Ptr = Ld->getBasePtr();
15910 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15911 TLI.getPointerTy());
15912 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15914 for (unsigned i = 0; i < NumLoads; ++i) {
15915 // Perform a single load.
15916 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15917 Ptr, Ld->getPointerInfo(),
15918 Ld->isVolatile(), Ld->isNonTemporal(),
15919 Ld->isInvariant(), Ld->getAlignment());
15920 Chains.push_back(ScalarLoad.getValue(1));
15921 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15922 // another round of DAGCombining.
15924 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15926 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15927 ScalarLoad, DAG.getIntPtrConstant(i));
15929 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15932 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15935 // Bitcast the loaded value to a vector of the original element type, in
15936 // the size of the target vector type.
15937 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15938 unsigned SizeRatio = RegSz/MemSz;
15940 // Redistribute the loaded elements into the different locations.
15941 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15942 for (unsigned i = 0; i != NumElems; ++i)
15943 ShuffleVec[i*SizeRatio] = i;
15945 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15946 DAG.getUNDEF(WideVecVT),
15949 // Bitcast to the requested type.
15950 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15951 // Replace the original load with the new sequence
15952 // and return the new chain.
15953 return DCI.CombineTo(N, Shuff, TF, true);
15959 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15960 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15961 const X86Subtarget *Subtarget) {
15962 StoreSDNode *St = cast<StoreSDNode>(N);
15963 EVT VT = St->getValue().getValueType();
15964 EVT StVT = St->getMemoryVT();
15965 DebugLoc dl = St->getDebugLoc();
15966 SDValue StoredVal = St->getOperand(1);
15967 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15969 // If we are saving a concatenation of two XMM registers, perform two stores.
15970 // On Sandy Bridge, 256-bit memory operations are executed by two
15971 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15972 // memory operation.
15973 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
15974 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15975 StoredVal.getNumOperands() == 2) {
15976 SDValue Value0 = StoredVal.getOperand(0);
15977 SDValue Value1 = StoredVal.getOperand(1);
15979 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15980 SDValue Ptr0 = St->getBasePtr();
15981 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15983 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15984 St->getPointerInfo(), St->isVolatile(),
15985 St->isNonTemporal(), St->getAlignment());
15986 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15987 St->getPointerInfo(), St->isVolatile(),
15988 St->isNonTemporal(), St->getAlignment());
15989 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15992 // Optimize trunc store (of multiple scalars) to shuffle and store.
15993 // First, pack all of the elements in one place. Next, store to memory
15994 // in fewer chunks.
15995 if (St->isTruncatingStore() && VT.isVector()) {
15996 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15997 unsigned NumElems = VT.getVectorNumElements();
15998 assert(StVT != VT && "Cannot truncate to the same type");
15999 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16000 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16002 // From, To sizes and ElemCount must be pow of two
16003 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16004 // We are going to use the original vector elt for storing.
16005 // Accumulated smaller vector elements must be a multiple of the store size.
16006 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16008 unsigned SizeRatio = FromSz / ToSz;
16010 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16012 // Create a type on which we perform the shuffle
16013 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16014 StVT.getScalarType(), NumElems*SizeRatio);
16016 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16018 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16019 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16020 for (unsigned i = 0; i != NumElems; ++i)
16021 ShuffleVec[i] = i * SizeRatio;
16023 // Can't shuffle using an illegal type.
16024 if (!TLI.isTypeLegal(WideVecVT))
16027 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16028 DAG.getUNDEF(WideVecVT),
16030 // At this point all of the data is stored at the bottom of the
16031 // register. We now need to save it to mem.
16033 // Find the largest store unit
16034 MVT StoreType = MVT::i8;
16035 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16036 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16037 MVT Tp = (MVT::SimpleValueType)tp;
16038 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16042 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16043 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16044 (64 <= NumElems * ToSz))
16045 StoreType = MVT::f64;
16047 // Bitcast the original vector into a vector of store-size units
16048 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16049 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16050 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16051 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16052 SmallVector<SDValue, 8> Chains;
16053 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16054 TLI.getPointerTy());
16055 SDValue Ptr = St->getBasePtr();
16057 // Perform one or more big stores into memory.
16058 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16059 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16060 StoreType, ShuffWide,
16061 DAG.getIntPtrConstant(i));
16062 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16063 St->getPointerInfo(), St->isVolatile(),
16064 St->isNonTemporal(), St->getAlignment());
16065 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16066 Chains.push_back(Ch);
16069 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16074 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16075 // the FP state in cases where an emms may be missing.
16076 // A preferable solution to the general problem is to figure out the right
16077 // places to insert EMMS. This qualifies as a quick hack.
16079 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16080 if (VT.getSizeInBits() != 64)
16083 const Function *F = DAG.getMachineFunction().getFunction();
16084 bool NoImplicitFloatOps = F->getFnAttributes().
16085 hasAttribute(Attributes::NoImplicitFloat);
16086 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16087 && Subtarget->hasSSE2();
16088 if ((VT.isVector() ||
16089 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16090 isa<LoadSDNode>(St->getValue()) &&
16091 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16092 St->getChain().hasOneUse() && !St->isVolatile()) {
16093 SDNode* LdVal = St->getValue().getNode();
16094 LoadSDNode *Ld = 0;
16095 int TokenFactorIndex = -1;
16096 SmallVector<SDValue, 8> Ops;
16097 SDNode* ChainVal = St->getChain().getNode();
16098 // Must be a store of a load. We currently handle two cases: the load
16099 // is a direct child, and it's under an intervening TokenFactor. It is
16100 // possible to dig deeper under nested TokenFactors.
16101 if (ChainVal == LdVal)
16102 Ld = cast<LoadSDNode>(St->getChain());
16103 else if (St->getValue().hasOneUse() &&
16104 ChainVal->getOpcode() == ISD::TokenFactor) {
16105 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16106 if (ChainVal->getOperand(i).getNode() == LdVal) {
16107 TokenFactorIndex = i;
16108 Ld = cast<LoadSDNode>(St->getValue());
16110 Ops.push_back(ChainVal->getOperand(i));
16114 if (!Ld || !ISD::isNormalLoad(Ld))
16117 // If this is not the MMX case, i.e. we are just turning i64 load/store
16118 // into f64 load/store, avoid the transformation if there are multiple
16119 // uses of the loaded value.
16120 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16123 DebugLoc LdDL = Ld->getDebugLoc();
16124 DebugLoc StDL = N->getDebugLoc();
16125 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16126 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16128 if (Subtarget->is64Bit() || F64IsLegal) {
16129 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16130 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16131 Ld->getPointerInfo(), Ld->isVolatile(),
16132 Ld->isNonTemporal(), Ld->isInvariant(),
16133 Ld->getAlignment());
16134 SDValue NewChain = NewLd.getValue(1);
16135 if (TokenFactorIndex != -1) {
16136 Ops.push_back(NewChain);
16137 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16140 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16141 St->getPointerInfo(),
16142 St->isVolatile(), St->isNonTemporal(),
16143 St->getAlignment());
16146 // Otherwise, lower to two pairs of 32-bit loads / stores.
16147 SDValue LoAddr = Ld->getBasePtr();
16148 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16149 DAG.getConstant(4, MVT::i32));
16151 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16152 Ld->getPointerInfo(),
16153 Ld->isVolatile(), Ld->isNonTemporal(),
16154 Ld->isInvariant(), Ld->getAlignment());
16155 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16156 Ld->getPointerInfo().getWithOffset(4),
16157 Ld->isVolatile(), Ld->isNonTemporal(),
16159 MinAlign(Ld->getAlignment(), 4));
16161 SDValue NewChain = LoLd.getValue(1);
16162 if (TokenFactorIndex != -1) {
16163 Ops.push_back(LoLd);
16164 Ops.push_back(HiLd);
16165 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16169 LoAddr = St->getBasePtr();
16170 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16171 DAG.getConstant(4, MVT::i32));
16173 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16174 St->getPointerInfo(),
16175 St->isVolatile(), St->isNonTemporal(),
16176 St->getAlignment());
16177 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16178 St->getPointerInfo().getWithOffset(4),
16180 St->isNonTemporal(),
16181 MinAlign(St->getAlignment(), 4));
16182 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16187 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16188 /// and return the operands for the horizontal operation in LHS and RHS. A
16189 /// horizontal operation performs the binary operation on successive elements
16190 /// of its first operand, then on successive elements of its second operand,
16191 /// returning the resulting values in a vector. For example, if
16192 /// A = < float a0, float a1, float a2, float a3 >
16194 /// B = < float b0, float b1, float b2, float b3 >
16195 /// then the result of doing a horizontal operation on A and B is
16196 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16197 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16198 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16199 /// set to A, RHS to B, and the routine returns 'true'.
16200 /// Note that the binary operation should have the property that if one of the
16201 /// operands is UNDEF then the result is UNDEF.
16202 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16203 // Look for the following pattern: if
16204 // A = < float a0, float a1, float a2, float a3 >
16205 // B = < float b0, float b1, float b2, float b3 >
16207 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16208 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16209 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16210 // which is A horizontal-op B.
16212 // At least one of the operands should be a vector shuffle.
16213 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16214 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16217 EVT VT = LHS.getValueType();
16219 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16220 "Unsupported vector type for horizontal add/sub");
16222 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16223 // operate independently on 128-bit lanes.
16224 unsigned NumElts = VT.getVectorNumElements();
16225 unsigned NumLanes = VT.getSizeInBits()/128;
16226 unsigned NumLaneElts = NumElts / NumLanes;
16227 assert((NumLaneElts % 2 == 0) &&
16228 "Vector type should have an even number of elements in each lane");
16229 unsigned HalfLaneElts = NumLaneElts/2;
16231 // View LHS in the form
16232 // LHS = VECTOR_SHUFFLE A, B, LMask
16233 // If LHS is not a shuffle then pretend it is the shuffle
16234 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16235 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16238 SmallVector<int, 16> LMask(NumElts);
16239 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16240 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16241 A = LHS.getOperand(0);
16242 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16243 B = LHS.getOperand(1);
16244 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16245 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16247 if (LHS.getOpcode() != ISD::UNDEF)
16249 for (unsigned i = 0; i != NumElts; ++i)
16253 // Likewise, view RHS in the form
16254 // RHS = VECTOR_SHUFFLE C, D, RMask
16256 SmallVector<int, 16> RMask(NumElts);
16257 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16258 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16259 C = RHS.getOperand(0);
16260 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16261 D = RHS.getOperand(1);
16262 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16263 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16265 if (RHS.getOpcode() != ISD::UNDEF)
16267 for (unsigned i = 0; i != NumElts; ++i)
16271 // Check that the shuffles are both shuffling the same vectors.
16272 if (!(A == C && B == D) && !(A == D && B == C))
16275 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16276 if (!A.getNode() && !B.getNode())
16279 // If A and B occur in reverse order in RHS, then "swap" them (which means
16280 // rewriting the mask).
16282 CommuteVectorShuffleMask(RMask, NumElts);
16284 // At this point LHS and RHS are equivalent to
16285 // LHS = VECTOR_SHUFFLE A, B, LMask
16286 // RHS = VECTOR_SHUFFLE A, B, RMask
16287 // Check that the masks correspond to performing a horizontal operation.
16288 for (unsigned i = 0; i != NumElts; ++i) {
16289 int LIdx = LMask[i], RIdx = RMask[i];
16291 // Ignore any UNDEF components.
16292 if (LIdx < 0 || RIdx < 0 ||
16293 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16294 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16297 // Check that successive elements are being operated on. If not, this is
16298 // not a horizontal operation.
16299 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16300 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16301 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16302 if (!(LIdx == Index && RIdx == Index + 1) &&
16303 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16307 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16308 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16312 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16313 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16314 const X86Subtarget *Subtarget) {
16315 EVT VT = N->getValueType(0);
16316 SDValue LHS = N->getOperand(0);
16317 SDValue RHS = N->getOperand(1);
16319 // Try to synthesize horizontal adds from adds of shuffles.
16320 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16321 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16322 isHorizontalBinOp(LHS, RHS, true))
16323 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16327 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16328 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16329 const X86Subtarget *Subtarget) {
16330 EVT VT = N->getValueType(0);
16331 SDValue LHS = N->getOperand(0);
16332 SDValue RHS = N->getOperand(1);
16334 // Try to synthesize horizontal subs from subs of shuffles.
16335 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16336 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16337 isHorizontalBinOp(LHS, RHS, false))
16338 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16342 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16343 /// X86ISD::FXOR nodes.
16344 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16345 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16346 // F[X]OR(0.0, x) -> x
16347 // F[X]OR(x, 0.0) -> x
16348 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16349 if (C->getValueAPF().isPosZero())
16350 return N->getOperand(1);
16351 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16352 if (C->getValueAPF().isPosZero())
16353 return N->getOperand(0);
16357 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16358 /// X86ISD::FMAX nodes.
16359 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16360 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16362 // Only perform optimizations if UnsafeMath is used.
16363 if (!DAG.getTarget().Options.UnsafeFPMath)
16366 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16367 // into FMINC and FMAXC, which are Commutative operations.
16368 unsigned NewOp = 0;
16369 switch (N->getOpcode()) {
16370 default: llvm_unreachable("unknown opcode");
16371 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16372 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16375 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16376 N->getOperand(0), N->getOperand(1));
16380 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16381 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16382 // FAND(0.0, x) -> 0.0
16383 // FAND(x, 0.0) -> 0.0
16384 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16385 if (C->getValueAPF().isPosZero())
16386 return N->getOperand(0);
16387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16388 if (C->getValueAPF().isPosZero())
16389 return N->getOperand(1);
16393 static SDValue PerformBTCombine(SDNode *N,
16395 TargetLowering::DAGCombinerInfo &DCI) {
16396 // BT ignores high bits in the bit index operand.
16397 SDValue Op1 = N->getOperand(1);
16398 if (Op1.hasOneUse()) {
16399 unsigned BitWidth = Op1.getValueSizeInBits();
16400 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16401 APInt KnownZero, KnownOne;
16402 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16403 !DCI.isBeforeLegalizeOps());
16404 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16405 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16406 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16407 DCI.CommitTargetLoweringOpt(TLO);
16412 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16413 SDValue Op = N->getOperand(0);
16414 if (Op.getOpcode() == ISD::BITCAST)
16415 Op = Op.getOperand(0);
16416 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16417 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16418 VT.getVectorElementType().getSizeInBits() ==
16419 OpVT.getVectorElementType().getSizeInBits()) {
16420 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16425 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16426 TargetLowering::DAGCombinerInfo &DCI,
16427 const X86Subtarget *Subtarget) {
16428 if (!DCI.isBeforeLegalizeOps())
16431 if (!Subtarget->hasFp256())
16434 EVT VT = N->getValueType(0);
16435 SDValue Op = N->getOperand(0);
16436 EVT OpVT = Op.getValueType();
16437 DebugLoc dl = N->getDebugLoc();
16439 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16440 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16442 if (Subtarget->hasInt256())
16443 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16445 // Optimize vectors in AVX mode
16446 // Sign extend v8i16 to v8i32 and
16449 // Divide input vector into two parts
16450 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16451 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16452 // concat the vectors to original VT
16454 unsigned NumElems = OpVT.getVectorNumElements();
16455 SDValue Undef = DAG.getUNDEF(OpVT);
16457 SmallVector<int,8> ShufMask1(NumElems, -1);
16458 for (unsigned i = 0; i != NumElems/2; ++i)
16461 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16463 SmallVector<int,8> ShufMask2(NumElems, -1);
16464 for (unsigned i = 0; i != NumElems/2; ++i)
16465 ShufMask2[i] = i + NumElems/2;
16467 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16469 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16470 VT.getVectorNumElements()/2);
16472 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16473 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16475 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16480 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16481 const X86Subtarget* Subtarget) {
16482 DebugLoc dl = N->getDebugLoc();
16483 EVT VT = N->getValueType(0);
16485 // Let legalize expand this if it isn't a legal type yet.
16486 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16489 EVT ScalarVT = VT.getScalarType();
16490 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16491 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16494 SDValue A = N->getOperand(0);
16495 SDValue B = N->getOperand(1);
16496 SDValue C = N->getOperand(2);
16498 bool NegA = (A.getOpcode() == ISD::FNEG);
16499 bool NegB = (B.getOpcode() == ISD::FNEG);
16500 bool NegC = (C.getOpcode() == ISD::FNEG);
16502 // Negative multiplication when NegA xor NegB
16503 bool NegMul = (NegA != NegB);
16505 A = A.getOperand(0);
16507 B = B.getOperand(0);
16509 C = C.getOperand(0);
16513 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16515 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16517 return DAG.getNode(Opcode, dl, VT, A, B, C);
16520 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16521 TargetLowering::DAGCombinerInfo &DCI,
16522 const X86Subtarget *Subtarget) {
16523 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16524 // (and (i32 x86isd::setcc_carry), 1)
16525 // This eliminates the zext. This transformation is necessary because
16526 // ISD::SETCC is always legalized to i8.
16527 DebugLoc dl = N->getDebugLoc();
16528 SDValue N0 = N->getOperand(0);
16529 EVT VT = N->getValueType(0);
16530 EVT OpVT = N0.getValueType();
16532 if (N0.getOpcode() == ISD::AND &&
16534 N0.getOperand(0).hasOneUse()) {
16535 SDValue N00 = N0.getOperand(0);
16536 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16538 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16539 if (!C || C->getZExtValue() != 1)
16541 return DAG.getNode(ISD::AND, dl, VT,
16542 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16543 N00.getOperand(0), N00.getOperand(1)),
16544 DAG.getConstant(1, VT));
16547 // Optimize vectors in AVX mode:
16550 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16551 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16552 // Concat upper and lower parts.
16555 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16556 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16557 // Concat upper and lower parts.
16559 if (!DCI.isBeforeLegalizeOps())
16562 if (!Subtarget->hasFp256())
16565 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16566 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16568 if (Subtarget->hasInt256())
16569 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16571 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16572 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16573 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16575 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16576 VT.getVectorNumElements()/2);
16578 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16579 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16581 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16587 // Optimize x == -y --> x+y == 0
16588 // x != -y --> x+y != 0
16589 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16590 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16591 SDValue LHS = N->getOperand(0);
16592 SDValue RHS = N->getOperand(1);
16594 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16595 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16596 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16597 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16598 LHS.getValueType(), RHS, LHS.getOperand(1));
16599 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16600 addV, DAG.getConstant(0, addV.getValueType()), CC);
16602 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16604 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16605 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16606 RHS.getValueType(), LHS, RHS.getOperand(1));
16607 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16608 addV, DAG.getConstant(0, addV.getValueType()), CC);
16613 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
16614 // as "sbb reg,reg", since it can be extended without zext and produces
16615 // an all-ones bit which is more useful than 0/1 in some cases.
16616 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
16617 return DAG.getNode(ISD::AND, DL, MVT::i8,
16618 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16619 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
16620 DAG.getConstant(1, MVT::i8));
16623 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16624 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16625 TargetLowering::DAGCombinerInfo &DCI,
16626 const X86Subtarget *Subtarget) {
16627 DebugLoc DL = N->getDebugLoc();
16628 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16629 SDValue EFLAGS = N->getOperand(1);
16631 if (CC == X86::COND_A) {
16632 // Try to convert COND_A into COND_B in an attempt to facilitate
16633 // materializing "setb reg".
16635 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
16636 // cannot take an immediate as its first operand.
16638 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
16639 EFLAGS.getValueType().isInteger() &&
16640 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
16641 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
16642 EFLAGS.getNode()->getVTList(),
16643 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
16644 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
16645 return MaterializeSETB(DL, NewEFLAGS, DAG);
16649 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16650 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16652 if (CC == X86::COND_B)
16653 return MaterializeSETB(DL, EFLAGS, DAG);
16657 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16658 if (Flags.getNode()) {
16659 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16660 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16666 // Optimize branch condition evaluation.
16668 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16669 TargetLowering::DAGCombinerInfo &DCI,
16670 const X86Subtarget *Subtarget) {
16671 DebugLoc DL = N->getDebugLoc();
16672 SDValue Chain = N->getOperand(0);
16673 SDValue Dest = N->getOperand(1);
16674 SDValue EFLAGS = N->getOperand(3);
16675 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16679 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16680 if (Flags.getNode()) {
16681 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16682 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16689 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16690 const X86TargetLowering *XTLI) {
16691 SDValue Op0 = N->getOperand(0);
16692 EVT InVT = Op0->getValueType(0);
16694 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16695 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16696 DebugLoc dl = N->getDebugLoc();
16697 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16698 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16699 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16702 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16703 // a 32-bit target where SSE doesn't support i64->FP operations.
16704 if (Op0.getOpcode() == ISD::LOAD) {
16705 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16706 EVT VT = Ld->getValueType(0);
16707 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16708 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16709 !XTLI->getSubtarget()->is64Bit() &&
16710 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16711 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16712 Ld->getChain(), Op0, DAG);
16713 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16720 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16721 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16722 X86TargetLowering::DAGCombinerInfo &DCI) {
16723 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16724 // the result is either zero or one (depending on the input carry bit).
16725 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16726 if (X86::isZeroNode(N->getOperand(0)) &&
16727 X86::isZeroNode(N->getOperand(1)) &&
16728 // We don't have a good way to replace an EFLAGS use, so only do this when
16730 SDValue(N, 1).use_empty()) {
16731 DebugLoc DL = N->getDebugLoc();
16732 EVT VT = N->getValueType(0);
16733 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16734 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16735 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16736 DAG.getConstant(X86::COND_B,MVT::i8),
16738 DAG.getConstant(1, VT));
16739 return DCI.CombineTo(N, Res1, CarryOut);
16745 // fold (add Y, (sete X, 0)) -> adc 0, Y
16746 // (add Y, (setne X, 0)) -> sbb -1, Y
16747 // (sub (sete X, 0), Y) -> sbb 0, Y
16748 // (sub (setne X, 0), Y) -> adc -1, Y
16749 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16750 DebugLoc DL = N->getDebugLoc();
16752 // Look through ZExts.
16753 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16754 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16757 SDValue SetCC = Ext.getOperand(0);
16758 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16761 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16762 if (CC != X86::COND_E && CC != X86::COND_NE)
16765 SDValue Cmp = SetCC.getOperand(1);
16766 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16767 !X86::isZeroNode(Cmp.getOperand(1)) ||
16768 !Cmp.getOperand(0).getValueType().isInteger())
16771 SDValue CmpOp0 = Cmp.getOperand(0);
16772 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16773 DAG.getConstant(1, CmpOp0.getValueType()));
16775 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16776 if (CC == X86::COND_NE)
16777 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16778 DL, OtherVal.getValueType(), OtherVal,
16779 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16780 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16781 DL, OtherVal.getValueType(), OtherVal,
16782 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16785 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16786 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16787 const X86Subtarget *Subtarget) {
16788 EVT VT = N->getValueType(0);
16789 SDValue Op0 = N->getOperand(0);
16790 SDValue Op1 = N->getOperand(1);
16792 // Try to synthesize horizontal adds from adds of shuffles.
16793 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16794 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16795 isHorizontalBinOp(Op0, Op1, true))
16796 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16798 return OptimizeConditionalInDecrement(N, DAG);
16801 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16802 const X86Subtarget *Subtarget) {
16803 SDValue Op0 = N->getOperand(0);
16804 SDValue Op1 = N->getOperand(1);
16806 // X86 can't encode an immediate LHS of a sub. See if we can push the
16807 // negation into a preceding instruction.
16808 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16809 // If the RHS of the sub is a XOR with one use and a constant, invert the
16810 // immediate. Then add one to the LHS of the sub so we can turn
16811 // X-Y -> X+~Y+1, saving one register.
16812 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16813 isa<ConstantSDNode>(Op1.getOperand(1))) {
16814 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16815 EVT VT = Op0.getValueType();
16816 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16818 DAG.getConstant(~XorC, VT));
16819 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16820 DAG.getConstant(C->getAPIntValue()+1, VT));
16824 // Try to synthesize horizontal adds from adds of shuffles.
16825 EVT VT = N->getValueType(0);
16826 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16827 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16828 isHorizontalBinOp(Op0, Op1, true))
16829 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16831 return OptimizeConditionalInDecrement(N, DAG);
16834 /// performVZEXTCombine - Performs build vector combines
16835 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16836 TargetLowering::DAGCombinerInfo &DCI,
16837 const X86Subtarget *Subtarget) {
16838 // (vzext (bitcast (vzext (x)) -> (vzext x)
16839 SDValue In = N->getOperand(0);
16840 while (In.getOpcode() == ISD::BITCAST)
16841 In = In.getOperand(0);
16843 if (In.getOpcode() != X86ISD::VZEXT)
16846 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16849 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16850 DAGCombinerInfo &DCI) const {
16851 SelectionDAG &DAG = DCI.DAG;
16852 switch (N->getOpcode()) {
16854 case ISD::EXTRACT_VECTOR_ELT:
16855 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16857 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16858 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16859 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16860 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16861 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16862 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16865 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16866 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16867 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16868 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16869 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16870 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16871 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16872 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16873 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16875 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16877 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16878 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16879 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16880 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16881 case ISD::ANY_EXTEND:
16882 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16883 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16884 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16885 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16886 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16887 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16888 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
16889 case X86ISD::SHUFP: // Handle all target specific shuffles
16890 case X86ISD::PALIGN:
16891 case X86ISD::UNPCKH:
16892 case X86ISD::UNPCKL:
16893 case X86ISD::MOVHLPS:
16894 case X86ISD::MOVLHPS:
16895 case X86ISD::PSHUFD:
16896 case X86ISD::PSHUFHW:
16897 case X86ISD::PSHUFLW:
16898 case X86ISD::MOVSS:
16899 case X86ISD::MOVSD:
16900 case X86ISD::VPERMILP:
16901 case X86ISD::VPERM2X128:
16902 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16903 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16909 /// isTypeDesirableForOp - Return true if the target has native support for
16910 /// the specified value type and it is 'desirable' to use the type for the
16911 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16912 /// instruction encodings are longer and some i16 instructions are slow.
16913 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16914 if (!isTypeLegal(VT))
16916 if (VT != MVT::i16)
16923 case ISD::SIGN_EXTEND:
16924 case ISD::ZERO_EXTEND:
16925 case ISD::ANY_EXTEND:
16938 /// IsDesirableToPromoteOp - This method query the target whether it is
16939 /// beneficial for dag combiner to promote the specified node. If true, it
16940 /// should return the desired promotion type by reference.
16941 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16942 EVT VT = Op.getValueType();
16943 if (VT != MVT::i16)
16946 bool Promote = false;
16947 bool Commute = false;
16948 switch (Op.getOpcode()) {
16951 LoadSDNode *LD = cast<LoadSDNode>(Op);
16952 // If the non-extending load has a single use and it's not live out, then it
16953 // might be folded.
16954 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16955 Op.hasOneUse()*/) {
16956 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16957 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16958 // The only case where we'd want to promote LOAD (rather then it being
16959 // promoted as an operand is when it's only use is liveout.
16960 if (UI->getOpcode() != ISD::CopyToReg)
16967 case ISD::SIGN_EXTEND:
16968 case ISD::ZERO_EXTEND:
16969 case ISD::ANY_EXTEND:
16974 SDValue N0 = Op.getOperand(0);
16975 // Look out for (store (shl (load), x)).
16976 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16989 SDValue N0 = Op.getOperand(0);
16990 SDValue N1 = Op.getOperand(1);
16991 if (!Commute && MayFoldLoad(N1))
16993 // Avoid disabling potential load folding opportunities.
16994 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16996 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17006 //===----------------------------------------------------------------------===//
17007 // X86 Inline Assembly Support
17008 //===----------------------------------------------------------------------===//
17011 // Helper to match a string separated by whitespace.
17012 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17013 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17015 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17016 StringRef piece(*args[i]);
17017 if (!s.startswith(piece)) // Check if the piece matches.
17020 s = s.substr(piece.size());
17021 StringRef::size_type pos = s.find_first_not_of(" \t");
17022 if (pos == 0) // We matched a prefix.
17030 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17033 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17034 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17036 std::string AsmStr = IA->getAsmString();
17038 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17039 if (!Ty || Ty->getBitWidth() % 16 != 0)
17042 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17043 SmallVector<StringRef, 4> AsmPieces;
17044 SplitString(AsmStr, AsmPieces, ";\n");
17046 switch (AsmPieces.size()) {
17047 default: return false;
17049 // FIXME: this should verify that we are targeting a 486 or better. If not,
17050 // we will turn this bswap into something that will be lowered to logical
17051 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17052 // lower so don't worry about this.
17054 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17055 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17056 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17057 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17058 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17059 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17060 // No need to check constraints, nothing other than the equivalent of
17061 // "=r,0" would be valid here.
17062 return IntrinsicLowering::LowerToByteSwap(CI);
17065 // rorw $$8, ${0:w} --> llvm.bswap.i16
17066 if (CI->getType()->isIntegerTy(16) &&
17067 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17068 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17069 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17071 const std::string &ConstraintsStr = IA->getConstraintString();
17072 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17073 std::sort(AsmPieces.begin(), AsmPieces.end());
17074 if (AsmPieces.size() == 4 &&
17075 AsmPieces[0] == "~{cc}" &&
17076 AsmPieces[1] == "~{dirflag}" &&
17077 AsmPieces[2] == "~{flags}" &&
17078 AsmPieces[3] == "~{fpsr}")
17079 return IntrinsicLowering::LowerToByteSwap(CI);
17083 if (CI->getType()->isIntegerTy(32) &&
17084 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17085 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17086 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17087 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17089 const std::string &ConstraintsStr = IA->getConstraintString();
17090 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17091 std::sort(AsmPieces.begin(), AsmPieces.end());
17092 if (AsmPieces.size() == 4 &&
17093 AsmPieces[0] == "~{cc}" &&
17094 AsmPieces[1] == "~{dirflag}" &&
17095 AsmPieces[2] == "~{flags}" &&
17096 AsmPieces[3] == "~{fpsr}")
17097 return IntrinsicLowering::LowerToByteSwap(CI);
17100 if (CI->getType()->isIntegerTy(64)) {
17101 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17102 if (Constraints.size() >= 2 &&
17103 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17104 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17105 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17106 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17107 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17108 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17109 return IntrinsicLowering::LowerToByteSwap(CI);
17119 /// getConstraintType - Given a constraint letter, return the type of
17120 /// constraint it is for this target.
17121 X86TargetLowering::ConstraintType
17122 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17123 if (Constraint.size() == 1) {
17124 switch (Constraint[0]) {
17135 return C_RegisterClass;
17159 return TargetLowering::getConstraintType(Constraint);
17162 /// Examine constraint type and operand type and determine a weight value.
17163 /// This object must already have been set up with the operand type
17164 /// and the current alternative constraint selected.
17165 TargetLowering::ConstraintWeight
17166 X86TargetLowering::getSingleConstraintMatchWeight(
17167 AsmOperandInfo &info, const char *constraint) const {
17168 ConstraintWeight weight = CW_Invalid;
17169 Value *CallOperandVal = info.CallOperandVal;
17170 // If we don't have a value, we can't do a match,
17171 // but allow it at the lowest weight.
17172 if (CallOperandVal == NULL)
17174 Type *type = CallOperandVal->getType();
17175 // Look at the constraint type.
17176 switch (*constraint) {
17178 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17189 if (CallOperandVal->getType()->isIntegerTy())
17190 weight = CW_SpecificReg;
17195 if (type->isFloatingPointTy())
17196 weight = CW_SpecificReg;
17199 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17200 weight = CW_SpecificReg;
17204 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17205 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17206 weight = CW_Register;
17209 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17210 if (C->getZExtValue() <= 31)
17211 weight = CW_Constant;
17215 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17216 if (C->getZExtValue() <= 63)
17217 weight = CW_Constant;
17221 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17222 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17223 weight = CW_Constant;
17227 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17228 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17229 weight = CW_Constant;
17233 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17234 if (C->getZExtValue() <= 3)
17235 weight = CW_Constant;
17239 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17240 if (C->getZExtValue() <= 0xff)
17241 weight = CW_Constant;
17246 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17247 weight = CW_Constant;
17251 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17252 if ((C->getSExtValue() >= -0x80000000LL) &&
17253 (C->getSExtValue() <= 0x7fffffffLL))
17254 weight = CW_Constant;
17258 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17259 if (C->getZExtValue() <= 0xffffffff)
17260 weight = CW_Constant;
17267 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17268 /// with another that has more specific requirements based on the type of the
17269 /// corresponding operand.
17270 const char *X86TargetLowering::
17271 LowerXConstraint(EVT ConstraintVT) const {
17272 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17273 // 'f' like normal targets.
17274 if (ConstraintVT.isFloatingPoint()) {
17275 if (Subtarget->hasSSE2())
17277 if (Subtarget->hasSSE1())
17281 return TargetLowering::LowerXConstraint(ConstraintVT);
17284 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17285 /// vector. If it is invalid, don't add anything to Ops.
17286 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17287 std::string &Constraint,
17288 std::vector<SDValue>&Ops,
17289 SelectionDAG &DAG) const {
17290 SDValue Result(0, 0);
17292 // Only support length 1 constraints for now.
17293 if (Constraint.length() > 1) return;
17295 char ConstraintLetter = Constraint[0];
17296 switch (ConstraintLetter) {
17299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17300 if (C->getZExtValue() <= 31) {
17301 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17308 if (C->getZExtValue() <= 63) {
17309 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17315 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17316 if (isInt<8>(C->getSExtValue())) {
17317 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17323 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17324 if (C->getZExtValue() <= 255) {
17325 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17331 // 32-bit signed value
17332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17333 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17334 C->getSExtValue())) {
17335 // Widen to 64 bits here to get it sign extended.
17336 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17339 // FIXME gcc accepts some relocatable values here too, but only in certain
17340 // memory models; it's complicated.
17345 // 32-bit unsigned value
17346 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17347 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17348 C->getZExtValue())) {
17349 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17353 // FIXME gcc accepts some relocatable values here too, but only in certain
17354 // memory models; it's complicated.
17358 // Literal immediates are always ok.
17359 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17360 // Widen to 64 bits here to get it sign extended.
17361 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17365 // In any sort of PIC mode addresses need to be computed at runtime by
17366 // adding in a register or some sort of table lookup. These can't
17367 // be used as immediates.
17368 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17371 // If we are in non-pic codegen mode, we allow the address of a global (with
17372 // an optional displacement) to be used with 'i'.
17373 GlobalAddressSDNode *GA = 0;
17374 int64_t Offset = 0;
17376 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17378 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17379 Offset += GA->getOffset();
17381 } else if (Op.getOpcode() == ISD::ADD) {
17382 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17383 Offset += C->getZExtValue();
17384 Op = Op.getOperand(0);
17387 } else if (Op.getOpcode() == ISD::SUB) {
17388 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17389 Offset += -C->getZExtValue();
17390 Op = Op.getOperand(0);
17395 // Otherwise, this isn't something we can handle, reject it.
17399 const GlobalValue *GV = GA->getGlobal();
17400 // If we require an extra load to get this address, as in PIC mode, we
17401 // can't accept it.
17402 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17403 getTargetMachine())))
17406 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17407 GA->getValueType(0), Offset);
17412 if (Result.getNode()) {
17413 Ops.push_back(Result);
17416 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17419 std::pair<unsigned, const TargetRegisterClass*>
17420 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17422 // First, see if this is a constraint that directly corresponds to an LLVM
17424 if (Constraint.size() == 1) {
17425 // GCC Constraint Letters
17426 switch (Constraint[0]) {
17428 // TODO: Slight differences here in allocation order and leaving
17429 // RIP in the class. Do they matter any more here than they do
17430 // in the normal allocation?
17431 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17432 if (Subtarget->is64Bit()) {
17433 if (VT == MVT::i32 || VT == MVT::f32)
17434 return std::make_pair(0U, &X86::GR32RegClass);
17435 if (VT == MVT::i16)
17436 return std::make_pair(0U, &X86::GR16RegClass);
17437 if (VT == MVT::i8 || VT == MVT::i1)
17438 return std::make_pair(0U, &X86::GR8RegClass);
17439 if (VT == MVT::i64 || VT == MVT::f64)
17440 return std::make_pair(0U, &X86::GR64RegClass);
17443 // 32-bit fallthrough
17444 case 'Q': // Q_REGS
17445 if (VT == MVT::i32 || VT == MVT::f32)
17446 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17447 if (VT == MVT::i16)
17448 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17449 if (VT == MVT::i8 || VT == MVT::i1)
17450 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17451 if (VT == MVT::i64)
17452 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17454 case 'r': // GENERAL_REGS
17455 case 'l': // INDEX_REGS
17456 if (VT == MVT::i8 || VT == MVT::i1)
17457 return std::make_pair(0U, &X86::GR8RegClass);
17458 if (VT == MVT::i16)
17459 return std::make_pair(0U, &X86::GR16RegClass);
17460 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17461 return std::make_pair(0U, &X86::GR32RegClass);
17462 return std::make_pair(0U, &X86::GR64RegClass);
17463 case 'R': // LEGACY_REGS
17464 if (VT == MVT::i8 || VT == MVT::i1)
17465 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17466 if (VT == MVT::i16)
17467 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17468 if (VT == MVT::i32 || !Subtarget->is64Bit())
17469 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17470 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17471 case 'f': // FP Stack registers.
17472 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17473 // value to the correct fpstack register class.
17474 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17475 return std::make_pair(0U, &X86::RFP32RegClass);
17476 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17477 return std::make_pair(0U, &X86::RFP64RegClass);
17478 return std::make_pair(0U, &X86::RFP80RegClass);
17479 case 'y': // MMX_REGS if MMX allowed.
17480 if (!Subtarget->hasMMX()) break;
17481 return std::make_pair(0U, &X86::VR64RegClass);
17482 case 'Y': // SSE_REGS if SSE2 allowed
17483 if (!Subtarget->hasSSE2()) break;
17485 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17486 if (!Subtarget->hasSSE1()) break;
17488 switch (VT.getSimpleVT().SimpleTy) {
17490 // Scalar SSE types.
17493 return std::make_pair(0U, &X86::FR32RegClass);
17496 return std::make_pair(0U, &X86::FR64RegClass);
17504 return std::make_pair(0U, &X86::VR128RegClass);
17512 return std::make_pair(0U, &X86::VR256RegClass);
17518 // Use the default implementation in TargetLowering to convert the register
17519 // constraint into a member of a register class.
17520 std::pair<unsigned, const TargetRegisterClass*> Res;
17521 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17523 // Not found as a standard register?
17524 if (Res.second == 0) {
17525 // Map st(0) -> st(7) -> ST0
17526 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17527 tolower(Constraint[1]) == 's' &&
17528 tolower(Constraint[2]) == 't' &&
17529 Constraint[3] == '(' &&
17530 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17531 Constraint[5] == ')' &&
17532 Constraint[6] == '}') {
17534 Res.first = X86::ST0+Constraint[4]-'0';
17535 Res.second = &X86::RFP80RegClass;
17539 // GCC allows "st(0)" to be called just plain "st".
17540 if (StringRef("{st}").equals_lower(Constraint)) {
17541 Res.first = X86::ST0;
17542 Res.second = &X86::RFP80RegClass;
17547 if (StringRef("{flags}").equals_lower(Constraint)) {
17548 Res.first = X86::EFLAGS;
17549 Res.second = &X86::CCRRegClass;
17553 // 'A' means EAX + EDX.
17554 if (Constraint == "A") {
17555 Res.first = X86::EAX;
17556 Res.second = &X86::GR32_ADRegClass;
17562 // Otherwise, check to see if this is a register class of the wrong value
17563 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17564 // turn into {ax},{dx}.
17565 if (Res.second->hasType(VT))
17566 return Res; // Correct type already, nothing to do.
17568 // All of the single-register GCC register classes map their values onto
17569 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17570 // really want an 8-bit or 32-bit register, map to the appropriate register
17571 // class and return the appropriate register.
17572 if (Res.second == &X86::GR16RegClass) {
17573 if (VT == MVT::i8) {
17574 unsigned DestReg = 0;
17575 switch (Res.first) {
17577 case X86::AX: DestReg = X86::AL; break;
17578 case X86::DX: DestReg = X86::DL; break;
17579 case X86::CX: DestReg = X86::CL; break;
17580 case X86::BX: DestReg = X86::BL; break;
17583 Res.first = DestReg;
17584 Res.second = &X86::GR8RegClass;
17586 } else if (VT == MVT::i32) {
17587 unsigned DestReg = 0;
17588 switch (Res.first) {
17590 case X86::AX: DestReg = X86::EAX; break;
17591 case X86::DX: DestReg = X86::EDX; break;
17592 case X86::CX: DestReg = X86::ECX; break;
17593 case X86::BX: DestReg = X86::EBX; break;
17594 case X86::SI: DestReg = X86::ESI; break;
17595 case X86::DI: DestReg = X86::EDI; break;
17596 case X86::BP: DestReg = X86::EBP; break;
17597 case X86::SP: DestReg = X86::ESP; break;
17600 Res.first = DestReg;
17601 Res.second = &X86::GR32RegClass;
17603 } else if (VT == MVT::i64) {
17604 unsigned DestReg = 0;
17605 switch (Res.first) {
17607 case X86::AX: DestReg = X86::RAX; break;
17608 case X86::DX: DestReg = X86::RDX; break;
17609 case X86::CX: DestReg = X86::RCX; break;
17610 case X86::BX: DestReg = X86::RBX; break;
17611 case X86::SI: DestReg = X86::RSI; break;
17612 case X86::DI: DestReg = X86::RDI; break;
17613 case X86::BP: DestReg = X86::RBP; break;
17614 case X86::SP: DestReg = X86::RSP; break;
17617 Res.first = DestReg;
17618 Res.second = &X86::GR64RegClass;
17621 } else if (Res.second == &X86::FR32RegClass ||
17622 Res.second == &X86::FR64RegClass ||
17623 Res.second == &X86::VR128RegClass) {
17624 // Handle references to XMM physical registers that got mapped into the
17625 // wrong class. This can happen with constraints like {xmm0} where the
17626 // target independent register mapper will just pick the first match it can
17627 // find, ignoring the required type.
17629 if (VT == MVT::f32 || VT == MVT::i32)
17630 Res.second = &X86::FR32RegClass;
17631 else if (VT == MVT::f64 || VT == MVT::i64)
17632 Res.second = &X86::FR64RegClass;
17633 else if (X86::VR128RegClass.hasType(VT))
17634 Res.second = &X86::VR128RegClass;
17635 else if (X86::VR256RegClass.hasType(VT))
17636 Res.second = &X86::VR256RegClass;
17642 //===----------------------------------------------------------------------===//
17646 //===----------------------------------------------------------------------===//
17648 struct X86CostTblEntry {
17655 FindInTable(const X86CostTblEntry *Tbl, unsigned len, int ISD, MVT Ty) {
17656 for (unsigned int i = 0; i < len; ++i)
17657 if (Tbl[i].ISD == ISD && Tbl[i].Type == Ty)
17660 // Could not find an entry.
17664 struct X86TypeConversionCostTblEntry {
17672 FindInConvertTable(const X86TypeConversionCostTblEntry *Tbl, unsigned len,
17673 int ISD, MVT Dst, MVT Src) {
17674 for (unsigned int i = 0; i < len; ++i)
17675 if (Tbl[i].ISD == ISD && Tbl[i].Src == Src && Tbl[i].Dst == Dst)
17678 // Could not find an entry.
17682 ScalarTargetTransformInfo::PopcntHwSupport
17683 X86ScalarTargetTransformImpl::getPopcntHwSupport(unsigned TyWidth) const {
17684 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
17685 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17687 // TODO: Currently the __builtin_popcount() implementation using SSE3
17688 // instructions is inefficient. Once the problem is fixed, we should
17689 // call ST.hasSSE3() instead of ST.hasSSE4().
17690 return ST.hasSSE41() ? Fast : None;
17694 X86VectorTargetTransformInfo::getArithmeticInstrCost(unsigned Opcode,
17696 // Legalize the type.
17697 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Ty);
17699 int ISD = InstructionOpcodeToISD(Opcode);
17700 assert(ISD && "Invalid opcode");
17702 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17704 static const X86CostTblEntry AVX1CostTable[] = {
17705 // We don't have to scalarize unsupported ops. We can issue two half-sized
17706 // operations and we only need to extract the upper YMM half.
17707 // Two ops + 1 extract + 1 insert = 4.
17708 { ISD::MUL, MVT::v8i32, 4 },
17709 { ISD::SUB, MVT::v8i32, 4 },
17710 { ISD::ADD, MVT::v8i32, 4 },
17711 { ISD::MUL, MVT::v4i64, 4 },
17712 { ISD::SUB, MVT::v4i64, 4 },
17713 { ISD::ADD, MVT::v4i64, 4 },
17716 // Look for AVX1 lowering tricks.
17718 int Idx = FindInTable(AVX1CostTable, array_lengthof(AVX1CostTable), ISD,
17721 return LT.first * AVX1CostTable[Idx].Cost;
17723 // Fallback to the default implementation.
17724 return VectorTargetTransformImpl::getArithmeticInstrCost(Opcode, Ty);
17728 X86VectorTargetTransformInfo::getVectorInstrCost(unsigned Opcode, Type *Val,
17729 unsigned Index) const {
17730 assert(Val->isVectorTy() && "This must be a vector type");
17732 if (Index != -1U) {
17733 // Legalize the type.
17734 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(Val);
17736 // This type is legalized to a scalar type.
17737 if (!LT.second.isVector())
17740 // The type may be split. Normalize the index to the new type.
17741 unsigned Width = LT.second.getVectorNumElements();
17742 Index = Index % Width;
17744 // Floating point scalars are already located in index #0.
17745 if (Val->getScalarType()->isFloatingPointTy() && Index == 0)
17749 return VectorTargetTransformImpl::getVectorInstrCost(Opcode, Val, Index);
17752 unsigned X86VectorTargetTransformInfo::getCmpSelInstrCost(unsigned Opcode,
17754 Type *CondTy) const {
17755 // Legalize the type.
17756 std::pair<unsigned, MVT> LT = getTypeLegalizationCost(ValTy);
17758 MVT MTy = LT.second;
17760 int ISD = InstructionOpcodeToISD(Opcode);
17761 assert(ISD && "Invalid opcode");
17763 const X86Subtarget &ST =
17764 TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17766 static const X86CostTblEntry SSE42CostTbl[] = {
17767 { ISD::SETCC, MVT::v2f64, 1 },
17768 { ISD::SETCC, MVT::v4f32, 1 },
17769 { ISD::SETCC, MVT::v2i64, 1 },
17770 { ISD::SETCC, MVT::v4i32, 1 },
17771 { ISD::SETCC, MVT::v8i16, 1 },
17772 { ISD::SETCC, MVT::v16i8, 1 },
17775 static const X86CostTblEntry AVX1CostTbl[] = {
17776 { ISD::SETCC, MVT::v4f64, 1 },
17777 { ISD::SETCC, MVT::v8f32, 1 },
17778 // AVX1 does not support 8-wide integer compare.
17779 { ISD::SETCC, MVT::v4i64, 4 },
17780 { ISD::SETCC, MVT::v8i32, 4 },
17781 { ISD::SETCC, MVT::v16i16, 4 },
17782 { ISD::SETCC, MVT::v32i8, 4 },
17785 static const X86CostTblEntry AVX2CostTbl[] = {
17786 { ISD::SETCC, MVT::v4i64, 1 },
17787 { ISD::SETCC, MVT::v8i32, 1 },
17788 { ISD::SETCC, MVT::v16i16, 1 },
17789 { ISD::SETCC, MVT::v32i8, 1 },
17792 if (ST.hasSSE42()) {
17793 int Idx = FindInTable(SSE42CostTbl, array_lengthof(SSE42CostTbl), ISD, MTy);
17795 return LT.first * SSE42CostTbl[Idx].Cost;
17799 int Idx = FindInTable(AVX1CostTbl, array_lengthof(AVX1CostTbl), ISD, MTy);
17801 return LT.first * AVX1CostTbl[Idx].Cost;
17804 if (ST.hasAVX2()) {
17805 int Idx = FindInTable(AVX2CostTbl, array_lengthof(AVX2CostTbl), ISD, MTy);
17807 return LT.first * AVX2CostTbl[Idx].Cost;
17810 return VectorTargetTransformImpl::getCmpSelInstrCost(Opcode, ValTy, CondTy);
17813 unsigned X86VectorTargetTransformInfo::getCastInstrCost(unsigned Opcode,
17816 int ISD = InstructionOpcodeToISD(Opcode);
17817 assert(ISD && "Invalid opcode");
17819 EVT SrcTy = TLI->getValueType(Src);
17820 EVT DstTy = TLI->getValueType(Dst);
17822 if (!SrcTy.isSimple() || !DstTy.isSimple())
17823 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);
17825 const X86Subtarget &ST = TLI->getTargetMachine().getSubtarget<X86Subtarget>();
17827 static const X86TypeConversionCostTblEntry AVXConversionTbl[] = {
17828 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
17829 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1 },
17830 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
17831 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 1 },
17832 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 1 },
17833 { ISD::TRUNCATE, MVT::v8i16, MVT::v8i32, 1 },
17834 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
17835 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
17836 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 1 },
17837 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 1 },
17838 { ISD::FP_TO_SINT, MVT::v8i8, MVT::v8f32, 1 },
17839 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 1 },
17840 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i1, 6 },
17841 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i1, 9 },
17842 { ISD::TRUNCATE, MVT::v8i32, MVT::v8i64, 3 },
17846 int Idx = FindInConvertTable(AVXConversionTbl,
17847 array_lengthof(AVXConversionTbl),
17848 ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT());
17850 return AVXConversionTbl[Idx].Cost;
17853 return VectorTargetTransformImpl::getCastInstrCost(Opcode, Dst, Src);