1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
161 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
163 RegInfo = TM.getRegisterInfo();
164 TD = getDataLayout();
166 // Set up the TargetLowering object.
167 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
169 // X86 is weird, it always uses i8 for shift amounts and setcc results.
170 setBooleanContents(ZeroOrOneBooleanContent);
171 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
172 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174 // For 64-bit since we have so many registers use the ILP scheduler, for
175 // 32-bit code use the register pressure specific scheduling.
176 // For Atom, always use ILP scheduling.
177 if (Subtarget->isAtom())
178 setSchedulingPreference(Sched::ILP);
179 else if (Subtarget->is64Bit())
180 setSchedulingPreference(Sched::ILP);
182 setSchedulingPreference(Sched::RegPressure);
183 setStackPointerRegisterToSaveRestore(X86StackPtr);
185 // Bypass i32 with i8 on Atom when compiling with O2
186 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
187 addBypassSlowDiv(32, 8);
189 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
190 // Setup Windows compiler runtime calls.
191 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
192 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
193 setLibcallName(RTLIB::SREM_I64, "_allrem");
194 setLibcallName(RTLIB::UREM_I64, "_aullrem");
195 setLibcallName(RTLIB::MUL_I64, "_allmul");
196 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
200 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
202 // The _ftol2 runtime function has an unusual calling conv, which
203 // is modeled by a special pseudo-instruction.
204 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
206 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
207 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
210 if (Subtarget->isTargetDarwin()) {
211 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
212 setUseUnderscoreSetJmp(false);
213 setUseUnderscoreLongJmp(false);
214 } else if (Subtarget->isTargetMingw()) {
215 // MS runtime is weird: it exports _setjmp, but longjmp!
216 setUseUnderscoreSetJmp(true);
217 setUseUnderscoreLongJmp(false);
219 setUseUnderscoreSetJmp(true);
220 setUseUnderscoreLongJmp(true);
223 // Set up the register classes.
224 addRegisterClass(MVT::i8, &X86::GR8RegClass);
225 addRegisterClass(MVT::i16, &X86::GR16RegClass);
226 addRegisterClass(MVT::i32, &X86::GR32RegClass);
227 if (Subtarget->is64Bit())
228 addRegisterClass(MVT::i64, &X86::GR64RegClass);
230 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
232 // We don't accept any truncstore of integer registers.
233 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
235 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
236 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
237 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
238 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
240 // SETOEQ and SETUNE require checking two conditions.
241 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
243 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
246 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
248 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
250 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
252 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
256 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
257 } else if (!TM.Options.UseSoftFloat) {
258 // We have an algorithm for SSE2->double, and we turn this into a
259 // 64-bit FILD followed by conditional FADD for other targets.
260 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
261 // We have an algorithm for SSE2, and we turn this into a 64-bit
262 // FILD for other targets.
263 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
266 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
268 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
271 if (!TM.Options.UseSoftFloat) {
272 // SSE has no i16 to fp conversion, only i32
273 if (X86ScalarSSEf32) {
274 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
275 // f32 and f64 cases are Legal, f80 case is not
276 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
283 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
286 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
287 // are Legal, f80 is custom lowered.
288 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
289 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
291 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
293 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
294 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
296 if (X86ScalarSSEf32) {
297 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
298 // f32 and f64 cases are Legal, f80 case is not
299 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
302 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
305 // Handle FP_TO_UINT by promoting the destination to a larger signed
307 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
309 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
313 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
314 } else if (!TM.Options.UseSoftFloat) {
315 // Since AVX is a superset of SSE3, only check for SSE here.
316 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
317 // Expand FP_TO_UINT into a select.
318 // FIXME: We would like to use a Custom expander here eventually to do
319 // the optimal thing for SSE vs. the default expansion in the legalizer.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
322 // With SSE3 we can use fisttpll to convert to a signed i64; without
323 // SSE, we're stuck with a fistpll.
324 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
327 if (isTargetFTOL()) {
328 // Use the _ftol2 runtime function, which has a pseudo-instruction
329 // to handle its weird calling convention.
330 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
333 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
334 if (!X86ScalarSSEf64) {
335 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
336 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
339 // Without SSE, i64->f64 goes through memory.
340 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
344 // Scalar integer divide and remainder are lowered to use operations that
345 // produce two results, to match the available instructions. This exposes
346 // the two-result form to trivial CSE, which is able to combine x/y and x%y
347 // into a single instruction.
349 // Scalar integer multiply-high is also lowered to use two-result
350 // operations, to match the available instructions. However, plain multiply
351 // (low) operations are left as Legal, as there are single-result
352 // instructions for this in x86. Using the two-result multiply instructions
353 // when both high and low results are needed must be arranged by dagcombine.
354 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
356 setOperationAction(ISD::MULHS, VT, Expand);
357 setOperationAction(ISD::MULHU, VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::UDIV, VT, Expand);
360 setOperationAction(ISD::SREM, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
363 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
364 setOperationAction(ISD::ADDC, VT, Custom);
365 setOperationAction(ISD::ADDE, VT, Custom);
366 setOperationAction(ISD::SUBC, VT, Custom);
367 setOperationAction(ISD::SUBE, VT, Custom);
370 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
371 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
372 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
373 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
374 if (Subtarget->is64Bit())
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
379 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f32 , Expand);
381 setOperationAction(ISD::FREM , MVT::f64 , Expand);
382 setOperationAction(ISD::FREM , MVT::f80 , Expand);
383 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
385 // Promote the i8 variants and force them on up to i32 which has a shorter
387 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
388 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
390 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
391 if (Subtarget->hasBMI()) {
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
393 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
394 if (Subtarget->is64Bit())
395 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
397 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
398 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
399 if (Subtarget->is64Bit())
400 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
403 if (Subtarget->hasLZCNT()) {
404 // When promoting the i8 variants, force them to i32 for a shorter
406 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
407 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
409 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
411 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
412 if (Subtarget->is64Bit())
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
417 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
420 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
427 if (Subtarget->hasPOPCNT()) {
428 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
430 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
432 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
433 if (Subtarget->is64Bit())
434 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
437 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
438 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
440 // These should be promoted to a larger select which is supported.
441 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
442 // X86 wants to expand cmov itself.
443 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
445 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
448 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
451 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
454 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
455 if (Subtarget->is64Bit()) {
456 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
457 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
459 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
460 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
461 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
462 // support continuation, user-level threading, and etc.. As a result, no
463 // other SjLj exception interfaces are implemented and please don't build
464 // your own exception handling based on them.
465 // LLVM/Clang supports zero-cost DWARF exception handling.
466 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
467 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
470 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
471 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
473 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
474 if (Subtarget->is64Bit())
475 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
476 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
477 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
478 if (Subtarget->is64Bit()) {
479 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
480 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
481 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
482 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
483 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
485 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
486 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
488 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
489 if (Subtarget->is64Bit()) {
490 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
492 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
495 if (Subtarget->hasSSE1())
496 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
498 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
499 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
501 // On X86 and X86-64, atomic operations are lowered to locked instructions.
502 // Locked instructions, in turn, have implicit fence semantics (all memory
503 // operations are flushed before issuing the locked instruction, and they
504 // are not buffered), so we can fold away the common pattern of
505 // fence-atomic-fence.
506 setShouldFoldAtomicFences(true);
508 // Expand certain atomics
509 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
511 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
512 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
513 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
516 if (!Subtarget->is64Bit()) {
517 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
528 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
531 if (Subtarget->hasCmpxchg16b()) {
532 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
535 // FIXME - use subtarget debug flags
536 if (!Subtarget->isTargetDarwin() &&
537 !Subtarget->isTargetELF() &&
538 !Subtarget->isTargetCygMing()) {
539 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
542 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
543 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
544 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
545 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
546 if (Subtarget->is64Bit()) {
547 setExceptionPointerRegister(X86::RAX);
548 setExceptionSelectorRegister(X86::RDX);
550 setExceptionPointerRegister(X86::EAX);
551 setExceptionSelectorRegister(X86::EDX);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
554 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
556 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
557 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
559 setOperationAction(ISD::TRAP, MVT::Other, Legal);
560 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
562 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
563 setOperationAction(ISD::VASTART , MVT::Other, Custom);
564 setOperationAction(ISD::VAEND , MVT::Other, Expand);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::VAARG , MVT::Other, Custom);
567 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
569 setOperationAction(ISD::VAARG , MVT::Other, Expand);
570 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
573 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
574 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
576 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
577 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
578 MVT::i64 : MVT::i32, Custom);
579 else if (TM.Options.EnableSegmentedStacks)
580 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
581 MVT::i64 : MVT::i32, Custom);
583 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
584 MVT::i64 : MVT::i32, Expand);
586 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
587 // f32 and f64 use SSE.
588 // Set up the FP register classes.
589 addRegisterClass(MVT::f32, &X86::FR32RegClass);
590 addRegisterClass(MVT::f64, &X86::FR64RegClass);
592 // Use ANDPD to simulate FABS.
593 setOperationAction(ISD::FABS , MVT::f64, Custom);
594 setOperationAction(ISD::FABS , MVT::f32, Custom);
596 // Use XORP to simulate FNEG.
597 setOperationAction(ISD::FNEG , MVT::f64, Custom);
598 setOperationAction(ISD::FNEG , MVT::f32, Custom);
600 // Use ANDPD and ORPD to simulate FCOPYSIGN.
601 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
602 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
604 // Lower this to FGETSIGNx86 plus an AND.
605 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
606 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
608 // We don't support sin/cos/fmod
609 setOperationAction(ISD::FSIN , MVT::f64, Expand);
610 setOperationAction(ISD::FCOS , MVT::f64, Expand);
611 setOperationAction(ISD::FSIN , MVT::f32, Expand);
612 setOperationAction(ISD::FCOS , MVT::f32, Expand);
614 // Expand FP immediates into loads from the stack, except for the special
616 addLegalFPImmediate(APFloat(+0.0)); // xorpd
617 addLegalFPImmediate(APFloat(+0.0f)); // xorps
618 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
619 // Use SSE for f32, x87 for f64.
620 // Set up the FP register classes.
621 addRegisterClass(MVT::f32, &X86::FR32RegClass);
622 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
624 // Use ANDPS to simulate FABS.
625 setOperationAction(ISD::FABS , MVT::f32, Custom);
627 // Use XORP to simulate FNEG.
628 setOperationAction(ISD::FNEG , MVT::f32, Custom);
630 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
632 // Use ANDPS and ORPS to simulate FCOPYSIGN.
633 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
634 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
636 // We don't support sin/cos/fmod
637 setOperationAction(ISD::FSIN , MVT::f32, Expand);
638 setOperationAction(ISD::FCOS , MVT::f32, Expand);
640 // Special cases we handle for FP constants.
641 addLegalFPImmediate(APFloat(+0.0f)); // xorps
642 addLegalFPImmediate(APFloat(+0.0)); // FLD0
643 addLegalFPImmediate(APFloat(+1.0)); // FLD1
644 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
645 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647 if (!TM.Options.UnsafeFPMath) {
648 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
649 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
651 } else if (!TM.Options.UseSoftFloat) {
652 // f32 and f64 in x87.
653 // Set up the FP register classes.
654 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
655 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
657 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
658 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
660 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
662 if (!TM.Options.UnsafeFPMath) {
663 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
664 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
666 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
668 addLegalFPImmediate(APFloat(+0.0)); // FLD0
669 addLegalFPImmediate(APFloat(+1.0)); // FLD1
670 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
673 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
674 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
675 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
678 // We don't support FMA.
679 setOperationAction(ISD::FMA, MVT::f64, Expand);
680 setOperationAction(ISD::FMA, MVT::f32, Expand);
682 // Long double always uses X87.
683 if (!TM.Options.UseSoftFloat) {
684 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
685 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
686 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
688 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
689 addLegalFPImmediate(TmpFlt); // FLD0
691 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
694 APFloat TmpFlt2(+1.0);
695 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
697 addLegalFPImmediate(TmpFlt2); // FLD1
698 TmpFlt2.changeSign();
699 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
702 if (!TM.Options.UnsafeFPMath) {
703 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
704 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
707 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
708 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
709 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
710 setOperationAction(ISD::FRINT, MVT::f80, Expand);
711 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
712 setOperationAction(ISD::FMA, MVT::f80, Expand);
715 // Always use a library call for pow.
716 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
718 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
720 setOperationAction(ISD::FLOG, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
722 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP, MVT::f80, Expand);
724 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
726 // First set operation action for all vector types to either promote
727 // (for widening) or expand (for scalarization). Then we will selectively
728 // turn on ones that can be effectively codegen'd.
729 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
730 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
731 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
749 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FMA, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::FFLOOR, (MVT::SimpleValueType)VT, Expand);
758 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
763 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
764 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
765 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
766 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
767 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
768 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
769 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
770 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
771 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
772 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
773 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
774 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
775 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
776 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
777 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
778 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
779 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
780 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
781 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
782 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
783 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
784 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
785 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
786 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
787 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
788 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
789 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
790 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
791 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
792 setTruncStoreAction((MVT::SimpleValueType)VT,
793 (MVT::SimpleValueType)InnerVT, Expand);
794 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
795 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
796 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
799 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
800 // with -msoft-float, disable use of MMX as well.
801 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
802 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
803 // No operations on x86mmx supported, everything uses intrinsics.
806 // MMX-sized vectors (other than x86mmx) are expected to be expanded
807 // into smaller operations.
808 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
809 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
810 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
811 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
812 setOperationAction(ISD::AND, MVT::v8i8, Expand);
813 setOperationAction(ISD::AND, MVT::v4i16, Expand);
814 setOperationAction(ISD::AND, MVT::v2i32, Expand);
815 setOperationAction(ISD::AND, MVT::v1i64, Expand);
816 setOperationAction(ISD::OR, MVT::v8i8, Expand);
817 setOperationAction(ISD::OR, MVT::v4i16, Expand);
818 setOperationAction(ISD::OR, MVT::v2i32, Expand);
819 setOperationAction(ISD::OR, MVT::v1i64, Expand);
820 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
821 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
822 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
823 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
824 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
829 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
830 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
831 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
832 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
833 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
834 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
835 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
836 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
838 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
839 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
841 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
842 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
843 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
844 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
845 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
846 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
847 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
848 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
849 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
850 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
855 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
856 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
858 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
859 // registers cannot be used even for integer operations.
860 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
861 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
862 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
863 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
865 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
866 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
867 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
868 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
869 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
870 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
871 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
872 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
873 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
874 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
875 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
876 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
877 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
878 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
879 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
880 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
881 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
883 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
884 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
885 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
886 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
888 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
889 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
891 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
892 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896 MVT VT = (MVT::SimpleValueType)i;
897 // Do not attempt to custom lower non-power-of-2 vectors
898 if (!isPowerOf2_32(VT.getVectorNumElements()))
900 // Do not attempt to custom lower non-128-bit vectors
901 if (!VT.is128BitVector())
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
909 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
910 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
911 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
915 if (Subtarget->is64Bit()) {
916 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
917 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
920 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
921 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
922 MVT VT = (MVT::SimpleValueType)i;
924 // Do not attempt to promote non-128-bit vectors
925 if (!VT.is128BitVector())
928 setOperationAction(ISD::AND, VT, Promote);
929 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
930 setOperationAction(ISD::OR, VT, Promote);
931 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
932 setOperationAction(ISD::XOR, VT, Promote);
933 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
934 setOperationAction(ISD::LOAD, VT, Promote);
935 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
936 setOperationAction(ISD::SELECT, VT, Promote);
937 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
940 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // Custom lower v2i64 and v2f64 selects.
943 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
944 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
945 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
946 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
948 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
949 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
951 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
952 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
953 // As there is no 64-bit GPR available, we need build a special custom
954 // sequence to convert from v2i32 to v2f32.
955 if (!Subtarget->is64Bit())
956 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
958 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
959 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
961 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
964 if (Subtarget->hasSSE41()) {
965 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
966 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
967 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
968 setOperationAction(ISD::FRINT, MVT::f32, Legal);
969 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
970 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
973 setOperationAction(ISD::FRINT, MVT::f64, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
976 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
977 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
979 // FIXME: Do we need to handle scalar-to-vector here?
980 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
982 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
983 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
984 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
985 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
986 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
988 // i8 and i16 vectors are custom , because the source register and source
989 // source memory operand types are not the same width. f32 vectors are
990 // custom since the immediate controlling the insert encodes additional
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
994 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
997 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
998 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
999 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1000 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1002 // FIXME: these should be Legal but thats only for the case where
1003 // the index is constant. For now custom expand to deal with that.
1004 if (Subtarget->is64Bit()) {
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1006 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010 if (Subtarget->hasSSE2()) {
1011 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1012 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1014 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1015 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1017 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1018 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1020 if (Subtarget->hasAVX2()) {
1021 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1022 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1024 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1025 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1027 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1029 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1030 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1032 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1033 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1035 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1039 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1040 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1041 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1043 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1044 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1045 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1047 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1048 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1049 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1051 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1052 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1053 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1054 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1055 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1057 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1058 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1060 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1061 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1062 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1063 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1064 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1066 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1067 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1069 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1071 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1073 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1074 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1075 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1077 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1079 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1081 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1083 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1084 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1086 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1087 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1089 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1090 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1092 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1093 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1094 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1095 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1097 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1098 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1099 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1101 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1102 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1103 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1104 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1106 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1107 setOperationAction(ISD::FMA, MVT::v8f32, Custom);
1108 setOperationAction(ISD::FMA, MVT::v4f64, Custom);
1109 setOperationAction(ISD::FMA, MVT::v4f32, Custom);
1110 setOperationAction(ISD::FMA, MVT::v2f64, Custom);
1111 setOperationAction(ISD::FMA, MVT::f32, Custom);
1112 setOperationAction(ISD::FMA, MVT::f64, Custom);
1115 if (Subtarget->hasAVX2()) {
1116 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1117 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1118 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1119 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1121 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1122 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1123 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1124 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1126 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1127 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1128 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1129 // Don't lower v32i8 because there is no 128-bit byte mul
1131 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1133 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1134 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1136 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1137 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1139 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1141 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1142 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1143 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1144 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1146 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1147 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1148 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1149 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1151 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1152 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1153 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1154 // Don't lower v32i8 because there is no 128-bit byte mul
1156 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1157 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1159 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1160 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1162 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1165 // Custom lower several nodes for 256-bit types.
1166 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1167 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1168 MVT VT = (MVT::SimpleValueType)i;
1170 // Extract subvector is special because the value type
1171 // (result) is 128-bit but the source is 256-bit wide.
1172 if (VT.is128BitVector())
1173 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1175 // Do not attempt to custom lower other non-256-bit vectors
1176 if (!VT.is256BitVector())
1179 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1180 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1181 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1182 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1183 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1184 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1185 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1188 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1189 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1190 MVT VT = (MVT::SimpleValueType)i;
1192 // Do not attempt to promote non-256-bit vectors
1193 if (!VT.is256BitVector())
1196 setOperationAction(ISD::AND, VT, Promote);
1197 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1198 setOperationAction(ISD::OR, VT, Promote);
1199 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1200 setOperationAction(ISD::XOR, VT, Promote);
1201 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1202 setOperationAction(ISD::LOAD, VT, Promote);
1203 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1204 setOperationAction(ISD::SELECT, VT, Promote);
1205 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1209 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1210 // of this type with custom code.
1211 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1212 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1213 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1217 // We want to custom lower some of our intrinsics.
1218 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1219 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1222 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1223 // handle type legalization for these operations here.
1225 // FIXME: We really should do custom legalization for addition and
1226 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1227 // than generic legalization for 64-bit multiplication-with-overflow, though.
1228 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1229 // Add/Sub/Mul with overflow operations are custom lowered.
1231 setOperationAction(ISD::SADDO, VT, Custom);
1232 setOperationAction(ISD::UADDO, VT, Custom);
1233 setOperationAction(ISD::SSUBO, VT, Custom);
1234 setOperationAction(ISD::USUBO, VT, Custom);
1235 setOperationAction(ISD::SMULO, VT, Custom);
1236 setOperationAction(ISD::UMULO, VT, Custom);
1239 // There are no 8-bit 3-address imul/mul instructions
1240 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1241 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1243 if (!Subtarget->is64Bit()) {
1244 // These libcalls are not available in 32-bit.
1245 setLibcallName(RTLIB::SHL_I128, 0);
1246 setLibcallName(RTLIB::SRL_I128, 0);
1247 setLibcallName(RTLIB::SRA_I128, 0);
1250 // We have target-specific dag combine patterns for the following nodes:
1251 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1252 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1253 setTargetDAGCombine(ISD::VSELECT);
1254 setTargetDAGCombine(ISD::SELECT);
1255 setTargetDAGCombine(ISD::SHL);
1256 setTargetDAGCombine(ISD::SRA);
1257 setTargetDAGCombine(ISD::SRL);
1258 setTargetDAGCombine(ISD::OR);
1259 setTargetDAGCombine(ISD::AND);
1260 setTargetDAGCombine(ISD::ADD);
1261 setTargetDAGCombine(ISD::FADD);
1262 setTargetDAGCombine(ISD::FSUB);
1263 setTargetDAGCombine(ISD::FMA);
1264 setTargetDAGCombine(ISD::SUB);
1265 setTargetDAGCombine(ISD::LOAD);
1266 setTargetDAGCombine(ISD::STORE);
1267 setTargetDAGCombine(ISD::ZERO_EXTEND);
1268 setTargetDAGCombine(ISD::ANY_EXTEND);
1269 setTargetDAGCombine(ISD::SIGN_EXTEND);
1270 setTargetDAGCombine(ISD::TRUNCATE);
1271 setTargetDAGCombine(ISD::SINT_TO_FP);
1272 setTargetDAGCombine(ISD::SETCC);
1273 if (Subtarget->is64Bit())
1274 setTargetDAGCombine(ISD::MUL);
1275 setTargetDAGCombine(ISD::XOR);
1277 computeRegisterProperties();
1279 // On Darwin, -Os means optimize for size without hurting performance,
1280 // do not reduce the limit.
1281 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1282 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1283 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1284 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1285 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1286 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1287 setPrefLoopAlignment(4); // 2^4 bytes.
1288 benefitFromCodePlacementOpt = true;
1290 // Predictable cmov don't hurt on atom because it's in-order.
1291 predictableSelectIsExpensive = !Subtarget->isAtom();
1293 setPrefFunctionAlignment(4); // 2^4 bytes.
1297 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1298 if (!VT.isVector()) return MVT::i8;
1299 return VT.changeVectorElementTypeToInteger();
1303 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1304 /// the desired ByVal argument alignment.
1305 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1308 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1309 if (VTy->getBitWidth() == 128)
1311 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1312 unsigned EltAlign = 0;
1313 getMaxByValAlign(ATy->getElementType(), EltAlign);
1314 if (EltAlign > MaxAlign)
1315 MaxAlign = EltAlign;
1316 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1317 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1318 unsigned EltAlign = 0;
1319 getMaxByValAlign(STy->getElementType(i), EltAlign);
1320 if (EltAlign > MaxAlign)
1321 MaxAlign = EltAlign;
1328 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1329 /// function arguments in the caller parameter area. For X86, aggregates
1330 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1331 /// are at 4-byte boundaries.
1332 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1333 if (Subtarget->is64Bit()) {
1334 // Max of 8 and alignment of type.
1335 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1342 if (Subtarget->hasSSE1())
1343 getMaxByValAlign(Ty, Align);
1347 /// getOptimalMemOpType - Returns the target specific optimal type for load
1348 /// and store operations as a result of memset, memcpy, and memmove
1349 /// lowering. If DstAlign is zero that means it's safe to destination
1350 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1351 /// means there isn't a need to check it against alignment requirement,
1352 /// probably because the source does not need to be loaded. If
1353 /// 'IsZeroVal' is true, that means it's safe to return a
1354 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1355 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1356 /// constant so it does not need to be loaded.
1357 /// It returns EVT::Other if the type should be determined using generic
1358 /// target-independent logic.
1360 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1361 unsigned DstAlign, unsigned SrcAlign,
1364 MachineFunction &MF) const {
1365 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1366 // linux. This is because the stack realignment code can't handle certain
1367 // cases like PR2962. This should be removed when PR2962 is fixed.
1368 const Function *F = MF.getFunction();
1370 !F->getFnAttributes().hasAttribute(Attributes::NoImplicitFloat)) {
1372 (Subtarget->isUnalignedMemAccessFast() ||
1373 ((DstAlign == 0 || DstAlign >= 16) &&
1374 (SrcAlign == 0 || SrcAlign >= 16))) &&
1375 Subtarget->getStackAlignment() >= 16) {
1376 if (Subtarget->getStackAlignment() >= 32) {
1377 if (Subtarget->hasAVX2())
1379 if (Subtarget->hasAVX())
1382 if (Subtarget->hasSSE2())
1384 if (Subtarget->hasSSE1())
1386 } else if (!MemcpyStrSrc && Size >= 8 &&
1387 !Subtarget->is64Bit() &&
1388 Subtarget->getStackAlignment() >= 8 &&
1389 Subtarget->hasSSE2()) {
1390 // Do not use f64 to lower memcpy if source is string constant. It's
1391 // better to use i32 to avoid the loads.
1395 if (Subtarget->is64Bit() && Size >= 8)
1400 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1401 /// current function. The returned value is a member of the
1402 /// MachineJumpTableInfo::JTEntryKind enum.
1403 unsigned X86TargetLowering::getJumpTableEncoding() const {
1404 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1406 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1407 Subtarget->isPICStyleGOT())
1408 return MachineJumpTableInfo::EK_Custom32;
1410 // Otherwise, use the normal jump table encoding heuristics.
1411 return TargetLowering::getJumpTableEncoding();
1415 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1416 const MachineBasicBlock *MBB,
1417 unsigned uid,MCContext &Ctx) const{
1418 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1419 Subtarget->isPICStyleGOT());
1420 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1422 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1423 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1426 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1428 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1429 SelectionDAG &DAG) const {
1430 if (!Subtarget->is64Bit())
1431 // This doesn't have DebugLoc associated with it, but is not really the
1432 // same as a Register.
1433 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1437 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1438 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1440 const MCExpr *X86TargetLowering::
1441 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1442 MCContext &Ctx) const {
1443 // X86-64 uses RIP relative addressing based on the jump table label.
1444 if (Subtarget->isPICStyleRIPRel())
1445 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1447 // Otherwise, the reference is relative to the PIC base.
1448 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1451 // FIXME: Why this routine is here? Move to RegInfo!
1452 std::pair<const TargetRegisterClass*, uint8_t>
1453 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1454 const TargetRegisterClass *RRC = 0;
1456 switch (VT.getSimpleVT().SimpleTy) {
1458 return TargetLowering::findRepresentativeClass(VT);
1459 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1460 RRC = Subtarget->is64Bit() ?
1461 (const TargetRegisterClass*)&X86::GR64RegClass :
1462 (const TargetRegisterClass*)&X86::GR32RegClass;
1465 RRC = &X86::VR64RegClass;
1467 case MVT::f32: case MVT::f64:
1468 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1469 case MVT::v4f32: case MVT::v2f64:
1470 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1472 RRC = &X86::VR128RegClass;
1475 return std::make_pair(RRC, Cost);
1478 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1479 unsigned &Offset) const {
1480 if (!Subtarget->isTargetLinux())
1483 if (Subtarget->is64Bit()) {
1484 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1486 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1499 //===----------------------------------------------------------------------===//
1500 // Return Value Calling Convention Implementation
1501 //===----------------------------------------------------------------------===//
1503 #include "X86GenCallingConv.inc"
1506 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1507 MachineFunction &MF, bool isVarArg,
1508 const SmallVectorImpl<ISD::OutputArg> &Outs,
1509 LLVMContext &Context) const {
1510 SmallVector<CCValAssign, 16> RVLocs;
1511 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1513 return CCInfo.CheckReturn(Outs, RetCC_X86);
1517 X86TargetLowering::LowerReturn(SDValue Chain,
1518 CallingConv::ID CallConv, bool isVarArg,
1519 const SmallVectorImpl<ISD::OutputArg> &Outs,
1520 const SmallVectorImpl<SDValue> &OutVals,
1521 DebugLoc dl, SelectionDAG &DAG) const {
1522 MachineFunction &MF = DAG.getMachineFunction();
1523 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1525 SmallVector<CCValAssign, 16> RVLocs;
1526 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1527 RVLocs, *DAG.getContext());
1528 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1530 // Add the regs to the liveout set for the function.
1531 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1532 for (unsigned i = 0; i != RVLocs.size(); ++i)
1533 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1534 MRI.addLiveOut(RVLocs[i].getLocReg());
1538 SmallVector<SDValue, 6> RetOps;
1539 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1540 // Operand #1 = Bytes To Pop
1541 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1544 // Copy the result values into the output registers.
1545 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1546 CCValAssign &VA = RVLocs[i];
1547 assert(VA.isRegLoc() && "Can only return in registers!");
1548 SDValue ValToCopy = OutVals[i];
1549 EVT ValVT = ValToCopy.getValueType();
1551 // Promote values to the appropriate types
1552 if (VA.getLocInfo() == CCValAssign::SExt)
1553 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1554 else if (VA.getLocInfo() == CCValAssign::ZExt)
1555 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1556 else if (VA.getLocInfo() == CCValAssign::AExt)
1557 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1558 else if (VA.getLocInfo() == CCValAssign::BCvt)
1559 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1561 // If this is x86-64, and we disabled SSE, we can't return FP values,
1562 // or SSE or MMX vectors.
1563 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1564 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1565 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1566 report_fatal_error("SSE register return with SSE disabled");
1568 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1569 // llvm-gcc has never done it right and no one has noticed, so this
1570 // should be OK for now.
1571 if (ValVT == MVT::f64 &&
1572 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1573 report_fatal_error("SSE2 register return with SSE2 disabled");
1575 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1576 // the RET instruction and handled by the FP Stackifier.
1577 if (VA.getLocReg() == X86::ST0 ||
1578 VA.getLocReg() == X86::ST1) {
1579 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1580 // change the value to the FP stack register class.
1581 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1582 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1583 RetOps.push_back(ValToCopy);
1584 // Don't emit a copytoreg.
1588 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1589 // which is returned in RAX / RDX.
1590 if (Subtarget->is64Bit()) {
1591 if (ValVT == MVT::x86mmx) {
1592 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1593 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1594 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1596 // If we don't have SSE2 available, convert to v4f32 so the generated
1597 // register is legal.
1598 if (!Subtarget->hasSSE2())
1599 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1604 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1605 Flag = Chain.getValue(1);
1608 // The x86-64 ABI for returning structs by value requires that we copy
1609 // the sret argument into %rax for the return. We saved the argument into
1610 // a virtual register in the entry block, so now we copy the value out
1612 if (Subtarget->is64Bit() &&
1613 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1614 MachineFunction &MF = DAG.getMachineFunction();
1615 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1616 unsigned Reg = FuncInfo->getSRetReturnReg();
1618 "SRetReturnReg should have been set in LowerFormalArguments().");
1619 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1621 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1622 Flag = Chain.getValue(1);
1624 // RAX now acts like a return value.
1625 MRI.addLiveOut(X86::RAX);
1628 RetOps[0] = Chain; // Update chain.
1630 // Add the flag if we have it.
1632 RetOps.push_back(Flag);
1634 return DAG.getNode(X86ISD::RET_FLAG, dl,
1635 MVT::Other, &RetOps[0], RetOps.size());
1638 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1639 if (N->getNumValues() != 1)
1641 if (!N->hasNUsesOfValue(1, 0))
1644 SDValue TCChain = Chain;
1645 SDNode *Copy = *N->use_begin();
1646 if (Copy->getOpcode() == ISD::CopyToReg) {
1647 // If the copy has a glue operand, we conservatively assume it isn't safe to
1648 // perform a tail call.
1649 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1651 TCChain = Copy->getOperand(0);
1652 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1655 bool HasRet = false;
1656 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1658 if (UI->getOpcode() != X86ISD::RET_FLAG)
1671 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1672 ISD::NodeType ExtendKind) const {
1674 // TODO: Is this also valid on 32-bit?
1675 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1676 ReturnMVT = MVT::i8;
1678 ReturnMVT = MVT::i32;
1680 EVT MinVT = getRegisterType(Context, ReturnMVT);
1681 return VT.bitsLT(MinVT) ? MinVT : VT;
1684 /// LowerCallResult - Lower the result values of a call into the
1685 /// appropriate copies out of appropriate physical registers.
1688 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1689 CallingConv::ID CallConv, bool isVarArg,
1690 const SmallVectorImpl<ISD::InputArg> &Ins,
1691 DebugLoc dl, SelectionDAG &DAG,
1692 SmallVectorImpl<SDValue> &InVals) const {
1694 // Assign locations to each value returned by this call.
1695 SmallVector<CCValAssign, 16> RVLocs;
1696 bool Is64Bit = Subtarget->is64Bit();
1697 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1698 getTargetMachine(), RVLocs, *DAG.getContext());
1699 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1701 // Copy all of the result registers out of their specified physreg.
1702 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1703 CCValAssign &VA = RVLocs[i];
1704 EVT CopyVT = VA.getValVT();
1706 // If this is x86-64, and we disabled SSE, we can't return FP values
1707 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1708 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1709 report_fatal_error("SSE register return with SSE disabled");
1714 // If this is a call to a function that returns an fp value on the floating
1715 // point stack, we must guarantee the value is popped from the stack, so
1716 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1717 // if the return value is not used. We use the FpPOP_RETVAL instruction
1719 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1720 // If we prefer to use the value in xmm registers, copy it out as f80 and
1721 // use a truncate to move it from fp stack reg to xmm reg.
1722 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1723 SDValue Ops[] = { Chain, InFlag };
1724 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1725 MVT::Other, MVT::Glue, Ops, 2), 1);
1726 Val = Chain.getValue(0);
1728 // Round the f80 to the right size, which also moves it to the appropriate
1730 if (CopyVT != VA.getValVT())
1731 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1732 // This truncation won't change the value.
1733 DAG.getIntPtrConstant(1));
1735 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1736 CopyVT, InFlag).getValue(1);
1737 Val = Chain.getValue(0);
1739 InFlag = Chain.getValue(2);
1740 InVals.push_back(Val);
1747 //===----------------------------------------------------------------------===//
1748 // C & StdCall & Fast Calling Convention implementation
1749 //===----------------------------------------------------------------------===//
1750 // StdCall calling convention seems to be standard for many Windows' API
1751 // routines and around. It differs from C calling convention just a little:
1752 // callee should clean up the stack, not caller. Symbols should be also
1753 // decorated in some fancy way :) It doesn't support any vector arguments.
1754 // For info on fast calling convention see Fast Calling Convention (tail call)
1755 // implementation LowerX86_32FastCCCallTo.
1757 /// CallIsStructReturn - Determines whether a call uses struct return
1759 enum StructReturnType {
1764 static StructReturnType
1765 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1767 return NotStructReturn;
1769 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1770 if (!Flags.isSRet())
1771 return NotStructReturn;
1772 if (Flags.isInReg())
1773 return RegStructReturn;
1774 return StackStructReturn;
1777 /// ArgsAreStructReturn - Determines whether a function uses struct
1778 /// return semantics.
1779 static StructReturnType
1780 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1782 return NotStructReturn;
1784 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1785 if (!Flags.isSRet())
1786 return NotStructReturn;
1787 if (Flags.isInReg())
1788 return RegStructReturn;
1789 return StackStructReturn;
1792 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1793 /// by "Src" to address "Dst" with size and alignment information specified by
1794 /// the specific parameter attribute. The copy will be passed as a byval
1795 /// function parameter.
1797 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1798 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1800 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1802 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1803 /*isVolatile*/false, /*AlwaysInline=*/true,
1804 MachinePointerInfo(), MachinePointerInfo());
1807 /// IsTailCallConvention - Return true if the calling convention is one that
1808 /// supports tail call optimization.
1809 static bool IsTailCallConvention(CallingConv::ID CC) {
1810 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1813 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1814 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1818 CallingConv::ID CalleeCC = CS.getCallingConv();
1819 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1825 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1826 /// a tailcall target by changing its ABI.
1827 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1828 bool GuaranteedTailCallOpt) {
1829 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1833 X86TargetLowering::LowerMemArgument(SDValue Chain,
1834 CallingConv::ID CallConv,
1835 const SmallVectorImpl<ISD::InputArg> &Ins,
1836 DebugLoc dl, SelectionDAG &DAG,
1837 const CCValAssign &VA,
1838 MachineFrameInfo *MFI,
1840 // Create the nodes corresponding to a load from this parameter slot.
1841 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1842 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1843 getTargetMachine().Options.GuaranteedTailCallOpt);
1844 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1847 // If value is passed by pointer we have address passed instead of the value
1849 if (VA.getLocInfo() == CCValAssign::Indirect)
1850 ValVT = VA.getLocVT();
1852 ValVT = VA.getValVT();
1854 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1855 // changed with more analysis.
1856 // In case of tail call optimization mark all arguments mutable. Since they
1857 // could be overwritten by lowering of arguments in case of a tail call.
1858 if (Flags.isByVal()) {
1859 unsigned Bytes = Flags.getByValSize();
1860 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1861 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1862 return DAG.getFrameIndex(FI, getPointerTy());
1864 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1865 VA.getLocMemOffset(), isImmutable);
1866 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1867 return DAG.getLoad(ValVT, dl, Chain, FIN,
1868 MachinePointerInfo::getFixedStack(FI),
1869 false, false, false, 0);
1874 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1875 CallingConv::ID CallConv,
1877 const SmallVectorImpl<ISD::InputArg> &Ins,
1880 SmallVectorImpl<SDValue> &InVals)
1882 MachineFunction &MF = DAG.getMachineFunction();
1883 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1885 const Function* Fn = MF.getFunction();
1886 if (Fn->hasExternalLinkage() &&
1887 Subtarget->isTargetCygMing() &&
1888 Fn->getName() == "main")
1889 FuncInfo->setForceFramePointer(true);
1891 MachineFrameInfo *MFI = MF.getFrameInfo();
1892 bool Is64Bit = Subtarget->is64Bit();
1893 bool IsWindows = Subtarget->isTargetWindows();
1894 bool IsWin64 = Subtarget->isTargetWin64();
1896 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1897 "Var args not supported with calling convention fastcc or ghc");
1899 // Assign locations to all of the incoming arguments.
1900 SmallVector<CCValAssign, 16> ArgLocs;
1901 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1902 ArgLocs, *DAG.getContext());
1904 // Allocate shadow area for Win64
1906 CCInfo.AllocateStack(32, 8);
1909 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1911 unsigned LastVal = ~0U;
1913 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1914 CCValAssign &VA = ArgLocs[i];
1915 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1917 assert(VA.getValNo() != LastVal &&
1918 "Don't support value assigned to multiple locs yet");
1920 LastVal = VA.getValNo();
1922 if (VA.isRegLoc()) {
1923 EVT RegVT = VA.getLocVT();
1924 const TargetRegisterClass *RC;
1925 if (RegVT == MVT::i32)
1926 RC = &X86::GR32RegClass;
1927 else if (Is64Bit && RegVT == MVT::i64)
1928 RC = &X86::GR64RegClass;
1929 else if (RegVT == MVT::f32)
1930 RC = &X86::FR32RegClass;
1931 else if (RegVT == MVT::f64)
1932 RC = &X86::FR64RegClass;
1933 else if (RegVT.is256BitVector())
1934 RC = &X86::VR256RegClass;
1935 else if (RegVT.is128BitVector())
1936 RC = &X86::VR128RegClass;
1937 else if (RegVT == MVT::x86mmx)
1938 RC = &X86::VR64RegClass;
1940 llvm_unreachable("Unknown argument type!");
1942 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1943 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1945 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1946 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1948 if (VA.getLocInfo() == CCValAssign::SExt)
1949 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1950 DAG.getValueType(VA.getValVT()));
1951 else if (VA.getLocInfo() == CCValAssign::ZExt)
1952 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1953 DAG.getValueType(VA.getValVT()));
1954 else if (VA.getLocInfo() == CCValAssign::BCvt)
1955 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1957 if (VA.isExtInLoc()) {
1958 // Handle MMX values passed in XMM regs.
1959 if (RegVT.isVector()) {
1960 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1963 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1966 assert(VA.isMemLoc());
1967 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1970 // If value is passed via pointer - do a load.
1971 if (VA.getLocInfo() == CCValAssign::Indirect)
1972 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1973 MachinePointerInfo(), false, false, false, 0);
1975 InVals.push_back(ArgValue);
1978 // The x86-64 ABI for returning structs by value requires that we copy
1979 // the sret argument into %rax for the return. Save the argument into
1980 // a virtual register so that we can access it from the return points.
1981 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1982 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1983 unsigned Reg = FuncInfo->getSRetReturnReg();
1985 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1986 FuncInfo->setSRetReturnReg(Reg);
1988 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1989 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1992 unsigned StackSize = CCInfo.getNextStackOffset();
1993 // Align stack specially for tail calls.
1994 if (FuncIsMadeTailCallSafe(CallConv,
1995 MF.getTarget().Options.GuaranteedTailCallOpt))
1996 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1998 // If the function takes variable number of arguments, make a frame index for
1999 // the start of the first vararg value... for expansion of llvm.va_start.
2001 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2002 CallConv != CallingConv::X86_ThisCall)) {
2003 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2006 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2008 // FIXME: We should really autogenerate these arrays
2009 static const uint16_t GPR64ArgRegsWin64[] = {
2010 X86::RCX, X86::RDX, X86::R8, X86::R9
2012 static const uint16_t GPR64ArgRegs64Bit[] = {
2013 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2015 static const uint16_t XMMArgRegs64Bit[] = {
2016 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2017 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2019 const uint16_t *GPR64ArgRegs;
2020 unsigned NumXMMRegs = 0;
2023 // The XMM registers which might contain var arg parameters are shadowed
2024 // in their paired GPR. So we only need to save the GPR to their home
2026 TotalNumIntRegs = 4;
2027 GPR64ArgRegs = GPR64ArgRegsWin64;
2029 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2030 GPR64ArgRegs = GPR64ArgRegs64Bit;
2032 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2035 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2038 bool NoImplicitFloatOps = Fn->getFnAttributes().
2039 hasAttribute(Attributes::NoImplicitFloat);
2040 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2041 "SSE register cannot be used when SSE is disabled!");
2042 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2043 NoImplicitFloatOps) &&
2044 "SSE register cannot be used when SSE is disabled!");
2045 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2046 !Subtarget->hasSSE1())
2047 // Kernel mode asks for SSE to be disabled, so don't push them
2049 TotalNumXMMRegs = 0;
2052 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2053 // Get to the caller-allocated home save location. Add 8 to account
2054 // for the return address.
2055 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2056 FuncInfo->setRegSaveFrameIndex(
2057 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2058 // Fixup to set vararg frame on shadow area (4 x i64).
2060 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2062 // For X86-64, if there are vararg parameters that are passed via
2063 // registers, then we must store them to their spots on the stack so
2064 // they may be loaded by deferencing the result of va_next.
2065 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2066 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2067 FuncInfo->setRegSaveFrameIndex(
2068 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2072 // Store the integer parameter registers.
2073 SmallVector<SDValue, 8> MemOps;
2074 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2076 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2077 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2078 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2079 DAG.getIntPtrConstant(Offset));
2080 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2081 &X86::GR64RegClass);
2082 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2084 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2085 MachinePointerInfo::getFixedStack(
2086 FuncInfo->getRegSaveFrameIndex(), Offset),
2088 MemOps.push_back(Store);
2092 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2093 // Now store the XMM (fp + vector) parameter registers.
2094 SmallVector<SDValue, 11> SaveXMMOps;
2095 SaveXMMOps.push_back(Chain);
2097 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2098 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2099 SaveXMMOps.push_back(ALVal);
2101 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2102 FuncInfo->getRegSaveFrameIndex()));
2103 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2104 FuncInfo->getVarArgsFPOffset()));
2106 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2107 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2108 &X86::VR128RegClass);
2109 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2110 SaveXMMOps.push_back(Val);
2112 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2114 &SaveXMMOps[0], SaveXMMOps.size()));
2117 if (!MemOps.empty())
2118 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119 &MemOps[0], MemOps.size());
2123 // Some CCs need callee pop.
2124 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2125 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2126 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2128 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2129 // If this is an sret function, the return should pop the hidden pointer.
2130 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2131 argsAreStructReturn(Ins) == StackStructReturn)
2132 FuncInfo->setBytesToPopOnReturn(4);
2136 // RegSaveFrameIndex is X86-64 only.
2137 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2138 if (CallConv == CallingConv::X86_FastCall ||
2139 CallConv == CallingConv::X86_ThisCall)
2140 // fastcc functions can't have varargs.
2141 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2144 FuncInfo->setArgumentStackSize(StackSize);
2150 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2151 SDValue StackPtr, SDValue Arg,
2152 DebugLoc dl, SelectionDAG &DAG,
2153 const CCValAssign &VA,
2154 ISD::ArgFlagsTy Flags) const {
2155 unsigned LocMemOffset = VA.getLocMemOffset();
2156 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2157 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2158 if (Flags.isByVal())
2159 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2161 return DAG.getStore(Chain, dl, Arg, PtrOff,
2162 MachinePointerInfo::getStack(LocMemOffset),
2166 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2167 /// optimization is performed and it is required.
2169 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2170 SDValue &OutRetAddr, SDValue Chain,
2171 bool IsTailCall, bool Is64Bit,
2172 int FPDiff, DebugLoc dl) const {
2173 // Adjust the Return address stack slot.
2174 EVT VT = getPointerTy();
2175 OutRetAddr = getReturnAddressFrameIndex(DAG);
2177 // Load the "old" Return address.
2178 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2179 false, false, false, 0);
2180 return SDValue(OutRetAddr.getNode(), 1);
2183 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2184 /// optimization is performed and it is required (FPDiff!=0).
2186 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2187 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2188 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2189 // Store the return address to the appropriate stack slot.
2190 if (!FPDiff) return Chain;
2191 // Calculate the new stack slot for the return address.
2192 int NewReturnAddrFI =
2193 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2194 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2195 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2196 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2202 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2203 SmallVectorImpl<SDValue> &InVals) const {
2204 SelectionDAG &DAG = CLI.DAG;
2205 DebugLoc &dl = CLI.DL;
2206 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2207 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2208 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2209 SDValue Chain = CLI.Chain;
2210 SDValue Callee = CLI.Callee;
2211 CallingConv::ID CallConv = CLI.CallConv;
2212 bool &isTailCall = CLI.IsTailCall;
2213 bool isVarArg = CLI.IsVarArg;
2215 MachineFunction &MF = DAG.getMachineFunction();
2216 bool Is64Bit = Subtarget->is64Bit();
2217 bool IsWin64 = Subtarget->isTargetWin64();
2218 bool IsWindows = Subtarget->isTargetWindows();
2219 StructReturnType SR = callIsStructReturn(Outs);
2220 bool IsSibcall = false;
2222 if (MF.getTarget().Options.DisableTailCalls)
2226 // Check if it's really possible to do a tail call.
2227 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2228 isVarArg, SR != NotStructReturn,
2229 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2230 Outs, OutVals, Ins, DAG);
2232 // Sibcalls are automatically detected tailcalls which do not require
2234 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2241 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2242 "Var args not supported with calling convention fastcc or ghc");
2244 // Analyze operands of the call, assigning locations to each operand.
2245 SmallVector<CCValAssign, 16> ArgLocs;
2246 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2247 ArgLocs, *DAG.getContext());
2249 // Allocate shadow area for Win64
2251 CCInfo.AllocateStack(32, 8);
2254 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2256 // Get a count of how many bytes are to be pushed on the stack.
2257 unsigned NumBytes = CCInfo.getNextStackOffset();
2259 // This is a sibcall. The memory operands are available in caller's
2260 // own caller's stack.
2262 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2263 IsTailCallConvention(CallConv))
2264 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2267 if (isTailCall && !IsSibcall) {
2268 // Lower arguments at fp - stackoffset + fpdiff.
2269 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2270 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2272 FPDiff = NumBytesCallerPushed - NumBytes;
2274 // Set the delta of movement of the returnaddr stackslot.
2275 // But only set if delta is greater than previous delta.
2276 if (FPDiff < X86Info->getTCReturnAddrDelta())
2277 X86Info->setTCReturnAddrDelta(FPDiff);
2281 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2283 SDValue RetAddrFrIdx;
2284 // Load return address for tail calls.
2285 if (isTailCall && FPDiff)
2286 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2287 Is64Bit, FPDiff, dl);
2289 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2290 SmallVector<SDValue, 8> MemOpChains;
2293 // Walk the register/memloc assignments, inserting copies/loads. In the case
2294 // of tail call optimization arguments are handle later.
2295 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2296 CCValAssign &VA = ArgLocs[i];
2297 EVT RegVT = VA.getLocVT();
2298 SDValue Arg = OutVals[i];
2299 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2300 bool isByVal = Flags.isByVal();
2302 // Promote the value if needed.
2303 switch (VA.getLocInfo()) {
2304 default: llvm_unreachable("Unknown loc info!");
2305 case CCValAssign::Full: break;
2306 case CCValAssign::SExt:
2307 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2309 case CCValAssign::ZExt:
2310 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2312 case CCValAssign::AExt:
2313 if (RegVT.is128BitVector()) {
2314 // Special case: passing MMX values in XMM registers.
2315 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2316 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2317 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2319 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2321 case CCValAssign::BCvt:
2322 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2324 case CCValAssign::Indirect: {
2325 // Store the argument.
2326 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2327 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2328 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2329 MachinePointerInfo::getFixedStack(FI),
2336 if (VA.isRegLoc()) {
2337 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2338 if (isVarArg && IsWin64) {
2339 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2340 // shadow reg if callee is a varargs function.
2341 unsigned ShadowReg = 0;
2342 switch (VA.getLocReg()) {
2343 case X86::XMM0: ShadowReg = X86::RCX; break;
2344 case X86::XMM1: ShadowReg = X86::RDX; break;
2345 case X86::XMM2: ShadowReg = X86::R8; break;
2346 case X86::XMM3: ShadowReg = X86::R9; break;
2349 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2351 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2352 assert(VA.isMemLoc());
2353 if (StackPtr.getNode() == 0)
2354 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2355 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2356 dl, DAG, VA, Flags));
2360 if (!MemOpChains.empty())
2361 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2362 &MemOpChains[0], MemOpChains.size());
2364 if (Subtarget->isPICStyleGOT()) {
2365 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2368 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2369 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2371 // If we are tail calling and generating PIC/GOT style code load the
2372 // address of the callee into ECX. The value in ecx is used as target of
2373 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2374 // for tail calls on PIC/GOT architectures. Normally we would just put the
2375 // address of GOT into ebx and then call target@PLT. But for tail calls
2376 // ebx would be restored (since ebx is callee saved) before jumping to the
2379 // Note: The actual moving to ECX is done further down.
2380 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2381 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2382 !G->getGlobal()->hasProtectedVisibility())
2383 Callee = LowerGlobalAddress(Callee, DAG);
2384 else if (isa<ExternalSymbolSDNode>(Callee))
2385 Callee = LowerExternalSymbol(Callee, DAG);
2389 if (Is64Bit && isVarArg && !IsWin64) {
2390 // From AMD64 ABI document:
2391 // For calls that may call functions that use varargs or stdargs
2392 // (prototype-less calls or calls to functions containing ellipsis (...) in
2393 // the declaration) %al is used as hidden argument to specify the number
2394 // of SSE registers used. The contents of %al do not need to match exactly
2395 // the number of registers, but must be an ubound on the number of SSE
2396 // registers used and is in the range 0 - 8 inclusive.
2398 // Count the number of XMM registers allocated.
2399 static const uint16_t XMMArgRegs[] = {
2400 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2401 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2403 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2404 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2405 && "SSE registers cannot be used when SSE is disabled");
2407 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2408 DAG.getConstant(NumXMMRegs, MVT::i8)));
2411 // For tail calls lower the arguments to the 'real' stack slot.
2413 // Force all the incoming stack arguments to be loaded from the stack
2414 // before any new outgoing arguments are stored to the stack, because the
2415 // outgoing stack slots may alias the incoming argument stack slots, and
2416 // the alias isn't otherwise explicit. This is slightly more conservative
2417 // than necessary, because it means that each store effectively depends
2418 // on every argument instead of just those arguments it would clobber.
2419 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2421 SmallVector<SDValue, 8> MemOpChains2;
2424 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2425 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2426 CCValAssign &VA = ArgLocs[i];
2429 assert(VA.isMemLoc());
2430 SDValue Arg = OutVals[i];
2431 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2432 // Create frame index.
2433 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2434 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2435 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2436 FIN = DAG.getFrameIndex(FI, getPointerTy());
2438 if (Flags.isByVal()) {
2439 // Copy relative to framepointer.
2440 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2441 if (StackPtr.getNode() == 0)
2442 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2444 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2446 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2450 // Store relative to framepointer.
2451 MemOpChains2.push_back(
2452 DAG.getStore(ArgChain, dl, Arg, FIN,
2453 MachinePointerInfo::getFixedStack(FI),
2459 if (!MemOpChains2.empty())
2460 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2461 &MemOpChains2[0], MemOpChains2.size());
2463 // Store the return address to the appropriate stack slot.
2464 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2465 getPointerTy(), RegInfo->getSlotSize(),
2469 // Build a sequence of copy-to-reg nodes chained together with token chain
2470 // and flag operands which copy the outgoing args into registers.
2472 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2473 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2474 RegsToPass[i].second, InFlag);
2475 InFlag = Chain.getValue(1);
2478 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2479 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2480 // In the 64-bit large code model, we have to make all calls
2481 // through a register, since the call instruction's 32-bit
2482 // pc-relative offset may not be large enough to hold the whole
2484 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2485 // If the callee is a GlobalAddress node (quite common, every direct call
2486 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2489 // We should use extra load for direct calls to dllimported functions in
2491 const GlobalValue *GV = G->getGlobal();
2492 if (!GV->hasDLLImportLinkage()) {
2493 unsigned char OpFlags = 0;
2494 bool ExtraLoad = false;
2495 unsigned WrapperKind = ISD::DELETED_NODE;
2497 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2498 // external symbols most go through the PLT in PIC mode. If the symbol
2499 // has hidden or protected visibility, or if it is static or local, then
2500 // we don't need to use the PLT - we can directly call it.
2501 if (Subtarget->isTargetELF() &&
2502 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2503 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2504 OpFlags = X86II::MO_PLT;
2505 } else if (Subtarget->isPICStyleStubAny() &&
2506 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2507 (!Subtarget->getTargetTriple().isMacOSX() ||
2508 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2509 // PC-relative references to external symbols should go through $stub,
2510 // unless we're building with the leopard linker or later, which
2511 // automatically synthesizes these stubs.
2512 OpFlags = X86II::MO_DARWIN_STUB;
2513 } else if (Subtarget->isPICStyleRIPRel() &&
2514 isa<Function>(GV) &&
2515 cast<Function>(GV)->getFnAttributes().
2516 hasAttribute(Attributes::NonLazyBind)) {
2517 // If the function is marked as non-lazy, generate an indirect call
2518 // which loads from the GOT directly. This avoids runtime overhead
2519 // at the cost of eager binding (and one extra byte of encoding).
2520 OpFlags = X86II::MO_GOTPCREL;
2521 WrapperKind = X86ISD::WrapperRIP;
2525 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2526 G->getOffset(), OpFlags);
2528 // Add a wrapper if needed.
2529 if (WrapperKind != ISD::DELETED_NODE)
2530 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2531 // Add extra indirection if needed.
2533 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2534 MachinePointerInfo::getGOT(),
2535 false, false, false, 0);
2537 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2538 unsigned char OpFlags = 0;
2540 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2541 // external symbols should go through the PLT.
2542 if (Subtarget->isTargetELF() &&
2543 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2544 OpFlags = X86II::MO_PLT;
2545 } else if (Subtarget->isPICStyleStubAny() &&
2546 (!Subtarget->getTargetTriple().isMacOSX() ||
2547 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2548 // PC-relative references to external symbols should go through $stub,
2549 // unless we're building with the leopard linker or later, which
2550 // automatically synthesizes these stubs.
2551 OpFlags = X86II::MO_DARWIN_STUB;
2554 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2558 // Returns a chain & a flag for retval copy to use.
2559 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2560 SmallVector<SDValue, 8> Ops;
2562 if (!IsSibcall && isTailCall) {
2563 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2564 DAG.getIntPtrConstant(0, true), InFlag);
2565 InFlag = Chain.getValue(1);
2568 Ops.push_back(Chain);
2569 Ops.push_back(Callee);
2572 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2574 // Add argument registers to the end of the list so that they are known live
2576 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2577 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2578 RegsToPass[i].second.getValueType()));
2580 // Add a register mask operand representing the call-preserved registers.
2581 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2582 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2583 assert(Mask && "Missing call preserved mask for calling convention");
2584 Ops.push_back(DAG.getRegisterMask(Mask));
2586 if (InFlag.getNode())
2587 Ops.push_back(InFlag);
2591 //// If this is the first return lowered for this function, add the regs
2592 //// to the liveout set for the function.
2593 // This isn't right, although it's probably harmless on x86; liveouts
2594 // should be computed from returns not tail calls. Consider a void
2595 // function making a tail call to a function returning int.
2596 return DAG.getNode(X86ISD::TC_RETURN, dl,
2597 NodeTys, &Ops[0], Ops.size());
2600 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2601 InFlag = Chain.getValue(1);
2603 // Create the CALLSEQ_END node.
2604 unsigned NumBytesForCalleeToPush;
2605 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2606 getTargetMachine().Options.GuaranteedTailCallOpt))
2607 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2608 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2609 SR == StackStructReturn)
2610 // If this is a call to a struct-return function, the callee
2611 // pops the hidden struct pointer, so we have to push it back.
2612 // This is common for Darwin/X86, Linux & Mingw32 targets.
2613 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2614 NumBytesForCalleeToPush = 4;
2616 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2618 // Returns a flag for retval copy to use.
2620 Chain = DAG.getCALLSEQ_END(Chain,
2621 DAG.getIntPtrConstant(NumBytes, true),
2622 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2625 InFlag = Chain.getValue(1);
2628 // Handle result values, copying them out of physregs into vregs that we
2630 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2631 Ins, dl, DAG, InVals);
2635 //===----------------------------------------------------------------------===//
2636 // Fast Calling Convention (tail call) implementation
2637 //===----------------------------------------------------------------------===//
2639 // Like std call, callee cleans arguments, convention except that ECX is
2640 // reserved for storing the tail called function address. Only 2 registers are
2641 // free for argument passing (inreg). Tail call optimization is performed
2643 // * tailcallopt is enabled
2644 // * caller/callee are fastcc
2645 // On X86_64 architecture with GOT-style position independent code only local
2646 // (within module) calls are supported at the moment.
2647 // To keep the stack aligned according to platform abi the function
2648 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2649 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2650 // If a tail called function callee has more arguments than the caller the
2651 // caller needs to make sure that there is room to move the RETADDR to. This is
2652 // achieved by reserving an area the size of the argument delta right after the
2653 // original REtADDR, but before the saved framepointer or the spilled registers
2654 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2666 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2667 /// for a 16 byte align requirement.
2669 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2670 SelectionDAG& DAG) const {
2671 MachineFunction &MF = DAG.getMachineFunction();
2672 const TargetMachine &TM = MF.getTarget();
2673 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2674 unsigned StackAlignment = TFI.getStackAlignment();
2675 uint64_t AlignMask = StackAlignment - 1;
2676 int64_t Offset = StackSize;
2677 unsigned SlotSize = RegInfo->getSlotSize();
2678 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2679 // Number smaller than 12 so just add the difference.
2680 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2682 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2683 Offset = ((~AlignMask) & Offset) + StackAlignment +
2684 (StackAlignment-SlotSize);
2689 /// MatchingStackOffset - Return true if the given stack call argument is
2690 /// already available in the same position (relatively) of the caller's
2691 /// incoming argument stack.
2693 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2694 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2695 const X86InstrInfo *TII) {
2696 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2698 if (Arg.getOpcode() == ISD::CopyFromReg) {
2699 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2700 if (!TargetRegisterInfo::isVirtualRegister(VR))
2702 MachineInstr *Def = MRI->getVRegDef(VR);
2705 if (!Flags.isByVal()) {
2706 if (!TII->isLoadFromStackSlot(Def, FI))
2709 unsigned Opcode = Def->getOpcode();
2710 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2711 Def->getOperand(1).isFI()) {
2712 FI = Def->getOperand(1).getIndex();
2713 Bytes = Flags.getByValSize();
2717 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2718 if (Flags.isByVal())
2719 // ByVal argument is passed in as a pointer but it's now being
2720 // dereferenced. e.g.
2721 // define @foo(%struct.X* %A) {
2722 // tail call @bar(%struct.X* byval %A)
2725 SDValue Ptr = Ld->getBasePtr();
2726 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2729 FI = FINode->getIndex();
2730 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2731 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2732 FI = FINode->getIndex();
2733 Bytes = Flags.getByValSize();
2737 assert(FI != INT_MAX);
2738 if (!MFI->isFixedObjectIndex(FI))
2740 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2743 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2744 /// for tail call optimization. Targets which want to do tail call
2745 /// optimization should implement this function.
2747 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2748 CallingConv::ID CalleeCC,
2750 bool isCalleeStructRet,
2751 bool isCallerStructRet,
2753 const SmallVectorImpl<ISD::OutputArg> &Outs,
2754 const SmallVectorImpl<SDValue> &OutVals,
2755 const SmallVectorImpl<ISD::InputArg> &Ins,
2756 SelectionDAG& DAG) const {
2757 if (!IsTailCallConvention(CalleeCC) &&
2758 CalleeCC != CallingConv::C)
2761 // If -tailcallopt is specified, make fastcc functions tail-callable.
2762 const MachineFunction &MF = DAG.getMachineFunction();
2763 const Function *CallerF = DAG.getMachineFunction().getFunction();
2765 // If the function return type is x86_fp80 and the callee return type is not,
2766 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2767 // perform a tailcall optimization here.
2768 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2771 CallingConv::ID CallerCC = CallerF->getCallingConv();
2772 bool CCMatch = CallerCC == CalleeCC;
2774 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2775 if (IsTailCallConvention(CalleeCC) && CCMatch)
2780 // Look for obvious safe cases to perform tail call optimization that do not
2781 // require ABI changes. This is what gcc calls sibcall.
2783 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2784 // emit a special epilogue.
2785 if (RegInfo->needsStackRealignment(MF))
2788 // Also avoid sibcall optimization if either caller or callee uses struct
2789 // return semantics.
2790 if (isCalleeStructRet || isCallerStructRet)
2793 // An stdcall caller is expected to clean up its arguments; the callee
2794 // isn't going to do that.
2795 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2798 // Do not sibcall optimize vararg calls unless all arguments are passed via
2800 if (isVarArg && !Outs.empty()) {
2802 // Optimizing for varargs on Win64 is unlikely to be safe without
2803 // additional testing.
2804 if (Subtarget->isTargetWin64())
2807 SmallVector<CCValAssign, 16> ArgLocs;
2808 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2809 getTargetMachine(), ArgLocs, *DAG.getContext());
2811 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2812 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2813 if (!ArgLocs[i].isRegLoc())
2817 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2818 // stack. Therefore, if it's not used by the call it is not safe to optimize
2819 // this into a sibcall.
2820 bool Unused = false;
2821 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2828 SmallVector<CCValAssign, 16> RVLocs;
2829 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2830 getTargetMachine(), RVLocs, *DAG.getContext());
2831 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2832 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2833 CCValAssign &VA = RVLocs[i];
2834 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2839 // If the calling conventions do not match, then we'd better make sure the
2840 // results are returned in the same way as what the caller expects.
2842 SmallVector<CCValAssign, 16> RVLocs1;
2843 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2844 getTargetMachine(), RVLocs1, *DAG.getContext());
2845 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2847 SmallVector<CCValAssign, 16> RVLocs2;
2848 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2849 getTargetMachine(), RVLocs2, *DAG.getContext());
2850 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2852 if (RVLocs1.size() != RVLocs2.size())
2854 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2855 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2857 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2859 if (RVLocs1[i].isRegLoc()) {
2860 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2863 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2869 // If the callee takes no arguments then go on to check the results of the
2871 if (!Outs.empty()) {
2872 // Check if stack adjustment is needed. For now, do not do this if any
2873 // argument is passed on the stack.
2874 SmallVector<CCValAssign, 16> ArgLocs;
2875 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2876 getTargetMachine(), ArgLocs, *DAG.getContext());
2878 // Allocate shadow area for Win64
2879 if (Subtarget->isTargetWin64()) {
2880 CCInfo.AllocateStack(32, 8);
2883 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2884 if (CCInfo.getNextStackOffset()) {
2885 MachineFunction &MF = DAG.getMachineFunction();
2886 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2889 // Check if the arguments are already laid out in the right way as
2890 // the caller's fixed stack objects.
2891 MachineFrameInfo *MFI = MF.getFrameInfo();
2892 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2893 const X86InstrInfo *TII =
2894 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2895 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2896 CCValAssign &VA = ArgLocs[i];
2897 SDValue Arg = OutVals[i];
2898 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2899 if (VA.getLocInfo() == CCValAssign::Indirect)
2901 if (!VA.isRegLoc()) {
2902 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2909 // If the tailcall address may be in a register, then make sure it's
2910 // possible to register allocate for it. In 32-bit, the call address can
2911 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2912 // callee-saved registers are restored. These happen to be the same
2913 // registers used to pass 'inreg' arguments so watch out for those.
2914 if (!Subtarget->is64Bit() &&
2915 !isa<GlobalAddressSDNode>(Callee) &&
2916 !isa<ExternalSymbolSDNode>(Callee)) {
2917 unsigned NumInRegs = 0;
2918 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2919 CCValAssign &VA = ArgLocs[i];
2922 unsigned Reg = VA.getLocReg();
2925 case X86::EAX: case X86::EDX: case X86::ECX:
2926 if (++NumInRegs == 3)
2938 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2939 const TargetLibraryInfo *libInfo) const {
2940 return X86::createFastISel(funcInfo, libInfo);
2944 //===----------------------------------------------------------------------===//
2945 // Other Lowering Hooks
2946 //===----------------------------------------------------------------------===//
2948 static bool MayFoldLoad(SDValue Op) {
2949 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2952 static bool MayFoldIntoStore(SDValue Op) {
2953 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2956 static bool isTargetShuffle(unsigned Opcode) {
2958 default: return false;
2959 case X86ISD::PSHUFD:
2960 case X86ISD::PSHUFHW:
2961 case X86ISD::PSHUFLW:
2963 case X86ISD::PALIGN:
2964 case X86ISD::MOVLHPS:
2965 case X86ISD::MOVLHPD:
2966 case X86ISD::MOVHLPS:
2967 case X86ISD::MOVLPS:
2968 case X86ISD::MOVLPD:
2969 case X86ISD::MOVSHDUP:
2970 case X86ISD::MOVSLDUP:
2971 case X86ISD::MOVDDUP:
2974 case X86ISD::UNPCKL:
2975 case X86ISD::UNPCKH:
2976 case X86ISD::VPERMILP:
2977 case X86ISD::VPERM2X128:
2978 case X86ISD::VPERMI:
2983 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2984 SDValue V1, SelectionDAG &DAG) {
2986 default: llvm_unreachable("Unknown x86 shuffle node");
2987 case X86ISD::MOVSHDUP:
2988 case X86ISD::MOVSLDUP:
2989 case X86ISD::MOVDDUP:
2990 return DAG.getNode(Opc, dl, VT, V1);
2994 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2995 SDValue V1, unsigned TargetMask,
2996 SelectionDAG &DAG) {
2998 default: llvm_unreachable("Unknown x86 shuffle node");
2999 case X86ISD::PSHUFD:
3000 case X86ISD::PSHUFHW:
3001 case X86ISD::PSHUFLW:
3002 case X86ISD::VPERMILP:
3003 case X86ISD::VPERMI:
3004 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3008 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3009 SDValue V1, SDValue V2, unsigned TargetMask,
3010 SelectionDAG &DAG) {
3012 default: llvm_unreachable("Unknown x86 shuffle node");
3013 case X86ISD::PALIGN:
3015 case X86ISD::VPERM2X128:
3016 return DAG.getNode(Opc, dl, VT, V1, V2,
3017 DAG.getConstant(TargetMask, MVT::i8));
3021 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3022 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3024 default: llvm_unreachable("Unknown x86 shuffle node");
3025 case X86ISD::MOVLHPS:
3026 case X86ISD::MOVLHPD:
3027 case X86ISD::MOVHLPS:
3028 case X86ISD::MOVLPS:
3029 case X86ISD::MOVLPD:
3032 case X86ISD::UNPCKL:
3033 case X86ISD::UNPCKH:
3034 return DAG.getNode(Opc, dl, VT, V1, V2);
3038 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3039 MachineFunction &MF = DAG.getMachineFunction();
3040 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3041 int ReturnAddrIndex = FuncInfo->getRAIndex();
3043 if (ReturnAddrIndex == 0) {
3044 // Set up a frame object for the return address.
3045 unsigned SlotSize = RegInfo->getSlotSize();
3046 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3048 FuncInfo->setRAIndex(ReturnAddrIndex);
3051 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3055 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3056 bool hasSymbolicDisplacement) {
3057 // Offset should fit into 32 bit immediate field.
3058 if (!isInt<32>(Offset))
3061 // If we don't have a symbolic displacement - we don't have any extra
3063 if (!hasSymbolicDisplacement)
3066 // FIXME: Some tweaks might be needed for medium code model.
3067 if (M != CodeModel::Small && M != CodeModel::Kernel)
3070 // For small code model we assume that latest object is 16MB before end of 31
3071 // bits boundary. We may also accept pretty large negative constants knowing
3072 // that all objects are in the positive half of address space.
3073 if (M == CodeModel::Small && Offset < 16*1024*1024)
3076 // For kernel code model we know that all object resist in the negative half
3077 // of 32bits address space. We may not accept negative offsets, since they may
3078 // be just off and we may accept pretty large positive ones.
3079 if (M == CodeModel::Kernel && Offset > 0)
3085 /// isCalleePop - Determines whether the callee is required to pop its
3086 /// own arguments. Callee pop is necessary to support tail calls.
3087 bool X86::isCalleePop(CallingConv::ID CallingConv,
3088 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3092 switch (CallingConv) {
3095 case CallingConv::X86_StdCall:
3097 case CallingConv::X86_FastCall:
3099 case CallingConv::X86_ThisCall:
3101 case CallingConv::Fast:
3103 case CallingConv::GHC:
3108 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3109 /// specific condition code, returning the condition code and the LHS/RHS of the
3110 /// comparison to make.
3111 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3112 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3114 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3115 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3116 // X > -1 -> X == 0, jump !sign.
3117 RHS = DAG.getConstant(0, RHS.getValueType());
3118 return X86::COND_NS;
3120 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3121 // X < 0 -> X == 0, jump on sign.
3124 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3126 RHS = DAG.getConstant(0, RHS.getValueType());
3127 return X86::COND_LE;
3131 switch (SetCCOpcode) {
3132 default: llvm_unreachable("Invalid integer condition!");
3133 case ISD::SETEQ: return X86::COND_E;
3134 case ISD::SETGT: return X86::COND_G;
3135 case ISD::SETGE: return X86::COND_GE;
3136 case ISD::SETLT: return X86::COND_L;
3137 case ISD::SETLE: return X86::COND_LE;
3138 case ISD::SETNE: return X86::COND_NE;
3139 case ISD::SETULT: return X86::COND_B;
3140 case ISD::SETUGT: return X86::COND_A;
3141 case ISD::SETULE: return X86::COND_BE;
3142 case ISD::SETUGE: return X86::COND_AE;
3146 // First determine if it is required or is profitable to flip the operands.
3148 // If LHS is a foldable load, but RHS is not, flip the condition.
3149 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3150 !ISD::isNON_EXTLoad(RHS.getNode())) {
3151 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3152 std::swap(LHS, RHS);
3155 switch (SetCCOpcode) {
3161 std::swap(LHS, RHS);
3165 // On a floating point condition, the flags are set as follows:
3167 // 0 | 0 | 0 | X > Y
3168 // 0 | 0 | 1 | X < Y
3169 // 1 | 0 | 0 | X == Y
3170 // 1 | 1 | 1 | unordered
3171 switch (SetCCOpcode) {
3172 default: llvm_unreachable("Condcode should be pre-legalized away");
3174 case ISD::SETEQ: return X86::COND_E;
3175 case ISD::SETOLT: // flipped
3177 case ISD::SETGT: return X86::COND_A;
3178 case ISD::SETOLE: // flipped
3180 case ISD::SETGE: return X86::COND_AE;
3181 case ISD::SETUGT: // flipped
3183 case ISD::SETLT: return X86::COND_B;
3184 case ISD::SETUGE: // flipped
3186 case ISD::SETLE: return X86::COND_BE;
3188 case ISD::SETNE: return X86::COND_NE;
3189 case ISD::SETUO: return X86::COND_P;
3190 case ISD::SETO: return X86::COND_NP;
3192 case ISD::SETUNE: return X86::COND_INVALID;
3196 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3197 /// code. Current x86 isa includes the following FP cmov instructions:
3198 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3199 static bool hasFPCMov(unsigned X86CC) {
3215 /// isFPImmLegal - Returns true if the target can instruction select the
3216 /// specified FP immediate natively. If false, the legalizer will
3217 /// materialize the FP immediate as a load from a constant pool.
3218 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3219 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3220 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3226 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3227 /// the specified range (L, H].
3228 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3229 return (Val < 0) || (Val >= Low && Val < Hi);
3232 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3233 /// specified value.
3234 static bool isUndefOrEqual(int Val, int CmpVal) {
3235 if (Val < 0 || Val == CmpVal)
3240 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3241 /// from position Pos and ending in Pos+Size, falls within the specified
3242 /// sequential range (L, L+Pos]. or is undef.
3243 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3244 unsigned Pos, unsigned Size, int Low) {
3245 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3246 if (!isUndefOrEqual(Mask[i], Low))
3251 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3252 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3253 /// the second operand.
3254 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3255 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3256 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3257 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3258 return (Mask[0] < 2 && Mask[1] < 2);
3262 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3263 /// is suitable for input to PSHUFHW.
3264 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3265 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3268 // Lower quadword copied in order or undef.
3269 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3272 // Upper quadword shuffled.
3273 for (unsigned i = 4; i != 8; ++i)
3274 if (!isUndefOrInRange(Mask[i], 4, 8))
3277 if (VT == MVT::v16i16) {
3278 // Lower quadword copied in order or undef.
3279 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3282 // Upper quadword shuffled.
3283 for (unsigned i = 12; i != 16; ++i)
3284 if (!isUndefOrInRange(Mask[i], 12, 16))
3291 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3292 /// is suitable for input to PSHUFLW.
3293 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3294 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3297 // Upper quadword copied in order.
3298 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3301 // Lower quadword shuffled.
3302 for (unsigned i = 0; i != 4; ++i)
3303 if (!isUndefOrInRange(Mask[i], 0, 4))
3306 if (VT == MVT::v16i16) {
3307 // Upper quadword copied in order.
3308 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3311 // Lower quadword shuffled.
3312 for (unsigned i = 8; i != 12; ++i)
3313 if (!isUndefOrInRange(Mask[i], 8, 12))
3320 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3321 /// is suitable for input to PALIGNR.
3322 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3323 const X86Subtarget *Subtarget) {
3324 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3325 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3328 unsigned NumElts = VT.getVectorNumElements();
3329 unsigned NumLanes = VT.getSizeInBits()/128;
3330 unsigned NumLaneElts = NumElts/NumLanes;
3332 // Do not handle 64-bit element shuffles with palignr.
3333 if (NumLaneElts == 2)
3336 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3338 for (i = 0; i != NumLaneElts; ++i) {
3343 // Lane is all undef, go to next lane
3344 if (i == NumLaneElts)
3347 int Start = Mask[i+l];
3349 // Make sure its in this lane in one of the sources
3350 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3351 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3354 // If not lane 0, then we must match lane 0
3355 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3358 // Correct second source to be contiguous with first source
3359 if (Start >= (int)NumElts)
3360 Start -= NumElts - NumLaneElts;
3362 // Make sure we're shifting in the right direction.
3363 if (Start <= (int)(i+l))
3368 // Check the rest of the elements to see if they are consecutive.
3369 for (++i; i != NumLaneElts; ++i) {
3370 int Idx = Mask[i+l];
3372 // Make sure its in this lane
3373 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3374 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3377 // If not lane 0, then we must match lane 0
3378 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3381 if (Idx >= (int)NumElts)
3382 Idx -= NumElts - NumLaneElts;
3384 if (!isUndefOrEqual(Idx, Start+i))
3393 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3394 /// the two vector operands have swapped position.
3395 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3396 unsigned NumElems) {
3397 for (unsigned i = 0; i != NumElems; ++i) {
3401 else if (idx < (int)NumElems)
3402 Mask[i] = idx + NumElems;
3404 Mask[i] = idx - NumElems;
3408 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3409 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3410 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3411 /// reverse of what x86 shuffles want.
3412 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3413 bool Commuted = false) {
3414 if (!HasAVX && VT.getSizeInBits() == 256)
3417 unsigned NumElems = VT.getVectorNumElements();
3418 unsigned NumLanes = VT.getSizeInBits()/128;
3419 unsigned NumLaneElems = NumElems/NumLanes;
3421 if (NumLaneElems != 2 && NumLaneElems != 4)
3424 // VSHUFPSY divides the resulting vector into 4 chunks.
3425 // The sources are also splitted into 4 chunks, and each destination
3426 // chunk must come from a different source chunk.
3428 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3429 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3431 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3432 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3434 // VSHUFPDY divides the resulting vector into 4 chunks.
3435 // The sources are also splitted into 4 chunks, and each destination
3436 // chunk must come from a different source chunk.
3438 // SRC1 => X3 X2 X1 X0
3439 // SRC2 => Y3 Y2 Y1 Y0
3441 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3443 unsigned HalfLaneElems = NumLaneElems/2;
3444 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3445 for (unsigned i = 0; i != NumLaneElems; ++i) {
3446 int Idx = Mask[i+l];
3447 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3448 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3450 // For VSHUFPSY, the mask of the second half must be the same as the
3451 // first but with the appropriate offsets. This works in the same way as
3452 // VPERMILPS works with masks.
3453 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3455 if (!isUndefOrEqual(Idx, Mask[i]+l))
3463 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3464 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3465 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3466 if (!VT.is128BitVector())
3469 unsigned NumElems = VT.getVectorNumElements();
3474 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3475 return isUndefOrEqual(Mask[0], 6) &&
3476 isUndefOrEqual(Mask[1], 7) &&
3477 isUndefOrEqual(Mask[2], 2) &&
3478 isUndefOrEqual(Mask[3], 3);
3481 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3482 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3484 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3485 if (!VT.is128BitVector())
3488 unsigned NumElems = VT.getVectorNumElements();
3493 return isUndefOrEqual(Mask[0], 2) &&
3494 isUndefOrEqual(Mask[1], 3) &&
3495 isUndefOrEqual(Mask[2], 2) &&
3496 isUndefOrEqual(Mask[3], 3);
3499 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3500 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3501 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3502 if (!VT.is128BitVector())
3505 unsigned NumElems = VT.getVectorNumElements();
3507 if (NumElems != 2 && NumElems != 4)
3510 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3511 if (!isUndefOrEqual(Mask[i], i + NumElems))
3514 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3515 if (!isUndefOrEqual(Mask[i], i))
3521 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3522 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3523 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3524 if (!VT.is128BitVector())
3527 unsigned NumElems = VT.getVectorNumElements();
3529 if (NumElems != 2 && NumElems != 4)
3532 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3533 if (!isUndefOrEqual(Mask[i], i))
3536 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3537 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3544 // Some special combinations that can be optimized.
3547 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3548 SelectionDAG &DAG) {
3549 EVT VT = SVOp->getValueType(0);
3550 DebugLoc dl = SVOp->getDebugLoc();
3552 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3555 ArrayRef<int> Mask = SVOp->getMask();
3557 // These are the special masks that may be optimized.
3558 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3559 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3560 bool MatchEvenMask = true;
3561 bool MatchOddMask = true;
3562 for (int i=0; i<8; ++i) {
3563 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3564 MatchEvenMask = false;
3565 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3566 MatchOddMask = false;
3569 if (!MatchEvenMask && !MatchOddMask)
3572 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3574 SDValue Op0 = SVOp->getOperand(0);
3575 SDValue Op1 = SVOp->getOperand(1);
3577 if (MatchEvenMask) {
3578 // Shift the second operand right to 32 bits.
3579 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3580 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3582 // Shift the first operand left to 32 bits.
3583 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3584 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3586 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3587 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3590 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3591 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3592 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3593 bool HasAVX2, bool V2IsSplat = false) {
3594 unsigned NumElts = VT.getVectorNumElements();
3596 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3597 "Unsupported vector type for unpckh");
3599 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3600 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3603 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3604 // independently on 128-bit lanes.
3605 unsigned NumLanes = VT.getSizeInBits()/128;
3606 unsigned NumLaneElts = NumElts/NumLanes;
3608 for (unsigned l = 0; l != NumLanes; ++l) {
3609 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3610 i != (l+1)*NumLaneElts;
3613 int BitI1 = Mask[i+1];
3614 if (!isUndefOrEqual(BitI, j))
3617 if (!isUndefOrEqual(BitI1, NumElts))
3620 if (!isUndefOrEqual(BitI1, j + NumElts))
3629 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3630 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3631 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3632 bool HasAVX2, bool V2IsSplat = false) {
3633 unsigned NumElts = VT.getVectorNumElements();
3635 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3636 "Unsupported vector type for unpckh");
3638 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3639 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3642 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3643 // independently on 128-bit lanes.
3644 unsigned NumLanes = VT.getSizeInBits()/128;
3645 unsigned NumLaneElts = NumElts/NumLanes;
3647 for (unsigned l = 0; l != NumLanes; ++l) {
3648 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3649 i != (l+1)*NumLaneElts; i += 2, ++j) {
3651 int BitI1 = Mask[i+1];
3652 if (!isUndefOrEqual(BitI, j))
3655 if (isUndefOrEqual(BitI1, NumElts))
3658 if (!isUndefOrEqual(BitI1, j+NumElts))
3666 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3667 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3669 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3671 unsigned NumElts = VT.getVectorNumElements();
3673 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3674 "Unsupported vector type for unpckh");
3676 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3677 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3680 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3681 // FIXME: Need a better way to get rid of this, there's no latency difference
3682 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3683 // the former later. We should also remove the "_undef" special mask.
3684 if (NumElts == 4 && VT.getSizeInBits() == 256)
3687 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3688 // independently on 128-bit lanes.
3689 unsigned NumLanes = VT.getSizeInBits()/128;
3690 unsigned NumLaneElts = NumElts/NumLanes;
3692 for (unsigned l = 0; l != NumLanes; ++l) {
3693 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3694 i != (l+1)*NumLaneElts;
3697 int BitI1 = Mask[i+1];
3699 if (!isUndefOrEqual(BitI, j))
3701 if (!isUndefOrEqual(BitI1, j))
3709 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3710 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3712 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3713 unsigned NumElts = VT.getVectorNumElements();
3715 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3716 "Unsupported vector type for unpckh");
3718 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3719 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3722 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3723 // independently on 128-bit lanes.
3724 unsigned NumLanes = VT.getSizeInBits()/128;
3725 unsigned NumLaneElts = NumElts/NumLanes;
3727 for (unsigned l = 0; l != NumLanes; ++l) {
3728 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3729 i != (l+1)*NumLaneElts; i += 2, ++j) {
3731 int BitI1 = Mask[i+1];
3732 if (!isUndefOrEqual(BitI, j))
3734 if (!isUndefOrEqual(BitI1, j))
3741 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3742 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3743 /// MOVSD, and MOVD, i.e. setting the lowest element.
3744 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3745 if (VT.getVectorElementType().getSizeInBits() < 32)
3747 if (!VT.is128BitVector())
3750 unsigned NumElts = VT.getVectorNumElements();
3752 if (!isUndefOrEqual(Mask[0], NumElts))
3755 for (unsigned i = 1; i != NumElts; ++i)
3756 if (!isUndefOrEqual(Mask[i], i))
3762 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3763 /// as permutations between 128-bit chunks or halves. As an example: this
3765 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3766 /// The first half comes from the second half of V1 and the second half from the
3767 /// the second half of V2.
3768 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3769 if (!HasAVX || !VT.is256BitVector())
3772 // The shuffle result is divided into half A and half B. In total the two
3773 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3774 // B must come from C, D, E or F.
3775 unsigned HalfSize = VT.getVectorNumElements()/2;
3776 bool MatchA = false, MatchB = false;
3778 // Check if A comes from one of C, D, E, F.
3779 for (unsigned Half = 0; Half != 4; ++Half) {
3780 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3786 // Check if B comes from one of C, D, E, F.
3787 for (unsigned Half = 0; Half != 4; ++Half) {
3788 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3794 return MatchA && MatchB;
3797 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3798 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3799 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3800 EVT VT = SVOp->getValueType(0);
3802 unsigned HalfSize = VT.getVectorNumElements()/2;
3804 unsigned FstHalf = 0, SndHalf = 0;
3805 for (unsigned i = 0; i < HalfSize; ++i) {
3806 if (SVOp->getMaskElt(i) > 0) {
3807 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3811 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3812 if (SVOp->getMaskElt(i) > 0) {
3813 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3818 return (FstHalf | (SndHalf << 4));
3821 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3822 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3823 /// Note that VPERMIL mask matching is different depending whether theunderlying
3824 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3825 /// to the same elements of the low, but to the higher half of the source.
3826 /// In VPERMILPD the two lanes could be shuffled independently of each other
3827 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3828 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3832 unsigned NumElts = VT.getVectorNumElements();
3833 // Only match 256-bit with 32/64-bit types
3834 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3837 unsigned NumLanes = VT.getSizeInBits()/128;
3838 unsigned LaneSize = NumElts/NumLanes;
3839 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3840 for (unsigned i = 0; i != LaneSize; ++i) {
3841 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3843 if (NumElts != 8 || l == 0)
3845 // VPERMILPS handling
3848 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3856 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3857 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3858 /// element of vector 2 and the other elements to come from vector 1 in order.
3859 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3860 bool V2IsSplat = false, bool V2IsUndef = false) {
3861 if (!VT.is128BitVector())
3864 unsigned NumOps = VT.getVectorNumElements();
3865 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3868 if (!isUndefOrEqual(Mask[0], 0))
3871 for (unsigned i = 1; i != NumOps; ++i)
3872 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3873 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3874 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3880 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3881 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3882 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3883 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3884 const X86Subtarget *Subtarget) {
3885 if (!Subtarget->hasSSE3())
3888 unsigned NumElems = VT.getVectorNumElements();
3890 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3891 (VT.getSizeInBits() == 256 && NumElems != 8))
3894 // "i+1" is the value the indexed mask element must have
3895 for (unsigned i = 0; i != NumElems; i += 2)
3896 if (!isUndefOrEqual(Mask[i], i+1) ||
3897 !isUndefOrEqual(Mask[i+1], i+1))
3903 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3904 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3905 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3906 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3907 const X86Subtarget *Subtarget) {
3908 if (!Subtarget->hasSSE3())
3911 unsigned NumElems = VT.getVectorNumElements();
3913 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3914 (VT.getSizeInBits() == 256 && NumElems != 8))
3917 // "i" is the value the indexed mask element must have
3918 for (unsigned i = 0; i != NumElems; i += 2)
3919 if (!isUndefOrEqual(Mask[i], i) ||
3920 !isUndefOrEqual(Mask[i+1], i))
3926 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3927 /// specifies a shuffle of elements that is suitable for input to 256-bit
3928 /// version of MOVDDUP.
3929 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3930 if (!HasAVX || !VT.is256BitVector())
3933 unsigned NumElts = VT.getVectorNumElements();
3937 for (unsigned i = 0; i != NumElts/2; ++i)
3938 if (!isUndefOrEqual(Mask[i], 0))
3940 for (unsigned i = NumElts/2; i != NumElts; ++i)
3941 if (!isUndefOrEqual(Mask[i], NumElts/2))
3946 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3947 /// specifies a shuffle of elements that is suitable for input to 128-bit
3948 /// version of MOVDDUP.
3949 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3950 if (!VT.is128BitVector())
3953 unsigned e = VT.getVectorNumElements() / 2;
3954 for (unsigned i = 0; i != e; ++i)
3955 if (!isUndefOrEqual(Mask[i], i))
3957 for (unsigned i = 0; i != e; ++i)
3958 if (!isUndefOrEqual(Mask[e+i], i))
3963 /// isVEXTRACTF128Index - Return true if the specified
3964 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3965 /// suitable for input to VEXTRACTF128.
3966 bool X86::isVEXTRACTF128Index(SDNode *N) {
3967 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3970 // The index should be aligned on a 128-bit boundary.
3972 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3974 unsigned VL = N->getValueType(0).getVectorNumElements();
3975 unsigned VBits = N->getValueType(0).getSizeInBits();
3976 unsigned ElSize = VBits / VL;
3977 bool Result = (Index * ElSize) % 128 == 0;
3982 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3983 /// operand specifies a subvector insert that is suitable for input to
3985 bool X86::isVINSERTF128Index(SDNode *N) {
3986 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3989 // The index should be aligned on a 128-bit boundary.
3991 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3993 unsigned VL = N->getValueType(0).getVectorNumElements();
3994 unsigned VBits = N->getValueType(0).getSizeInBits();
3995 unsigned ElSize = VBits / VL;
3996 bool Result = (Index * ElSize) % 128 == 0;
4001 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4002 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4003 /// Handles 128-bit and 256-bit.
4004 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4005 EVT VT = N->getValueType(0);
4007 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4008 "Unsupported vector type for PSHUF/SHUFP");
4010 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4011 // independently on 128-bit lanes.
4012 unsigned NumElts = VT.getVectorNumElements();
4013 unsigned NumLanes = VT.getSizeInBits()/128;
4014 unsigned NumLaneElts = NumElts/NumLanes;
4016 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4017 "Only supports 2 or 4 elements per lane");
4019 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4021 for (unsigned i = 0; i != NumElts; ++i) {
4022 int Elt = N->getMaskElt(i);
4023 if (Elt < 0) continue;
4024 Elt &= NumLaneElts - 1;
4025 unsigned ShAmt = (i << Shift) % 8;
4026 Mask |= Elt << ShAmt;
4032 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4033 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4034 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4035 EVT VT = N->getValueType(0);
4037 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4038 "Unsupported vector type for PSHUFHW");
4040 unsigned NumElts = VT.getVectorNumElements();
4043 for (unsigned l = 0; l != NumElts; l += 8) {
4044 // 8 nodes per lane, but we only care about the last 4.
4045 for (unsigned i = 0; i < 4; ++i) {
4046 int Elt = N->getMaskElt(l+i+4);
4047 if (Elt < 0) continue;
4048 Elt &= 0x3; // only 2-bits.
4049 Mask |= Elt << (i * 2);
4056 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4057 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4058 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4059 EVT VT = N->getValueType(0);
4061 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4062 "Unsupported vector type for PSHUFHW");
4064 unsigned NumElts = VT.getVectorNumElements();
4067 for (unsigned l = 0; l != NumElts; l += 8) {
4068 // 8 nodes per lane, but we only care about the first 4.
4069 for (unsigned i = 0; i < 4; ++i) {
4070 int Elt = N->getMaskElt(l+i);
4071 if (Elt < 0) continue;
4072 Elt &= 0x3; // only 2-bits
4073 Mask |= Elt << (i * 2);
4080 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4081 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4082 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4083 EVT VT = SVOp->getValueType(0);
4084 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4086 unsigned NumElts = VT.getVectorNumElements();
4087 unsigned NumLanes = VT.getSizeInBits()/128;
4088 unsigned NumLaneElts = NumElts/NumLanes;
4092 for (i = 0; i != NumElts; ++i) {
4093 Val = SVOp->getMaskElt(i);
4097 if (Val >= (int)NumElts)
4098 Val -= NumElts - NumLaneElts;
4100 assert(Val - i > 0 && "PALIGNR imm should be positive");
4101 return (Val - i) * EltSize;
4104 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4105 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4107 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4108 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4109 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4112 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4114 EVT VecVT = N->getOperand(0).getValueType();
4115 EVT ElVT = VecVT.getVectorElementType();
4117 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4118 return Index / NumElemsPerChunk;
4121 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4122 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4124 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4125 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4126 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4129 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4131 EVT VecVT = N->getValueType(0);
4132 EVT ElVT = VecVT.getVectorElementType();
4134 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4135 return Index / NumElemsPerChunk;
4138 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4139 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4140 /// Handles 256-bit.
4141 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4142 EVT VT = N->getValueType(0);
4144 unsigned NumElts = VT.getVectorNumElements();
4146 assert((VT.is256BitVector() && NumElts == 4) &&
4147 "Unsupported vector type for VPERMQ/VPERMPD");
4150 for (unsigned i = 0; i != NumElts; ++i) {
4151 int Elt = N->getMaskElt(i);
4154 Mask |= Elt << (i*2);
4159 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4161 bool X86::isZeroNode(SDValue Elt) {
4162 return ((isa<ConstantSDNode>(Elt) &&
4163 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4164 (isa<ConstantFPSDNode>(Elt) &&
4165 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4168 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4169 /// their permute mask.
4170 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4171 SelectionDAG &DAG) {
4172 EVT VT = SVOp->getValueType(0);
4173 unsigned NumElems = VT.getVectorNumElements();
4174 SmallVector<int, 8> MaskVec;
4176 for (unsigned i = 0; i != NumElems; ++i) {
4177 int Idx = SVOp->getMaskElt(i);
4179 if (Idx < (int)NumElems)
4184 MaskVec.push_back(Idx);
4186 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4187 SVOp->getOperand(0), &MaskVec[0]);
4190 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4191 /// match movhlps. The lower half elements should come from upper half of
4192 /// V1 (and in order), and the upper half elements should come from the upper
4193 /// half of V2 (and in order).
4194 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4195 if (!VT.is128BitVector())
4197 if (VT.getVectorNumElements() != 4)
4199 for (unsigned i = 0, e = 2; i != e; ++i)
4200 if (!isUndefOrEqual(Mask[i], i+2))
4202 for (unsigned i = 2; i != 4; ++i)
4203 if (!isUndefOrEqual(Mask[i], i+4))
4208 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4209 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4211 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4212 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4214 N = N->getOperand(0).getNode();
4215 if (!ISD::isNON_EXTLoad(N))
4218 *LD = cast<LoadSDNode>(N);
4222 // Test whether the given value is a vector value which will be legalized
4224 static bool WillBeConstantPoolLoad(SDNode *N) {
4225 if (N->getOpcode() != ISD::BUILD_VECTOR)
4228 // Check for any non-constant elements.
4229 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4230 switch (N->getOperand(i).getNode()->getOpcode()) {
4232 case ISD::ConstantFP:
4239 // Vectors of all-zeros and all-ones are materialized with special
4240 // instructions rather than being loaded.
4241 return !ISD::isBuildVectorAllZeros(N) &&
4242 !ISD::isBuildVectorAllOnes(N);
4245 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4246 /// match movlp{s|d}. The lower half elements should come from lower half of
4247 /// V1 (and in order), and the upper half elements should come from the upper
4248 /// half of V2 (and in order). And since V1 will become the source of the
4249 /// MOVLP, it must be either a vector load or a scalar load to vector.
4250 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4251 ArrayRef<int> Mask, EVT VT) {
4252 if (!VT.is128BitVector())
4255 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4257 // Is V2 is a vector load, don't do this transformation. We will try to use
4258 // load folding shufps op.
4259 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4262 unsigned NumElems = VT.getVectorNumElements();
4264 if (NumElems != 2 && NumElems != 4)
4266 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4267 if (!isUndefOrEqual(Mask[i], i))
4269 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4270 if (!isUndefOrEqual(Mask[i], i+NumElems))
4275 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4277 static bool isSplatVector(SDNode *N) {
4278 if (N->getOpcode() != ISD::BUILD_VECTOR)
4281 SDValue SplatValue = N->getOperand(0);
4282 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4283 if (N->getOperand(i) != SplatValue)
4288 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4289 /// to an zero vector.
4290 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4291 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4292 SDValue V1 = N->getOperand(0);
4293 SDValue V2 = N->getOperand(1);
4294 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4295 for (unsigned i = 0; i != NumElems; ++i) {
4296 int Idx = N->getMaskElt(i);
4297 if (Idx >= (int)NumElems) {
4298 unsigned Opc = V2.getOpcode();
4299 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4301 if (Opc != ISD::BUILD_VECTOR ||
4302 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4304 } else if (Idx >= 0) {
4305 unsigned Opc = V1.getOpcode();
4306 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4308 if (Opc != ISD::BUILD_VECTOR ||
4309 !X86::isZeroNode(V1.getOperand(Idx)))
4316 /// getZeroVector - Returns a vector of specified type with all zero elements.
4318 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4319 SelectionDAG &DAG, DebugLoc dl) {
4320 assert(VT.isVector() && "Expected a vector type");
4321 unsigned Size = VT.getSizeInBits();
4323 // Always build SSE zero vectors as <4 x i32> bitcasted
4324 // to their dest type. This ensures they get CSE'd.
4326 if (Size == 128) { // SSE
4327 if (Subtarget->hasSSE2()) { // SSE2
4328 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4329 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4331 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4332 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4334 } else if (Size == 256) { // AVX
4335 if (Subtarget->hasAVX2()) { // AVX2
4336 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4337 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4338 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4340 // 256-bit logic and arithmetic instructions in AVX are all
4341 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4342 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4343 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4344 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4347 llvm_unreachable("Unexpected vector type");
4349 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4352 /// getOnesVector - Returns a vector of specified type with all bits set.
4353 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4354 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4355 /// Then bitcast to their original type, ensuring they get CSE'd.
4356 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4358 assert(VT.isVector() && "Expected a vector type");
4359 unsigned Size = VT.getSizeInBits();
4361 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4364 if (HasAVX2) { // AVX2
4365 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4366 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4368 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4369 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4371 } else if (Size == 128) {
4372 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4374 llvm_unreachable("Unexpected vector type");
4376 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4379 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4380 /// that point to V2 points to its first element.
4381 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4382 for (unsigned i = 0; i != NumElems; ++i) {
4383 if (Mask[i] > (int)NumElems) {
4389 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4390 /// operation of specified width.
4391 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4393 unsigned NumElems = VT.getVectorNumElements();
4394 SmallVector<int, 8> Mask;
4395 Mask.push_back(NumElems);
4396 for (unsigned i = 1; i != NumElems; ++i)
4398 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4401 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4402 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4404 unsigned NumElems = VT.getVectorNumElements();
4405 SmallVector<int, 8> Mask;
4406 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4408 Mask.push_back(i + NumElems);
4410 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4413 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4414 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4416 unsigned NumElems = VT.getVectorNumElements();
4417 SmallVector<int, 8> Mask;
4418 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4419 Mask.push_back(i + Half);
4420 Mask.push_back(i + NumElems + Half);
4422 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4425 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4426 // a generic shuffle instruction because the target has no such instructions.
4427 // Generate shuffles which repeat i16 and i8 several times until they can be
4428 // represented by v4f32 and then be manipulated by target suported shuffles.
4429 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4430 EVT VT = V.getValueType();
4431 int NumElems = VT.getVectorNumElements();
4432 DebugLoc dl = V.getDebugLoc();
4434 while (NumElems > 4) {
4435 if (EltNo < NumElems/2) {
4436 V = getUnpackl(DAG, dl, VT, V, V);
4438 V = getUnpackh(DAG, dl, VT, V, V);
4439 EltNo -= NumElems/2;
4446 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4447 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4448 EVT VT = V.getValueType();
4449 DebugLoc dl = V.getDebugLoc();
4450 unsigned Size = VT.getSizeInBits();
4453 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4454 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4455 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4457 } else if (Size == 256) {
4458 // To use VPERMILPS to splat scalars, the second half of indicies must
4459 // refer to the higher part, which is a duplication of the lower one,
4460 // because VPERMILPS can only handle in-lane permutations.
4461 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4462 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4464 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4465 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4468 llvm_unreachable("Vector size not supported");
4470 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4473 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4474 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4475 EVT SrcVT = SV->getValueType(0);
4476 SDValue V1 = SV->getOperand(0);
4477 DebugLoc dl = SV->getDebugLoc();
4479 int EltNo = SV->getSplatIndex();
4480 int NumElems = SrcVT.getVectorNumElements();
4481 unsigned Size = SrcVT.getSizeInBits();
4483 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4484 "Unknown how to promote splat for type");
4486 // Extract the 128-bit part containing the splat element and update
4487 // the splat element index when it refers to the higher register.
4489 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4490 if (EltNo >= NumElems/2)
4491 EltNo -= NumElems/2;
4494 // All i16 and i8 vector types can't be used directly by a generic shuffle
4495 // instruction because the target has no such instruction. Generate shuffles
4496 // which repeat i16 and i8 several times until they fit in i32, and then can
4497 // be manipulated by target suported shuffles.
4498 EVT EltVT = SrcVT.getVectorElementType();
4499 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4500 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4502 // Recreate the 256-bit vector and place the same 128-bit vector
4503 // into the low and high part. This is necessary because we want
4504 // to use VPERM* to shuffle the vectors
4506 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4509 return getLegalSplat(DAG, V1, EltNo);
4512 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4513 /// vector of zero or undef vector. This produces a shuffle where the low
4514 /// element of V2 is swizzled into the zero/undef vector, landing at element
4515 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4516 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4518 const X86Subtarget *Subtarget,
4519 SelectionDAG &DAG) {
4520 EVT VT = V2.getValueType();
4522 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4523 unsigned NumElems = VT.getVectorNumElements();
4524 SmallVector<int, 16> MaskVec;
4525 for (unsigned i = 0; i != NumElems; ++i)
4526 // If this is the insertion idx, put the low elt of V2 here.
4527 MaskVec.push_back(i == Idx ? NumElems : i);
4528 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4531 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4532 /// target specific opcode. Returns true if the Mask could be calculated.
4533 /// Sets IsUnary to true if only uses one source.
4534 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4535 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4536 unsigned NumElems = VT.getVectorNumElements();
4540 switch(N->getOpcode()) {
4542 ImmN = N->getOperand(N->getNumOperands()-1);
4543 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4545 case X86ISD::UNPCKH:
4546 DecodeUNPCKHMask(VT, Mask);
4548 case X86ISD::UNPCKL:
4549 DecodeUNPCKLMask(VT, Mask);
4551 case X86ISD::MOVHLPS:
4552 DecodeMOVHLPSMask(NumElems, Mask);
4554 case X86ISD::MOVLHPS:
4555 DecodeMOVLHPSMask(NumElems, Mask);
4557 case X86ISD::PSHUFD:
4558 case X86ISD::VPERMILP:
4559 ImmN = N->getOperand(N->getNumOperands()-1);
4560 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4563 case X86ISD::PSHUFHW:
4564 ImmN = N->getOperand(N->getNumOperands()-1);
4565 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568 case X86ISD::PSHUFLW:
4569 ImmN = N->getOperand(N->getNumOperands()-1);
4570 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4573 case X86ISD::VPERMI:
4574 ImmN = N->getOperand(N->getNumOperands()-1);
4575 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4579 case X86ISD::MOVSD: {
4580 // The index 0 always comes from the first element of the second source,
4581 // this is why MOVSS and MOVSD are used in the first place. The other
4582 // elements come from the other positions of the first source vector
4583 Mask.push_back(NumElems);
4584 for (unsigned i = 1; i != NumElems; ++i) {
4589 case X86ISD::VPERM2X128:
4590 ImmN = N->getOperand(N->getNumOperands()-1);
4591 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592 if (Mask.empty()) return false;
4594 case X86ISD::MOVDDUP:
4595 case X86ISD::MOVLHPD:
4596 case X86ISD::MOVLPD:
4597 case X86ISD::MOVLPS:
4598 case X86ISD::MOVSHDUP:
4599 case X86ISD::MOVSLDUP:
4600 case X86ISD::PALIGN:
4601 // Not yet implemented
4603 default: llvm_unreachable("unknown target shuffle node");
4609 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4610 /// element of the result of the vector shuffle.
4611 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4614 return SDValue(); // Limit search depth.
4616 SDValue V = SDValue(N, 0);
4617 EVT VT = V.getValueType();
4618 unsigned Opcode = V.getOpcode();
4620 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4621 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4622 int Elt = SV->getMaskElt(Index);
4625 return DAG.getUNDEF(VT.getVectorElementType());
4627 unsigned NumElems = VT.getVectorNumElements();
4628 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4629 : SV->getOperand(1);
4630 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4633 // Recurse into target specific vector shuffles to find scalars.
4634 if (isTargetShuffle(Opcode)) {
4635 MVT ShufVT = V.getValueType().getSimpleVT();
4636 unsigned NumElems = ShufVT.getVectorNumElements();
4637 SmallVector<int, 16> ShuffleMask;
4640 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4643 int Elt = ShuffleMask[Index];
4645 return DAG.getUNDEF(ShufVT.getVectorElementType());
4647 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4649 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4653 // Actual nodes that may contain scalar elements
4654 if (Opcode == ISD::BITCAST) {
4655 V = V.getOperand(0);
4656 EVT SrcVT = V.getValueType();
4657 unsigned NumElems = VT.getVectorNumElements();
4659 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4663 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4664 return (Index == 0) ? V.getOperand(0)
4665 : DAG.getUNDEF(VT.getVectorElementType());
4667 if (V.getOpcode() == ISD::BUILD_VECTOR)
4668 return V.getOperand(Index);
4673 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4674 /// shuffle operation which come from a consecutively from a zero. The
4675 /// search can start in two different directions, from left or right.
4677 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4678 bool ZerosFromLeft, SelectionDAG &DAG) {
4680 for (i = 0; i != NumElems; ++i) {
4681 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4682 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4683 if (!(Elt.getNode() &&
4684 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4691 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4692 /// correspond consecutively to elements from one of the vector operands,
4693 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4695 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4696 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4697 unsigned NumElems, unsigned &OpNum) {
4698 bool SeenV1 = false;
4699 bool SeenV2 = false;
4701 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4702 int Idx = SVOp->getMaskElt(i);
4703 // Ignore undef indicies
4707 if (Idx < (int)NumElems)
4712 // Only accept consecutive elements from the same vector
4713 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4717 OpNum = SeenV1 ? 0 : 1;
4721 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4722 /// logical left shift of a vector.
4723 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4724 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4725 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4726 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4727 false /* check zeros from right */, DAG);
4733 // Considering the elements in the mask that are not consecutive zeros,
4734 // check if they consecutively come from only one of the source vectors.
4736 // V1 = {X, A, B, C} 0
4738 // vector_shuffle V1, V2 <1, 2, 3, X>
4740 if (!isShuffleMaskConsecutive(SVOp,
4741 0, // Mask Start Index
4742 NumElems-NumZeros, // Mask End Index(exclusive)
4743 NumZeros, // Where to start looking in the src vector
4744 NumElems, // Number of elements in vector
4745 OpSrc)) // Which source operand ?
4750 ShVal = SVOp->getOperand(OpSrc);
4754 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4755 /// logical left shift of a vector.
4756 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4757 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4758 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4759 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4760 true /* check zeros from left */, DAG);
4766 // Considering the elements in the mask that are not consecutive zeros,
4767 // check if they consecutively come from only one of the source vectors.
4769 // 0 { A, B, X, X } = V2
4771 // vector_shuffle V1, V2 <X, X, 4, 5>
4773 if (!isShuffleMaskConsecutive(SVOp,
4774 NumZeros, // Mask Start Index
4775 NumElems, // Mask End Index(exclusive)
4776 0, // Where to start looking in the src vector
4777 NumElems, // Number of elements in vector
4778 OpSrc)) // Which source operand ?
4783 ShVal = SVOp->getOperand(OpSrc);
4787 /// isVectorShift - Returns true if the shuffle can be implemented as a
4788 /// logical left or right shift of a vector.
4789 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4790 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4791 // Although the logic below support any bitwidth size, there are no
4792 // shift instructions which handle more than 128-bit vectors.
4793 if (!SVOp->getValueType(0).is128BitVector())
4796 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4797 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4803 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4805 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4806 unsigned NumNonZero, unsigned NumZero,
4808 const X86Subtarget* Subtarget,
4809 const TargetLowering &TLI) {
4813 DebugLoc dl = Op.getDebugLoc();
4816 for (unsigned i = 0; i < 16; ++i) {
4817 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4818 if (ThisIsNonZero && First) {
4820 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4822 V = DAG.getUNDEF(MVT::v8i16);
4827 SDValue ThisElt(0, 0), LastElt(0, 0);
4828 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4829 if (LastIsNonZero) {
4830 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4831 MVT::i16, Op.getOperand(i-1));
4833 if (ThisIsNonZero) {
4834 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4835 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4836 ThisElt, DAG.getConstant(8, MVT::i8));
4838 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4842 if (ThisElt.getNode())
4843 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4844 DAG.getIntPtrConstant(i/2));
4848 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4851 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4853 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4854 unsigned NumNonZero, unsigned NumZero,
4856 const X86Subtarget* Subtarget,
4857 const TargetLowering &TLI) {
4861 DebugLoc dl = Op.getDebugLoc();
4864 for (unsigned i = 0; i < 8; ++i) {
4865 bool isNonZero = (NonZeros & (1 << i)) != 0;
4869 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4871 V = DAG.getUNDEF(MVT::v8i16);
4874 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4875 MVT::v8i16, V, Op.getOperand(i),
4876 DAG.getIntPtrConstant(i));
4883 /// getVShift - Return a vector logical shift node.
4885 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4886 unsigned NumBits, SelectionDAG &DAG,
4887 const TargetLowering &TLI, DebugLoc dl) {
4888 assert(VT.is128BitVector() && "Unknown type for VShift");
4889 EVT ShVT = MVT::v2i64;
4890 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4891 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4892 return DAG.getNode(ISD::BITCAST, dl, VT,
4893 DAG.getNode(Opc, dl, ShVT, SrcOp,
4894 DAG.getConstant(NumBits,
4895 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4899 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4900 SelectionDAG &DAG) const {
4902 // Check if the scalar load can be widened into a vector load. And if
4903 // the address is "base + cst" see if the cst can be "absorbed" into
4904 // the shuffle mask.
4905 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4906 SDValue Ptr = LD->getBasePtr();
4907 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4909 EVT PVT = LD->getValueType(0);
4910 if (PVT != MVT::i32 && PVT != MVT::f32)
4915 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4916 FI = FINode->getIndex();
4918 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4919 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4920 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4921 Offset = Ptr.getConstantOperandVal(1);
4922 Ptr = Ptr.getOperand(0);
4927 // FIXME: 256-bit vector instructions don't require a strict alignment,
4928 // improve this code to support it better.
4929 unsigned RequiredAlign = VT.getSizeInBits()/8;
4930 SDValue Chain = LD->getChain();
4931 // Make sure the stack object alignment is at least 16 or 32.
4932 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4933 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4934 if (MFI->isFixedObjectIndex(FI)) {
4935 // Can't change the alignment. FIXME: It's possible to compute
4936 // the exact stack offset and reference FI + adjust offset instead.
4937 // If someone *really* cares about this. That's the way to implement it.
4940 MFI->setObjectAlignment(FI, RequiredAlign);
4944 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4945 // Ptr + (Offset & ~15).
4948 if ((Offset % RequiredAlign) & 3)
4950 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4952 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4953 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4955 int EltNo = (Offset - StartOffset) >> 2;
4956 unsigned NumElems = VT.getVectorNumElements();
4958 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4959 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4960 LD->getPointerInfo().getWithOffset(StartOffset),
4961 false, false, false, 0);
4963 SmallVector<int, 8> Mask;
4964 for (unsigned i = 0; i != NumElems; ++i)
4965 Mask.push_back(EltNo);
4967 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4973 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4974 /// vector of type 'VT', see if the elements can be replaced by a single large
4975 /// load which has the same value as a build_vector whose operands are 'elts'.
4977 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4979 /// FIXME: we'd also like to handle the case where the last elements are zero
4980 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4981 /// There's even a handy isZeroNode for that purpose.
4982 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4983 DebugLoc &DL, SelectionDAG &DAG) {
4984 EVT EltVT = VT.getVectorElementType();
4985 unsigned NumElems = Elts.size();
4987 LoadSDNode *LDBase = NULL;
4988 unsigned LastLoadedElt = -1U;
4990 // For each element in the initializer, see if we've found a load or an undef.
4991 // If we don't find an initial load element, or later load elements are
4992 // non-consecutive, bail out.
4993 for (unsigned i = 0; i < NumElems; ++i) {
4994 SDValue Elt = Elts[i];
4996 if (!Elt.getNode() ||
4997 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5000 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5002 LDBase = cast<LoadSDNode>(Elt.getNode());
5006 if (Elt.getOpcode() == ISD::UNDEF)
5009 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5010 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5015 // If we have found an entire vector of loads and undefs, then return a large
5016 // load of the entire vector width starting at the base pointer. If we found
5017 // consecutive loads for the low half, generate a vzext_load node.
5018 if (LastLoadedElt == NumElems - 1) {
5019 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5020 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5021 LDBase->getPointerInfo(),
5022 LDBase->isVolatile(), LDBase->isNonTemporal(),
5023 LDBase->isInvariant(), 0);
5024 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5025 LDBase->getPointerInfo(),
5026 LDBase->isVolatile(), LDBase->isNonTemporal(),
5027 LDBase->isInvariant(), LDBase->getAlignment());
5029 if (NumElems == 4 && LastLoadedElt == 1 &&
5030 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5031 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5032 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5034 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5035 LDBase->getPointerInfo(),
5036 LDBase->getAlignment(),
5037 false/*isVolatile*/, true/*ReadMem*/,
5040 // Make sure the newly-created LOAD is in the same position as LDBase in
5041 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5042 // update uses of LDBase's output chain to use the TokenFactor.
5043 if (LDBase->hasAnyUseOfValue(1)) {
5044 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5045 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5046 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5047 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5048 SDValue(ResNode.getNode(), 1));
5051 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5056 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5057 /// to generate a splat value for the following cases:
5058 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5059 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5060 /// a scalar load, or a constant.
5061 /// The VBROADCAST node is returned when a pattern is found,
5062 /// or SDValue() otherwise.
5064 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5065 if (!Subtarget->hasAVX())
5068 EVT VT = Op.getValueType();
5069 DebugLoc dl = Op.getDebugLoc();
5071 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5072 "Unsupported vector type for broadcast.");
5077 switch (Op.getOpcode()) {
5079 // Unknown pattern found.
5082 case ISD::BUILD_VECTOR: {
5083 // The BUILD_VECTOR node must be a splat.
5084 if (!isSplatVector(Op.getNode()))
5087 Ld = Op.getOperand(0);
5088 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5089 Ld.getOpcode() == ISD::ConstantFP);
5091 // The suspected load node has several users. Make sure that all
5092 // of its users are from the BUILD_VECTOR node.
5093 // Constants may have multiple users.
5094 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5099 case ISD::VECTOR_SHUFFLE: {
5100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5102 // Shuffles must have a splat mask where the first element is
5104 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5107 SDValue Sc = Op.getOperand(0);
5108 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5109 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5111 if (!Subtarget->hasAVX2())
5114 // Use the register form of the broadcast instruction available on AVX2.
5115 if (VT.is256BitVector())
5116 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5117 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5120 Ld = Sc.getOperand(0);
5121 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5122 Ld.getOpcode() == ISD::ConstantFP);
5124 // The scalar_to_vector node and the suspected
5125 // load node must have exactly one user.
5126 // Constants may have multiple users.
5127 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5133 bool Is256 = VT.is256BitVector();
5135 // Handle the broadcasting a single constant scalar from the constant pool
5136 // into a vector. On Sandybridge it is still better to load a constant vector
5137 // from the constant pool and not to broadcast it from a scalar.
5138 if (ConstSplatVal && Subtarget->hasAVX2()) {
5139 EVT CVT = Ld.getValueType();
5140 assert(!CVT.isVector() && "Must not broadcast a vector type");
5141 unsigned ScalarSize = CVT.getSizeInBits();
5143 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5144 const Constant *C = 0;
5145 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5146 C = CI->getConstantIntValue();
5147 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5148 C = CF->getConstantFPValue();
5150 assert(C && "Invalid constant type");
5152 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5153 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5154 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5155 MachinePointerInfo::getConstantPool(),
5156 false, false, false, Alignment);
5158 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5162 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5163 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5165 // Handle AVX2 in-register broadcasts.
5166 if (!IsLoad && Subtarget->hasAVX2() &&
5167 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5168 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5170 // The scalar source must be a normal load.
5174 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5175 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5177 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5178 // double since there is no vbroadcastsd xmm
5179 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5180 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5181 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5184 // Unsupported broadcast.
5189 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5190 EVT VT = Op.getValueType();
5192 // Skip if insert_vec_elt is not supported.
5193 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5196 DebugLoc DL = Op.getDebugLoc();
5197 unsigned NumElems = Op.getNumOperands();
5201 SmallVector<unsigned, 4> InsertIndices;
5202 SmallVector<int, 8> Mask(NumElems, -1);
5204 for (unsigned i = 0; i != NumElems; ++i) {
5205 unsigned Opc = Op.getOperand(i).getOpcode();
5207 if (Opc == ISD::UNDEF)
5210 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5211 // Quit if more than 1 elements need inserting.
5212 if (InsertIndices.size() > 1)
5215 InsertIndices.push_back(i);
5219 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5220 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5222 // Quit if extracted from vector of different type.
5223 if (ExtractedFromVec.getValueType() != VT)
5226 // Quit if non-constant index.
5227 if (!isa<ConstantSDNode>(ExtIdx))
5230 if (VecIn1.getNode() == 0)
5231 VecIn1 = ExtractedFromVec;
5232 else if (VecIn1 != ExtractedFromVec) {
5233 if (VecIn2.getNode() == 0)
5234 VecIn2 = ExtractedFromVec;
5235 else if (VecIn2 != ExtractedFromVec)
5236 // Quit if more than 2 vectors to shuffle
5240 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5242 if (ExtractedFromVec == VecIn1)
5244 else if (ExtractedFromVec == VecIn2)
5245 Mask[i] = Idx + NumElems;
5248 if (VecIn1.getNode() == 0)
5251 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5252 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5253 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5254 unsigned Idx = InsertIndices[i];
5255 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5256 DAG.getIntPtrConstant(Idx));
5263 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5264 DebugLoc dl = Op.getDebugLoc();
5266 EVT VT = Op.getValueType();
5267 EVT ExtVT = VT.getVectorElementType();
5268 unsigned NumElems = Op.getNumOperands();
5270 // Vectors containing all zeros can be matched by pxor and xorps later
5271 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5272 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5273 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5274 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5277 return getZeroVector(VT, Subtarget, DAG, dl);
5280 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5281 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5282 // vpcmpeqd on 256-bit vectors.
5283 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5284 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5287 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5290 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5291 if (Broadcast.getNode())
5294 unsigned EVTBits = ExtVT.getSizeInBits();
5296 unsigned NumZero = 0;
5297 unsigned NumNonZero = 0;
5298 unsigned NonZeros = 0;
5299 bool IsAllConstants = true;
5300 SmallSet<SDValue, 8> Values;
5301 for (unsigned i = 0; i < NumElems; ++i) {
5302 SDValue Elt = Op.getOperand(i);
5303 if (Elt.getOpcode() == ISD::UNDEF)
5306 if (Elt.getOpcode() != ISD::Constant &&
5307 Elt.getOpcode() != ISD::ConstantFP)
5308 IsAllConstants = false;
5309 if (X86::isZeroNode(Elt))
5312 NonZeros |= (1 << i);
5317 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5318 if (NumNonZero == 0)
5319 return DAG.getUNDEF(VT);
5321 // Special case for single non-zero, non-undef, element.
5322 if (NumNonZero == 1) {
5323 unsigned Idx = CountTrailingZeros_32(NonZeros);
5324 SDValue Item = Op.getOperand(Idx);
5326 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5327 // the value are obviously zero, truncate the value to i32 and do the
5328 // insertion that way. Only do this if the value is non-constant or if the
5329 // value is a constant being inserted into element 0. It is cheaper to do
5330 // a constant pool load than it is to do a movd + shuffle.
5331 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5332 (!IsAllConstants || Idx == 0)) {
5333 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5335 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5336 EVT VecVT = MVT::v4i32;
5337 unsigned VecElts = 4;
5339 // Truncate the value (which may itself be a constant) to i32, and
5340 // convert it to a vector with movd (S2V+shuffle to zero extend).
5341 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5342 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5343 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5345 // Now we have our 32-bit value zero extended in the low element of
5346 // a vector. If Idx != 0, swizzle it into place.
5348 SmallVector<int, 4> Mask;
5349 Mask.push_back(Idx);
5350 for (unsigned i = 1; i != VecElts; ++i)
5352 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5355 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5359 // If we have a constant or non-constant insertion into the low element of
5360 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5361 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5362 // depending on what the source datatype is.
5365 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5367 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5368 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5369 if (VT.is256BitVector()) {
5370 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5371 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5372 Item, DAG.getIntPtrConstant(0));
5374 assert(VT.is128BitVector() && "Expected an SSE value type!");
5375 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5376 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5377 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5380 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5381 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5382 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5383 if (VT.is256BitVector()) {
5384 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5385 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5387 assert(VT.is128BitVector() && "Expected an SSE value type!");
5388 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5390 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5394 // Is it a vector logical left shift?
5395 if (NumElems == 2 && Idx == 1 &&
5396 X86::isZeroNode(Op.getOperand(0)) &&
5397 !X86::isZeroNode(Op.getOperand(1))) {
5398 unsigned NumBits = VT.getSizeInBits();
5399 return getVShift(true, VT,
5400 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5401 VT, Op.getOperand(1)),
5402 NumBits/2, DAG, *this, dl);
5405 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5408 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5409 // is a non-constant being inserted into an element other than the low one,
5410 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5411 // movd/movss) to move this into the low element, then shuffle it into
5413 if (EVTBits == 32) {
5414 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5416 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5417 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5418 SmallVector<int, 8> MaskVec;
5419 for (unsigned i = 0; i != NumElems; ++i)
5420 MaskVec.push_back(i == Idx ? 0 : 1);
5421 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5425 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5426 if (Values.size() == 1) {
5427 if (EVTBits == 32) {
5428 // Instead of a shuffle like this:
5429 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5430 // Check if it's possible to issue this instead.
5431 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5432 unsigned Idx = CountTrailingZeros_32(NonZeros);
5433 SDValue Item = Op.getOperand(Idx);
5434 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5435 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5440 // A vector full of immediates; various special cases are already
5441 // handled, so this is best done with a single constant-pool load.
5445 // For AVX-length vectors, build the individual 128-bit pieces and use
5446 // shuffles to put them in place.
5447 if (VT.is256BitVector()) {
5448 SmallVector<SDValue, 32> V;
5449 for (unsigned i = 0; i != NumElems; ++i)
5450 V.push_back(Op.getOperand(i));
5452 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5454 // Build both the lower and upper subvector.
5455 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5456 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5459 // Recreate the wider vector with the lower and upper part.
5460 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5463 // Let legalizer expand 2-wide build_vectors.
5464 if (EVTBits == 64) {
5465 if (NumNonZero == 1) {
5466 // One half is zero or undef.
5467 unsigned Idx = CountTrailingZeros_32(NonZeros);
5468 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5469 Op.getOperand(Idx));
5470 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5475 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5476 if (EVTBits == 8 && NumElems == 16) {
5477 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5479 if (V.getNode()) return V;
5482 if (EVTBits == 16 && NumElems == 8) {
5483 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5485 if (V.getNode()) return V;
5488 // If element VT is == 32 bits, turn it into a number of shuffles.
5489 SmallVector<SDValue, 8> V(NumElems);
5490 if (NumElems == 4 && NumZero > 0) {
5491 for (unsigned i = 0; i < 4; ++i) {
5492 bool isZero = !(NonZeros & (1 << i));
5494 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5496 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5499 for (unsigned i = 0; i < 2; ++i) {
5500 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5503 V[i] = V[i*2]; // Must be a zero vector.
5506 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5509 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5512 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5517 bool Reverse1 = (NonZeros & 0x3) == 2;
5518 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5522 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5523 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5525 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5528 if (Values.size() > 1 && VT.is128BitVector()) {
5529 // Check for a build vector of consecutive loads.
5530 for (unsigned i = 0; i < NumElems; ++i)
5531 V[i] = Op.getOperand(i);
5533 // Check for elements which are consecutive loads.
5534 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5538 // Check for a build vector from mostly shuffle plus few inserting.
5539 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5543 // For SSE 4.1, use insertps to put the high elements into the low element.
5544 if (getSubtarget()->hasSSE41()) {
5546 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5547 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5549 Result = DAG.getUNDEF(VT);
5551 for (unsigned i = 1; i < NumElems; ++i) {
5552 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5553 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5554 Op.getOperand(i), DAG.getIntPtrConstant(i));
5559 // Otherwise, expand into a number of unpckl*, start by extending each of
5560 // our (non-undef) elements to the full vector width with the element in the
5561 // bottom slot of the vector (which generates no code for SSE).
5562 for (unsigned i = 0; i < NumElems; ++i) {
5563 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5564 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5566 V[i] = DAG.getUNDEF(VT);
5569 // Next, we iteratively mix elements, e.g. for v4f32:
5570 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5571 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5572 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5573 unsigned EltStride = NumElems >> 1;
5574 while (EltStride != 0) {
5575 for (unsigned i = 0; i < EltStride; ++i) {
5576 // If V[i+EltStride] is undef and this is the first round of mixing,
5577 // then it is safe to just drop this shuffle: V[i] is already in the
5578 // right place, the one element (since it's the first round) being
5579 // inserted as undef can be dropped. This isn't safe for successive
5580 // rounds because they will permute elements within both vectors.
5581 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5582 EltStride == NumElems/2)
5585 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5594 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5595 // to create 256-bit vectors from two other 128-bit ones.
5596 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5597 DebugLoc dl = Op.getDebugLoc();
5598 EVT ResVT = Op.getValueType();
5600 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5602 SDValue V1 = Op.getOperand(0);
5603 SDValue V2 = Op.getOperand(1);
5604 unsigned NumElems = ResVT.getVectorNumElements();
5606 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5609 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5610 assert(Op.getNumOperands() == 2);
5612 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5613 // from two other 128-bit ones.
5614 return LowerAVXCONCAT_VECTORS(Op, DAG);
5617 // Try to lower a shuffle node into a simple blend instruction.
5619 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5620 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5621 SDValue V1 = SVOp->getOperand(0);
5622 SDValue V2 = SVOp->getOperand(1);
5623 DebugLoc dl = SVOp->getDebugLoc();
5624 MVT VT = SVOp->getValueType(0).getSimpleVT();
5625 unsigned NumElems = VT.getVectorNumElements();
5627 if (!Subtarget->hasSSE41())
5633 switch (VT.SimpleTy) {
5634 default: return SDValue();
5636 ISDNo = X86ISD::BLENDPW;
5641 ISDNo = X86ISD::BLENDPS;
5646 ISDNo = X86ISD::BLENDPD;
5651 if (!Subtarget->hasAVX())
5653 ISDNo = X86ISD::BLENDPS;
5658 if (!Subtarget->hasAVX())
5660 ISDNo = X86ISD::BLENDPD;
5664 assert(ISDNo && "Invalid Op Number");
5666 unsigned MaskVals = 0;
5668 for (unsigned i = 0; i != NumElems; ++i) {
5669 int EltIdx = SVOp->getMaskElt(i);
5670 if (EltIdx == (int)i || EltIdx < 0)
5672 else if (EltIdx == (int)(i + NumElems))
5673 continue; // Bit is set to zero;
5678 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5679 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5680 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5681 DAG.getConstant(MaskVals, MVT::i32));
5682 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5685 // v8i16 shuffles - Prefer shuffles in the following order:
5686 // 1. [all] pshuflw, pshufhw, optional move
5687 // 2. [ssse3] 1 x pshufb
5688 // 3. [ssse3] 2 x pshufb + 1 x por
5689 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5691 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5692 SelectionDAG &DAG) {
5693 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5694 SDValue V1 = SVOp->getOperand(0);
5695 SDValue V2 = SVOp->getOperand(1);
5696 DebugLoc dl = SVOp->getDebugLoc();
5697 SmallVector<int, 8> MaskVals;
5699 // Determine if more than 1 of the words in each of the low and high quadwords
5700 // of the result come from the same quadword of one of the two inputs. Undef
5701 // mask values count as coming from any quadword, for better codegen.
5702 unsigned LoQuad[] = { 0, 0, 0, 0 };
5703 unsigned HiQuad[] = { 0, 0, 0, 0 };
5704 std::bitset<4> InputQuads;
5705 for (unsigned i = 0; i < 8; ++i) {
5706 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5707 int EltIdx = SVOp->getMaskElt(i);
5708 MaskVals.push_back(EltIdx);
5717 InputQuads.set(EltIdx / 4);
5720 int BestLoQuad = -1;
5721 unsigned MaxQuad = 1;
5722 for (unsigned i = 0; i < 4; ++i) {
5723 if (LoQuad[i] > MaxQuad) {
5725 MaxQuad = LoQuad[i];
5729 int BestHiQuad = -1;
5731 for (unsigned i = 0; i < 4; ++i) {
5732 if (HiQuad[i] > MaxQuad) {
5734 MaxQuad = HiQuad[i];
5738 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5739 // of the two input vectors, shuffle them into one input vector so only a
5740 // single pshufb instruction is necessary. If There are more than 2 input
5741 // quads, disable the next transformation since it does not help SSSE3.
5742 bool V1Used = InputQuads[0] || InputQuads[1];
5743 bool V2Used = InputQuads[2] || InputQuads[3];
5744 if (Subtarget->hasSSSE3()) {
5745 if (InputQuads.count() == 2 && V1Used && V2Used) {
5746 BestLoQuad = InputQuads[0] ? 0 : 1;
5747 BestHiQuad = InputQuads[2] ? 2 : 3;
5749 if (InputQuads.count() > 2) {
5755 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5756 // the shuffle mask. If a quad is scored as -1, that means that it contains
5757 // words from all 4 input quadwords.
5759 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5761 BestLoQuad < 0 ? 0 : BestLoQuad,
5762 BestHiQuad < 0 ? 1 : BestHiQuad
5764 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5765 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5766 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5767 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5769 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5770 // source words for the shuffle, to aid later transformations.
5771 bool AllWordsInNewV = true;
5772 bool InOrder[2] = { true, true };
5773 for (unsigned i = 0; i != 8; ++i) {
5774 int idx = MaskVals[i];
5776 InOrder[i/4] = false;
5777 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5779 AllWordsInNewV = false;
5783 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5784 if (AllWordsInNewV) {
5785 for (int i = 0; i != 8; ++i) {
5786 int idx = MaskVals[i];
5789 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5790 if ((idx != i) && idx < 4)
5792 if ((idx != i) && idx > 3)
5801 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5802 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5803 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5804 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5805 unsigned TargetMask = 0;
5806 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5807 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5808 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5809 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5810 getShufflePSHUFLWImmediate(SVOp);
5811 V1 = NewV.getOperand(0);
5812 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5816 // If we have SSSE3, and all words of the result are from 1 input vector,
5817 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5818 // is present, fall back to case 4.
5819 if (Subtarget->hasSSSE3()) {
5820 SmallVector<SDValue,16> pshufbMask;
5822 // If we have elements from both input vectors, set the high bit of the
5823 // shuffle mask element to zero out elements that come from V2 in the V1
5824 // mask, and elements that come from V1 in the V2 mask, so that the two
5825 // results can be OR'd together.
5826 bool TwoInputs = V1Used && V2Used;
5827 for (unsigned i = 0; i != 8; ++i) {
5828 int EltIdx = MaskVals[i] * 2;
5829 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5830 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5831 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5832 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5834 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5835 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5836 DAG.getNode(ISD::BUILD_VECTOR, dl,
5837 MVT::v16i8, &pshufbMask[0], 16));
5839 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5841 // Calculate the shuffle mask for the second input, shuffle it, and
5842 // OR it with the first shuffled input.
5844 for (unsigned i = 0; i != 8; ++i) {
5845 int EltIdx = MaskVals[i] * 2;
5846 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5847 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5848 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5849 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5851 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5852 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5853 DAG.getNode(ISD::BUILD_VECTOR, dl,
5854 MVT::v16i8, &pshufbMask[0], 16));
5855 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5856 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5859 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5860 // and update MaskVals with new element order.
5861 std::bitset<8> InOrder;
5862 if (BestLoQuad >= 0) {
5863 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5864 for (int i = 0; i != 4; ++i) {
5865 int idx = MaskVals[i];
5868 } else if ((idx / 4) == BestLoQuad) {
5873 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5876 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5878 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5880 getShufflePSHUFLWImmediate(SVOp), DAG);
5884 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5885 // and update MaskVals with the new element order.
5886 if (BestHiQuad >= 0) {
5887 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5888 for (unsigned i = 4; i != 8; ++i) {
5889 int idx = MaskVals[i];
5892 } else if ((idx / 4) == BestHiQuad) {
5893 MaskV[i] = (idx & 3) + 4;
5897 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5900 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5901 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5902 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5904 getShufflePSHUFHWImmediate(SVOp), DAG);
5908 // In case BestHi & BestLo were both -1, which means each quadword has a word
5909 // from each of the four input quadwords, calculate the InOrder bitvector now
5910 // before falling through to the insert/extract cleanup.
5911 if (BestLoQuad == -1 && BestHiQuad == -1) {
5913 for (int i = 0; i != 8; ++i)
5914 if (MaskVals[i] < 0 || MaskVals[i] == i)
5918 // The other elements are put in the right place using pextrw and pinsrw.
5919 for (unsigned i = 0; i != 8; ++i) {
5922 int EltIdx = MaskVals[i];
5925 SDValue ExtOp = (EltIdx < 8) ?
5926 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5927 DAG.getIntPtrConstant(EltIdx)) :
5928 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5929 DAG.getIntPtrConstant(EltIdx - 8));
5930 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5931 DAG.getIntPtrConstant(i));
5936 // v16i8 shuffles - Prefer shuffles in the following order:
5937 // 1. [ssse3] 1 x pshufb
5938 // 2. [ssse3] 2 x pshufb + 1 x por
5939 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5941 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5943 const X86TargetLowering &TLI) {
5944 SDValue V1 = SVOp->getOperand(0);
5945 SDValue V2 = SVOp->getOperand(1);
5946 DebugLoc dl = SVOp->getDebugLoc();
5947 ArrayRef<int> MaskVals = SVOp->getMask();
5949 // If we have SSSE3, case 1 is generated when all result bytes come from
5950 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5951 // present, fall back to case 3.
5953 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5954 if (TLI.getSubtarget()->hasSSSE3()) {
5955 SmallVector<SDValue,16> pshufbMask;
5957 // If all result elements are from one input vector, then only translate
5958 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5960 // Otherwise, we have elements from both input vectors, and must zero out
5961 // elements that come from V2 in the first mask, and V1 in the second mask
5962 // so that we can OR them together.
5963 for (unsigned i = 0; i != 16; ++i) {
5964 int EltIdx = MaskVals[i];
5965 if (EltIdx < 0 || EltIdx >= 16)
5967 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5969 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5970 DAG.getNode(ISD::BUILD_VECTOR, dl,
5971 MVT::v16i8, &pshufbMask[0], 16));
5973 // As PSHUFB will zero elements with negative indices, it's safe to ignore
5974 // the 2nd operand if it's undefined or zero.
5975 if (V2.getOpcode() == ISD::UNDEF ||
5976 ISD::isBuildVectorAllZeros(V2.getNode()))
5979 // Calculate the shuffle mask for the second input, shuffle it, and
5980 // OR it with the first shuffled input.
5982 for (unsigned i = 0; i != 16; ++i) {
5983 int EltIdx = MaskVals[i];
5984 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5985 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5987 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5988 DAG.getNode(ISD::BUILD_VECTOR, dl,
5989 MVT::v16i8, &pshufbMask[0], 16));
5990 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5993 // No SSSE3 - Calculate in place words and then fix all out of place words
5994 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5995 // the 16 different words that comprise the two doublequadword input vectors.
5996 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5997 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5999 for (int i = 0; i != 8; ++i) {
6000 int Elt0 = MaskVals[i*2];
6001 int Elt1 = MaskVals[i*2+1];
6003 // This word of the result is all undef, skip it.
6004 if (Elt0 < 0 && Elt1 < 0)
6007 // This word of the result is already in the correct place, skip it.
6008 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6011 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6012 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6015 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6016 // using a single extract together, load it and store it.
6017 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6018 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6019 DAG.getIntPtrConstant(Elt1 / 2));
6020 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6021 DAG.getIntPtrConstant(i));
6025 // If Elt1 is defined, extract it from the appropriate source. If the
6026 // source byte is not also odd, shift the extracted word left 8 bits
6027 // otherwise clear the bottom 8 bits if we need to do an or.
6029 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6030 DAG.getIntPtrConstant(Elt1 / 2));
6031 if ((Elt1 & 1) == 0)
6032 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6034 TLI.getShiftAmountTy(InsElt.getValueType())));
6036 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6037 DAG.getConstant(0xFF00, MVT::i16));
6039 // If Elt0 is defined, extract it from the appropriate source. If the
6040 // source byte is not also even, shift the extracted word right 8 bits. If
6041 // Elt1 was also defined, OR the extracted values together before
6042 // inserting them in the result.
6044 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6045 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6046 if ((Elt0 & 1) != 0)
6047 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6049 TLI.getShiftAmountTy(InsElt0.getValueType())));
6051 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6052 DAG.getConstant(0x00FF, MVT::i16));
6053 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6056 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6057 DAG.getIntPtrConstant(i));
6059 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6062 // v32i8 shuffles - Translate to VPSHUFB if possible.
6064 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6065 const X86Subtarget *Subtarget,
6066 SelectionDAG &DAG) {
6067 EVT VT = SVOp->getValueType(0);
6068 SDValue V1 = SVOp->getOperand(0);
6069 SDValue V2 = SVOp->getOperand(1);
6070 DebugLoc dl = SVOp->getDebugLoc();
6071 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6073 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6074 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6075 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6077 // VPSHUFB may be generated if
6078 // (1) one of input vector is undefined or zeroinitializer.
6079 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6080 // And (2) the mask indexes don't cross the 128-bit lane.
6081 if (VT != MVT::v32i8 || !Subtarget->hasAVX2() ||
6082 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6085 if (V1IsAllZero && !V2IsAllZero) {
6086 CommuteVectorShuffleMask(MaskVals, 32);
6089 SmallVector<SDValue, 32> pshufbMask;
6090 for (unsigned i = 0; i != 32; i++) {
6091 int EltIdx = MaskVals[i];
6092 if (EltIdx < 0 || EltIdx >= 32)
6095 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6096 // Cross lane is not allowed.
6100 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6102 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6103 DAG.getNode(ISD::BUILD_VECTOR, dl,
6104 MVT::v32i8, &pshufbMask[0], 32));
6107 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6108 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6109 /// done when every pair / quad of shuffle mask elements point to elements in
6110 /// the right sequence. e.g.
6111 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6113 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6114 SelectionDAG &DAG, DebugLoc dl) {
6115 MVT VT = SVOp->getValueType(0).getSimpleVT();
6116 unsigned NumElems = VT.getVectorNumElements();
6119 switch (VT.SimpleTy) {
6120 default: llvm_unreachable("Unexpected!");
6121 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6122 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6123 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6124 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6125 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6126 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6129 SmallVector<int, 8> MaskVec;
6130 for (unsigned i = 0; i != NumElems; i += Scale) {
6132 for (unsigned j = 0; j != Scale; ++j) {
6133 int EltIdx = SVOp->getMaskElt(i+j);
6137 StartIdx = (EltIdx / Scale);
6138 if (EltIdx != (int)(StartIdx*Scale + j))
6141 MaskVec.push_back(StartIdx);
6144 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6145 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6146 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6149 /// getVZextMovL - Return a zero-extending vector move low node.
6151 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6152 SDValue SrcOp, SelectionDAG &DAG,
6153 const X86Subtarget *Subtarget, DebugLoc dl) {
6154 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6155 LoadSDNode *LD = NULL;
6156 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6157 LD = dyn_cast<LoadSDNode>(SrcOp);
6159 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6161 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6162 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6163 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6164 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6165 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6167 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6168 return DAG.getNode(ISD::BITCAST, dl, VT,
6169 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6170 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6178 return DAG.getNode(ISD::BITCAST, dl, VT,
6179 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6180 DAG.getNode(ISD::BITCAST, dl,
6184 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6185 /// which could not be matched by any known target speficic shuffle
6187 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6189 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6190 if (NewOp.getNode())
6193 EVT VT = SVOp->getValueType(0);
6195 unsigned NumElems = VT.getVectorNumElements();
6196 unsigned NumLaneElems = NumElems / 2;
6198 DebugLoc dl = SVOp->getDebugLoc();
6199 MVT EltVT = VT.getVectorElementType().getSimpleVT();
6200 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6203 SmallVector<int, 16> Mask;
6204 for (unsigned l = 0; l < 2; ++l) {
6205 // Build a shuffle mask for the output, discovering on the fly which
6206 // input vectors to use as shuffle operands (recorded in InputUsed).
6207 // If building a suitable shuffle vector proves too hard, then bail
6208 // out with UseBuildVector set.
6209 bool UseBuildVector = false;
6210 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6211 unsigned LaneStart = l * NumLaneElems;
6212 for (unsigned i = 0; i != NumLaneElems; ++i) {
6213 // The mask element. This indexes into the input.
6214 int Idx = SVOp->getMaskElt(i+LaneStart);
6216 // the mask element does not index into any input vector.
6221 // The input vector this mask element indexes into.
6222 int Input = Idx / NumLaneElems;
6224 // Turn the index into an offset from the start of the input vector.
6225 Idx -= Input * NumLaneElems;
6227 // Find or create a shuffle vector operand to hold this input.
6229 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6230 if (InputUsed[OpNo] == Input)
6231 // This input vector is already an operand.
6233 if (InputUsed[OpNo] < 0) {
6234 // Create a new operand for this input vector.
6235 InputUsed[OpNo] = Input;
6240 if (OpNo >= array_lengthof(InputUsed)) {
6241 // More than two input vectors used! Give up on trying to create a
6242 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6243 UseBuildVector = true;
6247 // Add the mask index for the new shuffle vector.
6248 Mask.push_back(Idx + OpNo * NumLaneElems);
6251 if (UseBuildVector) {
6252 SmallVector<SDValue, 16> SVOps;
6253 for (unsigned i = 0; i != NumLaneElems; ++i) {
6254 // The mask element. This indexes into the input.
6255 int Idx = SVOp->getMaskElt(i+LaneStart);
6257 SVOps.push_back(DAG.getUNDEF(EltVT));
6261 // The input vector this mask element indexes into.
6262 int Input = Idx / NumElems;
6264 // Turn the index into an offset from the start of the input vector.
6265 Idx -= Input * NumElems;
6267 // Extract the vector element by hand.
6268 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6269 SVOp->getOperand(Input),
6270 DAG.getIntPtrConstant(Idx)));
6273 // Construct the output using a BUILD_VECTOR.
6274 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6276 } else if (InputUsed[0] < 0) {
6277 // No input vectors were used! The result is undefined.
6278 Output[l] = DAG.getUNDEF(NVT);
6280 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6281 (InputUsed[0] % 2) * NumLaneElems,
6283 // If only one input was used, use an undefined vector for the other.
6284 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6285 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6286 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6287 // At least one input vector was used. Create a new shuffle vector.
6288 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6294 // Concatenate the result back
6295 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6298 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6299 /// 4 elements, and match them with several different shuffle types.
6301 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6302 SDValue V1 = SVOp->getOperand(0);
6303 SDValue V2 = SVOp->getOperand(1);
6304 DebugLoc dl = SVOp->getDebugLoc();
6305 EVT VT = SVOp->getValueType(0);
6307 assert(VT.is128BitVector() && "Unsupported vector size");
6309 std::pair<int, int> Locs[4];
6310 int Mask1[] = { -1, -1, -1, -1 };
6311 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6315 for (unsigned i = 0; i != 4; ++i) {
6316 int Idx = PermMask[i];
6318 Locs[i] = std::make_pair(-1, -1);
6320 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6322 Locs[i] = std::make_pair(0, NumLo);
6326 Locs[i] = std::make_pair(1, NumHi);
6328 Mask1[2+NumHi] = Idx;
6334 if (NumLo <= 2 && NumHi <= 2) {
6335 // If no more than two elements come from either vector. This can be
6336 // implemented with two shuffles. First shuffle gather the elements.
6337 // The second shuffle, which takes the first shuffle as both of its
6338 // vector operands, put the elements into the right order.
6339 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6341 int Mask2[] = { -1, -1, -1, -1 };
6343 for (unsigned i = 0; i != 4; ++i)
6344 if (Locs[i].first != -1) {
6345 unsigned Idx = (i < 2) ? 0 : 4;
6346 Idx += Locs[i].first * 2 + Locs[i].second;
6350 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6353 if (NumLo == 3 || NumHi == 3) {
6354 // Otherwise, we must have three elements from one vector, call it X, and
6355 // one element from the other, call it Y. First, use a shufps to build an
6356 // intermediate vector with the one element from Y and the element from X
6357 // that will be in the same half in the final destination (the indexes don't
6358 // matter). Then, use a shufps to build the final vector, taking the half
6359 // containing the element from Y from the intermediate, and the other half
6362 // Normalize it so the 3 elements come from V1.
6363 CommuteVectorShuffleMask(PermMask, 4);
6367 // Find the element from V2.
6369 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6370 int Val = PermMask[HiIndex];
6377 Mask1[0] = PermMask[HiIndex];
6379 Mask1[2] = PermMask[HiIndex^1];
6381 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6384 Mask1[0] = PermMask[0];
6385 Mask1[1] = PermMask[1];
6386 Mask1[2] = HiIndex & 1 ? 6 : 4;
6387 Mask1[3] = HiIndex & 1 ? 4 : 6;
6388 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6391 Mask1[0] = HiIndex & 1 ? 2 : 0;
6392 Mask1[1] = HiIndex & 1 ? 0 : 2;
6393 Mask1[2] = PermMask[2];
6394 Mask1[3] = PermMask[3];
6399 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6402 // Break it into (shuffle shuffle_hi, shuffle_lo).
6403 int LoMask[] = { -1, -1, -1, -1 };
6404 int HiMask[] = { -1, -1, -1, -1 };
6406 int *MaskPtr = LoMask;
6407 unsigned MaskIdx = 0;
6410 for (unsigned i = 0; i != 4; ++i) {
6417 int Idx = PermMask[i];
6419 Locs[i] = std::make_pair(-1, -1);
6420 } else if (Idx < 4) {
6421 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6422 MaskPtr[LoIdx] = Idx;
6425 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6426 MaskPtr[HiIdx] = Idx;
6431 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6432 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6433 int MaskOps[] = { -1, -1, -1, -1 };
6434 for (unsigned i = 0; i != 4; ++i)
6435 if (Locs[i].first != -1)
6436 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6437 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6440 static bool MayFoldVectorLoad(SDValue V) {
6441 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6442 V = V.getOperand(0);
6444 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6445 V = V.getOperand(0);
6446 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6447 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6448 // BUILD_VECTOR (load), undef
6449 V = V.getOperand(0);
6451 return MayFoldLoad(V);
6454 // FIXME: the version above should always be used. Since there's
6455 // a bug where several vector shuffles can't be folded because the
6456 // DAG is not updated during lowering and a node claims to have two
6457 // uses while it only has one, use this version, and let isel match
6458 // another instruction if the load really happens to have more than
6459 // one use. Remove this version after this bug get fixed.
6460 // rdar://8434668, PR8156
6461 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6462 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6463 V = V.getOperand(0);
6464 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6465 V = V.getOperand(0);
6466 if (ISD::isNormalLoad(V.getNode()))
6472 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6473 EVT VT = Op.getValueType();
6475 // Canonizalize to v2f64.
6476 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6477 return DAG.getNode(ISD::BITCAST, dl, VT,
6478 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6483 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6485 SDValue V1 = Op.getOperand(0);
6486 SDValue V2 = Op.getOperand(1);
6487 EVT VT = Op.getValueType();
6489 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6491 if (HasSSE2 && VT == MVT::v2f64)
6492 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6494 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6495 return DAG.getNode(ISD::BITCAST, dl, VT,
6496 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6497 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6498 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6502 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6503 SDValue V1 = Op.getOperand(0);
6504 SDValue V2 = Op.getOperand(1);
6505 EVT VT = Op.getValueType();
6507 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6508 "unsupported shuffle type");
6510 if (V2.getOpcode() == ISD::UNDEF)
6514 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6518 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6519 SDValue V1 = Op.getOperand(0);
6520 SDValue V2 = Op.getOperand(1);
6521 EVT VT = Op.getValueType();
6522 unsigned NumElems = VT.getVectorNumElements();
6524 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6525 // operand of these instructions is only memory, so check if there's a
6526 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6528 bool CanFoldLoad = false;
6530 // Trivial case, when V2 comes from a load.
6531 if (MayFoldVectorLoad(V2))
6534 // When V1 is a load, it can be folded later into a store in isel, example:
6535 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6537 // (MOVLPSmr addr:$src1, VR128:$src2)
6538 // So, recognize this potential and also use MOVLPS or MOVLPD
6539 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6542 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6544 if (HasSSE2 && NumElems == 2)
6545 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6548 // If we don't care about the second element, proceed to use movss.
6549 if (SVOp->getMaskElt(1) != -1)
6550 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6553 // movl and movlp will both match v2i64, but v2i64 is never matched by
6554 // movl earlier because we make it strict to avoid messing with the movlp load
6555 // folding logic (see the code above getMOVLP call). Match it here then,
6556 // this is horrible, but will stay like this until we move all shuffle
6557 // matching to x86 specific nodes. Note that for the 1st condition all
6558 // types are matched with movsd.
6560 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6561 // as to remove this logic from here, as much as possible
6562 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6563 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6564 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6567 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6569 // Invert the operand order and use SHUFPS to match it.
6570 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6571 getShuffleSHUFImmediate(SVOp), DAG);
6574 // Reduce a vector shuffle to zext.
6576 X86TargetLowering::lowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6577 // PMOVZX is only available from SSE41.
6578 if (!Subtarget->hasSSE41())
6581 EVT VT = Op.getValueType();
6583 // Only AVX2 support 256-bit vector integer extending.
6584 if (!Subtarget->hasAVX2() && VT.is256BitVector())
6587 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6588 DebugLoc DL = Op.getDebugLoc();
6589 SDValue V1 = Op.getOperand(0);
6590 SDValue V2 = Op.getOperand(1);
6591 unsigned NumElems = VT.getVectorNumElements();
6593 // Extending is an unary operation and the element type of the source vector
6594 // won't be equal to or larger than i64.
6595 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6596 VT.getVectorElementType() == MVT::i64)
6599 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6600 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6601 while ((1U << Shift) < NumElems) {
6602 if (SVOp->getMaskElt(1U << Shift) == 1)
6605 // The maximal ratio is 8, i.e. from i8 to i64.
6610 // Check the shuffle mask.
6611 unsigned Mask = (1U << Shift) - 1;
6612 for (unsigned i = 0; i != NumElems; ++i) {
6613 int EltIdx = SVOp->getMaskElt(i);
6614 if ((i & Mask) != 0 && EltIdx != -1)
6616 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6620 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6621 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6622 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6624 if (!isTypeLegal(NVT))
6627 // Simplify the operand as it's prepared to be fed into shuffle.
6628 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6629 if (V1.getOpcode() == ISD::BITCAST &&
6630 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6631 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6633 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6634 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6635 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6636 ConstantSDNode *CIdx =
6637 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6638 // If it's foldable, i.e. normal load with single use, we will let code
6639 // selection to fold it. Otherwise, we will short the conversion sequence.
6640 if (CIdx && CIdx->getZExtValue() == 0 &&
6641 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6642 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6645 return DAG.getNode(ISD::BITCAST, DL, VT,
6646 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6650 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6651 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6652 EVT VT = Op.getValueType();
6653 DebugLoc dl = Op.getDebugLoc();
6654 SDValue V1 = Op.getOperand(0);
6655 SDValue V2 = Op.getOperand(1);
6657 if (isZeroShuffle(SVOp))
6658 return getZeroVector(VT, Subtarget, DAG, dl);
6660 // Handle splat operations
6661 if (SVOp->isSplat()) {
6662 unsigned NumElem = VT.getVectorNumElements();
6663 int Size = VT.getSizeInBits();
6665 // Use vbroadcast whenever the splat comes from a foldable load
6666 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6667 if (Broadcast.getNode())
6670 // Handle splats by matching through known shuffle masks
6671 if ((Size == 128 && NumElem <= 4) ||
6672 (Size == 256 && NumElem < 8))
6675 // All remaning splats are promoted to target supported vector shuffles.
6676 return PromoteSplat(SVOp, DAG);
6679 // Check integer expanding shuffles.
6680 SDValue NewOp = lowerVectorIntExtend(Op, DAG);
6681 if (NewOp.getNode())
6684 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6686 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6687 VT == MVT::v16i16 || VT == MVT::v32i8) {
6688 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6689 if (NewOp.getNode())
6690 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6691 } else if ((VT == MVT::v4i32 ||
6692 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6693 // FIXME: Figure out a cleaner way to do this.
6694 // Try to make use of movq to zero out the top part.
6695 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6696 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6697 if (NewOp.getNode()) {
6698 EVT NewVT = NewOp.getValueType();
6699 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6700 NewVT, true, false))
6701 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6702 DAG, Subtarget, dl);
6704 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6705 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6706 if (NewOp.getNode()) {
6707 EVT NewVT = NewOp.getValueType();
6708 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6709 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6710 DAG, Subtarget, dl);
6718 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6719 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6720 SDValue V1 = Op.getOperand(0);
6721 SDValue V2 = Op.getOperand(1);
6722 EVT VT = Op.getValueType();
6723 DebugLoc dl = Op.getDebugLoc();
6724 unsigned NumElems = VT.getVectorNumElements();
6725 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6726 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6727 bool V1IsSplat = false;
6728 bool V2IsSplat = false;
6729 bool HasSSE2 = Subtarget->hasSSE2();
6730 bool HasAVX = Subtarget->hasAVX();
6731 bool HasAVX2 = Subtarget->hasAVX2();
6732 MachineFunction &MF = DAG.getMachineFunction();
6733 bool OptForSize = MF.getFunction()->getFnAttributes().
6734 hasAttribute(Attributes::OptimizeForSize);
6736 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6738 if (V1IsUndef && V2IsUndef)
6739 return DAG.getUNDEF(VT);
6741 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6743 // Vector shuffle lowering takes 3 steps:
6745 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6746 // narrowing and commutation of operands should be handled.
6747 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6749 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6750 // so the shuffle can be broken into other shuffles and the legalizer can
6751 // try the lowering again.
6753 // The general idea is that no vector_shuffle operation should be left to
6754 // be matched during isel, all of them must be converted to a target specific
6757 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6758 // narrowing and commutation of operands should be handled. The actual code
6759 // doesn't include all of those, work in progress...
6760 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6761 if (NewOp.getNode())
6764 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6766 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6767 // unpckh_undef). Only use pshufd if speed is more important than size.
6768 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6769 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6770 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6771 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6773 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6774 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6775 return getMOVDDup(Op, dl, V1, DAG);
6777 if (isMOVHLPS_v_undef_Mask(M, VT))
6778 return getMOVHighToLow(Op, dl, DAG);
6780 // Use to match splats
6781 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6782 (VT == MVT::v2f64 || VT == MVT::v2i64))
6783 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6785 if (isPSHUFDMask(M, VT)) {
6786 // The actual implementation will match the mask in the if above and then
6787 // during isel it can match several different instructions, not only pshufd
6788 // as its name says, sad but true, emulate the behavior for now...
6789 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6790 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6792 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6794 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6795 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6797 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6798 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6800 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6804 // Check if this can be converted into a logical shift.
6805 bool isLeft = false;
6808 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6809 if (isShift && ShVal.hasOneUse()) {
6810 // If the shifted value has multiple uses, it may be cheaper to use
6811 // v_set0 + movlhps or movhlps, etc.
6812 EVT EltVT = VT.getVectorElementType();
6813 ShAmt *= EltVT.getSizeInBits();
6814 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6817 if (isMOVLMask(M, VT)) {
6818 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6819 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6820 if (!isMOVLPMask(M, VT)) {
6821 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6822 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6824 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6825 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6829 // FIXME: fold these into legal mask.
6830 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6831 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6833 if (isMOVHLPSMask(M, VT))
6834 return getMOVHighToLow(Op, dl, DAG);
6836 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6837 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6839 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6840 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6842 if (isMOVLPMask(M, VT))
6843 return getMOVLP(Op, dl, DAG, HasSSE2);
6845 if (ShouldXformToMOVHLPS(M, VT) ||
6846 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6847 return CommuteVectorShuffle(SVOp, DAG);
6850 // No better options. Use a vshldq / vsrldq.
6851 EVT EltVT = VT.getVectorElementType();
6852 ShAmt *= EltVT.getSizeInBits();
6853 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6856 bool Commuted = false;
6857 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6858 // 1,1,1,1 -> v8i16 though.
6859 V1IsSplat = isSplatVector(V1.getNode());
6860 V2IsSplat = isSplatVector(V2.getNode());
6862 // Canonicalize the splat or undef, if present, to be on the RHS.
6863 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6864 CommuteVectorShuffleMask(M, NumElems);
6866 std::swap(V1IsSplat, V2IsSplat);
6870 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6871 // Shuffling low element of v1 into undef, just return v1.
6874 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6875 // the instruction selector will not match, so get a canonical MOVL with
6876 // swapped operands to undo the commute.
6877 return getMOVL(DAG, dl, VT, V2, V1);
6880 if (isUNPCKLMask(M, VT, HasAVX2))
6881 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6883 if (isUNPCKHMask(M, VT, HasAVX2))
6884 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6887 // Normalize mask so all entries that point to V2 points to its first
6888 // element then try to match unpck{h|l} again. If match, return a
6889 // new vector_shuffle with the corrected mask.p
6890 SmallVector<int, 8> NewMask(M.begin(), M.end());
6891 NormalizeMask(NewMask, NumElems);
6892 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6893 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6894 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6895 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6899 // Commute is back and try unpck* again.
6900 // FIXME: this seems wrong.
6901 CommuteVectorShuffleMask(M, NumElems);
6903 std::swap(V1IsSplat, V2IsSplat);
6906 if (isUNPCKLMask(M, VT, HasAVX2))
6907 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6909 if (isUNPCKHMask(M, VT, HasAVX2))
6910 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6913 // Normalize the node to match x86 shuffle ops if needed
6914 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6915 return CommuteVectorShuffle(SVOp, DAG);
6917 // The checks below are all present in isShuffleMaskLegal, but they are
6918 // inlined here right now to enable us to directly emit target specific
6919 // nodes, and remove one by one until they don't return Op anymore.
6921 if (isPALIGNRMask(M, VT, Subtarget))
6922 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6923 getShufflePALIGNRImmediate(SVOp),
6926 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6927 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6928 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6929 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6932 if (isPSHUFHWMask(M, VT, HasAVX2))
6933 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6934 getShufflePSHUFHWImmediate(SVOp),
6937 if (isPSHUFLWMask(M, VT, HasAVX2))
6938 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6939 getShufflePSHUFLWImmediate(SVOp),
6942 if (isSHUFPMask(M, VT, HasAVX))
6943 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6944 getShuffleSHUFImmediate(SVOp), DAG);
6946 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6947 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6948 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6949 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6951 //===--------------------------------------------------------------------===//
6952 // Generate target specific nodes for 128 or 256-bit shuffles only
6953 // supported in the AVX instruction set.
6956 // Handle VMOVDDUPY permutations
6957 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6958 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6960 // Handle VPERMILPS/D* permutations
6961 if (isVPERMILPMask(M, VT, HasAVX)) {
6962 if (HasAVX2 && VT == MVT::v8i32)
6963 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6964 getShuffleSHUFImmediate(SVOp), DAG);
6965 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6966 getShuffleSHUFImmediate(SVOp), DAG);
6969 // Handle VPERM2F128/VPERM2I128 permutations
6970 if (isVPERM2X128Mask(M, VT, HasAVX))
6971 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6972 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6974 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6975 if (BlendOp.getNode())
6978 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6979 SmallVector<SDValue, 8> permclMask;
6980 for (unsigned i = 0; i != 8; ++i) {
6981 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6983 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6985 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6986 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6987 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6990 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6991 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6992 getShuffleCLImmediate(SVOp), DAG);
6995 //===--------------------------------------------------------------------===//
6996 // Since no target specific shuffle was selected for this generic one,
6997 // lower it into other known shuffles. FIXME: this isn't true yet, but
6998 // this is the plan.
7001 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7002 if (VT == MVT::v8i16) {
7003 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7004 if (NewOp.getNode())
7008 if (VT == MVT::v16i8) {
7009 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7010 if (NewOp.getNode())
7014 if (VT == MVT::v32i8) {
7015 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7016 if (NewOp.getNode())
7020 // Handle all 128-bit wide vectors with 4 elements, and match them with
7021 // several different shuffle types.
7022 if (NumElems == 4 && VT.is128BitVector())
7023 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7025 // Handle general 256-bit shuffles
7026 if (VT.is256BitVector())
7027 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7033 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7034 SelectionDAG &DAG) const {
7035 EVT VT = Op.getValueType();
7036 DebugLoc dl = Op.getDebugLoc();
7038 if (!Op.getOperand(0).getValueType().is128BitVector())
7041 if (VT.getSizeInBits() == 8) {
7042 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7043 Op.getOperand(0), Op.getOperand(1));
7044 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7045 DAG.getValueType(VT));
7046 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7049 if (VT.getSizeInBits() == 16) {
7050 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7051 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7053 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7054 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7055 DAG.getNode(ISD::BITCAST, dl,
7059 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7060 Op.getOperand(0), Op.getOperand(1));
7061 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7062 DAG.getValueType(VT));
7063 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7066 if (VT == MVT::f32) {
7067 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7068 // the result back to FR32 register. It's only worth matching if the
7069 // result has a single use which is a store or a bitcast to i32. And in
7070 // the case of a store, it's not worth it if the index is a constant 0,
7071 // because a MOVSSmr can be used instead, which is smaller and faster.
7072 if (!Op.hasOneUse())
7074 SDNode *User = *Op.getNode()->use_begin();
7075 if ((User->getOpcode() != ISD::STORE ||
7076 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7077 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7078 (User->getOpcode() != ISD::BITCAST ||
7079 User->getValueType(0) != MVT::i32))
7081 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7082 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7085 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7088 if (VT == MVT::i32 || VT == MVT::i64) {
7089 // ExtractPS/pextrq works with constant index.
7090 if (isa<ConstantSDNode>(Op.getOperand(1)))
7098 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7099 SelectionDAG &DAG) const {
7100 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7103 SDValue Vec = Op.getOperand(0);
7104 EVT VecVT = Vec.getValueType();
7106 // If this is a 256-bit vector result, first extract the 128-bit vector and
7107 // then extract the element from the 128-bit vector.
7108 if (VecVT.is256BitVector()) {
7109 DebugLoc dl = Op.getNode()->getDebugLoc();
7110 unsigned NumElems = VecVT.getVectorNumElements();
7111 SDValue Idx = Op.getOperand(1);
7112 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7114 // Get the 128-bit vector.
7115 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7117 if (IdxVal >= NumElems/2)
7118 IdxVal -= NumElems/2;
7119 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7120 DAG.getConstant(IdxVal, MVT::i32));
7123 assert(VecVT.is128BitVector() && "Unexpected vector length");
7125 if (Subtarget->hasSSE41()) {
7126 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7131 EVT VT = Op.getValueType();
7132 DebugLoc dl = Op.getDebugLoc();
7133 // TODO: handle v16i8.
7134 if (VT.getSizeInBits() == 16) {
7135 SDValue Vec = Op.getOperand(0);
7136 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7138 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7139 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7140 DAG.getNode(ISD::BITCAST, dl,
7143 // Transform it so it match pextrw which produces a 32-bit result.
7144 EVT EltVT = MVT::i32;
7145 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7146 Op.getOperand(0), Op.getOperand(1));
7147 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7148 DAG.getValueType(VT));
7149 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7152 if (VT.getSizeInBits() == 32) {
7153 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7157 // SHUFPS the element to the lowest double word, then movss.
7158 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7159 EVT VVT = Op.getOperand(0).getValueType();
7160 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7161 DAG.getUNDEF(VVT), Mask);
7162 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7163 DAG.getIntPtrConstant(0));
7166 if (VT.getSizeInBits() == 64) {
7167 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7168 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7169 // to match extract_elt for f64.
7170 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7174 // UNPCKHPD the element to the lowest double word, then movsd.
7175 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7176 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7177 int Mask[2] = { 1, -1 };
7178 EVT VVT = Op.getOperand(0).getValueType();
7179 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7180 DAG.getUNDEF(VVT), Mask);
7181 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7182 DAG.getIntPtrConstant(0));
7189 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7190 SelectionDAG &DAG) const {
7191 EVT VT = Op.getValueType();
7192 EVT EltVT = VT.getVectorElementType();
7193 DebugLoc dl = Op.getDebugLoc();
7195 SDValue N0 = Op.getOperand(0);
7196 SDValue N1 = Op.getOperand(1);
7197 SDValue N2 = Op.getOperand(2);
7199 if (!VT.is128BitVector())
7202 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7203 isa<ConstantSDNode>(N2)) {
7205 if (VT == MVT::v8i16)
7206 Opc = X86ISD::PINSRW;
7207 else if (VT == MVT::v16i8)
7208 Opc = X86ISD::PINSRB;
7210 Opc = X86ISD::PINSRB;
7212 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7214 if (N1.getValueType() != MVT::i32)
7215 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7216 if (N2.getValueType() != MVT::i32)
7217 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7218 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7221 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7222 // Bits [7:6] of the constant are the source select. This will always be
7223 // zero here. The DAG Combiner may combine an extract_elt index into these
7224 // bits. For example (insert (extract, 3), 2) could be matched by putting
7225 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7226 // Bits [5:4] of the constant are the destination select. This is the
7227 // value of the incoming immediate.
7228 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7229 // combine either bitwise AND or insert of float 0.0 to set these bits.
7230 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7231 // Create this as a scalar to vector..
7232 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7233 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7236 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7237 // PINSR* works with constant index.
7244 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7245 EVT VT = Op.getValueType();
7246 EVT EltVT = VT.getVectorElementType();
7248 DebugLoc dl = Op.getDebugLoc();
7249 SDValue N0 = Op.getOperand(0);
7250 SDValue N1 = Op.getOperand(1);
7251 SDValue N2 = Op.getOperand(2);
7253 // If this is a 256-bit vector result, first extract the 128-bit vector,
7254 // insert the element into the extracted half and then place it back.
7255 if (VT.is256BitVector()) {
7256 if (!isa<ConstantSDNode>(N2))
7259 // Get the desired 128-bit vector half.
7260 unsigned NumElems = VT.getVectorNumElements();
7261 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7262 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7264 // Insert the element into the desired half.
7265 bool Upper = IdxVal >= NumElems/2;
7266 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7267 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7269 // Insert the changed part back to the 256-bit vector
7270 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7273 if (Subtarget->hasSSE41())
7274 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7276 if (EltVT == MVT::i8)
7279 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7280 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7281 // as its second argument.
7282 if (N1.getValueType() != MVT::i32)
7283 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7284 if (N2.getValueType() != MVT::i32)
7285 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7286 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7291 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7292 LLVMContext *Context = DAG.getContext();
7293 DebugLoc dl = Op.getDebugLoc();
7294 EVT OpVT = Op.getValueType();
7296 // If this is a 256-bit vector result, first insert into a 128-bit
7297 // vector and then insert into the 256-bit vector.
7298 if (!OpVT.is128BitVector()) {
7299 // Insert into a 128-bit vector.
7300 EVT VT128 = EVT::getVectorVT(*Context,
7301 OpVT.getVectorElementType(),
7302 OpVT.getVectorNumElements() / 2);
7304 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7306 // Insert the 128-bit vector.
7307 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7310 if (OpVT == MVT::v1i64 &&
7311 Op.getOperand(0).getValueType() == MVT::i64)
7312 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7314 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7315 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7316 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7317 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7320 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7321 // a simple subregister reference or explicit instructions to grab
7322 // upper bits of a vector.
7323 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7324 SelectionDAG &DAG) {
7325 if (Subtarget->hasAVX()) {
7326 DebugLoc dl = Op.getNode()->getDebugLoc();
7327 SDValue Vec = Op.getNode()->getOperand(0);
7328 SDValue Idx = Op.getNode()->getOperand(1);
7330 if (Op.getNode()->getValueType(0).is128BitVector() &&
7331 Vec.getNode()->getValueType(0).is256BitVector() &&
7332 isa<ConstantSDNode>(Idx)) {
7333 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7334 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7340 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7341 // simple superregister reference or explicit instructions to insert
7342 // the upper bits of a vector.
7343 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7344 SelectionDAG &DAG) {
7345 if (Subtarget->hasAVX()) {
7346 DebugLoc dl = Op.getNode()->getDebugLoc();
7347 SDValue Vec = Op.getNode()->getOperand(0);
7348 SDValue SubVec = Op.getNode()->getOperand(1);
7349 SDValue Idx = Op.getNode()->getOperand(2);
7351 if (Op.getNode()->getValueType(0).is256BitVector() &&
7352 SubVec.getNode()->getValueType(0).is128BitVector() &&
7353 isa<ConstantSDNode>(Idx)) {
7354 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7355 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7361 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7362 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7363 // one of the above mentioned nodes. It has to be wrapped because otherwise
7364 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7365 // be used to form addressing mode. These wrapped nodes will be selected
7368 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7369 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7371 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7373 unsigned char OpFlag = 0;
7374 unsigned WrapperKind = X86ISD::Wrapper;
7375 CodeModel::Model M = getTargetMachine().getCodeModel();
7377 if (Subtarget->isPICStyleRIPRel() &&
7378 (M == CodeModel::Small || M == CodeModel::Kernel))
7379 WrapperKind = X86ISD::WrapperRIP;
7380 else if (Subtarget->isPICStyleGOT())
7381 OpFlag = X86II::MO_GOTOFF;
7382 else if (Subtarget->isPICStyleStubPIC())
7383 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7385 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7387 CP->getOffset(), OpFlag);
7388 DebugLoc DL = CP->getDebugLoc();
7389 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7390 // With PIC, the address is actually $g + Offset.
7392 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7393 DAG.getNode(X86ISD::GlobalBaseReg,
7394 DebugLoc(), getPointerTy()),
7401 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7402 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7404 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7406 unsigned char OpFlag = 0;
7407 unsigned WrapperKind = X86ISD::Wrapper;
7408 CodeModel::Model M = getTargetMachine().getCodeModel();
7410 if (Subtarget->isPICStyleRIPRel() &&
7411 (M == CodeModel::Small || M == CodeModel::Kernel))
7412 WrapperKind = X86ISD::WrapperRIP;
7413 else if (Subtarget->isPICStyleGOT())
7414 OpFlag = X86II::MO_GOTOFF;
7415 else if (Subtarget->isPICStyleStubPIC())
7416 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7418 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7420 DebugLoc DL = JT->getDebugLoc();
7421 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7423 // With PIC, the address is actually $g + Offset.
7425 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7426 DAG.getNode(X86ISD::GlobalBaseReg,
7427 DebugLoc(), getPointerTy()),
7434 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7435 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7437 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7439 unsigned char OpFlag = 0;
7440 unsigned WrapperKind = X86ISD::Wrapper;
7441 CodeModel::Model M = getTargetMachine().getCodeModel();
7443 if (Subtarget->isPICStyleRIPRel() &&
7444 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7445 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7446 OpFlag = X86II::MO_GOTPCREL;
7447 WrapperKind = X86ISD::WrapperRIP;
7448 } else if (Subtarget->isPICStyleGOT()) {
7449 OpFlag = X86II::MO_GOT;
7450 } else if (Subtarget->isPICStyleStubPIC()) {
7451 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7452 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7453 OpFlag = X86II::MO_DARWIN_NONLAZY;
7456 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7458 DebugLoc DL = Op.getDebugLoc();
7459 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7462 // With PIC, the address is actually $g + Offset.
7463 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7464 !Subtarget->is64Bit()) {
7465 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7466 DAG.getNode(X86ISD::GlobalBaseReg,
7467 DebugLoc(), getPointerTy()),
7471 // For symbols that require a load from a stub to get the address, emit the
7473 if (isGlobalStubReference(OpFlag))
7474 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7475 MachinePointerInfo::getGOT(), false, false, false, 0);
7481 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7482 // Create the TargetBlockAddressAddress node.
7483 unsigned char OpFlags =
7484 Subtarget->ClassifyBlockAddressReference();
7485 CodeModel::Model M = getTargetMachine().getCodeModel();
7486 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7487 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7488 DebugLoc dl = Op.getDebugLoc();
7489 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7492 if (Subtarget->isPICStyleRIPRel() &&
7493 (M == CodeModel::Small || M == CodeModel::Kernel))
7494 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7496 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7498 // With PIC, the address is actually $g + Offset.
7499 if (isGlobalRelativeToPICBase(OpFlags)) {
7500 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7501 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7509 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7511 SelectionDAG &DAG) const {
7512 // Create the TargetGlobalAddress node, folding in the constant
7513 // offset if it is legal.
7514 unsigned char OpFlags =
7515 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7516 CodeModel::Model M = getTargetMachine().getCodeModel();
7518 if (OpFlags == X86II::MO_NO_FLAG &&
7519 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7520 // A direct static reference to a global.
7521 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7524 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7527 if (Subtarget->isPICStyleRIPRel() &&
7528 (M == CodeModel::Small || M == CodeModel::Kernel))
7529 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7531 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7533 // With PIC, the address is actually $g + Offset.
7534 if (isGlobalRelativeToPICBase(OpFlags)) {
7535 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7536 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7540 // For globals that require a load from a stub to get the address, emit the
7542 if (isGlobalStubReference(OpFlags))
7543 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7544 MachinePointerInfo::getGOT(), false, false, false, 0);
7546 // If there was a non-zero offset that we didn't fold, create an explicit
7549 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7550 DAG.getConstant(Offset, getPointerTy()));
7556 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7557 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7558 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7559 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7563 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7564 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7565 unsigned char OperandFlags, bool LocalDynamic = false) {
7566 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7567 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7568 DebugLoc dl = GA->getDebugLoc();
7569 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7570 GA->getValueType(0),
7574 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7578 SDValue Ops[] = { Chain, TGA, *InFlag };
7579 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7581 SDValue Ops[] = { Chain, TGA };
7582 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7585 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7586 MFI->setAdjustsStack(true);
7588 SDValue Flag = Chain.getValue(1);
7589 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7592 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7594 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7597 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7598 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7599 DAG.getNode(X86ISD::GlobalBaseReg,
7600 DebugLoc(), PtrVT), InFlag);
7601 InFlag = Chain.getValue(1);
7603 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7606 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7608 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7610 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7611 X86::RAX, X86II::MO_TLSGD);
7614 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7618 DebugLoc dl = GA->getDebugLoc();
7620 // Get the start address of the TLS block for this module.
7621 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7622 .getInfo<X86MachineFunctionInfo>();
7623 MFI->incNumLocalDynamicTLSAccesses();
7627 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7628 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7631 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7632 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7633 InFlag = Chain.getValue(1);
7634 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7635 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7638 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7642 unsigned char OperandFlags = X86II::MO_DTPOFF;
7643 unsigned WrapperKind = X86ISD::Wrapper;
7644 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7645 GA->getValueType(0),
7646 GA->getOffset(), OperandFlags);
7647 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7649 // Add x@dtpoff with the base.
7650 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7653 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7654 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7655 const EVT PtrVT, TLSModel::Model model,
7656 bool is64Bit, bool isPIC) {
7657 DebugLoc dl = GA->getDebugLoc();
7659 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7660 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7661 is64Bit ? 257 : 256));
7663 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7664 DAG.getIntPtrConstant(0),
7665 MachinePointerInfo(Ptr),
7666 false, false, false, 0);
7668 unsigned char OperandFlags = 0;
7669 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7671 unsigned WrapperKind = X86ISD::Wrapper;
7672 if (model == TLSModel::LocalExec) {
7673 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7674 } else if (model == TLSModel::InitialExec) {
7676 OperandFlags = X86II::MO_GOTTPOFF;
7677 WrapperKind = X86ISD::WrapperRIP;
7679 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7682 llvm_unreachable("Unexpected model");
7685 // emit "addl x@ntpoff,%eax" (local exec)
7686 // or "addl x@indntpoff,%eax" (initial exec)
7687 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7688 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7689 GA->getValueType(0),
7690 GA->getOffset(), OperandFlags);
7691 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7693 if (model == TLSModel::InitialExec) {
7694 if (isPIC && !is64Bit) {
7695 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7696 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7700 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7701 MachinePointerInfo::getGOT(), false, false, false,
7705 // The address of the thread local variable is the add of the thread
7706 // pointer with the offset of the variable.
7707 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7711 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7713 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7714 const GlobalValue *GV = GA->getGlobal();
7716 if (Subtarget->isTargetELF()) {
7717 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7720 case TLSModel::GeneralDynamic:
7721 if (Subtarget->is64Bit())
7722 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7723 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7724 case TLSModel::LocalDynamic:
7725 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7726 Subtarget->is64Bit());
7727 case TLSModel::InitialExec:
7728 case TLSModel::LocalExec:
7729 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7730 Subtarget->is64Bit(),
7731 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7733 llvm_unreachable("Unknown TLS model.");
7736 if (Subtarget->isTargetDarwin()) {
7737 // Darwin only has one model of TLS. Lower to that.
7738 unsigned char OpFlag = 0;
7739 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7740 X86ISD::WrapperRIP : X86ISD::Wrapper;
7742 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7744 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7745 !Subtarget->is64Bit();
7747 OpFlag = X86II::MO_TLVP_PIC_BASE;
7749 OpFlag = X86II::MO_TLVP;
7750 DebugLoc DL = Op.getDebugLoc();
7751 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7752 GA->getValueType(0),
7753 GA->getOffset(), OpFlag);
7754 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7756 // With PIC32, the address is actually $g + Offset.
7758 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7759 DAG.getNode(X86ISD::GlobalBaseReg,
7760 DebugLoc(), getPointerTy()),
7763 // Lowering the machine isd will make sure everything is in the right
7765 SDValue Chain = DAG.getEntryNode();
7766 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7767 SDValue Args[] = { Chain, Offset };
7768 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7770 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7771 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7772 MFI->setAdjustsStack(true);
7774 // And our return value (tls address) is in the standard call return value
7776 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7777 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7781 if (Subtarget->isTargetWindows()) {
7782 // Just use the implicit TLS architecture
7783 // Need to generate someting similar to:
7784 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7786 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7787 // mov rcx, qword [rdx+rcx*8]
7788 // mov eax, .tls$:tlsvar
7789 // [rax+rcx] contains the address
7790 // Windows 64bit: gs:0x58
7791 // Windows 32bit: fs:__tls_array
7793 // If GV is an alias then use the aliasee for determining
7794 // thread-localness.
7795 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7796 GV = GA->resolveAliasedGlobal(false);
7797 DebugLoc dl = GA->getDebugLoc();
7798 SDValue Chain = DAG.getEntryNode();
7800 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7801 // %gs:0x58 (64-bit).
7802 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7803 ? Type::getInt8PtrTy(*DAG.getContext(),
7805 : Type::getInt32PtrTy(*DAG.getContext(),
7808 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7809 Subtarget->is64Bit()
7810 ? DAG.getIntPtrConstant(0x58)
7811 : DAG.getExternalSymbol("_tls_array",
7813 MachinePointerInfo(Ptr),
7814 false, false, false, 0);
7816 // Load the _tls_index variable
7817 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7818 if (Subtarget->is64Bit())
7819 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7820 IDX, MachinePointerInfo(), MVT::i32,
7823 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7824 false, false, false, 0);
7826 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize(0)),
7828 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7830 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7831 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7832 false, false, false, 0);
7834 // Get the offset of start of .tls section
7835 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7836 GA->getValueType(0),
7837 GA->getOffset(), X86II::MO_SECREL);
7838 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7840 // The address of the thread local variable is the add of the thread
7841 // pointer with the offset of the variable.
7842 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7845 llvm_unreachable("TLS not implemented for this target.");
7849 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7850 /// and take a 2 x i32 value to shift plus a shift amount.
7851 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7852 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7853 EVT VT = Op.getValueType();
7854 unsigned VTBits = VT.getSizeInBits();
7855 DebugLoc dl = Op.getDebugLoc();
7856 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7857 SDValue ShOpLo = Op.getOperand(0);
7858 SDValue ShOpHi = Op.getOperand(1);
7859 SDValue ShAmt = Op.getOperand(2);
7860 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7861 DAG.getConstant(VTBits - 1, MVT::i8))
7862 : DAG.getConstant(0, VT);
7865 if (Op.getOpcode() == ISD::SHL_PARTS) {
7866 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7867 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7869 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7870 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7873 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7874 DAG.getConstant(VTBits, MVT::i8));
7875 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7876 AndNode, DAG.getConstant(0, MVT::i8));
7879 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7880 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7881 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7883 if (Op.getOpcode() == ISD::SHL_PARTS) {
7884 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7885 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7887 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7888 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7891 SDValue Ops[2] = { Lo, Hi };
7892 return DAG.getMergeValues(Ops, 2, dl);
7895 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7896 SelectionDAG &DAG) const {
7897 EVT SrcVT = Op.getOperand(0).getValueType();
7899 if (SrcVT.isVector())
7902 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7903 "Unknown SINT_TO_FP to lower!");
7905 // These are really Legal; return the operand so the caller accepts it as
7907 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7909 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7910 Subtarget->is64Bit()) {
7914 DebugLoc dl = Op.getDebugLoc();
7915 unsigned Size = SrcVT.getSizeInBits()/8;
7916 MachineFunction &MF = DAG.getMachineFunction();
7917 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7918 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7919 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7921 MachinePointerInfo::getFixedStack(SSFI),
7923 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7926 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7928 SelectionDAG &DAG) const {
7930 DebugLoc DL = Op.getDebugLoc();
7932 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7934 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7936 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7938 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7940 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7941 MachineMemOperand *MMO;
7943 int SSFI = FI->getIndex();
7945 DAG.getMachineFunction()
7946 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7947 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7949 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7950 StackSlot = StackSlot.getOperand(1);
7952 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7953 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7955 Tys, Ops, array_lengthof(Ops),
7959 Chain = Result.getValue(1);
7960 SDValue InFlag = Result.getValue(2);
7962 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7963 // shouldn't be necessary except that RFP cannot be live across
7964 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7965 MachineFunction &MF = DAG.getMachineFunction();
7966 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7967 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7968 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7969 Tys = DAG.getVTList(MVT::Other);
7971 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7973 MachineMemOperand *MMO =
7974 DAG.getMachineFunction()
7975 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7976 MachineMemOperand::MOStore, SSFISize, SSFISize);
7978 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7979 Ops, array_lengthof(Ops),
7980 Op.getValueType(), MMO);
7981 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7982 MachinePointerInfo::getFixedStack(SSFI),
7983 false, false, false, 0);
7989 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7990 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7991 SelectionDAG &DAG) const {
7992 // This algorithm is not obvious. Here it is what we're trying to output:
7995 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7996 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8000 pshufd $0x4e, %xmm0, %xmm1
8005 DebugLoc dl = Op.getDebugLoc();
8006 LLVMContext *Context = DAG.getContext();
8008 // Build some magic constants.
8009 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8010 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8011 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8013 SmallVector<Constant*,2> CV1;
8015 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
8017 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
8018 Constant *C1 = ConstantVector::get(CV1);
8019 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8021 // Load the 64-bit value into an XMM register.
8022 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8024 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8025 MachinePointerInfo::getConstantPool(),
8026 false, false, false, 16);
8027 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8028 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8031 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8032 MachinePointerInfo::getConstantPool(),
8033 false, false, false, 16);
8034 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8035 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8038 if (Subtarget->hasSSE3()) {
8039 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8040 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8042 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8043 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8045 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8046 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8050 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8051 DAG.getIntPtrConstant(0));
8054 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8055 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8056 SelectionDAG &DAG) const {
8057 DebugLoc dl = Op.getDebugLoc();
8058 // FP constant to bias correct the final result.
8059 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8062 // Load the 32-bit value into an XMM register.
8063 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8066 // Zero out the upper parts of the register.
8067 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8069 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8070 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8071 DAG.getIntPtrConstant(0));
8073 // Or the load with the bias.
8074 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8075 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8076 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8078 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8079 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8080 MVT::v2f64, Bias)));
8081 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8082 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8083 DAG.getIntPtrConstant(0));
8085 // Subtract the bias.
8086 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8088 // Handle final rounding.
8089 EVT DestVT = Op.getValueType();
8091 if (DestVT.bitsLT(MVT::f64))
8092 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8093 DAG.getIntPtrConstant(0));
8094 if (DestVT.bitsGT(MVT::f64))
8095 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8097 // Handle final rounding.
8101 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8102 SelectionDAG &DAG) const {
8103 SDValue N0 = Op.getOperand(0);
8104 EVT SVT = N0.getValueType();
8105 DebugLoc dl = Op.getDebugLoc();
8107 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8108 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8109 "Custom UINT_TO_FP is not supported!");
8111 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, SVT.getVectorNumElements());
8112 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8113 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8116 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8117 SelectionDAG &DAG) const {
8118 SDValue N0 = Op.getOperand(0);
8119 DebugLoc dl = Op.getDebugLoc();
8121 if (Op.getValueType().isVector())
8122 return lowerUINT_TO_FP_vec(Op, DAG);
8124 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8125 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8126 // the optimization here.
8127 if (DAG.SignBitIsZero(N0))
8128 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8130 EVT SrcVT = N0.getValueType();
8131 EVT DstVT = Op.getValueType();
8132 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8133 return LowerUINT_TO_FP_i64(Op, DAG);
8134 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8135 return LowerUINT_TO_FP_i32(Op, DAG);
8136 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8139 // Make a 64-bit buffer, and use it to build an FILD.
8140 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8141 if (SrcVT == MVT::i32) {
8142 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8143 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8144 getPointerTy(), StackSlot, WordOff);
8145 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8146 StackSlot, MachinePointerInfo(),
8148 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8149 OffsetSlot, MachinePointerInfo(),
8151 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8155 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8156 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8157 StackSlot, MachinePointerInfo(),
8159 // For i64 source, we need to add the appropriate power of 2 if the input
8160 // was negative. This is the same as the optimization in
8161 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8162 // we must be careful to do the computation in x87 extended precision, not
8163 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8164 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8165 MachineMemOperand *MMO =
8166 DAG.getMachineFunction()
8167 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8168 MachineMemOperand::MOLoad, 8, 8);
8170 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8171 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8172 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8175 APInt FF(32, 0x5F800000ULL);
8177 // Check whether the sign bit is set.
8178 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8179 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8182 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8183 SDValue FudgePtr = DAG.getConstantPool(
8184 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8187 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8188 SDValue Zero = DAG.getIntPtrConstant(0);
8189 SDValue Four = DAG.getIntPtrConstant(4);
8190 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8192 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8194 // Load the value out, extending it from f32 to f80.
8195 // FIXME: Avoid the extend by constructing the right constant pool?
8196 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8197 FudgePtr, MachinePointerInfo::getConstantPool(),
8198 MVT::f32, false, false, 4);
8199 // Extend everything to 80 bits to force it to be done on x87.
8200 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8201 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8204 std::pair<SDValue,SDValue> X86TargetLowering::
8205 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
8206 DebugLoc DL = Op.getDebugLoc();
8208 EVT DstTy = Op.getValueType();
8210 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8211 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8215 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8216 DstTy.getSimpleVT() >= MVT::i16 &&
8217 "Unknown FP_TO_INT to lower!");
8219 // These are really Legal.
8220 if (DstTy == MVT::i32 &&
8221 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8222 return std::make_pair(SDValue(), SDValue());
8223 if (Subtarget->is64Bit() &&
8224 DstTy == MVT::i64 &&
8225 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8226 return std::make_pair(SDValue(), SDValue());
8228 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8229 // stack slot, or into the FTOL runtime function.
8230 MachineFunction &MF = DAG.getMachineFunction();
8231 unsigned MemSize = DstTy.getSizeInBits()/8;
8232 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8233 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8236 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8237 Opc = X86ISD::WIN_FTOL;
8239 switch (DstTy.getSimpleVT().SimpleTy) {
8240 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8241 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8242 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8243 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8246 SDValue Chain = DAG.getEntryNode();
8247 SDValue Value = Op.getOperand(0);
8248 EVT TheVT = Op.getOperand(0).getValueType();
8249 // FIXME This causes a redundant load/store if the SSE-class value is already
8250 // in memory, such as if it is on the callstack.
8251 if (isScalarFPTypeInSSEReg(TheVT)) {
8252 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8253 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8254 MachinePointerInfo::getFixedStack(SSFI),
8256 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8258 Chain, StackSlot, DAG.getValueType(TheVT)
8261 MachineMemOperand *MMO =
8262 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8263 MachineMemOperand::MOLoad, MemSize, MemSize);
8264 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8266 Chain = Value.getValue(1);
8267 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8268 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8271 MachineMemOperand *MMO =
8272 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8273 MachineMemOperand::MOStore, MemSize, MemSize);
8275 if (Opc != X86ISD::WIN_FTOL) {
8276 // Build the FP_TO_INT*_IN_MEM
8277 SDValue Ops[] = { Chain, Value, StackSlot };
8278 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8279 Ops, 3, DstTy, MMO);
8280 return std::make_pair(FIST, StackSlot);
8282 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8283 DAG.getVTList(MVT::Other, MVT::Glue),
8285 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8286 MVT::i32, ftol.getValue(1));
8287 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8288 MVT::i32, eax.getValue(2));
8289 SDValue Ops[] = { eax, edx };
8290 SDValue pair = IsReplace
8291 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8292 : DAG.getMergeValues(Ops, 2, DL);
8293 return std::make_pair(pair, SDValue());
8297 SDValue X86TargetLowering::lowerZERO_EXTEND(SDValue Op, SelectionDAG &DAG) const {
8298 DebugLoc DL = Op.getDebugLoc();
8299 EVT VT = Op.getValueType();
8300 SDValue In = Op.getOperand(0);
8301 EVT SVT = In.getValueType();
8303 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8304 VT.getVectorNumElements() != SVT.getVectorNumElements())
8307 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8309 // AVX2 has better support of integer extending.
8310 if (Subtarget->hasAVX2())
8311 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8313 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8314 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8315 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8316 DAG.getVectorShuffle(MVT::v8i16, DL, In, DAG.getUNDEF(MVT::v8i16), &Mask[0]));
8318 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8321 SDValue X86TargetLowering::lowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8322 DebugLoc DL = Op.getDebugLoc();
8323 EVT VT = Op.getValueType();
8324 EVT SVT = Op.getOperand(0).getValueType();
8326 if (!VT.is128BitVector() || !SVT.is256BitVector() ||
8327 VT.getVectorNumElements() != SVT.getVectorNumElements())
8330 assert(Subtarget->hasAVX() && "256-bit vector is observed without AVX!");
8332 unsigned NumElems = VT.getVectorNumElements();
8333 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8336 SDValue In = Op.getOperand(0);
8337 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8338 // Prepare truncation shuffle mask
8339 for (unsigned i = 0; i != NumElems; ++i)
8341 SDValue V = DAG.getVectorShuffle(NVT, DL,
8342 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8343 DAG.getUNDEF(NVT), &MaskVec[0]);
8344 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8345 DAG.getIntPtrConstant(0));
8348 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8349 SelectionDAG &DAG) const {
8350 if (Op.getValueType().isVector()) {
8351 if (Op.getValueType() == MVT::v8i16)
8352 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), Op.getValueType(),
8353 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8354 MVT::v8i32, Op.getOperand(0)));
8358 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8359 /*IsSigned=*/ true, /*IsReplace=*/ false);
8360 SDValue FIST = Vals.first, StackSlot = Vals.second;
8361 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8362 if (FIST.getNode() == 0) return Op;
8364 if (StackSlot.getNode())
8366 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8367 FIST, StackSlot, MachinePointerInfo(),
8368 false, false, false, 0);
8370 // The node is the result.
8374 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8375 SelectionDAG &DAG) const {
8376 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8377 /*IsSigned=*/ false, /*IsReplace=*/ false);
8378 SDValue FIST = Vals.first, StackSlot = Vals.second;
8379 assert(FIST.getNode() && "Unexpected failure");
8381 if (StackSlot.getNode())
8383 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8384 FIST, StackSlot, MachinePointerInfo(),
8385 false, false, false, 0);
8387 // The node is the result.
8391 SDValue X86TargetLowering::lowerFP_EXTEND(SDValue Op,
8392 SelectionDAG &DAG) const {
8393 DebugLoc DL = Op.getDebugLoc();
8394 EVT VT = Op.getValueType();
8395 SDValue In = Op.getOperand(0);
8396 EVT SVT = In.getValueType();
8398 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8400 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8401 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8402 In, DAG.getUNDEF(SVT)));
8405 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8406 LLVMContext *Context = DAG.getContext();
8407 DebugLoc dl = Op.getDebugLoc();
8408 EVT VT = Op.getValueType();
8410 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8411 if (VT.isVector()) {
8412 EltVT = VT.getVectorElementType();
8413 NumElts = VT.getVectorNumElements();
8416 if (EltVT == MVT::f64)
8417 C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8419 C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8420 C = ConstantVector::getSplat(NumElts, C);
8421 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8422 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8423 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8424 MachinePointerInfo::getConstantPool(),
8425 false, false, false, Alignment);
8426 if (VT.isVector()) {
8427 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8428 return DAG.getNode(ISD::BITCAST, dl, VT,
8429 DAG.getNode(ISD::AND, dl, ANDVT,
8430 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8432 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8434 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8437 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8438 LLVMContext *Context = DAG.getContext();
8439 DebugLoc dl = Op.getDebugLoc();
8440 EVT VT = Op.getValueType();
8442 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8443 if (VT.isVector()) {
8444 EltVT = VT.getVectorElementType();
8445 NumElts = VT.getVectorNumElements();
8448 if (EltVT == MVT::f64)
8449 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8451 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8452 C = ConstantVector::getSplat(NumElts, C);
8453 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8454 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8455 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8456 MachinePointerInfo::getConstantPool(),
8457 false, false, false, Alignment);
8458 if (VT.isVector()) {
8459 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8460 return DAG.getNode(ISD::BITCAST, dl, VT,
8461 DAG.getNode(ISD::XOR, dl, XORVT,
8462 DAG.getNode(ISD::BITCAST, dl, XORVT,
8464 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8467 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8470 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8471 LLVMContext *Context = DAG.getContext();
8472 SDValue Op0 = Op.getOperand(0);
8473 SDValue Op1 = Op.getOperand(1);
8474 DebugLoc dl = Op.getDebugLoc();
8475 EVT VT = Op.getValueType();
8476 EVT SrcVT = Op1.getValueType();
8478 // If second operand is smaller, extend it first.
8479 if (SrcVT.bitsLT(VT)) {
8480 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8483 // And if it is bigger, shrink it first.
8484 if (SrcVT.bitsGT(VT)) {
8485 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8489 // At this point the operands and the result should have the same
8490 // type, and that won't be f80 since that is not custom lowered.
8492 // First get the sign bit of second operand.
8493 SmallVector<Constant*,4> CV;
8494 if (SrcVT == MVT::f64) {
8495 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8496 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8498 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8499 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8500 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8501 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8503 Constant *C = ConstantVector::get(CV);
8504 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8505 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8506 MachinePointerInfo::getConstantPool(),
8507 false, false, false, 16);
8508 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8510 // Shift sign bit right or left if the two operands have different types.
8511 if (SrcVT.bitsGT(VT)) {
8512 // Op0 is MVT::f32, Op1 is MVT::f64.
8513 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8514 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8515 DAG.getConstant(32, MVT::i32));
8516 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8517 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8518 DAG.getIntPtrConstant(0));
8521 // Clear first operand sign bit.
8523 if (VT == MVT::f64) {
8524 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8525 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8527 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8528 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8529 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8530 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8532 C = ConstantVector::get(CV);
8533 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8534 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8535 MachinePointerInfo::getConstantPool(),
8536 false, false, false, 16);
8537 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8539 // Or the value with the sign bit.
8540 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8543 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8544 SDValue N0 = Op.getOperand(0);
8545 DebugLoc dl = Op.getDebugLoc();
8546 EVT VT = Op.getValueType();
8548 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8549 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8550 DAG.getConstant(1, VT));
8551 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8554 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8556 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op, SelectionDAG &DAG) const {
8557 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8559 if (!Subtarget->hasSSE41())
8562 if (!Op->hasOneUse())
8565 SDNode *N = Op.getNode();
8566 DebugLoc DL = N->getDebugLoc();
8568 SmallVector<SDValue, 8> Opnds;
8569 DenseMap<SDValue, unsigned> VecInMap;
8570 EVT VT = MVT::Other;
8572 // Recognize a special case where a vector is casted into wide integer to
8574 Opnds.push_back(N->getOperand(0));
8575 Opnds.push_back(N->getOperand(1));
8577 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8578 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8579 // BFS traverse all OR'd operands.
8580 if (I->getOpcode() == ISD::OR) {
8581 Opnds.push_back(I->getOperand(0));
8582 Opnds.push_back(I->getOperand(1));
8583 // Re-evaluate the number of nodes to be traversed.
8584 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8588 // Quit if a non-EXTRACT_VECTOR_ELT
8589 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8592 // Quit if without a constant index.
8593 SDValue Idx = I->getOperand(1);
8594 if (!isa<ConstantSDNode>(Idx))
8597 SDValue ExtractedFromVec = I->getOperand(0);
8598 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8599 if (M == VecInMap.end()) {
8600 VT = ExtractedFromVec.getValueType();
8601 // Quit if not 128/256-bit vector.
8602 if (!VT.is128BitVector() && !VT.is256BitVector())
8604 // Quit if not the same type.
8605 if (VecInMap.begin() != VecInMap.end() &&
8606 VT != VecInMap.begin()->first.getValueType())
8608 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8610 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8613 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8614 "Not extracted from 128-/256-bit vector.");
8616 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8617 SmallVector<SDValue, 8> VecIns;
8619 for (DenseMap<SDValue, unsigned>::const_iterator
8620 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8621 // Quit if not all elements are used.
8622 if (I->second != FullMask)
8624 VecIns.push_back(I->first);
8627 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8629 // Cast all vectors into TestVT for PTEST.
8630 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8631 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8633 // If more than one full vectors are evaluated, OR them first before PTEST.
8634 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8635 // Each iteration will OR 2 nodes and append the result until there is only
8636 // 1 node left, i.e. the final OR'd value of all vectors.
8637 SDValue LHS = VecIns[Slot];
8638 SDValue RHS = VecIns[Slot + 1];
8639 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8642 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8643 VecIns.back(), VecIns.back());
8646 /// Emit nodes that will be selected as "test Op0,Op0", or something
8648 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8649 SelectionDAG &DAG) const {
8650 DebugLoc dl = Op.getDebugLoc();
8652 // CF and OF aren't always set the way we want. Determine which
8653 // of these we need.
8654 bool NeedCF = false;
8655 bool NeedOF = false;
8658 case X86::COND_A: case X86::COND_AE:
8659 case X86::COND_B: case X86::COND_BE:
8662 case X86::COND_G: case X86::COND_GE:
8663 case X86::COND_L: case X86::COND_LE:
8664 case X86::COND_O: case X86::COND_NO:
8669 // See if we can use the EFLAGS value from the operand instead of
8670 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8671 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8672 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8673 // Emit a CMP with 0, which is the TEST pattern.
8674 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8675 DAG.getConstant(0, Op.getValueType()));
8677 unsigned Opcode = 0;
8678 unsigned NumOperands = 0;
8680 // Truncate operations may prevent the merge of the SETCC instruction
8681 // and the arithmetic intruction before it. Attempt to truncate the operands
8682 // of the arithmetic instruction and use a reduced bit-width instruction.
8683 bool NeedTruncation = false;
8684 SDValue ArithOp = Op;
8685 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8686 SDValue Arith = Op->getOperand(0);
8687 // Both the trunc and the arithmetic op need to have one user each.
8688 if (Arith->hasOneUse())
8689 switch (Arith.getOpcode()) {
8696 NeedTruncation = true;
8702 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8703 // which may be the result of a CAST. We use the variable 'Op', which is the
8704 // non-casted variable when we check for possible users.
8705 switch (ArithOp.getOpcode()) {
8707 // Due to an isel shortcoming, be conservative if this add is likely to be
8708 // selected as part of a load-modify-store instruction. When the root node
8709 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8710 // uses of other nodes in the match, such as the ADD in this case. This
8711 // leads to the ADD being left around and reselected, with the result being
8712 // two adds in the output. Alas, even if none our users are stores, that
8713 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8714 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8715 // climbing the DAG back to the root, and it doesn't seem to be worth the
8717 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8718 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8719 if (UI->getOpcode() != ISD::CopyToReg &&
8720 UI->getOpcode() != ISD::SETCC &&
8721 UI->getOpcode() != ISD::STORE)
8724 if (ConstantSDNode *C =
8725 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8726 // An add of one will be selected as an INC.
8727 if (C->getAPIntValue() == 1) {
8728 Opcode = X86ISD::INC;
8733 // An add of negative one (subtract of one) will be selected as a DEC.
8734 if (C->getAPIntValue().isAllOnesValue()) {
8735 Opcode = X86ISD::DEC;
8741 // Otherwise use a regular EFLAGS-setting add.
8742 Opcode = X86ISD::ADD;
8746 // If the primary and result isn't used, don't bother using X86ISD::AND,
8747 // because a TEST instruction will be better.
8748 bool NonFlagUse = false;
8749 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8750 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8752 unsigned UOpNo = UI.getOperandNo();
8753 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8754 // Look pass truncate.
8755 UOpNo = User->use_begin().getOperandNo();
8756 User = *User->use_begin();
8759 if (User->getOpcode() != ISD::BRCOND &&
8760 User->getOpcode() != ISD::SETCC &&
8761 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8774 // Due to the ISEL shortcoming noted above, be conservative if this op is
8775 // likely to be selected as part of a load-modify-store instruction.
8776 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8777 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8778 if (UI->getOpcode() == ISD::STORE)
8781 // Otherwise use a regular EFLAGS-setting instruction.
8782 switch (ArithOp.getOpcode()) {
8783 default: llvm_unreachable("unexpected operator!");
8784 case ISD::SUB: Opcode = X86ISD::SUB; break;
8785 case ISD::XOR: Opcode = X86ISD::XOR; break;
8786 case ISD::AND: Opcode = X86ISD::AND; break;
8788 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8789 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8790 if (EFLAGS.getNode())
8793 Opcode = X86ISD::OR;
8807 return SDValue(Op.getNode(), 1);
8813 // If we found that truncation is beneficial, perform the truncation and
8815 if (NeedTruncation) {
8816 EVT VT = Op.getValueType();
8817 SDValue WideVal = Op->getOperand(0);
8818 EVT WideVT = WideVal.getValueType();
8819 unsigned ConvertedOp = 0;
8820 // Use a target machine opcode to prevent further DAGCombine
8821 // optimizations that may separate the arithmetic operations
8822 // from the setcc node.
8823 switch (WideVal.getOpcode()) {
8825 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8826 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8827 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8828 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8829 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
8833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8834 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
8835 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
8836 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
8837 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
8843 // Emit a CMP with 0, which is the TEST pattern.
8844 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8845 DAG.getConstant(0, Op.getValueType()));
8847 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8848 SmallVector<SDValue, 4> Ops;
8849 for (unsigned i = 0; i != NumOperands; ++i)
8850 Ops.push_back(Op.getOperand(i));
8852 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8853 DAG.ReplaceAllUsesWith(Op, New);
8854 return SDValue(New.getNode(), 1);
8857 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8859 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8860 SelectionDAG &DAG) const {
8861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8862 if (C->getAPIntValue() == 0)
8863 return EmitTest(Op0, X86CC, DAG);
8865 DebugLoc dl = Op0.getDebugLoc();
8866 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
8867 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
8868 // Use SUB instead of CMP to enable CSE between SUB and CMP.
8869 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
8870 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
8872 return SDValue(Sub.getNode(), 1);
8874 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8877 /// Convert a comparison if required by the subtarget.
8878 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8879 SelectionDAG &DAG) const {
8880 // If the subtarget does not support the FUCOMI instruction, floating-point
8881 // comparisons have to be converted.
8882 if (Subtarget->hasCMov() ||
8883 Cmp.getOpcode() != X86ISD::CMP ||
8884 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8885 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8888 // The instruction selector will select an FUCOM instruction instead of
8889 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8890 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8891 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8892 DebugLoc dl = Cmp.getDebugLoc();
8893 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8894 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8895 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8896 DAG.getConstant(8, MVT::i8));
8897 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8898 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8901 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8902 /// if it's possible.
8903 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8904 DebugLoc dl, SelectionDAG &DAG) const {
8905 SDValue Op0 = And.getOperand(0);
8906 SDValue Op1 = And.getOperand(1);
8907 if (Op0.getOpcode() == ISD::TRUNCATE)
8908 Op0 = Op0.getOperand(0);
8909 if (Op1.getOpcode() == ISD::TRUNCATE)
8910 Op1 = Op1.getOperand(0);
8913 if (Op1.getOpcode() == ISD::SHL)
8914 std::swap(Op0, Op1);
8915 if (Op0.getOpcode() == ISD::SHL) {
8916 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8917 if (And00C->getZExtValue() == 1) {
8918 // If we looked past a truncate, check that it's only truncating away
8920 unsigned BitWidth = Op0.getValueSizeInBits();
8921 unsigned AndBitWidth = And.getValueSizeInBits();
8922 if (BitWidth > AndBitWidth) {
8924 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8925 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8929 RHS = Op0.getOperand(1);
8931 } else if (Op1.getOpcode() == ISD::Constant) {
8932 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8933 uint64_t AndRHSVal = AndRHS->getZExtValue();
8934 SDValue AndLHS = Op0;
8936 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8937 LHS = AndLHS.getOperand(0);
8938 RHS = AndLHS.getOperand(1);
8941 // Use BT if the immediate can't be encoded in a TEST instruction.
8942 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8944 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8948 if (LHS.getNode()) {
8949 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8950 // instruction. Since the shift amount is in-range-or-undefined, we know
8951 // that doing a bittest on the i32 value is ok. We extend to i32 because
8952 // the encoding for the i16 version is larger than the i32 version.
8953 // Also promote i16 to i32 for performance / code size reason.
8954 if (LHS.getValueType() == MVT::i8 ||
8955 LHS.getValueType() == MVT::i16)
8956 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8958 // If the operand types disagree, extend the shift amount to match. Since
8959 // BT ignores high bits (like shifts) we can use anyextend.
8960 if (LHS.getValueType() != RHS.getValueType())
8961 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8963 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8964 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8965 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8966 DAG.getConstant(Cond, MVT::i8), BT);
8972 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8974 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8976 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8977 SDValue Op0 = Op.getOperand(0);
8978 SDValue Op1 = Op.getOperand(1);
8979 DebugLoc dl = Op.getDebugLoc();
8980 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8982 // Optimize to BT if possible.
8983 // Lower (X & (1 << N)) == 0 to BT(X, N).
8984 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8985 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8986 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8987 Op1.getOpcode() == ISD::Constant &&
8988 cast<ConstantSDNode>(Op1)->isNullValue() &&
8989 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8990 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8991 if (NewSetCC.getNode())
8995 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8997 if (Op1.getOpcode() == ISD::Constant &&
8998 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8999 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9000 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9002 // If the input is a setcc, then reuse the input setcc or use a new one with
9003 // the inverted condition.
9004 if (Op0.getOpcode() == X86ISD::SETCC) {
9005 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9006 bool Invert = (CC == ISD::SETNE) ^
9007 cast<ConstantSDNode>(Op1)->isNullValue();
9008 if (!Invert) return Op0;
9010 CCode = X86::GetOppositeBranchCondition(CCode);
9011 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9012 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9016 bool isFP = Op1.getValueType().isFloatingPoint();
9017 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9018 if (X86CC == X86::COND_INVALID)
9021 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9022 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9023 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9024 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9027 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9028 // ones, and then concatenate the result back.
9029 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9030 EVT VT = Op.getValueType();
9032 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9033 "Unsupported value type for operation");
9035 unsigned NumElems = VT.getVectorNumElements();
9036 DebugLoc dl = Op.getDebugLoc();
9037 SDValue CC = Op.getOperand(2);
9039 // Extract the LHS vectors
9040 SDValue LHS = Op.getOperand(0);
9041 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9042 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9044 // Extract the RHS vectors
9045 SDValue RHS = Op.getOperand(1);
9046 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9047 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9049 // Issue the operation on the smaller types and concatenate the result back
9050 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9051 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9052 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9053 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9054 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9058 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
9060 SDValue Op0 = Op.getOperand(0);
9061 SDValue Op1 = Op.getOperand(1);
9062 SDValue CC = Op.getOperand(2);
9063 EVT VT = Op.getValueType();
9064 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9065 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
9066 DebugLoc dl = Op.getDebugLoc();
9070 EVT EltVT = Op0.getValueType().getVectorElementType();
9071 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9077 // SSE Condition code mapping:
9086 switch (SetCCOpcode) {
9087 default: llvm_unreachable("Unexpected SETCC condition");
9089 case ISD::SETEQ: SSECC = 0; break;
9091 case ISD::SETGT: Swap = true; // Fallthrough
9093 case ISD::SETOLT: SSECC = 1; break;
9095 case ISD::SETGE: Swap = true; // Fallthrough
9097 case ISD::SETOLE: SSECC = 2; break;
9098 case ISD::SETUO: SSECC = 3; break;
9100 case ISD::SETNE: SSECC = 4; break;
9101 case ISD::SETULE: Swap = true; // Fallthrough
9102 case ISD::SETUGE: SSECC = 5; break;
9103 case ISD::SETULT: Swap = true; // Fallthrough
9104 case ISD::SETUGT: SSECC = 6; break;
9105 case ISD::SETO: SSECC = 7; break;
9107 case ISD::SETONE: SSECC = 8; break;
9110 std::swap(Op0, Op1);
9112 // In the two special cases we can't handle, emit two comparisons.
9115 unsigned CombineOpc;
9116 if (SetCCOpcode == ISD::SETUEQ) {
9117 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9119 assert(SetCCOpcode == ISD::SETONE);
9120 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9123 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9124 DAG.getConstant(CC0, MVT::i8));
9125 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9126 DAG.getConstant(CC1, MVT::i8));
9127 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9129 // Handle all other FP comparisons here.
9130 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9131 DAG.getConstant(SSECC, MVT::i8));
9134 // Break 256-bit integer vector compare into smaller ones.
9135 if (VT.is256BitVector() && !Subtarget->hasAVX2())
9136 return Lower256IntVSETCC(Op, DAG);
9138 // We are handling one of the integer comparisons here. Since SSE only has
9139 // GT and EQ comparisons for integer, swapping operands and multiple
9140 // operations may be required for some comparisons.
9142 bool Swap = false, Invert = false, FlipSigns = false;
9144 switch (SetCCOpcode) {
9145 default: llvm_unreachable("Unexpected SETCC condition");
9146 case ISD::SETNE: Invert = true;
9147 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9148 case ISD::SETLT: Swap = true;
9149 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9150 case ISD::SETGE: Swap = true;
9151 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9152 case ISD::SETULT: Swap = true;
9153 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9154 case ISD::SETUGE: Swap = true;
9155 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9158 std::swap(Op0, Op1);
9160 // Check that the operation in question is available (most are plain SSE2,
9161 // but PCMPGTQ and PCMPEQQ have different requirements).
9162 if (VT == MVT::v2i64) {
9163 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9165 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41())
9169 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9170 // bits of the inputs before performing those operations.
9172 EVT EltVT = VT.getVectorElementType();
9173 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9175 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9176 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9178 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9179 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9182 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9184 // If the logical-not of the result is required, perform that now.
9186 Result = DAG.getNOT(dl, Result, VT);
9191 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9192 static bool isX86LogicalCmp(SDValue Op) {
9193 unsigned Opc = Op.getNode()->getOpcode();
9194 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9195 Opc == X86ISD::SAHF)
9197 if (Op.getResNo() == 1 &&
9198 (Opc == X86ISD::ADD ||
9199 Opc == X86ISD::SUB ||
9200 Opc == X86ISD::ADC ||
9201 Opc == X86ISD::SBB ||
9202 Opc == X86ISD::SMUL ||
9203 Opc == X86ISD::UMUL ||
9204 Opc == X86ISD::INC ||
9205 Opc == X86ISD::DEC ||
9206 Opc == X86ISD::OR ||
9207 Opc == X86ISD::XOR ||
9208 Opc == X86ISD::AND))
9211 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9217 static bool isZero(SDValue V) {
9218 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9219 return C && C->isNullValue();
9222 static bool isAllOnes(SDValue V) {
9223 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9224 return C && C->isAllOnesValue();
9227 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9228 if (V.getOpcode() != ISD::TRUNCATE)
9231 SDValue VOp0 = V.getOperand(0);
9232 unsigned InBits = VOp0.getValueSizeInBits();
9233 unsigned Bits = V.getValueSizeInBits();
9234 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9237 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9238 bool addTest = true;
9239 SDValue Cond = Op.getOperand(0);
9240 SDValue Op1 = Op.getOperand(1);
9241 SDValue Op2 = Op.getOperand(2);
9242 DebugLoc DL = Op.getDebugLoc();
9245 if (Cond.getOpcode() == ISD::SETCC) {
9246 SDValue NewCond = LowerSETCC(Cond, DAG);
9247 if (NewCond.getNode())
9251 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9252 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9253 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9254 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9255 if (Cond.getOpcode() == X86ISD::SETCC &&
9256 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9257 isZero(Cond.getOperand(1).getOperand(1))) {
9258 SDValue Cmp = Cond.getOperand(1);
9260 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9262 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9263 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9264 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9266 SDValue CmpOp0 = Cmp.getOperand(0);
9267 // Apply further optimizations for special cases
9268 // (select (x != 0), -1, 0) -> neg & sbb
9269 // (select (x == 0), 0, -1) -> neg & sbb
9270 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9271 if (YC->isNullValue() &&
9272 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9273 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9274 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9275 DAG.getConstant(0, CmpOp0.getValueType()),
9277 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9278 DAG.getConstant(X86::COND_B, MVT::i8),
9279 SDValue(Neg.getNode(), 1));
9283 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9284 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9285 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9287 SDValue Res = // Res = 0 or -1.
9288 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9289 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9291 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9292 Res = DAG.getNOT(DL, Res, Res.getValueType());
9294 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9295 if (N2C == 0 || !N2C->isNullValue())
9296 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9301 // Look past (and (setcc_carry (cmp ...)), 1).
9302 if (Cond.getOpcode() == ISD::AND &&
9303 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9304 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9305 if (C && C->getAPIntValue() == 1)
9306 Cond = Cond.getOperand(0);
9309 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9310 // setting operand in place of the X86ISD::SETCC.
9311 unsigned CondOpcode = Cond.getOpcode();
9312 if (CondOpcode == X86ISD::SETCC ||
9313 CondOpcode == X86ISD::SETCC_CARRY) {
9314 CC = Cond.getOperand(0);
9316 SDValue Cmp = Cond.getOperand(1);
9317 unsigned Opc = Cmp.getOpcode();
9318 EVT VT = Op.getValueType();
9320 bool IllegalFPCMov = false;
9321 if (VT.isFloatingPoint() && !VT.isVector() &&
9322 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9323 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9325 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9326 Opc == X86ISD::BT) { // FIXME
9330 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9331 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9332 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9333 Cond.getOperand(0).getValueType() != MVT::i8)) {
9334 SDValue LHS = Cond.getOperand(0);
9335 SDValue RHS = Cond.getOperand(1);
9339 switch (CondOpcode) {
9340 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9341 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9342 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9343 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9344 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9345 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9346 default: llvm_unreachable("unexpected overflowing operator");
9348 if (CondOpcode == ISD::UMULO)
9349 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9352 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9354 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9356 if (CondOpcode == ISD::UMULO)
9357 Cond = X86Op.getValue(2);
9359 Cond = X86Op.getValue(1);
9361 CC = DAG.getConstant(X86Cond, MVT::i8);
9366 // Look pass the truncate if the high bits are known zero.
9367 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9368 Cond = Cond.getOperand(0);
9370 // We know the result of AND is compared against zero. Try to match
9372 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9373 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9374 if (NewSetCC.getNode()) {
9375 CC = NewSetCC.getOperand(0);
9376 Cond = NewSetCC.getOperand(1);
9383 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9384 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9387 // a < b ? -1 : 0 -> RES = ~setcc_carry
9388 // a < b ? 0 : -1 -> RES = setcc_carry
9389 // a >= b ? -1 : 0 -> RES = setcc_carry
9390 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9391 if (Cond.getOpcode() == X86ISD::SUB) {
9392 Cond = ConvertCmpIfNecessary(Cond, DAG);
9393 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9395 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9396 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9397 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9398 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9399 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9400 return DAG.getNOT(DL, Res, Res.getValueType());
9405 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9406 // widen the cmov and push the truncate through. This avoids introducing a new
9407 // branch during isel and doesn't add any extensions.
9408 if (Op.getValueType() == MVT::i8 &&
9409 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9410 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9411 if (T1.getValueType() == T2.getValueType() &&
9412 // Blacklist CopyFromReg to avoid partial register stalls.
9413 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9414 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9415 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9416 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9420 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9421 // condition is true.
9422 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9423 SDValue Ops[] = { Op2, Op1, CC, Cond };
9424 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9427 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9428 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9429 // from the AND / OR.
9430 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9431 Opc = Op.getOpcode();
9432 if (Opc != ISD::OR && Opc != ISD::AND)
9434 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9435 Op.getOperand(0).hasOneUse() &&
9436 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9437 Op.getOperand(1).hasOneUse());
9440 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9441 // 1 and that the SETCC node has a single use.
9442 static bool isXor1OfSetCC(SDValue Op) {
9443 if (Op.getOpcode() != ISD::XOR)
9445 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9446 if (N1C && N1C->getAPIntValue() == 1) {
9447 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9448 Op.getOperand(0).hasOneUse();
9453 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9454 bool addTest = true;
9455 SDValue Chain = Op.getOperand(0);
9456 SDValue Cond = Op.getOperand(1);
9457 SDValue Dest = Op.getOperand(2);
9458 DebugLoc dl = Op.getDebugLoc();
9460 bool Inverted = false;
9462 if (Cond.getOpcode() == ISD::SETCC) {
9463 // Check for setcc([su]{add,sub,mul}o == 0).
9464 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9465 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9466 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9467 Cond.getOperand(0).getResNo() == 1 &&
9468 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9469 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9470 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9471 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9472 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9473 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9475 Cond = Cond.getOperand(0);
9477 SDValue NewCond = LowerSETCC(Cond, DAG);
9478 if (NewCond.getNode())
9483 // FIXME: LowerXALUO doesn't handle these!!
9484 else if (Cond.getOpcode() == X86ISD::ADD ||
9485 Cond.getOpcode() == X86ISD::SUB ||
9486 Cond.getOpcode() == X86ISD::SMUL ||
9487 Cond.getOpcode() == X86ISD::UMUL)
9488 Cond = LowerXALUO(Cond, DAG);
9491 // Look pass (and (setcc_carry (cmp ...)), 1).
9492 if (Cond.getOpcode() == ISD::AND &&
9493 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9494 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9495 if (C && C->getAPIntValue() == 1)
9496 Cond = Cond.getOperand(0);
9499 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9500 // setting operand in place of the X86ISD::SETCC.
9501 unsigned CondOpcode = Cond.getOpcode();
9502 if (CondOpcode == X86ISD::SETCC ||
9503 CondOpcode == X86ISD::SETCC_CARRY) {
9504 CC = Cond.getOperand(0);
9506 SDValue Cmp = Cond.getOperand(1);
9507 unsigned Opc = Cmp.getOpcode();
9508 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9509 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9513 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9517 // These can only come from an arithmetic instruction with overflow,
9518 // e.g. SADDO, UADDO.
9519 Cond = Cond.getNode()->getOperand(1);
9525 CondOpcode = Cond.getOpcode();
9526 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9527 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9528 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9529 Cond.getOperand(0).getValueType() != MVT::i8)) {
9530 SDValue LHS = Cond.getOperand(0);
9531 SDValue RHS = Cond.getOperand(1);
9535 switch (CondOpcode) {
9536 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9537 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9538 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9539 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9540 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9541 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9542 default: llvm_unreachable("unexpected overflowing operator");
9545 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9546 if (CondOpcode == ISD::UMULO)
9547 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9550 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9552 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9554 if (CondOpcode == ISD::UMULO)
9555 Cond = X86Op.getValue(2);
9557 Cond = X86Op.getValue(1);
9559 CC = DAG.getConstant(X86Cond, MVT::i8);
9563 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9564 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9565 if (CondOpc == ISD::OR) {
9566 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9567 // two branches instead of an explicit OR instruction with a
9569 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9570 isX86LogicalCmp(Cmp)) {
9571 CC = Cond.getOperand(0).getOperand(0);
9572 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9573 Chain, Dest, CC, Cmp);
9574 CC = Cond.getOperand(1).getOperand(0);
9578 } else { // ISD::AND
9579 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9580 // two branches instead of an explicit AND instruction with a
9581 // separate test. However, we only do this if this block doesn't
9582 // have a fall-through edge, because this requires an explicit
9583 // jmp when the condition is false.
9584 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9585 isX86LogicalCmp(Cmp) &&
9586 Op.getNode()->hasOneUse()) {
9587 X86::CondCode CCode =
9588 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9589 CCode = X86::GetOppositeBranchCondition(CCode);
9590 CC = DAG.getConstant(CCode, MVT::i8);
9591 SDNode *User = *Op.getNode()->use_begin();
9592 // Look for an unconditional branch following this conditional branch.
9593 // We need this because we need to reverse the successors in order
9594 // to implement FCMP_OEQ.
9595 if (User->getOpcode() == ISD::BR) {
9596 SDValue FalseBB = User->getOperand(1);
9598 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9599 assert(NewBR == User);
9603 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9604 Chain, Dest, CC, Cmp);
9605 X86::CondCode CCode =
9606 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9607 CCode = X86::GetOppositeBranchCondition(CCode);
9608 CC = DAG.getConstant(CCode, MVT::i8);
9614 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9615 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9616 // It should be transformed during dag combiner except when the condition
9617 // is set by a arithmetics with overflow node.
9618 X86::CondCode CCode =
9619 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9620 CCode = X86::GetOppositeBranchCondition(CCode);
9621 CC = DAG.getConstant(CCode, MVT::i8);
9622 Cond = Cond.getOperand(0).getOperand(1);
9624 } else if (Cond.getOpcode() == ISD::SETCC &&
9625 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9626 // For FCMP_OEQ, we can emit
9627 // two branches instead of an explicit AND instruction with a
9628 // separate test. However, we only do this if this block doesn't
9629 // have a fall-through edge, because this requires an explicit
9630 // jmp when the condition is false.
9631 if (Op.getNode()->hasOneUse()) {
9632 SDNode *User = *Op.getNode()->use_begin();
9633 // Look for an unconditional branch following this conditional branch.
9634 // We need this because we need to reverse the successors in order
9635 // to implement FCMP_OEQ.
9636 if (User->getOpcode() == ISD::BR) {
9637 SDValue FalseBB = User->getOperand(1);
9639 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9640 assert(NewBR == User);
9644 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9645 Cond.getOperand(0), Cond.getOperand(1));
9646 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9647 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9648 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9649 Chain, Dest, CC, Cmp);
9650 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9655 } else if (Cond.getOpcode() == ISD::SETCC &&
9656 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9657 // For FCMP_UNE, we can emit
9658 // two branches instead of an explicit AND instruction with a
9659 // separate test. However, we only do this if this block doesn't
9660 // have a fall-through edge, because this requires an explicit
9661 // jmp when the condition is false.
9662 if (Op.getNode()->hasOneUse()) {
9663 SDNode *User = *Op.getNode()->use_begin();
9664 // Look for an unconditional branch following this conditional branch.
9665 // We need this because we need to reverse the successors in order
9666 // to implement FCMP_UNE.
9667 if (User->getOpcode() == ISD::BR) {
9668 SDValue FalseBB = User->getOperand(1);
9670 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9671 assert(NewBR == User);
9674 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9675 Cond.getOperand(0), Cond.getOperand(1));
9676 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9677 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9678 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9679 Chain, Dest, CC, Cmp);
9680 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9690 // Look pass the truncate if the high bits are known zero.
9691 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9692 Cond = Cond.getOperand(0);
9694 // We know the result of AND is compared against zero. Try to match
9696 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9697 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9698 if (NewSetCC.getNode()) {
9699 CC = NewSetCC.getOperand(0);
9700 Cond = NewSetCC.getOperand(1);
9707 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9708 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9710 Cond = ConvertCmpIfNecessary(Cond, DAG);
9711 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9712 Chain, Dest, CC, Cond);
9716 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9717 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9718 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9719 // that the guard pages used by the OS virtual memory manager are allocated in
9720 // correct sequence.
9722 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9723 SelectionDAG &DAG) const {
9724 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9725 getTargetMachine().Options.EnableSegmentedStacks) &&
9726 "This should be used only on Windows targets or when segmented stacks "
9728 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9729 DebugLoc dl = Op.getDebugLoc();
9732 SDValue Chain = Op.getOperand(0);
9733 SDValue Size = Op.getOperand(1);
9734 // FIXME: Ensure alignment here
9736 bool Is64Bit = Subtarget->is64Bit();
9737 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9739 if (getTargetMachine().Options.EnableSegmentedStacks) {
9740 MachineFunction &MF = DAG.getMachineFunction();
9741 MachineRegisterInfo &MRI = MF.getRegInfo();
9744 // The 64 bit implementation of segmented stacks needs to clobber both r10
9745 // r11. This makes it impossible to use it along with nested parameters.
9746 const Function *F = MF.getFunction();
9748 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9750 if (I->hasNestAttr())
9751 report_fatal_error("Cannot use segmented stacks with functions that "
9752 "have nested arguments.");
9755 const TargetRegisterClass *AddrRegClass =
9756 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9757 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9758 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9759 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9760 DAG.getRegister(Vreg, SPTy));
9761 SDValue Ops1[2] = { Value, Chain };
9762 return DAG.getMergeValues(Ops1, 2, dl);
9765 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9767 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9768 Flag = Chain.getValue(1);
9769 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9771 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9772 Flag = Chain.getValue(1);
9774 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9776 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9777 return DAG.getMergeValues(Ops1, 2, dl);
9781 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9782 MachineFunction &MF = DAG.getMachineFunction();
9783 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9785 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9786 DebugLoc DL = Op.getDebugLoc();
9788 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9789 // vastart just stores the address of the VarArgsFrameIndex slot into the
9790 // memory location argument.
9791 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9793 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9794 MachinePointerInfo(SV), false, false, 0);
9798 // gp_offset (0 - 6 * 8)
9799 // fp_offset (48 - 48 + 8 * 16)
9800 // overflow_arg_area (point to parameters coming in memory).
9802 SmallVector<SDValue, 8> MemOps;
9803 SDValue FIN = Op.getOperand(1);
9805 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9806 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9808 FIN, MachinePointerInfo(SV), false, false, 0);
9809 MemOps.push_back(Store);
9812 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9813 FIN, DAG.getIntPtrConstant(4));
9814 Store = DAG.getStore(Op.getOperand(0), DL,
9815 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9817 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9818 MemOps.push_back(Store);
9820 // Store ptr to overflow_arg_area
9821 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9822 FIN, DAG.getIntPtrConstant(4));
9823 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9825 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9826 MachinePointerInfo(SV, 8),
9828 MemOps.push_back(Store);
9830 // Store ptr to reg_save_area.
9831 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9832 FIN, DAG.getIntPtrConstant(8));
9833 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9835 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9836 MachinePointerInfo(SV, 16), false, false, 0);
9837 MemOps.push_back(Store);
9838 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9839 &MemOps[0], MemOps.size());
9842 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9843 assert(Subtarget->is64Bit() &&
9844 "LowerVAARG only handles 64-bit va_arg!");
9845 assert((Subtarget->isTargetLinux() ||
9846 Subtarget->isTargetDarwin()) &&
9847 "Unhandled target in LowerVAARG");
9848 assert(Op.getNode()->getNumOperands() == 4);
9849 SDValue Chain = Op.getOperand(0);
9850 SDValue SrcPtr = Op.getOperand(1);
9851 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9852 unsigned Align = Op.getConstantOperandVal(3);
9853 DebugLoc dl = Op.getDebugLoc();
9855 EVT ArgVT = Op.getNode()->getValueType(0);
9856 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9857 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
9860 // Decide which area this value should be read from.
9861 // TODO: Implement the AMD64 ABI in its entirety. This simple
9862 // selection mechanism works only for the basic types.
9863 if (ArgVT == MVT::f80) {
9864 llvm_unreachable("va_arg for f80 not yet implemented");
9865 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9866 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9867 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9868 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9870 llvm_unreachable("Unhandled argument type in LowerVAARG");
9874 // Sanity Check: Make sure using fp_offset makes sense.
9875 assert(!getTargetMachine().Options.UseSoftFloat &&
9876 !(DAG.getMachineFunction()
9877 .getFunction()->getFnAttributes()
9878 .hasAttribute(Attributes::NoImplicitFloat)) &&
9879 Subtarget->hasSSE1());
9882 // Insert VAARG_64 node into the DAG
9883 // VAARG_64 returns two values: Variable Argument Address, Chain
9884 SmallVector<SDValue, 11> InstOps;
9885 InstOps.push_back(Chain);
9886 InstOps.push_back(SrcPtr);
9887 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9888 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9889 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9890 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9891 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9892 VTs, &InstOps[0], InstOps.size(),
9894 MachinePointerInfo(SV),
9899 Chain = VAARG.getValue(1);
9901 // Load the next argument and return it
9902 return DAG.getLoad(ArgVT, dl,
9905 MachinePointerInfo(),
9906 false, false, false, 0);
9909 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
9910 SelectionDAG &DAG) {
9911 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9912 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9913 SDValue Chain = Op.getOperand(0);
9914 SDValue DstPtr = Op.getOperand(1);
9915 SDValue SrcPtr = Op.getOperand(2);
9916 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9917 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9918 DebugLoc DL = Op.getDebugLoc();
9920 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9921 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9923 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9926 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9927 // may or may not be a constant. Takes immediate version of shift as input.
9928 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9929 SDValue SrcOp, SDValue ShAmt,
9930 SelectionDAG &DAG) {
9931 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9933 if (isa<ConstantSDNode>(ShAmt)) {
9934 // Constant may be a TargetConstant. Use a regular constant.
9935 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9937 default: llvm_unreachable("Unknown target vector shift node");
9941 return DAG.getNode(Opc, dl, VT, SrcOp,
9942 DAG.getConstant(ShiftAmt, MVT::i32));
9946 // Change opcode to non-immediate version
9948 default: llvm_unreachable("Unknown target vector shift node");
9949 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9950 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9951 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9954 // Need to build a vector containing shift amount
9955 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9958 ShOps[1] = DAG.getConstant(0, MVT::i32);
9959 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
9960 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9962 // The return type has to be a 128-bit type with the same element
9963 // type as the input type.
9964 MVT EltVT = VT.getVectorElementType().getSimpleVT();
9965 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
9967 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
9968 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9971 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
9972 DebugLoc dl = Op.getDebugLoc();
9973 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9975 default: return SDValue(); // Don't custom lower most intrinsics.
9976 // Comparison intrinsics.
9977 case Intrinsic::x86_sse_comieq_ss:
9978 case Intrinsic::x86_sse_comilt_ss:
9979 case Intrinsic::x86_sse_comile_ss:
9980 case Intrinsic::x86_sse_comigt_ss:
9981 case Intrinsic::x86_sse_comige_ss:
9982 case Intrinsic::x86_sse_comineq_ss:
9983 case Intrinsic::x86_sse_ucomieq_ss:
9984 case Intrinsic::x86_sse_ucomilt_ss:
9985 case Intrinsic::x86_sse_ucomile_ss:
9986 case Intrinsic::x86_sse_ucomigt_ss:
9987 case Intrinsic::x86_sse_ucomige_ss:
9988 case Intrinsic::x86_sse_ucomineq_ss:
9989 case Intrinsic::x86_sse2_comieq_sd:
9990 case Intrinsic::x86_sse2_comilt_sd:
9991 case Intrinsic::x86_sse2_comile_sd:
9992 case Intrinsic::x86_sse2_comigt_sd:
9993 case Intrinsic::x86_sse2_comige_sd:
9994 case Intrinsic::x86_sse2_comineq_sd:
9995 case Intrinsic::x86_sse2_ucomieq_sd:
9996 case Intrinsic::x86_sse2_ucomilt_sd:
9997 case Intrinsic::x86_sse2_ucomile_sd:
9998 case Intrinsic::x86_sse2_ucomigt_sd:
9999 case Intrinsic::x86_sse2_ucomige_sd:
10000 case Intrinsic::x86_sse2_ucomineq_sd: {
10004 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10005 case Intrinsic::x86_sse_comieq_ss:
10006 case Intrinsic::x86_sse2_comieq_sd:
10007 Opc = X86ISD::COMI;
10010 case Intrinsic::x86_sse_comilt_ss:
10011 case Intrinsic::x86_sse2_comilt_sd:
10012 Opc = X86ISD::COMI;
10015 case Intrinsic::x86_sse_comile_ss:
10016 case Intrinsic::x86_sse2_comile_sd:
10017 Opc = X86ISD::COMI;
10020 case Intrinsic::x86_sse_comigt_ss:
10021 case Intrinsic::x86_sse2_comigt_sd:
10022 Opc = X86ISD::COMI;
10025 case Intrinsic::x86_sse_comige_ss:
10026 case Intrinsic::x86_sse2_comige_sd:
10027 Opc = X86ISD::COMI;
10030 case Intrinsic::x86_sse_comineq_ss:
10031 case Intrinsic::x86_sse2_comineq_sd:
10032 Opc = X86ISD::COMI;
10035 case Intrinsic::x86_sse_ucomieq_ss:
10036 case Intrinsic::x86_sse2_ucomieq_sd:
10037 Opc = X86ISD::UCOMI;
10040 case Intrinsic::x86_sse_ucomilt_ss:
10041 case Intrinsic::x86_sse2_ucomilt_sd:
10042 Opc = X86ISD::UCOMI;
10045 case Intrinsic::x86_sse_ucomile_ss:
10046 case Intrinsic::x86_sse2_ucomile_sd:
10047 Opc = X86ISD::UCOMI;
10050 case Intrinsic::x86_sse_ucomigt_ss:
10051 case Intrinsic::x86_sse2_ucomigt_sd:
10052 Opc = X86ISD::UCOMI;
10055 case Intrinsic::x86_sse_ucomige_ss:
10056 case Intrinsic::x86_sse2_ucomige_sd:
10057 Opc = X86ISD::UCOMI;
10060 case Intrinsic::x86_sse_ucomineq_ss:
10061 case Intrinsic::x86_sse2_ucomineq_sd:
10062 Opc = X86ISD::UCOMI;
10067 SDValue LHS = Op.getOperand(1);
10068 SDValue RHS = Op.getOperand(2);
10069 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10070 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10071 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10072 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10073 DAG.getConstant(X86CC, MVT::i8), Cond);
10074 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10077 // Arithmetic intrinsics.
10078 case Intrinsic::x86_sse2_pmulu_dq:
10079 case Intrinsic::x86_avx2_pmulu_dq:
10080 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10081 Op.getOperand(1), Op.getOperand(2));
10083 // SSE3/AVX horizontal add/sub intrinsics
10084 case Intrinsic::x86_sse3_hadd_ps:
10085 case Intrinsic::x86_sse3_hadd_pd:
10086 case Intrinsic::x86_avx_hadd_ps_256:
10087 case Intrinsic::x86_avx_hadd_pd_256:
10088 case Intrinsic::x86_sse3_hsub_ps:
10089 case Intrinsic::x86_sse3_hsub_pd:
10090 case Intrinsic::x86_avx_hsub_ps_256:
10091 case Intrinsic::x86_avx_hsub_pd_256:
10092 case Intrinsic::x86_ssse3_phadd_w_128:
10093 case Intrinsic::x86_ssse3_phadd_d_128:
10094 case Intrinsic::x86_avx2_phadd_w:
10095 case Intrinsic::x86_avx2_phadd_d:
10096 case Intrinsic::x86_ssse3_phsub_w_128:
10097 case Intrinsic::x86_ssse3_phsub_d_128:
10098 case Intrinsic::x86_avx2_phsub_w:
10099 case Intrinsic::x86_avx2_phsub_d: {
10102 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10103 case Intrinsic::x86_sse3_hadd_ps:
10104 case Intrinsic::x86_sse3_hadd_pd:
10105 case Intrinsic::x86_avx_hadd_ps_256:
10106 case Intrinsic::x86_avx_hadd_pd_256:
10107 Opcode = X86ISD::FHADD;
10109 case Intrinsic::x86_sse3_hsub_ps:
10110 case Intrinsic::x86_sse3_hsub_pd:
10111 case Intrinsic::x86_avx_hsub_ps_256:
10112 case Intrinsic::x86_avx_hsub_pd_256:
10113 Opcode = X86ISD::FHSUB;
10115 case Intrinsic::x86_ssse3_phadd_w_128:
10116 case Intrinsic::x86_ssse3_phadd_d_128:
10117 case Intrinsic::x86_avx2_phadd_w:
10118 case Intrinsic::x86_avx2_phadd_d:
10119 Opcode = X86ISD::HADD;
10121 case Intrinsic::x86_ssse3_phsub_w_128:
10122 case Intrinsic::x86_ssse3_phsub_d_128:
10123 case Intrinsic::x86_avx2_phsub_w:
10124 case Intrinsic::x86_avx2_phsub_d:
10125 Opcode = X86ISD::HSUB;
10128 return DAG.getNode(Opcode, dl, Op.getValueType(),
10129 Op.getOperand(1), Op.getOperand(2));
10132 // AVX2 variable shift intrinsics
10133 case Intrinsic::x86_avx2_psllv_d:
10134 case Intrinsic::x86_avx2_psllv_q:
10135 case Intrinsic::x86_avx2_psllv_d_256:
10136 case Intrinsic::x86_avx2_psllv_q_256:
10137 case Intrinsic::x86_avx2_psrlv_d:
10138 case Intrinsic::x86_avx2_psrlv_q:
10139 case Intrinsic::x86_avx2_psrlv_d_256:
10140 case Intrinsic::x86_avx2_psrlv_q_256:
10141 case Intrinsic::x86_avx2_psrav_d:
10142 case Intrinsic::x86_avx2_psrav_d_256: {
10145 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10146 case Intrinsic::x86_avx2_psllv_d:
10147 case Intrinsic::x86_avx2_psllv_q:
10148 case Intrinsic::x86_avx2_psllv_d_256:
10149 case Intrinsic::x86_avx2_psllv_q_256:
10152 case Intrinsic::x86_avx2_psrlv_d:
10153 case Intrinsic::x86_avx2_psrlv_q:
10154 case Intrinsic::x86_avx2_psrlv_d_256:
10155 case Intrinsic::x86_avx2_psrlv_q_256:
10158 case Intrinsic::x86_avx2_psrav_d:
10159 case Intrinsic::x86_avx2_psrav_d_256:
10163 return DAG.getNode(Opcode, dl, Op.getValueType(),
10164 Op.getOperand(1), Op.getOperand(2));
10167 case Intrinsic::x86_ssse3_pshuf_b_128:
10168 case Intrinsic::x86_avx2_pshuf_b:
10169 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10170 Op.getOperand(1), Op.getOperand(2));
10172 case Intrinsic::x86_ssse3_psign_b_128:
10173 case Intrinsic::x86_ssse3_psign_w_128:
10174 case Intrinsic::x86_ssse3_psign_d_128:
10175 case Intrinsic::x86_avx2_psign_b:
10176 case Intrinsic::x86_avx2_psign_w:
10177 case Intrinsic::x86_avx2_psign_d:
10178 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10179 Op.getOperand(1), Op.getOperand(2));
10181 case Intrinsic::x86_sse41_insertps:
10182 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10183 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10185 case Intrinsic::x86_avx_vperm2f128_ps_256:
10186 case Intrinsic::x86_avx_vperm2f128_pd_256:
10187 case Intrinsic::x86_avx_vperm2f128_si_256:
10188 case Intrinsic::x86_avx2_vperm2i128:
10189 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10190 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10192 case Intrinsic::x86_avx2_permd:
10193 case Intrinsic::x86_avx2_permps:
10194 // Operands intentionally swapped. Mask is last operand to intrinsic,
10195 // but second operand for node/intruction.
10196 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10197 Op.getOperand(2), Op.getOperand(1));
10199 // ptest and testp intrinsics. The intrinsic these come from are designed to
10200 // return an integer value, not just an instruction so lower it to the ptest
10201 // or testp pattern and a setcc for the result.
10202 case Intrinsic::x86_sse41_ptestz:
10203 case Intrinsic::x86_sse41_ptestc:
10204 case Intrinsic::x86_sse41_ptestnzc:
10205 case Intrinsic::x86_avx_ptestz_256:
10206 case Intrinsic::x86_avx_ptestc_256:
10207 case Intrinsic::x86_avx_ptestnzc_256:
10208 case Intrinsic::x86_avx_vtestz_ps:
10209 case Intrinsic::x86_avx_vtestc_ps:
10210 case Intrinsic::x86_avx_vtestnzc_ps:
10211 case Intrinsic::x86_avx_vtestz_pd:
10212 case Intrinsic::x86_avx_vtestc_pd:
10213 case Intrinsic::x86_avx_vtestnzc_pd:
10214 case Intrinsic::x86_avx_vtestz_ps_256:
10215 case Intrinsic::x86_avx_vtestc_ps_256:
10216 case Intrinsic::x86_avx_vtestnzc_ps_256:
10217 case Intrinsic::x86_avx_vtestz_pd_256:
10218 case Intrinsic::x86_avx_vtestc_pd_256:
10219 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10220 bool IsTestPacked = false;
10223 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10224 case Intrinsic::x86_avx_vtestz_ps:
10225 case Intrinsic::x86_avx_vtestz_pd:
10226 case Intrinsic::x86_avx_vtestz_ps_256:
10227 case Intrinsic::x86_avx_vtestz_pd_256:
10228 IsTestPacked = true; // Fallthrough
10229 case Intrinsic::x86_sse41_ptestz:
10230 case Intrinsic::x86_avx_ptestz_256:
10232 X86CC = X86::COND_E;
10234 case Intrinsic::x86_avx_vtestc_ps:
10235 case Intrinsic::x86_avx_vtestc_pd:
10236 case Intrinsic::x86_avx_vtestc_ps_256:
10237 case Intrinsic::x86_avx_vtestc_pd_256:
10238 IsTestPacked = true; // Fallthrough
10239 case Intrinsic::x86_sse41_ptestc:
10240 case Intrinsic::x86_avx_ptestc_256:
10242 X86CC = X86::COND_B;
10244 case Intrinsic::x86_avx_vtestnzc_ps:
10245 case Intrinsic::x86_avx_vtestnzc_pd:
10246 case Intrinsic::x86_avx_vtestnzc_ps_256:
10247 case Intrinsic::x86_avx_vtestnzc_pd_256:
10248 IsTestPacked = true; // Fallthrough
10249 case Intrinsic::x86_sse41_ptestnzc:
10250 case Intrinsic::x86_avx_ptestnzc_256:
10252 X86CC = X86::COND_A;
10256 SDValue LHS = Op.getOperand(1);
10257 SDValue RHS = Op.getOperand(2);
10258 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10259 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10260 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10261 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10262 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10265 // SSE/AVX shift intrinsics
10266 case Intrinsic::x86_sse2_psll_w:
10267 case Intrinsic::x86_sse2_psll_d:
10268 case Intrinsic::x86_sse2_psll_q:
10269 case Intrinsic::x86_avx2_psll_w:
10270 case Intrinsic::x86_avx2_psll_d:
10271 case Intrinsic::x86_avx2_psll_q:
10272 case Intrinsic::x86_sse2_psrl_w:
10273 case Intrinsic::x86_sse2_psrl_d:
10274 case Intrinsic::x86_sse2_psrl_q:
10275 case Intrinsic::x86_avx2_psrl_w:
10276 case Intrinsic::x86_avx2_psrl_d:
10277 case Intrinsic::x86_avx2_psrl_q:
10278 case Intrinsic::x86_sse2_psra_w:
10279 case Intrinsic::x86_sse2_psra_d:
10280 case Intrinsic::x86_avx2_psra_w:
10281 case Intrinsic::x86_avx2_psra_d: {
10284 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10285 case Intrinsic::x86_sse2_psll_w:
10286 case Intrinsic::x86_sse2_psll_d:
10287 case Intrinsic::x86_sse2_psll_q:
10288 case Intrinsic::x86_avx2_psll_w:
10289 case Intrinsic::x86_avx2_psll_d:
10290 case Intrinsic::x86_avx2_psll_q:
10291 Opcode = X86ISD::VSHL;
10293 case Intrinsic::x86_sse2_psrl_w:
10294 case Intrinsic::x86_sse2_psrl_d:
10295 case Intrinsic::x86_sse2_psrl_q:
10296 case Intrinsic::x86_avx2_psrl_w:
10297 case Intrinsic::x86_avx2_psrl_d:
10298 case Intrinsic::x86_avx2_psrl_q:
10299 Opcode = X86ISD::VSRL;
10301 case Intrinsic::x86_sse2_psra_w:
10302 case Intrinsic::x86_sse2_psra_d:
10303 case Intrinsic::x86_avx2_psra_w:
10304 case Intrinsic::x86_avx2_psra_d:
10305 Opcode = X86ISD::VSRA;
10308 return DAG.getNode(Opcode, dl, Op.getValueType(),
10309 Op.getOperand(1), Op.getOperand(2));
10312 // SSE/AVX immediate shift intrinsics
10313 case Intrinsic::x86_sse2_pslli_w:
10314 case Intrinsic::x86_sse2_pslli_d:
10315 case Intrinsic::x86_sse2_pslli_q:
10316 case Intrinsic::x86_avx2_pslli_w:
10317 case Intrinsic::x86_avx2_pslli_d:
10318 case Intrinsic::x86_avx2_pslli_q:
10319 case Intrinsic::x86_sse2_psrli_w:
10320 case Intrinsic::x86_sse2_psrli_d:
10321 case Intrinsic::x86_sse2_psrli_q:
10322 case Intrinsic::x86_avx2_psrli_w:
10323 case Intrinsic::x86_avx2_psrli_d:
10324 case Intrinsic::x86_avx2_psrli_q:
10325 case Intrinsic::x86_sse2_psrai_w:
10326 case Intrinsic::x86_sse2_psrai_d:
10327 case Intrinsic::x86_avx2_psrai_w:
10328 case Intrinsic::x86_avx2_psrai_d: {
10331 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10332 case Intrinsic::x86_sse2_pslli_w:
10333 case Intrinsic::x86_sse2_pslli_d:
10334 case Intrinsic::x86_sse2_pslli_q:
10335 case Intrinsic::x86_avx2_pslli_w:
10336 case Intrinsic::x86_avx2_pslli_d:
10337 case Intrinsic::x86_avx2_pslli_q:
10338 Opcode = X86ISD::VSHLI;
10340 case Intrinsic::x86_sse2_psrli_w:
10341 case Intrinsic::x86_sse2_psrli_d:
10342 case Intrinsic::x86_sse2_psrli_q:
10343 case Intrinsic::x86_avx2_psrli_w:
10344 case Intrinsic::x86_avx2_psrli_d:
10345 case Intrinsic::x86_avx2_psrli_q:
10346 Opcode = X86ISD::VSRLI;
10348 case Intrinsic::x86_sse2_psrai_w:
10349 case Intrinsic::x86_sse2_psrai_d:
10350 case Intrinsic::x86_avx2_psrai_w:
10351 case Intrinsic::x86_avx2_psrai_d:
10352 Opcode = X86ISD::VSRAI;
10355 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10356 Op.getOperand(1), Op.getOperand(2), DAG);
10359 case Intrinsic::x86_sse42_pcmpistria128:
10360 case Intrinsic::x86_sse42_pcmpestria128:
10361 case Intrinsic::x86_sse42_pcmpistric128:
10362 case Intrinsic::x86_sse42_pcmpestric128:
10363 case Intrinsic::x86_sse42_pcmpistrio128:
10364 case Intrinsic::x86_sse42_pcmpestrio128:
10365 case Intrinsic::x86_sse42_pcmpistris128:
10366 case Intrinsic::x86_sse42_pcmpestris128:
10367 case Intrinsic::x86_sse42_pcmpistriz128:
10368 case Intrinsic::x86_sse42_pcmpestriz128: {
10372 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10373 case Intrinsic::x86_sse42_pcmpistria128:
10374 Opcode = X86ISD::PCMPISTRI;
10375 X86CC = X86::COND_A;
10377 case Intrinsic::x86_sse42_pcmpestria128:
10378 Opcode = X86ISD::PCMPESTRI;
10379 X86CC = X86::COND_A;
10381 case Intrinsic::x86_sse42_pcmpistric128:
10382 Opcode = X86ISD::PCMPISTRI;
10383 X86CC = X86::COND_B;
10385 case Intrinsic::x86_sse42_pcmpestric128:
10386 Opcode = X86ISD::PCMPESTRI;
10387 X86CC = X86::COND_B;
10389 case Intrinsic::x86_sse42_pcmpistrio128:
10390 Opcode = X86ISD::PCMPISTRI;
10391 X86CC = X86::COND_O;
10393 case Intrinsic::x86_sse42_pcmpestrio128:
10394 Opcode = X86ISD::PCMPESTRI;
10395 X86CC = X86::COND_O;
10397 case Intrinsic::x86_sse42_pcmpistris128:
10398 Opcode = X86ISD::PCMPISTRI;
10399 X86CC = X86::COND_S;
10401 case Intrinsic::x86_sse42_pcmpestris128:
10402 Opcode = X86ISD::PCMPESTRI;
10403 X86CC = X86::COND_S;
10405 case Intrinsic::x86_sse42_pcmpistriz128:
10406 Opcode = X86ISD::PCMPISTRI;
10407 X86CC = X86::COND_E;
10409 case Intrinsic::x86_sse42_pcmpestriz128:
10410 Opcode = X86ISD::PCMPESTRI;
10411 X86CC = X86::COND_E;
10414 SmallVector<SDValue, 5> NewOps;
10415 NewOps.append(Op->op_begin()+1, Op->op_end());
10416 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10417 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10418 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10419 DAG.getConstant(X86CC, MVT::i8),
10420 SDValue(PCMP.getNode(), 1));
10421 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10424 case Intrinsic::x86_sse42_pcmpistri128:
10425 case Intrinsic::x86_sse42_pcmpestri128: {
10427 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10428 Opcode = X86ISD::PCMPISTRI;
10430 Opcode = X86ISD::PCMPESTRI;
10432 SmallVector<SDValue, 5> NewOps;
10433 NewOps.append(Op->op_begin()+1, Op->op_end());
10434 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10435 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10437 case Intrinsic::x86_fma_vfmadd_ps:
10438 case Intrinsic::x86_fma_vfmadd_pd:
10439 case Intrinsic::x86_fma_vfmsub_ps:
10440 case Intrinsic::x86_fma_vfmsub_pd:
10441 case Intrinsic::x86_fma_vfnmadd_ps:
10442 case Intrinsic::x86_fma_vfnmadd_pd:
10443 case Intrinsic::x86_fma_vfnmsub_ps:
10444 case Intrinsic::x86_fma_vfnmsub_pd:
10445 case Intrinsic::x86_fma_vfmaddsub_ps:
10446 case Intrinsic::x86_fma_vfmaddsub_pd:
10447 case Intrinsic::x86_fma_vfmsubadd_ps:
10448 case Intrinsic::x86_fma_vfmsubadd_pd:
10449 case Intrinsic::x86_fma_vfmadd_ps_256:
10450 case Intrinsic::x86_fma_vfmadd_pd_256:
10451 case Intrinsic::x86_fma_vfmsub_ps_256:
10452 case Intrinsic::x86_fma_vfmsub_pd_256:
10453 case Intrinsic::x86_fma_vfnmadd_ps_256:
10454 case Intrinsic::x86_fma_vfnmadd_pd_256:
10455 case Intrinsic::x86_fma_vfnmsub_ps_256:
10456 case Intrinsic::x86_fma_vfnmsub_pd_256:
10457 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10458 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10459 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10460 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10463 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10464 case Intrinsic::x86_fma_vfmadd_ps:
10465 case Intrinsic::x86_fma_vfmadd_pd:
10466 case Intrinsic::x86_fma_vfmadd_ps_256:
10467 case Intrinsic::x86_fma_vfmadd_pd_256:
10468 Opc = X86ISD::FMADD;
10470 case Intrinsic::x86_fma_vfmsub_ps:
10471 case Intrinsic::x86_fma_vfmsub_pd:
10472 case Intrinsic::x86_fma_vfmsub_ps_256:
10473 case Intrinsic::x86_fma_vfmsub_pd_256:
10474 Opc = X86ISD::FMSUB;
10476 case Intrinsic::x86_fma_vfnmadd_ps:
10477 case Intrinsic::x86_fma_vfnmadd_pd:
10478 case Intrinsic::x86_fma_vfnmadd_ps_256:
10479 case Intrinsic::x86_fma_vfnmadd_pd_256:
10480 Opc = X86ISD::FNMADD;
10482 case Intrinsic::x86_fma_vfnmsub_ps:
10483 case Intrinsic::x86_fma_vfnmsub_pd:
10484 case Intrinsic::x86_fma_vfnmsub_ps_256:
10485 case Intrinsic::x86_fma_vfnmsub_pd_256:
10486 Opc = X86ISD::FNMSUB;
10488 case Intrinsic::x86_fma_vfmaddsub_ps:
10489 case Intrinsic::x86_fma_vfmaddsub_pd:
10490 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10491 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10492 Opc = X86ISD::FMADDSUB;
10494 case Intrinsic::x86_fma_vfmsubadd_ps:
10495 case Intrinsic::x86_fma_vfmsubadd_pd:
10496 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10497 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10498 Opc = X86ISD::FMSUBADD;
10502 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10503 Op.getOperand(2), Op.getOperand(3));
10508 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10509 DebugLoc dl = Op.getDebugLoc();
10510 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10512 default: return SDValue(); // Don't custom lower most intrinsics.
10514 // RDRAND intrinsics.
10515 case Intrinsic::x86_rdrand_16:
10516 case Intrinsic::x86_rdrand_32:
10517 case Intrinsic::x86_rdrand_64: {
10518 // Emit the node with the right value type.
10519 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10520 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10522 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10523 // return the value from Rand, which is always 0, casted to i32.
10524 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10525 DAG.getConstant(1, Op->getValueType(1)),
10526 DAG.getConstant(X86::COND_B, MVT::i32),
10527 SDValue(Result.getNode(), 1) };
10528 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10529 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10532 // Return { result, isValid, chain }.
10533 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10534 SDValue(Result.getNode(), 2));
10539 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10540 SelectionDAG &DAG) const {
10541 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10542 MFI->setReturnAddressIsTaken(true);
10544 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10545 DebugLoc dl = Op.getDebugLoc();
10546 EVT PtrVT = getPointerTy();
10549 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10551 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10552 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10553 DAG.getNode(ISD::ADD, dl, PtrVT,
10554 FrameAddr, Offset),
10555 MachinePointerInfo(), false, false, false, 0);
10558 // Just load the return address.
10559 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10560 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10561 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10564 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10565 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10566 MFI->setFrameAddressIsTaken(true);
10568 EVT VT = Op.getValueType();
10569 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10570 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10571 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10572 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10574 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10575 MachinePointerInfo(),
10576 false, false, false, 0);
10580 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10581 SelectionDAG &DAG) const {
10582 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10585 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10586 SDValue Chain = Op.getOperand(0);
10587 SDValue Offset = Op.getOperand(1);
10588 SDValue Handler = Op.getOperand(2);
10589 DebugLoc dl = Op.getDebugLoc();
10591 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10592 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10594 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10596 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10597 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10598 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10599 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10601 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10603 return DAG.getNode(X86ISD::EH_RETURN, dl,
10605 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10608 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10609 SelectionDAG &DAG) const {
10610 DebugLoc DL = Op.getDebugLoc();
10611 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10612 DAG.getVTList(MVT::i32, MVT::Other),
10613 Op.getOperand(0), Op.getOperand(1));
10616 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10617 SelectionDAG &DAG) const {
10618 DebugLoc DL = Op.getDebugLoc();
10619 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10620 Op.getOperand(0), Op.getOperand(1));
10623 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10624 return Op.getOperand(0);
10627 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10628 SelectionDAG &DAG) const {
10629 SDValue Root = Op.getOperand(0);
10630 SDValue Trmp = Op.getOperand(1); // trampoline
10631 SDValue FPtr = Op.getOperand(2); // nested function
10632 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10633 DebugLoc dl = Op.getDebugLoc();
10635 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10636 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10638 if (Subtarget->is64Bit()) {
10639 SDValue OutChains[6];
10641 // Large code-model.
10642 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10643 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
10645 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
10646 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
10648 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10650 // Load the pointer to the nested function into R11.
10651 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10652 SDValue Addr = Trmp;
10653 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10654 Addr, MachinePointerInfo(TrmpAddr),
10657 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10658 DAG.getConstant(2, MVT::i64));
10659 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10660 MachinePointerInfo(TrmpAddr, 2),
10663 // Load the 'nest' parameter value into R10.
10664 // R10 is specified in X86CallingConv.td
10665 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10666 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10667 DAG.getConstant(10, MVT::i64));
10668 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10669 Addr, MachinePointerInfo(TrmpAddr, 10),
10672 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10673 DAG.getConstant(12, MVT::i64));
10674 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10675 MachinePointerInfo(TrmpAddr, 12),
10678 // Jump to the nested function.
10679 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10680 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10681 DAG.getConstant(20, MVT::i64));
10682 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10683 Addr, MachinePointerInfo(TrmpAddr, 20),
10686 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10687 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10688 DAG.getConstant(22, MVT::i64));
10689 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10690 MachinePointerInfo(TrmpAddr, 22),
10693 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10695 const Function *Func =
10696 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10697 CallingConv::ID CC = Func->getCallingConv();
10702 llvm_unreachable("Unsupported calling convention");
10703 case CallingConv::C:
10704 case CallingConv::X86_StdCall: {
10705 // Pass 'nest' parameter in ECX.
10706 // Must be kept in sync with X86CallingConv.td
10707 NestReg = X86::ECX;
10709 // Check that ECX wasn't needed by an 'inreg' parameter.
10710 FunctionType *FTy = Func->getFunctionType();
10711 const AttrListPtr &Attrs = Func->getAttributes();
10713 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10714 unsigned InRegCount = 0;
10717 for (FunctionType::param_iterator I = FTy->param_begin(),
10718 E = FTy->param_end(); I != E; ++I, ++Idx)
10719 if (Attrs.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
10720 // FIXME: should only count parameters that are lowered to integers.
10721 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10723 if (InRegCount > 2) {
10724 report_fatal_error("Nest register in use - reduce number of inreg"
10730 case CallingConv::X86_FastCall:
10731 case CallingConv::X86_ThisCall:
10732 case CallingConv::Fast:
10733 // Pass 'nest' parameter in EAX.
10734 // Must be kept in sync with X86CallingConv.td
10735 NestReg = X86::EAX;
10739 SDValue OutChains[4];
10740 SDValue Addr, Disp;
10742 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10743 DAG.getConstant(10, MVT::i32));
10744 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10746 // This is storing the opcode for MOV32ri.
10747 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10748 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
10749 OutChains[0] = DAG.getStore(Root, dl,
10750 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10751 Trmp, MachinePointerInfo(TrmpAddr),
10754 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10755 DAG.getConstant(1, MVT::i32));
10756 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10757 MachinePointerInfo(TrmpAddr, 1),
10760 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10761 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10762 DAG.getConstant(5, MVT::i32));
10763 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10764 MachinePointerInfo(TrmpAddr, 5),
10767 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10768 DAG.getConstant(6, MVT::i32));
10769 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10770 MachinePointerInfo(TrmpAddr, 6),
10773 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10777 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10778 SelectionDAG &DAG) const {
10780 The rounding mode is in bits 11:10 of FPSR, and has the following
10782 00 Round to nearest
10787 FLT_ROUNDS, on the other hand, expects the following:
10794 To perform the conversion, we do:
10795 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10798 MachineFunction &MF = DAG.getMachineFunction();
10799 const TargetMachine &TM = MF.getTarget();
10800 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10801 unsigned StackAlignment = TFI.getStackAlignment();
10802 EVT VT = Op.getValueType();
10803 DebugLoc DL = Op.getDebugLoc();
10805 // Save FP Control Word to stack slot
10806 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10807 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10810 MachineMemOperand *MMO =
10811 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10812 MachineMemOperand::MOStore, 2, 2);
10814 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10815 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10816 DAG.getVTList(MVT::Other),
10817 Ops, 2, MVT::i16, MMO);
10819 // Load FP Control Word from stack slot
10820 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10821 MachinePointerInfo(), false, false, false, 0);
10823 // Transform as necessary
10825 DAG.getNode(ISD::SRL, DL, MVT::i16,
10826 DAG.getNode(ISD::AND, DL, MVT::i16,
10827 CWD, DAG.getConstant(0x800, MVT::i16)),
10828 DAG.getConstant(11, MVT::i8));
10830 DAG.getNode(ISD::SRL, DL, MVT::i16,
10831 DAG.getNode(ISD::AND, DL, MVT::i16,
10832 CWD, DAG.getConstant(0x400, MVT::i16)),
10833 DAG.getConstant(9, MVT::i8));
10836 DAG.getNode(ISD::AND, DL, MVT::i16,
10837 DAG.getNode(ISD::ADD, DL, MVT::i16,
10838 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10839 DAG.getConstant(1, MVT::i16)),
10840 DAG.getConstant(3, MVT::i16));
10843 return DAG.getNode((VT.getSizeInBits() < 16 ?
10844 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10847 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
10848 EVT VT = Op.getValueType();
10850 unsigned NumBits = VT.getSizeInBits();
10851 DebugLoc dl = Op.getDebugLoc();
10853 Op = Op.getOperand(0);
10854 if (VT == MVT::i8) {
10855 // Zero extend to i32 since there is not an i8 bsr.
10857 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10860 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10861 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10862 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10864 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10867 DAG.getConstant(NumBits+NumBits-1, OpVT),
10868 DAG.getConstant(X86::COND_E, MVT::i8),
10871 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10873 // Finally xor with NumBits-1.
10874 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10877 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10881 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
10882 EVT VT = Op.getValueType();
10884 unsigned NumBits = VT.getSizeInBits();
10885 DebugLoc dl = Op.getDebugLoc();
10887 Op = Op.getOperand(0);
10888 if (VT == MVT::i8) {
10889 // Zero extend to i32 since there is not an i8 bsr.
10891 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10894 // Issue a bsr (scan bits in reverse).
10895 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10896 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10898 // And xor with NumBits-1.
10899 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10902 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10906 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
10907 EVT VT = Op.getValueType();
10908 unsigned NumBits = VT.getSizeInBits();
10909 DebugLoc dl = Op.getDebugLoc();
10910 Op = Op.getOperand(0);
10912 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10913 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10914 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10916 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10919 DAG.getConstant(NumBits, VT),
10920 DAG.getConstant(X86::COND_E, MVT::i8),
10923 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10926 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10927 // ones, and then concatenate the result back.
10928 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10929 EVT VT = Op.getValueType();
10931 assert(VT.is256BitVector() && VT.isInteger() &&
10932 "Unsupported value type for operation");
10934 unsigned NumElems = VT.getVectorNumElements();
10935 DebugLoc dl = Op.getDebugLoc();
10937 // Extract the LHS vectors
10938 SDValue LHS = Op.getOperand(0);
10939 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10940 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10942 // Extract the RHS vectors
10943 SDValue RHS = Op.getOperand(1);
10944 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10945 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10947 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10948 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10950 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10951 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10952 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10955 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
10956 assert(Op.getValueType().is256BitVector() &&
10957 Op.getValueType().isInteger() &&
10958 "Only handle AVX 256-bit vector integer operation");
10959 return Lower256IntArith(Op, DAG);
10962 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
10963 assert(Op.getValueType().is256BitVector() &&
10964 Op.getValueType().isInteger() &&
10965 "Only handle AVX 256-bit vector integer operation");
10966 return Lower256IntArith(Op, DAG);
10969 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
10970 SelectionDAG &DAG) {
10971 EVT VT = Op.getValueType();
10973 // Decompose 256-bit ops into smaller 128-bit ops.
10974 if (VT.is256BitVector() && !Subtarget->hasAVX2())
10975 return Lower256IntArith(Op, DAG);
10977 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10978 "Only know how to lower V2I64/V4I64 multiply");
10980 DebugLoc dl = Op.getDebugLoc();
10982 // Ahi = psrlqi(a, 32);
10983 // Bhi = psrlqi(b, 32);
10985 // AloBlo = pmuludq(a, b);
10986 // AloBhi = pmuludq(a, Bhi);
10987 // AhiBlo = pmuludq(Ahi, b);
10989 // AloBhi = psllqi(AloBhi, 32);
10990 // AhiBlo = psllqi(AhiBlo, 32);
10991 // return AloBlo + AloBhi + AhiBlo;
10993 SDValue A = Op.getOperand(0);
10994 SDValue B = Op.getOperand(1);
10996 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10998 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10999 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11001 // Bit cast to 32-bit vectors for MULUDQ
11002 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11003 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11004 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11005 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11006 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11008 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11009 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11010 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11012 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11013 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11015 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11016 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11019 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11021 EVT VT = Op.getValueType();
11022 DebugLoc dl = Op.getDebugLoc();
11023 SDValue R = Op.getOperand(0);
11024 SDValue Amt = Op.getOperand(1);
11025 LLVMContext *Context = DAG.getContext();
11027 if (!Subtarget->hasSSE2())
11030 // Optimize shl/srl/sra with constant shift amount.
11031 if (isSplatVector(Amt.getNode())) {
11032 SDValue SclrAmt = Amt->getOperand(0);
11033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11034 uint64_t ShiftAmt = C->getZExtValue();
11036 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11037 (Subtarget->hasAVX2() &&
11038 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11039 if (Op.getOpcode() == ISD::SHL)
11040 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11041 DAG.getConstant(ShiftAmt, MVT::i32));
11042 if (Op.getOpcode() == ISD::SRL)
11043 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11044 DAG.getConstant(ShiftAmt, MVT::i32));
11045 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11046 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11047 DAG.getConstant(ShiftAmt, MVT::i32));
11050 if (VT == MVT::v16i8) {
11051 if (Op.getOpcode() == ISD::SHL) {
11052 // Make a large shift.
11053 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11054 DAG.getConstant(ShiftAmt, MVT::i32));
11055 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11056 // Zero out the rightmost bits.
11057 SmallVector<SDValue, 16> V(16,
11058 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11060 return DAG.getNode(ISD::AND, dl, VT, SHL,
11061 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11063 if (Op.getOpcode() == ISD::SRL) {
11064 // Make a large shift.
11065 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11066 DAG.getConstant(ShiftAmt, MVT::i32));
11067 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11068 // Zero out the leftmost bits.
11069 SmallVector<SDValue, 16> V(16,
11070 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11072 return DAG.getNode(ISD::AND, dl, VT, SRL,
11073 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11075 if (Op.getOpcode() == ISD::SRA) {
11076 if (ShiftAmt == 7) {
11077 // R s>> 7 === R s< 0
11078 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11079 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11082 // R s>> a === ((R u>> a) ^ m) - m
11083 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11084 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11086 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11087 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11088 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11091 llvm_unreachable("Unknown shift opcode.");
11094 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
11095 if (Op.getOpcode() == ISD::SHL) {
11096 // Make a large shift.
11097 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11098 DAG.getConstant(ShiftAmt, MVT::i32));
11099 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11100 // Zero out the rightmost bits.
11101 SmallVector<SDValue, 32> V(32,
11102 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11104 return DAG.getNode(ISD::AND, dl, VT, SHL,
11105 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11107 if (Op.getOpcode() == ISD::SRL) {
11108 // Make a large shift.
11109 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11110 DAG.getConstant(ShiftAmt, MVT::i32));
11111 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11112 // Zero out the leftmost bits.
11113 SmallVector<SDValue, 32> V(32,
11114 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11116 return DAG.getNode(ISD::AND, dl, VT, SRL,
11117 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11119 if (Op.getOpcode() == ISD::SRA) {
11120 if (ShiftAmt == 7) {
11121 // R s>> 7 === R s< 0
11122 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11123 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11126 // R s>> a === ((R u>> a) ^ m) - m
11127 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11128 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11130 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11131 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11132 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11135 llvm_unreachable("Unknown shift opcode.");
11140 // Lower SHL with variable shift amount.
11141 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11142 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11143 DAG.getConstant(23, MVT::i32));
11145 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11146 Constant *C = ConstantDataVector::get(*Context, CV);
11147 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11148 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11149 MachinePointerInfo::getConstantPool(),
11150 false, false, false, 16);
11152 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11153 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11154 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11155 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11157 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11158 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11161 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11162 DAG.getConstant(5, MVT::i32));
11163 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11165 // Turn 'a' into a mask suitable for VSELECT
11166 SDValue VSelM = DAG.getConstant(0x80, VT);
11167 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11168 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11170 SDValue CM1 = DAG.getConstant(0x0f, VT);
11171 SDValue CM2 = DAG.getConstant(0x3f, VT);
11173 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11174 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11175 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11176 DAG.getConstant(4, MVT::i32), DAG);
11177 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11178 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11181 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11182 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11183 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11185 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11186 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11187 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11188 DAG.getConstant(2, MVT::i32), DAG);
11189 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11190 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11193 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11194 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11195 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11197 // return VSELECT(r, r+r, a);
11198 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11199 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11203 // Decompose 256-bit shifts into smaller 128-bit shifts.
11204 if (VT.is256BitVector()) {
11205 unsigned NumElems = VT.getVectorNumElements();
11206 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11207 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11209 // Extract the two vectors
11210 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11211 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11213 // Recreate the shift amount vectors
11214 SDValue Amt1, Amt2;
11215 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11216 // Constant shift amount
11217 SmallVector<SDValue, 4> Amt1Csts;
11218 SmallVector<SDValue, 4> Amt2Csts;
11219 for (unsigned i = 0; i != NumElems/2; ++i)
11220 Amt1Csts.push_back(Amt->getOperand(i));
11221 for (unsigned i = NumElems/2; i != NumElems; ++i)
11222 Amt2Csts.push_back(Amt->getOperand(i));
11224 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11225 &Amt1Csts[0], NumElems/2);
11226 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11227 &Amt2Csts[0], NumElems/2);
11229 // Variable shift amount
11230 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11231 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11234 // Issue new vector shifts for the smaller types
11235 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11236 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11238 // Concatenate the result back
11239 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11245 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11246 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11247 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11248 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11249 // has only one use.
11250 SDNode *N = Op.getNode();
11251 SDValue LHS = N->getOperand(0);
11252 SDValue RHS = N->getOperand(1);
11253 unsigned BaseOp = 0;
11255 DebugLoc DL = Op.getDebugLoc();
11256 switch (Op.getOpcode()) {
11257 default: llvm_unreachable("Unknown ovf instruction!");
11259 // A subtract of one will be selected as a INC. Note that INC doesn't
11260 // set CF, so we can't do this for UADDO.
11261 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11263 BaseOp = X86ISD::INC;
11264 Cond = X86::COND_O;
11267 BaseOp = X86ISD::ADD;
11268 Cond = X86::COND_O;
11271 BaseOp = X86ISD::ADD;
11272 Cond = X86::COND_B;
11275 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11276 // set CF, so we can't do this for USUBO.
11277 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11279 BaseOp = X86ISD::DEC;
11280 Cond = X86::COND_O;
11283 BaseOp = X86ISD::SUB;
11284 Cond = X86::COND_O;
11287 BaseOp = X86ISD::SUB;
11288 Cond = X86::COND_B;
11291 BaseOp = X86ISD::SMUL;
11292 Cond = X86::COND_O;
11294 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11295 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11297 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11300 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11301 DAG.getConstant(X86::COND_O, MVT::i32),
11302 SDValue(Sum.getNode(), 2));
11304 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11308 // Also sets EFLAGS.
11309 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11310 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11313 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11314 DAG.getConstant(Cond, MVT::i32),
11315 SDValue(Sum.getNode(), 1));
11317 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11320 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11321 SelectionDAG &DAG) const {
11322 DebugLoc dl = Op.getDebugLoc();
11323 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11324 EVT VT = Op.getValueType();
11326 if (!Subtarget->hasSSE2() || !VT.isVector())
11329 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11330 ExtraVT.getScalarType().getSizeInBits();
11331 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11333 switch (VT.getSimpleVT().SimpleTy) {
11334 default: return SDValue();
11337 if (!Subtarget->hasAVX())
11339 if (!Subtarget->hasAVX2()) {
11340 // needs to be split
11341 unsigned NumElems = VT.getVectorNumElements();
11343 // Extract the LHS vectors
11344 SDValue LHS = Op.getOperand(0);
11345 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11346 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11348 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11349 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11351 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11352 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11353 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11355 SDValue Extra = DAG.getValueType(ExtraVT);
11357 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11358 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11360 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11365 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11366 Op.getOperand(0), ShAmt, DAG);
11367 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11373 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11374 SelectionDAG &DAG) {
11375 DebugLoc dl = Op.getDebugLoc();
11377 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11378 // There isn't any reason to disable it if the target processor supports it.
11379 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11380 SDValue Chain = Op.getOperand(0);
11381 SDValue Zero = DAG.getConstant(0, MVT::i32);
11383 DAG.getRegister(X86::ESP, MVT::i32), // Base
11384 DAG.getTargetConstant(1, MVT::i8), // Scale
11385 DAG.getRegister(0, MVT::i32), // Index
11386 DAG.getTargetConstant(0, MVT::i32), // Disp
11387 DAG.getRegister(0, MVT::i32), // Segment.
11392 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11393 array_lengthof(Ops));
11394 return SDValue(Res, 0);
11397 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11399 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11401 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11402 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11403 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11404 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11406 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11407 if (!Op1 && !Op2 && !Op3 && Op4)
11408 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11410 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11411 if (Op1 && !Op2 && !Op3 && !Op4)
11412 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11414 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11416 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11419 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11420 SelectionDAG &DAG) {
11421 DebugLoc dl = Op.getDebugLoc();
11422 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11423 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11424 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11425 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11427 // The only fence that needs an instruction is a sequentially-consistent
11428 // cross-thread fence.
11429 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11430 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11431 // no-sse2). There isn't any reason to disable it if the target processor
11433 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11434 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11436 SDValue Chain = Op.getOperand(0);
11437 SDValue Zero = DAG.getConstant(0, MVT::i32);
11439 DAG.getRegister(X86::ESP, MVT::i32), // Base
11440 DAG.getTargetConstant(1, MVT::i8), // Scale
11441 DAG.getRegister(0, MVT::i32), // Index
11442 DAG.getTargetConstant(0, MVT::i32), // Disp
11443 DAG.getRegister(0, MVT::i32), // Segment.
11448 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11449 array_lengthof(Ops));
11450 return SDValue(Res, 0);
11453 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11454 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11458 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11459 SelectionDAG &DAG) {
11460 EVT T = Op.getValueType();
11461 DebugLoc DL = Op.getDebugLoc();
11464 switch(T.getSimpleVT().SimpleTy) {
11465 default: llvm_unreachable("Invalid value type!");
11466 case MVT::i8: Reg = X86::AL; size = 1; break;
11467 case MVT::i16: Reg = X86::AX; size = 2; break;
11468 case MVT::i32: Reg = X86::EAX; size = 4; break;
11470 assert(Subtarget->is64Bit() && "Node not type legal!");
11471 Reg = X86::RAX; size = 8;
11474 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11475 Op.getOperand(2), SDValue());
11476 SDValue Ops[] = { cpIn.getValue(0),
11479 DAG.getTargetConstant(size, MVT::i8),
11480 cpIn.getValue(1) };
11481 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11482 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11483 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11486 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11490 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11491 SelectionDAG &DAG) {
11492 assert(Subtarget->is64Bit() && "Result not type legalized?");
11493 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11494 SDValue TheChain = Op.getOperand(0);
11495 DebugLoc dl = Op.getDebugLoc();
11496 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11497 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11498 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11500 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11501 DAG.getConstant(32, MVT::i8));
11503 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11506 return DAG.getMergeValues(Ops, 2, dl);
11509 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11510 EVT SrcVT = Op.getOperand(0).getValueType();
11511 EVT DstVT = Op.getValueType();
11512 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11513 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11514 assert((DstVT == MVT::i64 ||
11515 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11516 "Unexpected custom BITCAST");
11517 // i64 <=> MMX conversions are Legal.
11518 if (SrcVT==MVT::i64 && DstVT.isVector())
11520 if (DstVT==MVT::i64 && SrcVT.isVector())
11522 // MMX <=> MMX conversions are Legal.
11523 if (SrcVT.isVector() && DstVT.isVector())
11525 // All other conversions need to be expanded.
11529 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11530 SDNode *Node = Op.getNode();
11531 DebugLoc dl = Node->getDebugLoc();
11532 EVT T = Node->getValueType(0);
11533 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11534 DAG.getConstant(0, T), Node->getOperand(2));
11535 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11536 cast<AtomicSDNode>(Node)->getMemoryVT(),
11537 Node->getOperand(0),
11538 Node->getOperand(1), negOp,
11539 cast<AtomicSDNode>(Node)->getSrcValue(),
11540 cast<AtomicSDNode>(Node)->getAlignment(),
11541 cast<AtomicSDNode>(Node)->getOrdering(),
11542 cast<AtomicSDNode>(Node)->getSynchScope());
11545 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11546 SDNode *Node = Op.getNode();
11547 DebugLoc dl = Node->getDebugLoc();
11548 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11550 // Convert seq_cst store -> xchg
11551 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11552 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11553 // (The only way to get a 16-byte store is cmpxchg16b)
11554 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11555 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11556 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11557 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11558 cast<AtomicSDNode>(Node)->getMemoryVT(),
11559 Node->getOperand(0),
11560 Node->getOperand(1), Node->getOperand(2),
11561 cast<AtomicSDNode>(Node)->getMemOperand(),
11562 cast<AtomicSDNode>(Node)->getOrdering(),
11563 cast<AtomicSDNode>(Node)->getSynchScope());
11564 return Swap.getValue(1);
11566 // Other atomic stores have a simple pattern.
11570 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11571 EVT VT = Op.getNode()->getValueType(0);
11573 // Let legalize expand this if it isn't a legal type yet.
11574 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11577 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11580 bool ExtraOp = false;
11581 switch (Op.getOpcode()) {
11582 default: llvm_unreachable("Invalid code");
11583 case ISD::ADDC: Opc = X86ISD::ADD; break;
11584 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
11585 case ISD::SUBC: Opc = X86ISD::SUB; break;
11586 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
11590 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11592 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
11593 Op.getOperand(1), Op.getOperand(2));
11596 /// LowerOperation - Provide custom lowering hooks for some operations.
11598 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11599 switch (Op.getOpcode()) {
11600 default: llvm_unreachable("Should not custom lower this!");
11601 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
11602 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
11603 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
11604 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
11605 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
11606 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
11607 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
11608 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
11609 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
11610 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
11611 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
11612 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
11613 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
11614 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
11615 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
11616 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
11617 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
11618 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
11619 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
11620 case ISD::SHL_PARTS:
11621 case ISD::SRA_PARTS:
11622 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
11623 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
11624 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
11625 case ISD::TRUNCATE: return lowerTRUNCATE(Op, DAG);
11626 case ISD::ZERO_EXTEND: return lowerZERO_EXTEND(Op, DAG);
11627 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
11628 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
11629 case ISD::FP_EXTEND: return lowerFP_EXTEND(Op, DAG);
11630 case ISD::FABS: return LowerFABS(Op, DAG);
11631 case ISD::FNEG: return LowerFNEG(Op, DAG);
11632 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
11633 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
11634 case ISD::SETCC: return LowerSETCC(Op, DAG);
11635 case ISD::SELECT: return LowerSELECT(Op, DAG);
11636 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
11637 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
11638 case ISD::VASTART: return LowerVASTART(Op, DAG);
11639 case ISD::VAARG: return LowerVAARG(Op, DAG);
11640 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
11641 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
11642 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
11643 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
11644 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
11645 case ISD::FRAME_TO_ARGS_OFFSET:
11646 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
11647 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
11648 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
11649 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
11650 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
11651 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
11652 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
11653 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11654 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11655 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11656 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11657 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
11660 case ISD::SHL: return LowerShift(Op, DAG);
11666 case ISD::UMULO: return LowerXALUO(Op, DAG);
11667 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
11668 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11672 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11673 case ISD::ADD: return LowerADD(Op, DAG);
11674 case ISD::SUB: return LowerSUB(Op, DAG);
11678 static void ReplaceATOMIC_LOAD(SDNode *Node,
11679 SmallVectorImpl<SDValue> &Results,
11680 SelectionDAG &DAG) {
11681 DebugLoc dl = Node->getDebugLoc();
11682 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11684 // Convert wide load -> cmpxchg8b/cmpxchg16b
11685 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11686 // (The only way to get a 16-byte load is cmpxchg16b)
11687 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11688 SDValue Zero = DAG.getConstant(0, VT);
11689 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11690 Node->getOperand(0),
11691 Node->getOperand(1), Zero, Zero,
11692 cast<AtomicSDNode>(Node)->getMemOperand(),
11693 cast<AtomicSDNode>(Node)->getOrdering(),
11694 cast<AtomicSDNode>(Node)->getSynchScope());
11695 Results.push_back(Swap.getValue(0));
11696 Results.push_back(Swap.getValue(1));
11700 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11701 SelectionDAG &DAG, unsigned NewOp) {
11702 DebugLoc dl = Node->getDebugLoc();
11703 assert (Node->getValueType(0) == MVT::i64 &&
11704 "Only know how to expand i64 atomics");
11706 SDValue Chain = Node->getOperand(0);
11707 SDValue In1 = Node->getOperand(1);
11708 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11709 Node->getOperand(2), DAG.getIntPtrConstant(0));
11710 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11711 Node->getOperand(2), DAG.getIntPtrConstant(1));
11712 SDValue Ops[] = { Chain, In1, In2L, In2H };
11713 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11715 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11716 cast<MemSDNode>(Node)->getMemOperand());
11717 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11718 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11719 Results.push_back(Result.getValue(2));
11722 /// ReplaceNodeResults - Replace a node with an illegal result type
11723 /// with a new node built out of custom code.
11724 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11725 SmallVectorImpl<SDValue>&Results,
11726 SelectionDAG &DAG) const {
11727 DebugLoc dl = N->getDebugLoc();
11728 switch (N->getOpcode()) {
11730 llvm_unreachable("Do not know how to custom type legalize this operation!");
11731 case ISD::SIGN_EXTEND_INREG:
11736 // We don't want to expand or promote these.
11738 case ISD::FP_TO_SINT:
11739 case ISD::FP_TO_UINT: {
11740 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11742 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11745 std::pair<SDValue,SDValue> Vals =
11746 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11747 SDValue FIST = Vals.first, StackSlot = Vals.second;
11748 if (FIST.getNode() != 0) {
11749 EVT VT = N->getValueType(0);
11750 // Return a load from the stack slot.
11751 if (StackSlot.getNode() != 0)
11752 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11753 MachinePointerInfo(),
11754 false, false, false, 0));
11756 Results.push_back(FIST);
11760 case ISD::UINT_TO_FP: {
11761 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
11762 N->getValueType(0) != MVT::v2f32)
11764 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
11766 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11768 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
11769 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
11770 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
11771 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
11772 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
11773 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
11776 case ISD::FP_ROUND: {
11777 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
11778 Results.push_back(V);
11781 case ISD::READCYCLECOUNTER: {
11782 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11783 SDValue TheChain = N->getOperand(0);
11784 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11785 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11787 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11789 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11790 SDValue Ops[] = { eax, edx };
11791 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11792 Results.push_back(edx.getValue(1));
11795 case ISD::ATOMIC_CMP_SWAP: {
11796 EVT T = N->getValueType(0);
11797 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11798 bool Regs64bit = T == MVT::i128;
11799 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11800 SDValue cpInL, cpInH;
11801 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11802 DAG.getConstant(0, HalfT));
11803 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11804 DAG.getConstant(1, HalfT));
11805 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11806 Regs64bit ? X86::RAX : X86::EAX,
11808 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11809 Regs64bit ? X86::RDX : X86::EDX,
11810 cpInH, cpInL.getValue(1));
11811 SDValue swapInL, swapInH;
11812 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11813 DAG.getConstant(0, HalfT));
11814 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11815 DAG.getConstant(1, HalfT));
11816 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11817 Regs64bit ? X86::RBX : X86::EBX,
11818 swapInL, cpInH.getValue(1));
11819 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11820 Regs64bit ? X86::RCX : X86::ECX,
11821 swapInH, swapInL.getValue(1));
11822 SDValue Ops[] = { swapInH.getValue(0),
11824 swapInH.getValue(1) };
11825 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11826 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11827 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11828 X86ISD::LCMPXCHG8_DAG;
11829 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11831 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11832 Regs64bit ? X86::RAX : X86::EAX,
11833 HalfT, Result.getValue(1));
11834 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11835 Regs64bit ? X86::RDX : X86::EDX,
11836 HalfT, cpOutL.getValue(2));
11837 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11838 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11839 Results.push_back(cpOutH.getValue(1));
11842 case ISD::ATOMIC_LOAD_ADD:
11843 case ISD::ATOMIC_LOAD_AND:
11844 case ISD::ATOMIC_LOAD_NAND:
11845 case ISD::ATOMIC_LOAD_OR:
11846 case ISD::ATOMIC_LOAD_SUB:
11847 case ISD::ATOMIC_LOAD_XOR:
11848 case ISD::ATOMIC_LOAD_MAX:
11849 case ISD::ATOMIC_LOAD_MIN:
11850 case ISD::ATOMIC_LOAD_UMAX:
11851 case ISD::ATOMIC_LOAD_UMIN:
11852 case ISD::ATOMIC_SWAP: {
11854 switch (N->getOpcode()) {
11855 default: llvm_unreachable("Unexpected opcode");
11856 case ISD::ATOMIC_LOAD_ADD:
11857 Opc = X86ISD::ATOMADD64_DAG;
11859 case ISD::ATOMIC_LOAD_AND:
11860 Opc = X86ISD::ATOMAND64_DAG;
11862 case ISD::ATOMIC_LOAD_NAND:
11863 Opc = X86ISD::ATOMNAND64_DAG;
11865 case ISD::ATOMIC_LOAD_OR:
11866 Opc = X86ISD::ATOMOR64_DAG;
11868 case ISD::ATOMIC_LOAD_SUB:
11869 Opc = X86ISD::ATOMSUB64_DAG;
11871 case ISD::ATOMIC_LOAD_XOR:
11872 Opc = X86ISD::ATOMXOR64_DAG;
11874 case ISD::ATOMIC_LOAD_MAX:
11875 Opc = X86ISD::ATOMMAX64_DAG;
11877 case ISD::ATOMIC_LOAD_MIN:
11878 Opc = X86ISD::ATOMMIN64_DAG;
11880 case ISD::ATOMIC_LOAD_UMAX:
11881 Opc = X86ISD::ATOMUMAX64_DAG;
11883 case ISD::ATOMIC_LOAD_UMIN:
11884 Opc = X86ISD::ATOMUMIN64_DAG;
11886 case ISD::ATOMIC_SWAP:
11887 Opc = X86ISD::ATOMSWAP64_DAG;
11890 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
11893 case ISD::ATOMIC_LOAD:
11894 ReplaceATOMIC_LOAD(N, Results, DAG);
11898 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11900 default: return NULL;
11901 case X86ISD::BSF: return "X86ISD::BSF";
11902 case X86ISD::BSR: return "X86ISD::BSR";
11903 case X86ISD::SHLD: return "X86ISD::SHLD";
11904 case X86ISD::SHRD: return "X86ISD::SHRD";
11905 case X86ISD::FAND: return "X86ISD::FAND";
11906 case X86ISD::FOR: return "X86ISD::FOR";
11907 case X86ISD::FXOR: return "X86ISD::FXOR";
11908 case X86ISD::FSRL: return "X86ISD::FSRL";
11909 case X86ISD::FILD: return "X86ISD::FILD";
11910 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11911 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11912 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11913 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11914 case X86ISD::FLD: return "X86ISD::FLD";
11915 case X86ISD::FST: return "X86ISD::FST";
11916 case X86ISD::CALL: return "X86ISD::CALL";
11917 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11918 case X86ISD::BT: return "X86ISD::BT";
11919 case X86ISD::CMP: return "X86ISD::CMP";
11920 case X86ISD::COMI: return "X86ISD::COMI";
11921 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11922 case X86ISD::SETCC: return "X86ISD::SETCC";
11923 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11924 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11925 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11926 case X86ISD::CMOV: return "X86ISD::CMOV";
11927 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11928 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11929 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11930 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11931 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11932 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11933 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11934 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11935 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11936 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11937 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11938 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11939 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11940 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11941 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11942 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11943 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11944 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11945 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11946 case X86ISD::HADD: return "X86ISD::HADD";
11947 case X86ISD::HSUB: return "X86ISD::HSUB";
11948 case X86ISD::FHADD: return "X86ISD::FHADD";
11949 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11950 case X86ISD::FMAX: return "X86ISD::FMAX";
11951 case X86ISD::FMIN: return "X86ISD::FMIN";
11952 case X86ISD::FMAXC: return "X86ISD::FMAXC";
11953 case X86ISD::FMINC: return "X86ISD::FMINC";
11954 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11955 case X86ISD::FRCP: return "X86ISD::FRCP";
11956 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11957 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
11958 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11959 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
11960 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
11961 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11962 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11963 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11964 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11965 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11966 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11967 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11968 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11969 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11970 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11971 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11972 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11973 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11974 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
11975 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11976 case X86ISD::VZEXT: return "X86ISD::VZEXT";
11977 case X86ISD::VSEXT: return "X86ISD::VSEXT";
11978 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
11979 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
11980 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11981 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11982 case X86ISD::VSHL: return "X86ISD::VSHL";
11983 case X86ISD::VSRL: return "X86ISD::VSRL";
11984 case X86ISD::VSRA: return "X86ISD::VSRA";
11985 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11986 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11987 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11988 case X86ISD::CMPP: return "X86ISD::CMPP";
11989 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11990 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11991 case X86ISD::ADD: return "X86ISD::ADD";
11992 case X86ISD::SUB: return "X86ISD::SUB";
11993 case X86ISD::ADC: return "X86ISD::ADC";
11994 case X86ISD::SBB: return "X86ISD::SBB";
11995 case X86ISD::SMUL: return "X86ISD::SMUL";
11996 case X86ISD::UMUL: return "X86ISD::UMUL";
11997 case X86ISD::INC: return "X86ISD::INC";
11998 case X86ISD::DEC: return "X86ISD::DEC";
11999 case X86ISD::OR: return "X86ISD::OR";
12000 case X86ISD::XOR: return "X86ISD::XOR";
12001 case X86ISD::AND: return "X86ISD::AND";
12002 case X86ISD::ANDN: return "X86ISD::ANDN";
12003 case X86ISD::BLSI: return "X86ISD::BLSI";
12004 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12005 case X86ISD::BLSR: return "X86ISD::BLSR";
12006 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12007 case X86ISD::PTEST: return "X86ISD::PTEST";
12008 case X86ISD::TESTP: return "X86ISD::TESTP";
12009 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12010 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12011 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12012 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12013 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12014 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12015 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12016 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12017 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12018 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12019 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12020 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12021 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12022 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12023 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12024 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12025 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12026 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12027 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12028 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12029 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12030 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12031 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12032 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12033 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12034 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12035 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12036 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12037 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12038 case X86ISD::SAHF: return "X86ISD::SAHF";
12039 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12040 case X86ISD::FMADD: return "X86ISD::FMADD";
12041 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12042 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12043 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12044 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12045 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12049 // isLegalAddressingMode - Return true if the addressing mode represented
12050 // by AM is legal for this target, for a load/store of the specified type.
12051 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12053 // X86 supports extremely general addressing modes.
12054 CodeModel::Model M = getTargetMachine().getCodeModel();
12055 Reloc::Model R = getTargetMachine().getRelocationModel();
12057 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12058 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12063 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12065 // If a reference to this global requires an extra load, we can't fold it.
12066 if (isGlobalStubReference(GVFlags))
12069 // If BaseGV requires a register for the PIC base, we cannot also have a
12070 // BaseReg specified.
12071 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12074 // If lower 4G is not available, then we must use rip-relative addressing.
12075 if ((M != CodeModel::Small || R != Reloc::Static) &&
12076 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12080 switch (AM.Scale) {
12086 // These scales always work.
12091 // These scales are formed with basereg+scalereg. Only accept if there is
12096 default: // Other stuff never works.
12104 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12105 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12107 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12108 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12109 if (NumBits1 <= NumBits2)
12114 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12115 return Imm == (int32_t)Imm;
12118 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12119 // Can also use sub to handle negated immediates.
12120 return Imm == (int32_t)Imm;
12123 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12124 if (!VT1.isInteger() || !VT2.isInteger())
12126 unsigned NumBits1 = VT1.getSizeInBits();
12127 unsigned NumBits2 = VT2.getSizeInBits();
12128 if (NumBits1 <= NumBits2)
12133 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12134 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12135 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12138 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12139 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12140 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12143 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12144 // i16 instructions are longer (0x66 prefix) and potentially slower.
12145 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12148 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12149 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12150 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12151 /// are assumed to be legal.
12153 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12155 // Very little shuffling can be done for 64-bit vectors right now.
12156 if (VT.getSizeInBits() == 64)
12159 // FIXME: pshufb, blends, shifts.
12160 return (VT.getVectorNumElements() == 2 ||
12161 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12162 isMOVLMask(M, VT) ||
12163 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
12164 isPSHUFDMask(M, VT) ||
12165 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
12166 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
12167 isPALIGNRMask(M, VT, Subtarget) ||
12168 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
12169 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
12170 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
12171 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
12175 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12177 unsigned NumElts = VT.getVectorNumElements();
12178 // FIXME: This collection of masks seems suspect.
12181 if (NumElts == 4 && VT.is128BitVector()) {
12182 return (isMOVLMask(Mask, VT) ||
12183 isCommutedMOVLMask(Mask, VT, true) ||
12184 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
12185 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
12190 //===----------------------------------------------------------------------===//
12191 // X86 Scheduler Hooks
12192 //===----------------------------------------------------------------------===//
12194 // private utility function
12196 // Get CMPXCHG opcode for the specified data type.
12197 static unsigned getCmpXChgOpcode(EVT VT) {
12198 switch (VT.getSimpleVT().SimpleTy) {
12199 case MVT::i8: return X86::LCMPXCHG8;
12200 case MVT::i16: return X86::LCMPXCHG16;
12201 case MVT::i32: return X86::LCMPXCHG32;
12202 case MVT::i64: return X86::LCMPXCHG64;
12206 llvm_unreachable("Invalid operand size!");
12209 // Get LOAD opcode for the specified data type.
12210 static unsigned getLoadOpcode(EVT VT) {
12211 switch (VT.getSimpleVT().SimpleTy) {
12212 case MVT::i8: return X86::MOV8rm;
12213 case MVT::i16: return X86::MOV16rm;
12214 case MVT::i32: return X86::MOV32rm;
12215 case MVT::i64: return X86::MOV64rm;
12219 llvm_unreachable("Invalid operand size!");
12222 // Get opcode of the non-atomic one from the specified atomic instruction.
12223 static unsigned getNonAtomicOpcode(unsigned Opc) {
12225 case X86::ATOMAND8: return X86::AND8rr;
12226 case X86::ATOMAND16: return X86::AND16rr;
12227 case X86::ATOMAND32: return X86::AND32rr;
12228 case X86::ATOMAND64: return X86::AND64rr;
12229 case X86::ATOMOR8: return X86::OR8rr;
12230 case X86::ATOMOR16: return X86::OR16rr;
12231 case X86::ATOMOR32: return X86::OR32rr;
12232 case X86::ATOMOR64: return X86::OR64rr;
12233 case X86::ATOMXOR8: return X86::XOR8rr;
12234 case X86::ATOMXOR16: return X86::XOR16rr;
12235 case X86::ATOMXOR32: return X86::XOR32rr;
12236 case X86::ATOMXOR64: return X86::XOR64rr;
12238 llvm_unreachable("Unhandled atomic-load-op opcode!");
12241 // Get opcode of the non-atomic one from the specified atomic instruction with
12243 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12244 unsigned &ExtraOpc) {
12246 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12247 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12248 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12249 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12250 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12251 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12252 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12253 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12254 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12255 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12256 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12257 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12258 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12259 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12260 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12261 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12262 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12263 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12264 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12265 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12267 llvm_unreachable("Unhandled atomic-load-op opcode!");
12270 // Get opcode of the non-atomic one from the specified atomic instruction for
12271 // 64-bit data type on 32-bit target.
12272 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12274 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12275 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12276 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12277 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12278 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12279 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12280 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12281 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12282 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12283 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12285 llvm_unreachable("Unhandled atomic-load-op opcode!");
12288 // Get opcode of the non-atomic one from the specified atomic instruction for
12289 // 64-bit data type on 32-bit target with extra opcode.
12290 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12292 unsigned &ExtraOpc) {
12294 case X86::ATOMNAND6432:
12295 ExtraOpc = X86::NOT32r;
12296 HiOpc = X86::AND32rr;
12297 return X86::AND32rr;
12299 llvm_unreachable("Unhandled atomic-load-op opcode!");
12302 // Get pseudo CMOV opcode from the specified data type.
12303 static unsigned getPseudoCMOVOpc(EVT VT) {
12304 switch (VT.getSimpleVT().SimpleTy) {
12305 case MVT::i8: return X86::CMOV_GR8;
12306 case MVT::i16: return X86::CMOV_GR16;
12307 case MVT::i32: return X86::CMOV_GR32;
12311 llvm_unreachable("Unknown CMOV opcode!");
12314 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12315 // They will be translated into a spin-loop or compare-exchange loop from
12318 // dst = atomic-fetch-op MI.addr, MI.val
12324 // EAX = LOAD MI.addr
12326 // t1 = OP MI.val, EAX
12327 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12332 MachineBasicBlock *
12333 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12334 MachineBasicBlock *MBB) const {
12335 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12336 DebugLoc DL = MI->getDebugLoc();
12338 MachineFunction *MF = MBB->getParent();
12339 MachineRegisterInfo &MRI = MF->getRegInfo();
12341 const BasicBlock *BB = MBB->getBasicBlock();
12342 MachineFunction::iterator I = MBB;
12345 assert(MI->getNumOperands() <= X86::AddrNumOperands + 2 &&
12346 "Unexpected number of operands");
12348 assert(MI->hasOneMemOperand() &&
12349 "Expected atomic-load-op to have one memoperand");
12351 // Memory Reference
12352 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12353 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12355 unsigned DstReg, SrcReg;
12356 unsigned MemOpndSlot;
12358 unsigned CurOp = 0;
12360 DstReg = MI->getOperand(CurOp++).getReg();
12361 MemOpndSlot = CurOp;
12362 CurOp += X86::AddrNumOperands;
12363 SrcReg = MI->getOperand(CurOp++).getReg();
12365 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12366 MVT::SimpleValueType VT = *RC->vt_begin();
12367 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12369 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12370 unsigned LOADOpc = getLoadOpcode(VT);
12372 // For the atomic load-arith operator, we generate
12375 // EAX = LOAD [MI.addr]
12377 // t1 = OP MI.val, EAX
12378 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12382 MachineBasicBlock *thisMBB = MBB;
12383 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12384 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12385 MF->insert(I, mainMBB);
12386 MF->insert(I, sinkMBB);
12388 MachineInstrBuilder MIB;
12390 // Transfer the remainder of BB and its successor edges to sinkMBB.
12391 sinkMBB->splice(sinkMBB->begin(), MBB,
12392 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12393 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12396 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12397 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12398 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12399 MIB.setMemRefs(MMOBegin, MMOEnd);
12401 thisMBB->addSuccessor(mainMBB);
12404 MachineBasicBlock *origMainMBB = mainMBB;
12405 mainMBB->addLiveIn(AccPhyReg);
12407 // Copy AccPhyReg as it is used more than once.
12408 unsigned AccReg = MRI.createVirtualRegister(RC);
12409 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12410 .addReg(AccPhyReg);
12412 unsigned t1 = MRI.createVirtualRegister(RC);
12413 unsigned Opc = MI->getOpcode();
12416 llvm_unreachable("Unhandled atomic-load-op opcode!");
12417 case X86::ATOMAND8:
12418 case X86::ATOMAND16:
12419 case X86::ATOMAND32:
12420 case X86::ATOMAND64:
12422 case X86::ATOMOR16:
12423 case X86::ATOMOR32:
12424 case X86::ATOMOR64:
12425 case X86::ATOMXOR8:
12426 case X86::ATOMXOR16:
12427 case X86::ATOMXOR32:
12428 case X86::ATOMXOR64: {
12429 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12430 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12434 case X86::ATOMNAND8:
12435 case X86::ATOMNAND16:
12436 case X86::ATOMNAND32:
12437 case X86::ATOMNAND64: {
12438 unsigned t2 = MRI.createVirtualRegister(RC);
12440 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12441 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12443 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12446 case X86::ATOMMAX8:
12447 case X86::ATOMMAX16:
12448 case X86::ATOMMAX32:
12449 case X86::ATOMMAX64:
12450 case X86::ATOMMIN8:
12451 case X86::ATOMMIN16:
12452 case X86::ATOMMIN32:
12453 case X86::ATOMMIN64:
12454 case X86::ATOMUMAX8:
12455 case X86::ATOMUMAX16:
12456 case X86::ATOMUMAX32:
12457 case X86::ATOMUMAX64:
12458 case X86::ATOMUMIN8:
12459 case X86::ATOMUMIN16:
12460 case X86::ATOMUMIN32:
12461 case X86::ATOMUMIN64: {
12463 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12465 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12469 if (Subtarget->hasCMov()) {
12470 if (VT != MVT::i8) {
12472 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12476 // Promote i8 to i32 to use CMOV32
12477 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12478 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12479 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12480 unsigned t2 = MRI.createVirtualRegister(RC32);
12482 unsigned Undef = MRI.createVirtualRegister(RC32);
12483 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12485 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12488 .addImm(X86::sub_8bit);
12489 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12492 .addImm(X86::sub_8bit);
12494 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12498 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
12499 .addReg(t2, 0, X86::sub_8bit);
12502 // Use pseudo select and lower them.
12503 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
12504 "Invalid atomic-load-op transformation!");
12505 unsigned SelOpc = getPseudoCMOVOpc(VT);
12506 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
12507 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
12508 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
12509 .addReg(SrcReg).addReg(AccReg)
12511 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12517 // Copy AccPhyReg back from virtual register.
12518 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
12521 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12522 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12523 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12525 MIB.setMemRefs(MMOBegin, MMOEnd);
12527 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12529 mainMBB->addSuccessor(origMainMBB);
12530 mainMBB->addSuccessor(sinkMBB);
12533 sinkMBB->addLiveIn(AccPhyReg);
12535 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12536 TII->get(TargetOpcode::COPY), DstReg)
12537 .addReg(AccPhyReg);
12539 MI->eraseFromParent();
12543 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
12544 // instructions. They will be translated into a spin-loop or compare-exchange
12548 // dst = atomic-fetch-op MI.addr, MI.val
12554 // EAX = LOAD [MI.addr + 0]
12555 // EDX = LOAD [MI.addr + 4]
12557 // EBX = OP MI.val.lo, EAX
12558 // ECX = OP MI.val.hi, EDX
12559 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12564 MachineBasicBlock *
12565 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
12566 MachineBasicBlock *MBB) const {
12567 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12568 DebugLoc DL = MI->getDebugLoc();
12570 MachineFunction *MF = MBB->getParent();
12571 MachineRegisterInfo &MRI = MF->getRegInfo();
12573 const BasicBlock *BB = MBB->getBasicBlock();
12574 MachineFunction::iterator I = MBB;
12577 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12578 "Unexpected number of operands");
12580 assert(MI->hasOneMemOperand() &&
12581 "Expected atomic-load-op32 to have one memoperand");
12583 // Memory Reference
12584 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12585 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12587 unsigned DstLoReg, DstHiReg;
12588 unsigned SrcLoReg, SrcHiReg;
12589 unsigned MemOpndSlot;
12591 unsigned CurOp = 0;
12593 DstLoReg = MI->getOperand(CurOp++).getReg();
12594 DstHiReg = MI->getOperand(CurOp++).getReg();
12595 MemOpndSlot = CurOp;
12596 CurOp += X86::AddrNumOperands;
12597 SrcLoReg = MI->getOperand(CurOp++).getReg();
12598 SrcHiReg = MI->getOperand(CurOp++).getReg();
12600 const TargetRegisterClass *RC = &X86::GR32RegClass;
12601 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
12603 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
12604 unsigned LOADOpc = X86::MOV32rm;
12606 // For the atomic load-arith operator, we generate
12609 // EAX = LOAD [MI.addr + 0]
12610 // EDX = LOAD [MI.addr + 4]
12612 // EBX = OP MI.vallo, EAX
12613 // ECX = OP MI.valhi, EDX
12614 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
12618 MachineBasicBlock *thisMBB = MBB;
12619 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12620 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12621 MF->insert(I, mainMBB);
12622 MF->insert(I, sinkMBB);
12624 MachineInstrBuilder MIB;
12626 // Transfer the remainder of BB and its successor edges to sinkMBB.
12627 sinkMBB->splice(sinkMBB->begin(), MBB,
12628 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12629 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12633 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
12634 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12635 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12636 MIB.setMemRefs(MMOBegin, MMOEnd);
12638 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
12639 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12640 if (i == X86::AddrDisp)
12641 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
12643 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12645 MIB.setMemRefs(MMOBegin, MMOEnd);
12647 thisMBB->addSuccessor(mainMBB);
12650 MachineBasicBlock *origMainMBB = mainMBB;
12651 mainMBB->addLiveIn(X86::EAX);
12652 mainMBB->addLiveIn(X86::EDX);
12654 // Copy EDX:EAX as they are used more than once.
12655 unsigned LoReg = MRI.createVirtualRegister(RC);
12656 unsigned HiReg = MRI.createVirtualRegister(RC);
12657 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
12658 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
12660 unsigned t1L = MRI.createVirtualRegister(RC);
12661 unsigned t1H = MRI.createVirtualRegister(RC);
12663 unsigned Opc = MI->getOpcode();
12666 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
12667 case X86::ATOMAND6432:
12668 case X86::ATOMOR6432:
12669 case X86::ATOMXOR6432:
12670 case X86::ATOMADD6432:
12671 case X86::ATOMSUB6432: {
12673 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12674 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg).addReg(LoReg);
12675 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg).addReg(HiReg);
12678 case X86::ATOMNAND6432: {
12679 unsigned HiOpc, NOTOpc;
12680 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
12681 unsigned t2L = MRI.createVirtualRegister(RC);
12682 unsigned t2H = MRI.createVirtualRegister(RC);
12683 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
12684 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
12685 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
12686 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
12689 case X86::ATOMMAX6432:
12690 case X86::ATOMMIN6432:
12691 case X86::ATOMUMAX6432:
12692 case X86::ATOMUMIN6432: {
12694 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12695 unsigned cL = MRI.createVirtualRegister(RC8);
12696 unsigned cH = MRI.createVirtualRegister(RC8);
12697 unsigned cL32 = MRI.createVirtualRegister(RC);
12698 unsigned cH32 = MRI.createVirtualRegister(RC);
12699 unsigned cc = MRI.createVirtualRegister(RC);
12700 // cl := cmp src_lo, lo
12701 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12702 .addReg(SrcLoReg).addReg(LoReg);
12703 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
12704 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
12705 // ch := cmp src_hi, hi
12706 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
12707 .addReg(SrcHiReg).addReg(HiReg);
12708 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
12709 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
12710 // cc := if (src_hi == hi) ? cl : ch;
12711 if (Subtarget->hasCMov()) {
12712 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
12713 .addReg(cH32).addReg(cL32);
12715 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
12716 .addReg(cH32).addReg(cL32)
12717 .addImm(X86::COND_E);
12718 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12720 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
12721 if (Subtarget->hasCMov()) {
12722 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
12723 .addReg(SrcLoReg).addReg(LoReg);
12724 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
12725 .addReg(SrcHiReg).addReg(HiReg);
12727 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
12728 .addReg(SrcLoReg).addReg(LoReg)
12729 .addImm(X86::COND_NE);
12730 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12731 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
12732 .addReg(SrcHiReg).addReg(HiReg)
12733 .addImm(X86::COND_NE);
12734 mainMBB = EmitLoweredSelect(MIB, mainMBB);
12738 case X86::ATOMSWAP6432: {
12740 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
12741 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
12742 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
12747 // Copy EDX:EAX back from HiReg:LoReg
12748 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
12749 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
12750 // Copy ECX:EBX from t1H:t1L
12751 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
12752 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
12754 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
12755 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12756 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12757 MIB.setMemRefs(MMOBegin, MMOEnd);
12759 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
12761 mainMBB->addSuccessor(origMainMBB);
12762 mainMBB->addSuccessor(sinkMBB);
12765 sinkMBB->addLiveIn(X86::EAX);
12766 sinkMBB->addLiveIn(X86::EDX);
12768 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12769 TII->get(TargetOpcode::COPY), DstLoReg)
12771 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12772 TII->get(TargetOpcode::COPY), DstHiReg)
12775 MI->eraseFromParent();
12779 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
12780 // or XMM0_V32I8 in AVX all of this code can be replaced with that
12781 // in the .td file.
12782 MachineBasicBlock *
12783 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
12784 unsigned numArgs, bool memArg) const {
12785 assert(Subtarget->hasSSE42() &&
12786 "Target must have SSE4.2 or AVX features enabled");
12788 DebugLoc dl = MI->getDebugLoc();
12789 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12791 if (!Subtarget->hasAVX()) {
12793 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
12795 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
12798 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
12800 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
12803 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
12804 for (unsigned i = 0; i < numArgs; ++i) {
12805 MachineOperand &Op = MI->getOperand(i+1);
12806 if (!(Op.isReg() && Op.isImplicit()))
12807 MIB.addOperand(Op);
12809 BuildMI(*BB, MI, dl,
12810 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12811 .addReg(X86::XMM0);
12813 MI->eraseFromParent();
12817 MachineBasicBlock *
12818 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
12819 DebugLoc dl = MI->getDebugLoc();
12820 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12822 // Address into RAX/EAX, other two args into ECX, EDX.
12823 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
12824 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12825 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
12826 for (int i = 0; i < X86::AddrNumOperands; ++i)
12827 MIB.addOperand(MI->getOperand(i));
12829 unsigned ValOps = X86::AddrNumOperands;
12830 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
12831 .addReg(MI->getOperand(ValOps).getReg());
12832 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
12833 .addReg(MI->getOperand(ValOps+1).getReg());
12835 // The instruction doesn't actually take any operands though.
12836 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
12838 MI->eraseFromParent(); // The pseudo is gone now.
12842 MachineBasicBlock *
12843 X86TargetLowering::EmitVAARG64WithCustomInserter(
12845 MachineBasicBlock *MBB) const {
12846 // Emit va_arg instruction on X86-64.
12848 // Operands to this pseudo-instruction:
12849 // 0 ) Output : destination address (reg)
12850 // 1-5) Input : va_list address (addr, i64mem)
12851 // 6 ) ArgSize : Size (in bytes) of vararg type
12852 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
12853 // 8 ) Align : Alignment of type
12854 // 9 ) EFLAGS (implicit-def)
12856 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
12857 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
12859 unsigned DestReg = MI->getOperand(0).getReg();
12860 MachineOperand &Base = MI->getOperand(1);
12861 MachineOperand &Scale = MI->getOperand(2);
12862 MachineOperand &Index = MI->getOperand(3);
12863 MachineOperand &Disp = MI->getOperand(4);
12864 MachineOperand &Segment = MI->getOperand(5);
12865 unsigned ArgSize = MI->getOperand(6).getImm();
12866 unsigned ArgMode = MI->getOperand(7).getImm();
12867 unsigned Align = MI->getOperand(8).getImm();
12869 // Memory Reference
12870 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
12871 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12872 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12874 // Machine Information
12875 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12876 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
12877 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
12878 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
12879 DebugLoc DL = MI->getDebugLoc();
12881 // struct va_list {
12884 // i64 overflow_area (address)
12885 // i64 reg_save_area (address)
12887 // sizeof(va_list) = 24
12888 // alignment(va_list) = 8
12890 unsigned TotalNumIntRegs = 6;
12891 unsigned TotalNumXMMRegs = 8;
12892 bool UseGPOffset = (ArgMode == 1);
12893 bool UseFPOffset = (ArgMode == 2);
12894 unsigned MaxOffset = TotalNumIntRegs * 8 +
12895 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
12897 /* Align ArgSize to a multiple of 8 */
12898 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
12899 bool NeedsAlign = (Align > 8);
12901 MachineBasicBlock *thisMBB = MBB;
12902 MachineBasicBlock *overflowMBB;
12903 MachineBasicBlock *offsetMBB;
12904 MachineBasicBlock *endMBB;
12906 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
12907 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
12908 unsigned OffsetReg = 0;
12910 if (!UseGPOffset && !UseFPOffset) {
12911 // If we only pull from the overflow region, we don't create a branch.
12912 // We don't need to alter control flow.
12913 OffsetDestReg = 0; // unused
12914 OverflowDestReg = DestReg;
12917 overflowMBB = thisMBB;
12920 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12921 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12922 // If not, pull from overflow_area. (branch to overflowMBB)
12927 // offsetMBB overflowMBB
12932 // Registers for the PHI in endMBB
12933 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12934 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12936 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12937 MachineFunction *MF = MBB->getParent();
12938 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12939 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12940 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12942 MachineFunction::iterator MBBIter = MBB;
12945 // Insert the new basic blocks
12946 MF->insert(MBBIter, offsetMBB);
12947 MF->insert(MBBIter, overflowMBB);
12948 MF->insert(MBBIter, endMBB);
12950 // Transfer the remainder of MBB and its successor edges to endMBB.
12951 endMBB->splice(endMBB->begin(), thisMBB,
12952 llvm::next(MachineBasicBlock::iterator(MI)),
12954 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12956 // Make offsetMBB and overflowMBB successors of thisMBB
12957 thisMBB->addSuccessor(offsetMBB);
12958 thisMBB->addSuccessor(overflowMBB);
12960 // endMBB is a successor of both offsetMBB and overflowMBB
12961 offsetMBB->addSuccessor(endMBB);
12962 overflowMBB->addSuccessor(endMBB);
12964 // Load the offset value into a register
12965 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12966 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12970 .addDisp(Disp, UseFPOffset ? 4 : 0)
12971 .addOperand(Segment)
12972 .setMemRefs(MMOBegin, MMOEnd);
12974 // Check if there is enough room left to pull this argument.
12975 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12977 .addImm(MaxOffset + 8 - ArgSizeA8);
12979 // Branch to "overflowMBB" if offset >= max
12980 // Fall through to "offsetMBB" otherwise
12981 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12982 .addMBB(overflowMBB);
12985 // In offsetMBB, emit code to use the reg_save_area.
12987 assert(OffsetReg != 0);
12989 // Read the reg_save_area address.
12990 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12991 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12996 .addOperand(Segment)
12997 .setMemRefs(MMOBegin, MMOEnd);
12999 // Zero-extend the offset
13000 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13001 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13004 .addImm(X86::sub_32bit);
13006 // Add the offset to the reg_save_area to get the final address.
13007 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13008 .addReg(OffsetReg64)
13009 .addReg(RegSaveReg);
13011 // Compute the offset for the next argument
13012 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13013 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13015 .addImm(UseFPOffset ? 16 : 8);
13017 // Store it back into the va_list.
13018 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13022 .addDisp(Disp, UseFPOffset ? 4 : 0)
13023 .addOperand(Segment)
13024 .addReg(NextOffsetReg)
13025 .setMemRefs(MMOBegin, MMOEnd);
13028 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13033 // Emit code to use overflow area
13036 // Load the overflow_area address into a register.
13037 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13038 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13043 .addOperand(Segment)
13044 .setMemRefs(MMOBegin, MMOEnd);
13046 // If we need to align it, do so. Otherwise, just copy the address
13047 // to OverflowDestReg.
13049 // Align the overflow address
13050 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13051 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13053 // aligned_addr = (addr + (align-1)) & ~(align-1)
13054 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13055 .addReg(OverflowAddrReg)
13058 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13060 .addImm(~(uint64_t)(Align-1));
13062 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13063 .addReg(OverflowAddrReg);
13066 // Compute the next overflow address after this argument.
13067 // (the overflow address should be kept 8-byte aligned)
13068 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13069 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13070 .addReg(OverflowDestReg)
13071 .addImm(ArgSizeA8);
13073 // Store the new overflow address.
13074 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13079 .addOperand(Segment)
13080 .addReg(NextAddrReg)
13081 .setMemRefs(MMOBegin, MMOEnd);
13083 // If we branched, emit the PHI to the front of endMBB.
13085 BuildMI(*endMBB, endMBB->begin(), DL,
13086 TII->get(X86::PHI), DestReg)
13087 .addReg(OffsetDestReg).addMBB(offsetMBB)
13088 .addReg(OverflowDestReg).addMBB(overflowMBB);
13091 // Erase the pseudo instruction
13092 MI->eraseFromParent();
13097 MachineBasicBlock *
13098 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13100 MachineBasicBlock *MBB) const {
13101 // Emit code to save XMM registers to the stack. The ABI says that the
13102 // number of registers to save is given in %al, so it's theoretically
13103 // possible to do an indirect jump trick to avoid saving all of them,
13104 // however this code takes a simpler approach and just executes all
13105 // of the stores if %al is non-zero. It's less code, and it's probably
13106 // easier on the hardware branch predictor, and stores aren't all that
13107 // expensive anyway.
13109 // Create the new basic blocks. One block contains all the XMM stores,
13110 // and one block is the final destination regardless of whether any
13111 // stores were performed.
13112 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13113 MachineFunction *F = MBB->getParent();
13114 MachineFunction::iterator MBBIter = MBB;
13116 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13117 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13118 F->insert(MBBIter, XMMSaveMBB);
13119 F->insert(MBBIter, EndMBB);
13121 // Transfer the remainder of MBB and its successor edges to EndMBB.
13122 EndMBB->splice(EndMBB->begin(), MBB,
13123 llvm::next(MachineBasicBlock::iterator(MI)),
13125 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13127 // The original block will now fall through to the XMM save block.
13128 MBB->addSuccessor(XMMSaveMBB);
13129 // The XMMSaveMBB will fall through to the end block.
13130 XMMSaveMBB->addSuccessor(EndMBB);
13132 // Now add the instructions.
13133 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13134 DebugLoc DL = MI->getDebugLoc();
13136 unsigned CountReg = MI->getOperand(0).getReg();
13137 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13138 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13140 if (!Subtarget->isTargetWin64()) {
13141 // If %al is 0, branch around the XMM save block.
13142 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13143 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13144 MBB->addSuccessor(EndMBB);
13147 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13148 // In the XMM save block, save all the XMM argument registers.
13149 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13150 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13151 MachineMemOperand *MMO =
13152 F->getMachineMemOperand(
13153 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13154 MachineMemOperand::MOStore,
13155 /*Size=*/16, /*Align=*/16);
13156 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13157 .addFrameIndex(RegSaveFrameIndex)
13158 .addImm(/*Scale=*/1)
13159 .addReg(/*IndexReg=*/0)
13160 .addImm(/*Disp=*/Offset)
13161 .addReg(/*Segment=*/0)
13162 .addReg(MI->getOperand(i).getReg())
13163 .addMemOperand(MMO);
13166 MI->eraseFromParent(); // The pseudo instruction is gone now.
13171 // The EFLAGS operand of SelectItr might be missing a kill marker
13172 // because there were multiple uses of EFLAGS, and ISel didn't know
13173 // which to mark. Figure out whether SelectItr should have had a
13174 // kill marker, and set it if it should. Returns the correct kill
13176 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13177 MachineBasicBlock* BB,
13178 const TargetRegisterInfo* TRI) {
13179 // Scan forward through BB for a use/def of EFLAGS.
13180 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13181 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13182 const MachineInstr& mi = *miI;
13183 if (mi.readsRegister(X86::EFLAGS))
13185 if (mi.definesRegister(X86::EFLAGS))
13186 break; // Should have kill-flag - update below.
13189 // If we hit the end of the block, check whether EFLAGS is live into a
13191 if (miI == BB->end()) {
13192 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13193 sEnd = BB->succ_end();
13194 sItr != sEnd; ++sItr) {
13195 MachineBasicBlock* succ = *sItr;
13196 if (succ->isLiveIn(X86::EFLAGS))
13201 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13202 // out. SelectMI should have a kill flag on EFLAGS.
13203 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13207 MachineBasicBlock *
13208 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13209 MachineBasicBlock *BB) const {
13210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13211 DebugLoc DL = MI->getDebugLoc();
13213 // To "insert" a SELECT_CC instruction, we actually have to insert the
13214 // diamond control-flow pattern. The incoming instruction knows the
13215 // destination vreg to set, the condition code register to branch on, the
13216 // true/false values to select between, and a branch opcode to use.
13217 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13218 MachineFunction::iterator It = BB;
13224 // cmpTY ccX, r1, r2
13226 // fallthrough --> copy0MBB
13227 MachineBasicBlock *thisMBB = BB;
13228 MachineFunction *F = BB->getParent();
13229 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13230 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13231 F->insert(It, copy0MBB);
13232 F->insert(It, sinkMBB);
13234 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13235 // live into the sink and copy blocks.
13236 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13237 if (!MI->killsRegister(X86::EFLAGS) &&
13238 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13239 copy0MBB->addLiveIn(X86::EFLAGS);
13240 sinkMBB->addLiveIn(X86::EFLAGS);
13243 // Transfer the remainder of BB and its successor edges to sinkMBB.
13244 sinkMBB->splice(sinkMBB->begin(), BB,
13245 llvm::next(MachineBasicBlock::iterator(MI)),
13247 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13249 // Add the true and fallthrough blocks as its successors.
13250 BB->addSuccessor(copy0MBB);
13251 BB->addSuccessor(sinkMBB);
13253 // Create the conditional branch instruction.
13255 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13256 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13259 // %FalseValue = ...
13260 // # fallthrough to sinkMBB
13261 copy0MBB->addSuccessor(sinkMBB);
13264 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13266 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13267 TII->get(X86::PHI), MI->getOperand(0).getReg())
13268 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13269 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13271 MI->eraseFromParent(); // The pseudo instruction is gone now.
13275 MachineBasicBlock *
13276 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13277 bool Is64Bit) const {
13278 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13279 DebugLoc DL = MI->getDebugLoc();
13280 MachineFunction *MF = BB->getParent();
13281 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13283 assert(getTargetMachine().Options.EnableSegmentedStacks);
13285 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13286 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13289 // ... [Till the alloca]
13290 // If stacklet is not large enough, jump to mallocMBB
13293 // Allocate by subtracting from RSP
13294 // Jump to continueMBB
13297 // Allocate by call to runtime
13301 // [rest of original BB]
13304 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13305 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13306 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13308 MachineRegisterInfo &MRI = MF->getRegInfo();
13309 const TargetRegisterClass *AddrRegClass =
13310 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13312 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13313 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13314 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13315 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13316 sizeVReg = MI->getOperand(1).getReg(),
13317 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13319 MachineFunction::iterator MBBIter = BB;
13322 MF->insert(MBBIter, bumpMBB);
13323 MF->insert(MBBIter, mallocMBB);
13324 MF->insert(MBBIter, continueMBB);
13326 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13327 (MachineBasicBlock::iterator(MI)), BB->end());
13328 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13330 // Add code to the main basic block to check if the stack limit has been hit,
13331 // and if so, jump to mallocMBB otherwise to bumpMBB.
13332 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13333 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13334 .addReg(tmpSPVReg).addReg(sizeVReg);
13335 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13336 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13337 .addReg(SPLimitVReg);
13338 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13340 // bumpMBB simply decreases the stack pointer, since we know the current
13341 // stacklet has enough space.
13342 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13343 .addReg(SPLimitVReg);
13344 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13345 .addReg(SPLimitVReg);
13346 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13348 // Calls into a routine in libgcc to allocate more space from the heap.
13349 const uint32_t *RegMask =
13350 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13352 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13354 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13355 .addExternalSymbol("__morestack_allocate_stack_space")
13356 .addRegMask(RegMask)
13357 .addReg(X86::RDI, RegState::Implicit)
13358 .addReg(X86::RAX, RegState::ImplicitDefine);
13360 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13362 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13363 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13364 .addExternalSymbol("__morestack_allocate_stack_space")
13365 .addRegMask(RegMask)
13366 .addReg(X86::EAX, RegState::ImplicitDefine);
13370 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13373 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13374 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13375 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13377 // Set up the CFG correctly.
13378 BB->addSuccessor(bumpMBB);
13379 BB->addSuccessor(mallocMBB);
13380 mallocMBB->addSuccessor(continueMBB);
13381 bumpMBB->addSuccessor(continueMBB);
13383 // Take care of the PHI nodes.
13384 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13385 MI->getOperand(0).getReg())
13386 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13387 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13389 // Delete the original pseudo instruction.
13390 MI->eraseFromParent();
13393 return continueMBB;
13396 MachineBasicBlock *
13397 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13398 MachineBasicBlock *BB) const {
13399 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13400 DebugLoc DL = MI->getDebugLoc();
13402 assert(!Subtarget->isTargetEnvMacho());
13404 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13405 // non-trivial part is impdef of ESP.
13407 if (Subtarget->isTargetWin64()) {
13408 if (Subtarget->isTargetCygMing()) {
13409 // ___chkstk(Mingw64):
13410 // Clobbers R10, R11, RAX and EFLAGS.
13412 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13413 .addExternalSymbol("___chkstk")
13414 .addReg(X86::RAX, RegState::Implicit)
13415 .addReg(X86::RSP, RegState::Implicit)
13416 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13417 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13418 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13420 // __chkstk(MSVCRT): does not update stack pointer.
13421 // Clobbers R10, R11 and EFLAGS.
13422 // FIXME: RAX(allocated size) might be reused and not killed.
13423 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13424 .addExternalSymbol("__chkstk")
13425 .addReg(X86::RAX, RegState::Implicit)
13426 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13427 // RAX has the offset to subtracted from RSP.
13428 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13433 const char *StackProbeSymbol =
13434 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13436 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13437 .addExternalSymbol(StackProbeSymbol)
13438 .addReg(X86::EAX, RegState::Implicit)
13439 .addReg(X86::ESP, RegState::Implicit)
13440 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13441 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13442 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13445 MI->eraseFromParent(); // The pseudo instruction is gone now.
13449 MachineBasicBlock *
13450 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13451 MachineBasicBlock *BB) const {
13452 // This is pretty easy. We're taking the value that we received from
13453 // our load from the relocation, sticking it in either RDI (x86-64)
13454 // or EAX and doing an indirect call. The return value will then
13455 // be in the normal return register.
13456 const X86InstrInfo *TII
13457 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13458 DebugLoc DL = MI->getDebugLoc();
13459 MachineFunction *F = BB->getParent();
13461 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
13462 assert(MI->getOperand(3).isGlobal() && "This should be a global");
13464 // Get a register mask for the lowered call.
13465 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
13466 // proper register mask.
13467 const uint32_t *RegMask =
13468 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13469 if (Subtarget->is64Bit()) {
13470 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13471 TII->get(X86::MOV64rm), X86::RDI)
13473 .addImm(0).addReg(0)
13474 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13475 MI->getOperand(3).getTargetFlags())
13477 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
13478 addDirectMem(MIB, X86::RDI);
13479 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
13480 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
13481 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13482 TII->get(X86::MOV32rm), X86::EAX)
13484 .addImm(0).addReg(0)
13485 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13486 MI->getOperand(3).getTargetFlags())
13488 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13489 addDirectMem(MIB, X86::EAX);
13490 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13492 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
13493 TII->get(X86::MOV32rm), X86::EAX)
13494 .addReg(TII->getGlobalBaseReg(F))
13495 .addImm(0).addReg(0)
13496 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
13497 MI->getOperand(3).getTargetFlags())
13499 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
13500 addDirectMem(MIB, X86::EAX);
13501 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
13504 MI->eraseFromParent(); // The pseudo instruction is gone now.
13508 MachineBasicBlock *
13509 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
13510 MachineBasicBlock *MBB) const {
13511 DebugLoc DL = MI->getDebugLoc();
13512 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13514 MachineFunction *MF = MBB->getParent();
13515 MachineRegisterInfo &MRI = MF->getRegInfo();
13517 const BasicBlock *BB = MBB->getBasicBlock();
13518 MachineFunction::iterator I = MBB;
13521 // Memory Reference
13522 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13523 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13526 unsigned MemOpndSlot = 0;
13528 unsigned CurOp = 0;
13530 DstReg = MI->getOperand(CurOp++).getReg();
13531 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13532 assert(RC->hasType(MVT::i32) && "Invalid destination!");
13533 unsigned mainDstReg = MRI.createVirtualRegister(RC);
13534 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
13536 MemOpndSlot = CurOp;
13538 MVT PVT = getPointerTy();
13539 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13540 "Invalid Pointer Size!");
13542 // For v = setjmp(buf), we generate
13545 // buf[LabelOffset] = restoreMBB
13546 // SjLjSetup restoreMBB
13552 // v = phi(main, restore)
13557 MachineBasicBlock *thisMBB = MBB;
13558 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13559 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13560 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
13561 MF->insert(I, mainMBB);
13562 MF->insert(I, sinkMBB);
13563 MF->push_back(restoreMBB);
13565 MachineInstrBuilder MIB;
13567 // Transfer the remainder of BB and its successor edges to sinkMBB.
13568 sinkMBB->splice(sinkMBB->begin(), MBB,
13569 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13570 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13573 unsigned PtrStoreOpc = 0;
13574 unsigned LabelReg = 0;
13575 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13576 Reloc::Model RM = getTargetMachine().getRelocationModel();
13577 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
13578 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
13580 // Prepare IP either in reg or imm.
13581 if (!UseImmLabel) {
13582 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
13583 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13584 LabelReg = MRI.createVirtualRegister(PtrRC);
13585 if (Subtarget->is64Bit()) {
13586 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
13590 .addMBB(restoreMBB)
13593 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
13594 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
13595 .addReg(XII->getGlobalBaseReg(MF))
13598 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
13602 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
13604 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
13605 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13606 if (i == X86::AddrDisp)
13607 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
13609 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13612 MIB.addReg(LabelReg);
13614 MIB.addMBB(restoreMBB);
13615 MIB.setMemRefs(MMOBegin, MMOEnd);
13617 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
13618 .addMBB(restoreMBB);
13619 MIB.addRegMask(RegInfo->getNoPreservedMask());
13620 thisMBB->addSuccessor(mainMBB);
13621 thisMBB->addSuccessor(restoreMBB);
13625 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
13626 mainMBB->addSuccessor(sinkMBB);
13629 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13630 TII->get(X86::PHI), DstReg)
13631 .addReg(mainDstReg).addMBB(mainMBB)
13632 .addReg(restoreDstReg).addMBB(restoreMBB);
13635 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
13636 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
13637 restoreMBB->addSuccessor(sinkMBB);
13639 MI->eraseFromParent();
13643 MachineBasicBlock *
13644 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
13645 MachineBasicBlock *MBB) const {
13646 DebugLoc DL = MI->getDebugLoc();
13647 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13649 MachineFunction *MF = MBB->getParent();
13650 MachineRegisterInfo &MRI = MF->getRegInfo();
13652 // Memory Reference
13653 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13654 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13656 MVT PVT = getPointerTy();
13657 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13658 "Invalid Pointer Size!");
13660 const TargetRegisterClass *RC =
13661 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
13662 unsigned Tmp = MRI.createVirtualRegister(RC);
13663 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13664 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
13665 unsigned SP = RegInfo->getStackRegister();
13667 MachineInstrBuilder MIB;
13669 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13670 const int64_t SPOffset = 2 * PVT.getStoreSize();
13672 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
13673 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
13676 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
13677 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13678 MIB.addOperand(MI->getOperand(i));
13679 MIB.setMemRefs(MMOBegin, MMOEnd);
13681 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
13682 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13683 if (i == X86::AddrDisp)
13684 MIB.addDisp(MI->getOperand(i), LabelOffset);
13686 MIB.addOperand(MI->getOperand(i));
13688 MIB.setMemRefs(MMOBegin, MMOEnd);
13690 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
13691 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13692 if (i == X86::AddrDisp)
13693 MIB.addDisp(MI->getOperand(i), SPOffset);
13695 MIB.addOperand(MI->getOperand(i));
13697 MIB.setMemRefs(MMOBegin, MMOEnd);
13699 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
13701 MI->eraseFromParent();
13705 MachineBasicBlock *
13706 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
13707 MachineBasicBlock *BB) const {
13708 switch (MI->getOpcode()) {
13709 default: llvm_unreachable("Unexpected instr type to insert");
13710 case X86::TAILJMPd64:
13711 case X86::TAILJMPr64:
13712 case X86::TAILJMPm64:
13713 llvm_unreachable("TAILJMP64 would not be touched here.");
13714 case X86::TCRETURNdi64:
13715 case X86::TCRETURNri64:
13716 case X86::TCRETURNmi64:
13718 case X86::WIN_ALLOCA:
13719 return EmitLoweredWinAlloca(MI, BB);
13720 case X86::SEG_ALLOCA_32:
13721 return EmitLoweredSegAlloca(MI, BB, false);
13722 case X86::SEG_ALLOCA_64:
13723 return EmitLoweredSegAlloca(MI, BB, true);
13724 case X86::TLSCall_32:
13725 case X86::TLSCall_64:
13726 return EmitLoweredTLSCall(MI, BB);
13727 case X86::CMOV_GR8:
13728 case X86::CMOV_FR32:
13729 case X86::CMOV_FR64:
13730 case X86::CMOV_V4F32:
13731 case X86::CMOV_V2F64:
13732 case X86::CMOV_V2I64:
13733 case X86::CMOV_V8F32:
13734 case X86::CMOV_V4F64:
13735 case X86::CMOV_V4I64:
13736 case X86::CMOV_GR16:
13737 case X86::CMOV_GR32:
13738 case X86::CMOV_RFP32:
13739 case X86::CMOV_RFP64:
13740 case X86::CMOV_RFP80:
13741 return EmitLoweredSelect(MI, BB);
13743 case X86::FP32_TO_INT16_IN_MEM:
13744 case X86::FP32_TO_INT32_IN_MEM:
13745 case X86::FP32_TO_INT64_IN_MEM:
13746 case X86::FP64_TO_INT16_IN_MEM:
13747 case X86::FP64_TO_INT32_IN_MEM:
13748 case X86::FP64_TO_INT64_IN_MEM:
13749 case X86::FP80_TO_INT16_IN_MEM:
13750 case X86::FP80_TO_INT32_IN_MEM:
13751 case X86::FP80_TO_INT64_IN_MEM: {
13752 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13753 DebugLoc DL = MI->getDebugLoc();
13755 // Change the floating point control register to use "round towards zero"
13756 // mode when truncating to an integer value.
13757 MachineFunction *F = BB->getParent();
13758 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
13759 addFrameReference(BuildMI(*BB, MI, DL,
13760 TII->get(X86::FNSTCW16m)), CWFrameIdx);
13762 // Load the old value of the high byte of the control word...
13764 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
13765 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
13768 // Set the high part to be round to zero...
13769 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
13772 // Reload the modified control word now...
13773 addFrameReference(BuildMI(*BB, MI, DL,
13774 TII->get(X86::FLDCW16m)), CWFrameIdx);
13776 // Restore the memory image of control word to original value
13777 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
13780 // Get the X86 opcode to use.
13782 switch (MI->getOpcode()) {
13783 default: llvm_unreachable("illegal opcode!");
13784 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
13785 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
13786 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
13787 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
13788 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
13789 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
13790 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
13791 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
13792 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
13796 MachineOperand &Op = MI->getOperand(0);
13798 AM.BaseType = X86AddressMode::RegBase;
13799 AM.Base.Reg = Op.getReg();
13801 AM.BaseType = X86AddressMode::FrameIndexBase;
13802 AM.Base.FrameIndex = Op.getIndex();
13804 Op = MI->getOperand(1);
13806 AM.Scale = Op.getImm();
13807 Op = MI->getOperand(2);
13809 AM.IndexReg = Op.getImm();
13810 Op = MI->getOperand(3);
13811 if (Op.isGlobal()) {
13812 AM.GV = Op.getGlobal();
13814 AM.Disp = Op.getImm();
13816 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
13817 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
13819 // Reload the original control word now.
13820 addFrameReference(BuildMI(*BB, MI, DL,
13821 TII->get(X86::FLDCW16m)), CWFrameIdx);
13823 MI->eraseFromParent(); // The pseudo instruction is gone now.
13826 // String/text processing lowering.
13827 case X86::PCMPISTRM128REG:
13828 case X86::VPCMPISTRM128REG:
13829 case X86::PCMPISTRM128MEM:
13830 case X86::VPCMPISTRM128MEM:
13831 case X86::PCMPESTRM128REG:
13832 case X86::VPCMPESTRM128REG:
13833 case X86::PCMPESTRM128MEM:
13834 case X86::VPCMPESTRM128MEM: {
13837 switch (MI->getOpcode()) {
13838 default: llvm_unreachable("illegal opcode!");
13839 case X86::PCMPISTRM128REG:
13840 case X86::VPCMPISTRM128REG:
13841 NumArgs = 3; MemArg = false; break;
13842 case X86::PCMPISTRM128MEM:
13843 case X86::VPCMPISTRM128MEM:
13844 NumArgs = 3; MemArg = true; break;
13845 case X86::PCMPESTRM128REG:
13846 case X86::VPCMPESTRM128REG:
13847 NumArgs = 5; MemArg = false; break;
13848 case X86::PCMPESTRM128MEM:
13849 case X86::VPCMPESTRM128MEM:
13850 NumArgs = 5; MemArg = true; break;
13852 return EmitPCMP(MI, BB, NumArgs, MemArg);
13855 // Thread synchronization.
13857 return EmitMonitor(MI, BB);
13859 // Atomic Lowering.
13860 case X86::ATOMAND8:
13861 case X86::ATOMAND16:
13862 case X86::ATOMAND32:
13863 case X86::ATOMAND64:
13866 case X86::ATOMOR16:
13867 case X86::ATOMOR32:
13868 case X86::ATOMOR64:
13870 case X86::ATOMXOR16:
13871 case X86::ATOMXOR8:
13872 case X86::ATOMXOR32:
13873 case X86::ATOMXOR64:
13875 case X86::ATOMNAND8:
13876 case X86::ATOMNAND16:
13877 case X86::ATOMNAND32:
13878 case X86::ATOMNAND64:
13880 case X86::ATOMMAX8:
13881 case X86::ATOMMAX16:
13882 case X86::ATOMMAX32:
13883 case X86::ATOMMAX64:
13885 case X86::ATOMMIN8:
13886 case X86::ATOMMIN16:
13887 case X86::ATOMMIN32:
13888 case X86::ATOMMIN64:
13890 case X86::ATOMUMAX8:
13891 case X86::ATOMUMAX16:
13892 case X86::ATOMUMAX32:
13893 case X86::ATOMUMAX64:
13895 case X86::ATOMUMIN8:
13896 case X86::ATOMUMIN16:
13897 case X86::ATOMUMIN32:
13898 case X86::ATOMUMIN64:
13899 return EmitAtomicLoadArith(MI, BB);
13901 // This group does 64-bit operations on a 32-bit host.
13902 case X86::ATOMAND6432:
13903 case X86::ATOMOR6432:
13904 case X86::ATOMXOR6432:
13905 case X86::ATOMNAND6432:
13906 case X86::ATOMADD6432:
13907 case X86::ATOMSUB6432:
13908 case X86::ATOMMAX6432:
13909 case X86::ATOMMIN6432:
13910 case X86::ATOMUMAX6432:
13911 case X86::ATOMUMIN6432:
13912 case X86::ATOMSWAP6432:
13913 return EmitAtomicLoadArith6432(MI, BB);
13915 case X86::VASTART_SAVE_XMM_REGS:
13916 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
13918 case X86::VAARG_64:
13919 return EmitVAARG64WithCustomInserter(MI, BB);
13921 case X86::EH_SjLj_SetJmp32:
13922 case X86::EH_SjLj_SetJmp64:
13923 return emitEHSjLjSetJmp(MI, BB);
13925 case X86::EH_SjLj_LongJmp32:
13926 case X86::EH_SjLj_LongJmp64:
13927 return emitEHSjLjLongJmp(MI, BB);
13931 //===----------------------------------------------------------------------===//
13932 // X86 Optimization Hooks
13933 //===----------------------------------------------------------------------===//
13935 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
13938 const SelectionDAG &DAG,
13939 unsigned Depth) const {
13940 unsigned BitWidth = KnownZero.getBitWidth();
13941 unsigned Opc = Op.getOpcode();
13942 assert((Opc >= ISD::BUILTIN_OP_END ||
13943 Opc == ISD::INTRINSIC_WO_CHAIN ||
13944 Opc == ISD::INTRINSIC_W_CHAIN ||
13945 Opc == ISD::INTRINSIC_VOID) &&
13946 "Should use MaskedValueIsZero if you don't know whether Op"
13947 " is a target node!");
13949 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
13963 // These nodes' second result is a boolean.
13964 if (Op.getResNo() == 0)
13967 case X86ISD::SETCC:
13968 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13970 case ISD::INTRINSIC_WO_CHAIN: {
13971 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13972 unsigned NumLoBits = 0;
13975 case Intrinsic::x86_sse_movmsk_ps:
13976 case Intrinsic::x86_avx_movmsk_ps_256:
13977 case Intrinsic::x86_sse2_movmsk_pd:
13978 case Intrinsic::x86_avx_movmsk_pd_256:
13979 case Intrinsic::x86_mmx_pmovmskb:
13980 case Intrinsic::x86_sse2_pmovmskb_128:
13981 case Intrinsic::x86_avx2_pmovmskb: {
13982 // High bits of movmskp{s|d}, pmovmskb are known zero.
13984 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13985 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
13986 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
13987 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
13988 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
13989 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
13990 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
13991 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
13993 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14002 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14003 unsigned Depth) const {
14004 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14005 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14006 return Op.getValueType().getScalarType().getSizeInBits();
14012 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14013 /// node is a GlobalAddress + offset.
14014 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14015 const GlobalValue* &GA,
14016 int64_t &Offset) const {
14017 if (N->getOpcode() == X86ISD::Wrapper) {
14018 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14019 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14020 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14024 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14027 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14028 /// same as extracting the high 128-bit part of 256-bit vector and then
14029 /// inserting the result into the low part of a new 256-bit vector
14030 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14031 EVT VT = SVOp->getValueType(0);
14032 unsigned NumElems = VT.getVectorNumElements();
14034 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14035 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14036 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14037 SVOp->getMaskElt(j) >= 0)
14043 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14044 /// same as extracting the low 128-bit part of 256-bit vector and then
14045 /// inserting the result into the high part of a new 256-bit vector
14046 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14047 EVT VT = SVOp->getValueType(0);
14048 unsigned NumElems = VT.getVectorNumElements();
14050 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14051 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14052 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14053 SVOp->getMaskElt(j) >= 0)
14059 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14060 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14061 TargetLowering::DAGCombinerInfo &DCI,
14062 const X86Subtarget* Subtarget) {
14063 DebugLoc dl = N->getDebugLoc();
14064 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14065 SDValue V1 = SVOp->getOperand(0);
14066 SDValue V2 = SVOp->getOperand(1);
14067 EVT VT = SVOp->getValueType(0);
14068 unsigned NumElems = VT.getVectorNumElements();
14070 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14071 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14075 // V UNDEF BUILD_VECTOR UNDEF
14077 // CONCAT_VECTOR CONCAT_VECTOR
14080 // RESULT: V + zero extended
14082 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14083 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14084 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14087 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14090 // To match the shuffle mask, the first half of the mask should
14091 // be exactly the first vector, and all the rest a splat with the
14092 // first element of the second one.
14093 for (unsigned i = 0; i != NumElems/2; ++i)
14094 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14095 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14098 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14099 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14100 if (Ld->hasNUsesOfValue(1, 0)) {
14101 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14102 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14104 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14106 Ld->getPointerInfo(),
14107 Ld->getAlignment(),
14108 false/*isVolatile*/, true/*ReadMem*/,
14109 false/*WriteMem*/);
14110 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14114 // Emit a zeroed vector and insert the desired subvector on its
14116 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14117 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14118 return DCI.CombineTo(N, InsV);
14121 //===--------------------------------------------------------------------===//
14122 // Combine some shuffles into subvector extracts and inserts:
14125 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14126 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14127 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14128 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14129 return DCI.CombineTo(N, InsV);
14132 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14133 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14134 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14135 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14136 return DCI.CombineTo(N, InsV);
14142 /// PerformShuffleCombine - Performs several different shuffle combines.
14143 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14144 TargetLowering::DAGCombinerInfo &DCI,
14145 const X86Subtarget *Subtarget) {
14146 DebugLoc dl = N->getDebugLoc();
14147 EVT VT = N->getValueType(0);
14149 // Don't create instructions with illegal types after legalize types has run.
14150 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14151 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14154 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14155 if (Subtarget->hasAVX() && VT.is256BitVector() &&
14156 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14157 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14159 // Only handle 128 wide vector from here on.
14160 if (!VT.is128BitVector())
14163 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14164 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14165 // consecutive, non-overlapping, and in the right order.
14166 SmallVector<SDValue, 16> Elts;
14167 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14168 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14170 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14174 /// PerformTruncateCombine - Converts truncate operation to
14175 /// a sequence of vector shuffle operations.
14176 /// It is possible when we truncate 256-bit vector to 128-bit vector
14177 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14178 TargetLowering::DAGCombinerInfo &DCI,
14179 const X86Subtarget *Subtarget) {
14180 if (!DCI.isBeforeLegalizeOps())
14183 if (!Subtarget->hasAVX())
14186 EVT VT = N->getValueType(0);
14187 SDValue Op = N->getOperand(0);
14188 EVT OpVT = Op.getValueType();
14189 DebugLoc dl = N->getDebugLoc();
14191 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
14193 if (Subtarget->hasAVX2()) {
14194 // AVX2: v4i64 -> v4i32
14197 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
14199 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
14200 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
14203 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
14204 DAG.getIntPtrConstant(0));
14207 // AVX: v4i64 -> v4i32
14208 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14209 DAG.getIntPtrConstant(0));
14211 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14212 DAG.getIntPtrConstant(2));
14214 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14215 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14218 static const int ShufMask1[] = {0, 2, 0, 0};
14220 SDValue Undef = DAG.getUNDEF(VT);
14221 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, Undef, ShufMask1);
14222 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, Undef, ShufMask1);
14225 static const int ShufMask2[] = {0, 1, 4, 5};
14227 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
14230 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
14232 if (Subtarget->hasAVX2()) {
14233 // AVX2: v8i32 -> v8i16
14235 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
14238 SmallVector<SDValue,32> pshufbMask;
14239 for (unsigned i = 0; i < 2; ++i) {
14240 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
14241 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
14242 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
14243 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
14244 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
14245 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
14246 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
14247 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
14248 for (unsigned j = 0; j < 8; ++j)
14249 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
14251 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
14252 &pshufbMask[0], 32);
14253 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
14255 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
14257 static const int ShufMask[] = {0, 2, -1, -1};
14258 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
14261 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
14262 DAG.getIntPtrConstant(0));
14264 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
14267 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14268 DAG.getIntPtrConstant(0));
14270 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
14271 DAG.getIntPtrConstant(4));
14273 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
14274 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
14277 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
14278 -1, -1, -1, -1, -1, -1, -1, -1};
14280 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
14281 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, Undef, ShufMask1);
14282 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, Undef, ShufMask1);
14284 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
14285 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
14288 static const int ShufMask2[] = {0, 1, 4, 5};
14290 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
14291 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
14297 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14298 /// specific shuffle of a load can be folded into a single element load.
14299 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14300 /// shuffles have been customed lowered so we need to handle those here.
14301 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14302 TargetLowering::DAGCombinerInfo &DCI) {
14303 if (DCI.isBeforeLegalizeOps())
14306 SDValue InVec = N->getOperand(0);
14307 SDValue EltNo = N->getOperand(1);
14309 if (!isa<ConstantSDNode>(EltNo))
14312 EVT VT = InVec.getValueType();
14314 bool HasShuffleIntoBitcast = false;
14315 if (InVec.getOpcode() == ISD::BITCAST) {
14316 // Don't duplicate a load with other uses.
14317 if (!InVec.hasOneUse())
14319 EVT BCVT = InVec.getOperand(0).getValueType();
14320 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14322 InVec = InVec.getOperand(0);
14323 HasShuffleIntoBitcast = true;
14326 if (!isTargetShuffle(InVec.getOpcode()))
14329 // Don't duplicate a load with other uses.
14330 if (!InVec.hasOneUse())
14333 SmallVector<int, 16> ShuffleMask;
14335 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14339 // Select the input vector, guarding against out of range extract vector.
14340 unsigned NumElems = VT.getVectorNumElements();
14341 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14342 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14343 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14344 : InVec.getOperand(1);
14346 // If inputs to shuffle are the same for both ops, then allow 2 uses
14347 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14349 if (LdNode.getOpcode() == ISD::BITCAST) {
14350 // Don't duplicate a load with other uses.
14351 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14354 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14355 LdNode = LdNode.getOperand(0);
14358 if (!ISD::isNormalLoad(LdNode.getNode()))
14361 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14363 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14366 if (HasShuffleIntoBitcast) {
14367 // If there's a bitcast before the shuffle, check if the load type and
14368 // alignment is valid.
14369 unsigned Align = LN0->getAlignment();
14370 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14371 unsigned NewAlign = TLI.getDataLayout()->
14372 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14374 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14378 // All checks match so transform back to vector_shuffle so that DAG combiner
14379 // can finish the job
14380 DebugLoc dl = N->getDebugLoc();
14382 // Create shuffle node taking into account the case that its a unary shuffle
14383 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14384 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14385 InVec.getOperand(0), Shuffle,
14387 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14388 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14392 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14393 /// generation and convert it from being a bunch of shuffles and extracts
14394 /// to a simple store and scalar loads to extract the elements.
14395 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14396 TargetLowering::DAGCombinerInfo &DCI) {
14397 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14398 if (NewOp.getNode())
14401 SDValue InputVector = N->getOperand(0);
14402 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14403 // from mmx to v2i32 has a single usage.
14404 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14405 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14406 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14407 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14408 N->getValueType(0),
14409 InputVector.getNode()->getOperand(0));
14411 // Only operate on vectors of 4 elements, where the alternative shuffling
14412 // gets to be more expensive.
14413 if (InputVector.getValueType() != MVT::v4i32)
14416 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14417 // single use which is a sign-extend or zero-extend, and all elements are
14419 SmallVector<SDNode *, 4> Uses;
14420 unsigned ExtractedElements = 0;
14421 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14422 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14423 if (UI.getUse().getResNo() != InputVector.getResNo())
14426 SDNode *Extract = *UI;
14427 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14430 if (Extract->getValueType(0) != MVT::i32)
14432 if (!Extract->hasOneUse())
14434 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14435 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14437 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14440 // Record which element was extracted.
14441 ExtractedElements |=
14442 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14444 Uses.push_back(Extract);
14447 // If not all the elements were used, this may not be worthwhile.
14448 if (ExtractedElements != 15)
14451 // Ok, we've now decided to do the transformation.
14452 DebugLoc dl = InputVector.getDebugLoc();
14454 // Store the value to a temporary stack slot.
14455 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14456 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14457 MachinePointerInfo(), false, false, 0);
14459 // Replace each use (extract) with a load of the appropriate element.
14460 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14461 UE = Uses.end(); UI != UE; ++UI) {
14462 SDNode *Extract = *UI;
14464 // cOMpute the element's address.
14465 SDValue Idx = Extract->getOperand(1);
14467 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14468 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14469 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14470 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14472 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14473 StackPtr, OffsetVal);
14475 // Load the scalar.
14476 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14477 ScalarAddr, MachinePointerInfo(),
14478 false, false, false, 0);
14480 // Replace the exact with the load.
14481 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14484 // The replacement was made in place; don't return anything.
14488 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14490 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14491 TargetLowering::DAGCombinerInfo &DCI,
14492 const X86Subtarget *Subtarget) {
14493 DebugLoc DL = N->getDebugLoc();
14494 SDValue Cond = N->getOperand(0);
14495 // Get the LHS/RHS of the select.
14496 SDValue LHS = N->getOperand(1);
14497 SDValue RHS = N->getOperand(2);
14498 EVT VT = LHS.getValueType();
14500 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
14501 // instructions match the semantics of the common C idiom x<y?x:y but not
14502 // x<=y?x:y, because of how they handle negative zero (which can be
14503 // ignored in unsafe-math mode).
14504 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
14505 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
14506 (Subtarget->hasSSE2() ||
14507 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
14508 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14510 unsigned Opcode = 0;
14511 // Check for x CC y ? x : y.
14512 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14513 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14517 // Converting this to a min would handle NaNs incorrectly, and swapping
14518 // the operands would cause it to handle comparisons between positive
14519 // and negative zero incorrectly.
14520 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14521 if (!DAG.getTarget().Options.UnsafeFPMath &&
14522 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14524 std::swap(LHS, RHS);
14526 Opcode = X86ISD::FMIN;
14529 // Converting this to a min would handle comparisons between positive
14530 // and negative zero incorrectly.
14531 if (!DAG.getTarget().Options.UnsafeFPMath &&
14532 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14534 Opcode = X86ISD::FMIN;
14537 // Converting this to a min would handle both negative zeros and NaNs
14538 // incorrectly, but we can swap the operands to fix both.
14539 std::swap(LHS, RHS);
14543 Opcode = X86ISD::FMIN;
14547 // Converting this to a max would handle comparisons between positive
14548 // and negative zero incorrectly.
14549 if (!DAG.getTarget().Options.UnsafeFPMath &&
14550 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
14552 Opcode = X86ISD::FMAX;
14555 // Converting this to a max would handle NaNs incorrectly, and swapping
14556 // the operands would cause it to handle comparisons between positive
14557 // and negative zero incorrectly.
14558 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
14559 if (!DAG.getTarget().Options.UnsafeFPMath &&
14560 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
14562 std::swap(LHS, RHS);
14564 Opcode = X86ISD::FMAX;
14567 // Converting this to a max would handle both negative zeros and NaNs
14568 // incorrectly, but we can swap the operands to fix both.
14569 std::swap(LHS, RHS);
14573 Opcode = X86ISD::FMAX;
14576 // Check for x CC y ? y : x -- a min/max with reversed arms.
14577 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14578 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14582 // Converting this to a min would handle comparisons between positive
14583 // and negative zero incorrectly, and swapping the operands would
14584 // cause it to handle NaNs incorrectly.
14585 if (!DAG.getTarget().Options.UnsafeFPMath &&
14586 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
14587 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14589 std::swap(LHS, RHS);
14591 Opcode = X86ISD::FMIN;
14594 // Converting this to a min would handle NaNs incorrectly.
14595 if (!DAG.getTarget().Options.UnsafeFPMath &&
14596 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
14598 Opcode = X86ISD::FMIN;
14601 // Converting this to a min would handle both negative zeros and NaNs
14602 // incorrectly, but we can swap the operands to fix both.
14603 std::swap(LHS, RHS);
14607 Opcode = X86ISD::FMIN;
14611 // Converting this to a max would handle NaNs incorrectly.
14612 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14614 Opcode = X86ISD::FMAX;
14617 // Converting this to a max would handle comparisons between positive
14618 // and negative zero incorrectly, and swapping the operands would
14619 // cause it to handle NaNs incorrectly.
14620 if (!DAG.getTarget().Options.UnsafeFPMath &&
14621 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
14622 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
14624 std::swap(LHS, RHS);
14626 Opcode = X86ISD::FMAX;
14629 // Converting this to a max would handle both negative zeros and NaNs
14630 // incorrectly, but we can swap the operands to fix both.
14631 std::swap(LHS, RHS);
14635 Opcode = X86ISD::FMAX;
14641 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
14644 // If this is a select between two integer constants, try to do some
14646 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
14647 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
14648 // Don't do this for crazy integer types.
14649 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
14650 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
14651 // so that TrueC (the true value) is larger than FalseC.
14652 bool NeedsCondInvert = false;
14654 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
14655 // Efficiently invertible.
14656 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
14657 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
14658 isa<ConstantSDNode>(Cond.getOperand(1))))) {
14659 NeedsCondInvert = true;
14660 std::swap(TrueC, FalseC);
14663 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
14664 if (FalseC->getAPIntValue() == 0 &&
14665 TrueC->getAPIntValue().isPowerOf2()) {
14666 if (NeedsCondInvert) // Invert the condition if needed.
14667 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14668 DAG.getConstant(1, Cond.getValueType()));
14670 // Zero extend the condition if needed.
14671 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
14673 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14674 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
14675 DAG.getConstant(ShAmt, MVT::i8));
14678 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
14679 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14680 if (NeedsCondInvert) // Invert the condition if needed.
14681 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14682 DAG.getConstant(1, Cond.getValueType()));
14684 // Zero extend the condition if needed.
14685 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14686 FalseC->getValueType(0), Cond);
14687 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14688 SDValue(FalseC, 0));
14691 // Optimize cases that will turn into an LEA instruction. This requires
14692 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14693 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14694 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14695 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14697 bool isFastMultiplier = false;
14699 switch ((unsigned char)Diff) {
14701 case 1: // result = add base, cond
14702 case 2: // result = lea base( , cond*2)
14703 case 3: // result = lea base(cond, cond*2)
14704 case 4: // result = lea base( , cond*4)
14705 case 5: // result = lea base(cond, cond*4)
14706 case 8: // result = lea base( , cond*8)
14707 case 9: // result = lea base(cond, cond*8)
14708 isFastMultiplier = true;
14713 if (isFastMultiplier) {
14714 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
14715 if (NeedsCondInvert) // Invert the condition if needed.
14716 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
14717 DAG.getConstant(1, Cond.getValueType()));
14719 // Zero extend the condition if needed.
14720 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
14722 // Scale the condition by the difference.
14724 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
14725 DAG.getConstant(Diff, Cond.getValueType()));
14727 // Add the base if non-zero.
14728 if (FalseC->getAPIntValue() != 0)
14729 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14730 SDValue(FalseC, 0));
14737 // Canonicalize max and min:
14738 // (x > y) ? x : y -> (x >= y) ? x : y
14739 // (x < y) ? x : y -> (x <= y) ? x : y
14740 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
14741 // the need for an extra compare
14742 // against zero. e.g.
14743 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
14745 // testl %edi, %edi
14747 // cmovgl %edi, %eax
14751 // cmovsl %eax, %edi
14752 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
14753 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14754 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14755 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14760 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
14761 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
14762 Cond.getOperand(0), Cond.getOperand(1), NewCC);
14763 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
14768 // If we know that this node is legal then we know that it is going to be
14769 // matched by one of the SSE/AVX BLEND instructions. These instructions only
14770 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
14771 // to simplify previous instructions.
14772 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14773 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
14774 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
14775 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
14777 // Don't optimize vector selects that map to mask-registers.
14781 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
14782 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
14784 APInt KnownZero, KnownOne;
14785 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
14786 DCI.isBeforeLegalizeOps());
14787 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
14788 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
14789 DCI.CommitTargetLoweringOpt(TLO);
14795 // Check whether a boolean test is testing a boolean value generated by
14796 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
14799 // Simplify the following patterns:
14800 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
14801 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
14802 // to (Op EFLAGS Cond)
14804 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
14805 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
14806 // to (Op EFLAGS !Cond)
14808 // where Op could be BRCOND or CMOV.
14810 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
14811 // Quit if not CMP and SUB with its value result used.
14812 if (Cmp.getOpcode() != X86ISD::CMP &&
14813 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
14816 // Quit if not used as a boolean value.
14817 if (CC != X86::COND_E && CC != X86::COND_NE)
14820 // Check CMP operands. One of them should be 0 or 1 and the other should be
14821 // an SetCC or extended from it.
14822 SDValue Op1 = Cmp.getOperand(0);
14823 SDValue Op2 = Cmp.getOperand(1);
14826 const ConstantSDNode* C = 0;
14827 bool needOppositeCond = (CC == X86::COND_E);
14829 if ((C = dyn_cast<ConstantSDNode>(Op1)))
14831 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
14833 else // Quit if all operands are not constants.
14836 if (C->getZExtValue() == 1)
14837 needOppositeCond = !needOppositeCond;
14838 else if (C->getZExtValue() != 0)
14839 // Quit if the constant is neither 0 or 1.
14842 // Skip 'zext' node.
14843 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
14844 SetCC = SetCC.getOperand(0);
14846 switch (SetCC.getOpcode()) {
14847 case X86ISD::SETCC:
14848 // Set the condition code or opposite one if necessary.
14849 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
14850 if (needOppositeCond)
14851 CC = X86::GetOppositeBranchCondition(CC);
14852 return SetCC.getOperand(1);
14853 case X86ISD::CMOV: {
14854 // Check whether false/true value has canonical one, i.e. 0 or 1.
14855 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
14856 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
14857 // Quit if true value is not a constant.
14860 // Quit if false value is not a constant.
14862 // A special case for rdrand, where 0 is set if false cond is found.
14863 SDValue Op = SetCC.getOperand(0);
14864 if (Op.getOpcode() != X86ISD::RDRAND)
14867 // Quit if false value is not the constant 0 or 1.
14868 bool FValIsFalse = true;
14869 if (FVal && FVal->getZExtValue() != 0) {
14870 if (FVal->getZExtValue() != 1)
14872 // If FVal is 1, opposite cond is needed.
14873 needOppositeCond = !needOppositeCond;
14874 FValIsFalse = false;
14876 // Quit if TVal is not the constant opposite of FVal.
14877 if (FValIsFalse && TVal->getZExtValue() != 1)
14879 if (!FValIsFalse && TVal->getZExtValue() != 0)
14881 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
14882 if (needOppositeCond)
14883 CC = X86::GetOppositeBranchCondition(CC);
14884 return SetCC.getOperand(3);
14891 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
14892 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
14893 TargetLowering::DAGCombinerInfo &DCI,
14894 const X86Subtarget *Subtarget) {
14895 DebugLoc DL = N->getDebugLoc();
14897 // If the flag operand isn't dead, don't touch this CMOV.
14898 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
14901 SDValue FalseOp = N->getOperand(0);
14902 SDValue TrueOp = N->getOperand(1);
14903 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
14904 SDValue Cond = N->getOperand(3);
14906 if (CC == X86::COND_E || CC == X86::COND_NE) {
14907 switch (Cond.getOpcode()) {
14911 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
14912 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
14913 return (CC == X86::COND_E) ? FalseOp : TrueOp;
14919 Flags = checkBoolTestSetCCCombine(Cond, CC);
14920 if (Flags.getNode() &&
14921 // Extra check as FCMOV only supports a subset of X86 cond.
14922 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
14923 SDValue Ops[] = { FalseOp, TrueOp,
14924 DAG.getConstant(CC, MVT::i8), Flags };
14925 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
14926 Ops, array_lengthof(Ops));
14929 // If this is a select between two integer constants, try to do some
14930 // optimizations. Note that the operands are ordered the opposite of SELECT
14932 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
14933 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
14934 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
14935 // larger than FalseC (the false value).
14936 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
14937 CC = X86::GetOppositeBranchCondition(CC);
14938 std::swap(TrueC, FalseC);
14939 std::swap(TrueOp, FalseOp);
14942 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
14943 // This is efficient for any integer data type (including i8/i16) and
14945 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
14946 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14947 DAG.getConstant(CC, MVT::i8), Cond);
14949 // Zero extend the condition if needed.
14950 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
14952 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
14953 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
14954 DAG.getConstant(ShAmt, MVT::i8));
14955 if (N->getNumValues() == 2) // Dead flag value?
14956 return DCI.CombineTo(N, Cond, SDValue());
14960 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
14961 // for any integer data type, including i8/i16.
14962 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
14963 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14964 DAG.getConstant(CC, MVT::i8), Cond);
14966 // Zero extend the condition if needed.
14967 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
14968 FalseC->getValueType(0), Cond);
14969 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
14970 SDValue(FalseC, 0));
14972 if (N->getNumValues() == 2) // Dead flag value?
14973 return DCI.CombineTo(N, Cond, SDValue());
14977 // Optimize cases that will turn into an LEA instruction. This requires
14978 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
14979 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
14980 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
14981 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
14983 bool isFastMultiplier = false;
14985 switch ((unsigned char)Diff) {
14987 case 1: // result = add base, cond
14988 case 2: // result = lea base( , cond*2)
14989 case 3: // result = lea base(cond, cond*2)
14990 case 4: // result = lea base( , cond*4)
14991 case 5: // result = lea base(cond, cond*4)
14992 case 8: // result = lea base( , cond*8)
14993 case 9: // result = lea base(cond, cond*8)
14994 isFastMultiplier = true;
14999 if (isFastMultiplier) {
15000 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15001 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15002 DAG.getConstant(CC, MVT::i8), Cond);
15003 // Zero extend the condition if needed.
15004 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15006 // Scale the condition by the difference.
15008 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15009 DAG.getConstant(Diff, Cond.getValueType()));
15011 // Add the base if non-zero.
15012 if (FalseC->getAPIntValue() != 0)
15013 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15014 SDValue(FalseC, 0));
15015 if (N->getNumValues() == 2) // Dead flag value?
15016 return DCI.CombineTo(N, Cond, SDValue());
15023 // Handle these cases:
15024 // (select (x != c), e, c) -> select (x != c), e, x),
15025 // (select (x == c), c, e) -> select (x == c), x, e)
15026 // where the c is an integer constant, and the "select" is the combination
15027 // of CMOV and CMP.
15029 // The rationale for this change is that the conditional-move from a constant
15030 // needs two instructions, however, conditional-move from a register needs
15031 // only one instruction.
15033 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15034 // some instruction-combining opportunities. This opt needs to be
15035 // postponed as late as possible.
15037 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15038 // the DCI.xxxx conditions are provided to postpone the optimization as
15039 // late as possible.
15041 ConstantSDNode *CmpAgainst = 0;
15042 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15043 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15044 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15046 if (CC == X86::COND_NE &&
15047 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15048 CC = X86::GetOppositeBranchCondition(CC);
15049 std::swap(TrueOp, FalseOp);
15052 if (CC == X86::COND_E &&
15053 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15054 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15055 DAG.getConstant(CC, MVT::i8), Cond };
15056 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15057 array_lengthof(Ops));
15066 /// PerformMulCombine - Optimize a single multiply with constant into two
15067 /// in order to implement it with two cheaper instructions, e.g.
15068 /// LEA + SHL, LEA + LEA.
15069 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15070 TargetLowering::DAGCombinerInfo &DCI) {
15071 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15074 EVT VT = N->getValueType(0);
15075 if (VT != MVT::i64)
15078 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15081 uint64_t MulAmt = C->getZExtValue();
15082 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15085 uint64_t MulAmt1 = 0;
15086 uint64_t MulAmt2 = 0;
15087 if ((MulAmt % 9) == 0) {
15089 MulAmt2 = MulAmt / 9;
15090 } else if ((MulAmt % 5) == 0) {
15092 MulAmt2 = MulAmt / 5;
15093 } else if ((MulAmt % 3) == 0) {
15095 MulAmt2 = MulAmt / 3;
15098 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15099 DebugLoc DL = N->getDebugLoc();
15101 if (isPowerOf2_64(MulAmt2) &&
15102 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15103 // If second multiplifer is pow2, issue it first. We want the multiply by
15104 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15106 std::swap(MulAmt1, MulAmt2);
15109 if (isPowerOf2_64(MulAmt1))
15110 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15111 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15113 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15114 DAG.getConstant(MulAmt1, VT));
15116 if (isPowerOf2_64(MulAmt2))
15117 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15118 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15120 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15121 DAG.getConstant(MulAmt2, VT));
15123 // Do not add new nodes to DAG combiner worklist.
15124 DCI.CombineTo(N, NewMul, false);
15129 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15130 SDValue N0 = N->getOperand(0);
15131 SDValue N1 = N->getOperand(1);
15132 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15133 EVT VT = N0.getValueType();
15135 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15136 // since the result of setcc_c is all zero's or all ones.
15137 if (VT.isInteger() && !VT.isVector() &&
15138 N1C && N0.getOpcode() == ISD::AND &&
15139 N0.getOperand(1).getOpcode() == ISD::Constant) {
15140 SDValue N00 = N0.getOperand(0);
15141 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15142 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15143 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15144 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15145 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15146 APInt ShAmt = N1C->getAPIntValue();
15147 Mask = Mask.shl(ShAmt);
15149 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15150 N00, DAG.getConstant(Mask, VT));
15155 // Hardware support for vector shifts is sparse which makes us scalarize the
15156 // vector operations in many cases. Also, on sandybridge ADD is faster than
15158 // (shl V, 1) -> add V,V
15159 if (isSplatVector(N1.getNode())) {
15160 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15161 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15162 // We shift all of the values by one. In many cases we do not have
15163 // hardware support for this operation. This is better expressed as an ADD
15165 if (N1C && (1 == N1C->getZExtValue())) {
15166 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15173 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15175 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15176 TargetLowering::DAGCombinerInfo &DCI,
15177 const X86Subtarget *Subtarget) {
15178 EVT VT = N->getValueType(0);
15179 if (N->getOpcode() == ISD::SHL) {
15180 SDValue V = PerformSHLCombine(N, DAG);
15181 if (V.getNode()) return V;
15184 // On X86 with SSE2 support, we can transform this to a vector shift if
15185 // all elements are shifted by the same amount. We can't do this in legalize
15186 // because the a constant vector is typically transformed to a constant pool
15187 // so we have no knowledge of the shift amount.
15188 if (!Subtarget->hasSSE2())
15191 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15192 (!Subtarget->hasAVX2() ||
15193 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15196 SDValue ShAmtOp = N->getOperand(1);
15197 EVT EltVT = VT.getVectorElementType();
15198 DebugLoc DL = N->getDebugLoc();
15199 SDValue BaseShAmt = SDValue();
15200 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15201 unsigned NumElts = VT.getVectorNumElements();
15203 for (; i != NumElts; ++i) {
15204 SDValue Arg = ShAmtOp.getOperand(i);
15205 if (Arg.getOpcode() == ISD::UNDEF) continue;
15209 // Handle the case where the build_vector is all undef
15210 // FIXME: Should DAG allow this?
15214 for (; i != NumElts; ++i) {
15215 SDValue Arg = ShAmtOp.getOperand(i);
15216 if (Arg.getOpcode() == ISD::UNDEF) continue;
15217 if (Arg != BaseShAmt) {
15221 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15222 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15223 SDValue InVec = ShAmtOp.getOperand(0);
15224 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15225 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15227 for (; i != NumElts; ++i) {
15228 SDValue Arg = InVec.getOperand(i);
15229 if (Arg.getOpcode() == ISD::UNDEF) continue;
15233 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15234 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15235 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15236 if (C->getZExtValue() == SplatIdx)
15237 BaseShAmt = InVec.getOperand(1);
15240 if (BaseShAmt.getNode() == 0) {
15241 // Don't create instructions with illegal types after legalize
15243 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15244 !DCI.isBeforeLegalize())
15247 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15248 DAG.getIntPtrConstant(0));
15253 // The shift amount is an i32.
15254 if (EltVT.bitsGT(MVT::i32))
15255 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15256 else if (EltVT.bitsLT(MVT::i32))
15257 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15259 // The shift amount is identical so we can do a vector shift.
15260 SDValue ValOp = N->getOperand(0);
15261 switch (N->getOpcode()) {
15263 llvm_unreachable("Unknown shift opcode!");
15265 switch (VT.getSimpleVT().SimpleTy) {
15266 default: return SDValue();
15273 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15276 switch (VT.getSimpleVT().SimpleTy) {
15277 default: return SDValue();
15282 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15285 switch (VT.getSimpleVT().SimpleTy) {
15286 default: return SDValue();
15293 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15299 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15300 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15301 // and friends. Likewise for OR -> CMPNEQSS.
15302 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15303 TargetLowering::DAGCombinerInfo &DCI,
15304 const X86Subtarget *Subtarget) {
15307 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15308 // we're requiring SSE2 for both.
15309 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15310 SDValue N0 = N->getOperand(0);
15311 SDValue N1 = N->getOperand(1);
15312 SDValue CMP0 = N0->getOperand(1);
15313 SDValue CMP1 = N1->getOperand(1);
15314 DebugLoc DL = N->getDebugLoc();
15316 // The SETCCs should both refer to the same CMP.
15317 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15320 SDValue CMP00 = CMP0->getOperand(0);
15321 SDValue CMP01 = CMP0->getOperand(1);
15322 EVT VT = CMP00.getValueType();
15324 if (VT == MVT::f32 || VT == MVT::f64) {
15325 bool ExpectingFlags = false;
15326 // Check for any users that want flags:
15327 for (SDNode::use_iterator UI = N->use_begin(),
15329 !ExpectingFlags && UI != UE; ++UI)
15330 switch (UI->getOpcode()) {
15335 ExpectingFlags = true;
15337 case ISD::CopyToReg:
15338 case ISD::SIGN_EXTEND:
15339 case ISD::ZERO_EXTEND:
15340 case ISD::ANY_EXTEND:
15344 if (!ExpectingFlags) {
15345 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15346 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15348 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15349 X86::CondCode tmp = cc0;
15354 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15355 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15356 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15357 X86ISD::NodeType NTOperator = is64BitFP ?
15358 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15359 // FIXME: need symbolic constants for these magic numbers.
15360 // See X86ATTInstPrinter.cpp:printSSECC().
15361 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15362 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15363 DAG.getConstant(x86cc, MVT::i8));
15364 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15366 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15367 DAG.getConstant(1, MVT::i32));
15368 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15369 return OneBitOfTruth;
15377 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15378 /// so it can be folded inside ANDNP.
15379 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15380 EVT VT = N->getValueType(0);
15382 // Match direct AllOnes for 128 and 256-bit vectors
15383 if (ISD::isBuildVectorAllOnes(N))
15386 // Look through a bit convert.
15387 if (N->getOpcode() == ISD::BITCAST)
15388 N = N->getOperand(0).getNode();
15390 // Sometimes the operand may come from a insert_subvector building a 256-bit
15392 if (VT.is256BitVector() &&
15393 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15394 SDValue V1 = N->getOperand(0);
15395 SDValue V2 = N->getOperand(1);
15397 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15398 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15399 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15400 ISD::isBuildVectorAllOnes(V2.getNode()))
15407 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
15408 TargetLowering::DAGCombinerInfo &DCI,
15409 const X86Subtarget *Subtarget) {
15410 if (DCI.isBeforeLegalizeOps())
15413 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15417 EVT VT = N->getValueType(0);
15419 // Create ANDN, BLSI, and BLSR instructions
15420 // BLSI is X & (-X)
15421 // BLSR is X & (X-1)
15422 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
15423 SDValue N0 = N->getOperand(0);
15424 SDValue N1 = N->getOperand(1);
15425 DebugLoc DL = N->getDebugLoc();
15427 // Check LHS for not
15428 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
15429 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
15430 // Check RHS for not
15431 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
15432 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
15434 // Check LHS for neg
15435 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
15436 isZero(N0.getOperand(0)))
15437 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
15439 // Check RHS for neg
15440 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
15441 isZero(N1.getOperand(0)))
15442 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
15444 // Check LHS for X-1
15445 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15446 isAllOnes(N0.getOperand(1)))
15447 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
15449 // Check RHS for X-1
15450 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15451 isAllOnes(N1.getOperand(1)))
15452 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
15457 // Want to form ANDNP nodes:
15458 // 1) In the hopes of then easily combining them with OR and AND nodes
15459 // to form PBLEND/PSIGN.
15460 // 2) To match ANDN packed intrinsics
15461 if (VT != MVT::v2i64 && VT != MVT::v4i64)
15464 SDValue N0 = N->getOperand(0);
15465 SDValue N1 = N->getOperand(1);
15466 DebugLoc DL = N->getDebugLoc();
15468 // Check LHS for vnot
15469 if (N0.getOpcode() == ISD::XOR &&
15470 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
15471 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
15472 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
15474 // Check RHS for vnot
15475 if (N1.getOpcode() == ISD::XOR &&
15476 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
15477 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
15478 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
15483 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
15484 TargetLowering::DAGCombinerInfo &DCI,
15485 const X86Subtarget *Subtarget) {
15486 if (DCI.isBeforeLegalizeOps())
15489 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
15493 EVT VT = N->getValueType(0);
15495 SDValue N0 = N->getOperand(0);
15496 SDValue N1 = N->getOperand(1);
15498 // look for psign/blend
15499 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
15500 if (!Subtarget->hasSSSE3() ||
15501 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
15504 // Canonicalize pandn to RHS
15505 if (N0.getOpcode() == X86ISD::ANDNP)
15507 // or (and (m, y), (pandn m, x))
15508 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
15509 SDValue Mask = N1.getOperand(0);
15510 SDValue X = N1.getOperand(1);
15512 if (N0.getOperand(0) == Mask)
15513 Y = N0.getOperand(1);
15514 if (N0.getOperand(1) == Mask)
15515 Y = N0.getOperand(0);
15517 // Check to see if the mask appeared in both the AND and ANDNP and
15521 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
15522 // Look through mask bitcast.
15523 if (Mask.getOpcode() == ISD::BITCAST)
15524 Mask = Mask.getOperand(0);
15525 if (X.getOpcode() == ISD::BITCAST)
15526 X = X.getOperand(0);
15527 if (Y.getOpcode() == ISD::BITCAST)
15528 Y = Y.getOperand(0);
15530 EVT MaskVT = Mask.getValueType();
15532 // Validate that the Mask operand is a vector sra node.
15533 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
15534 // there is no psrai.b
15535 if (Mask.getOpcode() != X86ISD::VSRAI)
15538 // Check that the SRA is all signbits.
15539 SDValue SraC = Mask.getOperand(1);
15540 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
15541 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
15542 if ((SraAmt + 1) != EltBits)
15545 DebugLoc DL = N->getDebugLoc();
15547 // Now we know we at least have a plendvb with the mask val. See if
15548 // we can form a psignb/w/d.
15549 // psign = x.type == y.type == mask.type && y = sub(0, x);
15550 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
15551 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
15552 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
15553 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
15554 "Unsupported VT for PSIGN");
15555 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
15556 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15558 // PBLENDVB only available on SSE 4.1
15559 if (!Subtarget->hasSSE41())
15562 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
15564 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
15565 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
15566 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
15567 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
15568 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
15572 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
15575 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
15576 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
15578 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
15580 if (!N0.hasOneUse() || !N1.hasOneUse())
15583 SDValue ShAmt0 = N0.getOperand(1);
15584 if (ShAmt0.getValueType() != MVT::i8)
15586 SDValue ShAmt1 = N1.getOperand(1);
15587 if (ShAmt1.getValueType() != MVT::i8)
15589 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
15590 ShAmt0 = ShAmt0.getOperand(0);
15591 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
15592 ShAmt1 = ShAmt1.getOperand(0);
15594 DebugLoc DL = N->getDebugLoc();
15595 unsigned Opc = X86ISD::SHLD;
15596 SDValue Op0 = N0.getOperand(0);
15597 SDValue Op1 = N1.getOperand(0);
15598 if (ShAmt0.getOpcode() == ISD::SUB) {
15599 Opc = X86ISD::SHRD;
15600 std::swap(Op0, Op1);
15601 std::swap(ShAmt0, ShAmt1);
15604 unsigned Bits = VT.getSizeInBits();
15605 if (ShAmt1.getOpcode() == ISD::SUB) {
15606 SDValue Sum = ShAmt1.getOperand(0);
15607 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
15608 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
15609 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
15610 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
15611 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
15612 return DAG.getNode(Opc, DL, VT,
15614 DAG.getNode(ISD::TRUNCATE, DL,
15617 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
15618 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
15620 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
15621 return DAG.getNode(Opc, DL, VT,
15622 N0.getOperand(0), N1.getOperand(0),
15623 DAG.getNode(ISD::TRUNCATE, DL,
15630 // Generate NEG and CMOV for integer abs.
15631 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
15632 EVT VT = N->getValueType(0);
15634 // Since X86 does not have CMOV for 8-bit integer, we don't convert
15635 // 8-bit integer abs to NEG and CMOV.
15636 if (VT.isInteger() && VT.getSizeInBits() == 8)
15639 SDValue N0 = N->getOperand(0);
15640 SDValue N1 = N->getOperand(1);
15641 DebugLoc DL = N->getDebugLoc();
15643 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
15644 // and change it to SUB and CMOV.
15645 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
15646 N0.getOpcode() == ISD::ADD &&
15647 N0.getOperand(1) == N1 &&
15648 N1.getOpcode() == ISD::SRA &&
15649 N1.getOperand(0) == N0.getOperand(0))
15650 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
15651 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
15652 // Generate SUB & CMOV.
15653 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
15654 DAG.getConstant(0, VT), N0.getOperand(0));
15656 SDValue Ops[] = { N0.getOperand(0), Neg,
15657 DAG.getConstant(X86::COND_GE, MVT::i8),
15658 SDValue(Neg.getNode(), 1) };
15659 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
15660 Ops, array_lengthof(Ops));
15665 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
15666 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
15667 TargetLowering::DAGCombinerInfo &DCI,
15668 const X86Subtarget *Subtarget) {
15669 if (DCI.isBeforeLegalizeOps())
15672 if (Subtarget->hasCMov()) {
15673 SDValue RV = performIntegerAbsCombine(N, DAG);
15678 // Try forming BMI if it is available.
15679 if (!Subtarget->hasBMI())
15682 EVT VT = N->getValueType(0);
15684 if (VT != MVT::i32 && VT != MVT::i64)
15687 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
15689 // Create BLSMSK instructions by finding X ^ (X-1)
15690 SDValue N0 = N->getOperand(0);
15691 SDValue N1 = N->getOperand(1);
15692 DebugLoc DL = N->getDebugLoc();
15694 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
15695 isAllOnes(N0.getOperand(1)))
15696 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
15698 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
15699 isAllOnes(N1.getOperand(1)))
15700 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
15705 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
15706 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
15707 TargetLowering::DAGCombinerInfo &DCI,
15708 const X86Subtarget *Subtarget) {
15709 LoadSDNode *Ld = cast<LoadSDNode>(N);
15710 EVT RegVT = Ld->getValueType(0);
15711 EVT MemVT = Ld->getMemoryVT();
15712 DebugLoc dl = Ld->getDebugLoc();
15713 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15715 ISD::LoadExtType Ext = Ld->getExtensionType();
15717 // If this is a vector EXT Load then attempt to optimize it using a
15718 // shuffle. We need SSSE3 shuffles.
15719 // TODO: It is possible to support ZExt by zeroing the undef values
15720 // during the shuffle phase or after the shuffle.
15721 if (RegVT.isVector() && RegVT.isInteger() &&
15722 Ext == ISD::EXTLOAD && Subtarget->hasSSSE3()) {
15723 assert(MemVT != RegVT && "Cannot extend to the same type");
15724 assert(MemVT.isVector() && "Must load a vector from memory");
15726 unsigned NumElems = RegVT.getVectorNumElements();
15727 unsigned RegSz = RegVT.getSizeInBits();
15728 unsigned MemSz = MemVT.getSizeInBits();
15729 assert(RegSz > MemSz && "Register size must be greater than the mem size");
15731 // All sizes must be a power of two.
15732 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
15735 // Attempt to load the original value using scalar loads.
15736 // Find the largest scalar type that divides the total loaded size.
15737 MVT SclrLoadTy = MVT::i8;
15738 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15739 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15740 MVT Tp = (MVT::SimpleValueType)tp;
15741 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
15746 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15747 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
15749 SclrLoadTy = MVT::f64;
15751 // Calculate the number of scalar loads that we need to perform
15752 // in order to load our vector from memory.
15753 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
15755 // Represent our vector as a sequence of elements which are the
15756 // largest scalar that we can load.
15757 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
15758 RegSz/SclrLoadTy.getSizeInBits());
15760 // Represent the data using the same element type that is stored in
15761 // memory. In practice, we ''widen'' MemVT.
15762 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
15763 RegSz/MemVT.getScalarType().getSizeInBits());
15765 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
15766 "Invalid vector type");
15768 // We can't shuffle using an illegal type.
15769 if (!TLI.isTypeLegal(WideVecVT))
15772 SmallVector<SDValue, 8> Chains;
15773 SDValue Ptr = Ld->getBasePtr();
15774 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
15775 TLI.getPointerTy());
15776 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
15778 for (unsigned i = 0; i < NumLoads; ++i) {
15779 // Perform a single load.
15780 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
15781 Ptr, Ld->getPointerInfo(),
15782 Ld->isVolatile(), Ld->isNonTemporal(),
15783 Ld->isInvariant(), Ld->getAlignment());
15784 Chains.push_back(ScalarLoad.getValue(1));
15785 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
15786 // another round of DAGCombining.
15788 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
15790 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
15791 ScalarLoad, DAG.getIntPtrConstant(i));
15793 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15796 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15799 // Bitcast the loaded value to a vector of the original element type, in
15800 // the size of the target vector type.
15801 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
15802 unsigned SizeRatio = RegSz/MemSz;
15804 // Redistribute the loaded elements into the different locations.
15805 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15806 for (unsigned i = 0; i != NumElems; ++i)
15807 ShuffleVec[i*SizeRatio] = i;
15809 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
15810 DAG.getUNDEF(WideVecVT),
15813 // Bitcast to the requested type.
15814 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
15815 // Replace the original load with the new sequence
15816 // and return the new chain.
15817 return DCI.CombineTo(N, Shuff, TF, true);
15823 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
15824 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
15825 const X86Subtarget *Subtarget) {
15826 StoreSDNode *St = cast<StoreSDNode>(N);
15827 EVT VT = St->getValue().getValueType();
15828 EVT StVT = St->getMemoryVT();
15829 DebugLoc dl = St->getDebugLoc();
15830 SDValue StoredVal = St->getOperand(1);
15831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15833 // If we are saving a concatenation of two XMM registers, perform two stores.
15834 // On Sandy Bridge, 256-bit memory operations are executed by two
15835 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
15836 // memory operation.
15837 if (VT.is256BitVector() && !Subtarget->hasAVX2() &&
15838 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
15839 StoredVal.getNumOperands() == 2) {
15840 SDValue Value0 = StoredVal.getOperand(0);
15841 SDValue Value1 = StoredVal.getOperand(1);
15843 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
15844 SDValue Ptr0 = St->getBasePtr();
15845 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
15847 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
15848 St->getPointerInfo(), St->isVolatile(),
15849 St->isNonTemporal(), St->getAlignment());
15850 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
15851 St->getPointerInfo(), St->isVolatile(),
15852 St->isNonTemporal(), St->getAlignment());
15853 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
15856 // Optimize trunc store (of multiple scalars) to shuffle and store.
15857 // First, pack all of the elements in one place. Next, store to memory
15858 // in fewer chunks.
15859 if (St->isTruncatingStore() && VT.isVector()) {
15860 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15861 unsigned NumElems = VT.getVectorNumElements();
15862 assert(StVT != VT && "Cannot truncate to the same type");
15863 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
15864 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
15866 // From, To sizes and ElemCount must be pow of two
15867 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
15868 // We are going to use the original vector elt for storing.
15869 // Accumulated smaller vector elements must be a multiple of the store size.
15870 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
15872 unsigned SizeRatio = FromSz / ToSz;
15874 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
15876 // Create a type on which we perform the shuffle
15877 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
15878 StVT.getScalarType(), NumElems*SizeRatio);
15880 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
15882 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
15883 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
15884 for (unsigned i = 0; i != NumElems; ++i)
15885 ShuffleVec[i] = i * SizeRatio;
15887 // Can't shuffle using an illegal type.
15888 if (!TLI.isTypeLegal(WideVecVT))
15891 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
15892 DAG.getUNDEF(WideVecVT),
15894 // At this point all of the data is stored at the bottom of the
15895 // register. We now need to save it to mem.
15897 // Find the largest store unit
15898 MVT StoreType = MVT::i8;
15899 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
15900 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
15901 MVT Tp = (MVT::SimpleValueType)tp;
15902 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
15906 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
15907 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
15908 (64 <= NumElems * ToSz))
15909 StoreType = MVT::f64;
15911 // Bitcast the original vector into a vector of store-size units
15912 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
15913 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
15914 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
15915 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
15916 SmallVector<SDValue, 8> Chains;
15917 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
15918 TLI.getPointerTy());
15919 SDValue Ptr = St->getBasePtr();
15921 // Perform one or more big stores into memory.
15922 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
15923 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
15924 StoreType, ShuffWide,
15925 DAG.getIntPtrConstant(i));
15926 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
15927 St->getPointerInfo(), St->isVolatile(),
15928 St->isNonTemporal(), St->getAlignment());
15929 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
15930 Chains.push_back(Ch);
15933 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
15938 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
15939 // the FP state in cases where an emms may be missing.
15940 // A preferable solution to the general problem is to figure out the right
15941 // places to insert EMMS. This qualifies as a quick hack.
15943 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
15944 if (VT.getSizeInBits() != 64)
15947 const Function *F = DAG.getMachineFunction().getFunction();
15948 bool NoImplicitFloatOps = F->getFnAttributes().
15949 hasAttribute(Attributes::NoImplicitFloat);
15950 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
15951 && Subtarget->hasSSE2();
15952 if ((VT.isVector() ||
15953 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
15954 isa<LoadSDNode>(St->getValue()) &&
15955 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
15956 St->getChain().hasOneUse() && !St->isVolatile()) {
15957 SDNode* LdVal = St->getValue().getNode();
15958 LoadSDNode *Ld = 0;
15959 int TokenFactorIndex = -1;
15960 SmallVector<SDValue, 8> Ops;
15961 SDNode* ChainVal = St->getChain().getNode();
15962 // Must be a store of a load. We currently handle two cases: the load
15963 // is a direct child, and it's under an intervening TokenFactor. It is
15964 // possible to dig deeper under nested TokenFactors.
15965 if (ChainVal == LdVal)
15966 Ld = cast<LoadSDNode>(St->getChain());
15967 else if (St->getValue().hasOneUse() &&
15968 ChainVal->getOpcode() == ISD::TokenFactor) {
15969 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
15970 if (ChainVal->getOperand(i).getNode() == LdVal) {
15971 TokenFactorIndex = i;
15972 Ld = cast<LoadSDNode>(St->getValue());
15974 Ops.push_back(ChainVal->getOperand(i));
15978 if (!Ld || !ISD::isNormalLoad(Ld))
15981 // If this is not the MMX case, i.e. we are just turning i64 load/store
15982 // into f64 load/store, avoid the transformation if there are multiple
15983 // uses of the loaded value.
15984 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
15987 DebugLoc LdDL = Ld->getDebugLoc();
15988 DebugLoc StDL = N->getDebugLoc();
15989 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
15990 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
15992 if (Subtarget->is64Bit() || F64IsLegal) {
15993 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
15994 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
15995 Ld->getPointerInfo(), Ld->isVolatile(),
15996 Ld->isNonTemporal(), Ld->isInvariant(),
15997 Ld->getAlignment());
15998 SDValue NewChain = NewLd.getValue(1);
15999 if (TokenFactorIndex != -1) {
16000 Ops.push_back(NewChain);
16001 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16004 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16005 St->getPointerInfo(),
16006 St->isVolatile(), St->isNonTemporal(),
16007 St->getAlignment());
16010 // Otherwise, lower to two pairs of 32-bit loads / stores.
16011 SDValue LoAddr = Ld->getBasePtr();
16012 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16013 DAG.getConstant(4, MVT::i32));
16015 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16016 Ld->getPointerInfo(),
16017 Ld->isVolatile(), Ld->isNonTemporal(),
16018 Ld->isInvariant(), Ld->getAlignment());
16019 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16020 Ld->getPointerInfo().getWithOffset(4),
16021 Ld->isVolatile(), Ld->isNonTemporal(),
16023 MinAlign(Ld->getAlignment(), 4));
16025 SDValue NewChain = LoLd.getValue(1);
16026 if (TokenFactorIndex != -1) {
16027 Ops.push_back(LoLd);
16028 Ops.push_back(HiLd);
16029 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16033 LoAddr = St->getBasePtr();
16034 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16035 DAG.getConstant(4, MVT::i32));
16037 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16038 St->getPointerInfo(),
16039 St->isVolatile(), St->isNonTemporal(),
16040 St->getAlignment());
16041 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16042 St->getPointerInfo().getWithOffset(4),
16044 St->isNonTemporal(),
16045 MinAlign(St->getAlignment(), 4));
16046 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16051 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16052 /// and return the operands for the horizontal operation in LHS and RHS. A
16053 /// horizontal operation performs the binary operation on successive elements
16054 /// of its first operand, then on successive elements of its second operand,
16055 /// returning the resulting values in a vector. For example, if
16056 /// A = < float a0, float a1, float a2, float a3 >
16058 /// B = < float b0, float b1, float b2, float b3 >
16059 /// then the result of doing a horizontal operation on A and B is
16060 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16061 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16062 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16063 /// set to A, RHS to B, and the routine returns 'true'.
16064 /// Note that the binary operation should have the property that if one of the
16065 /// operands is UNDEF then the result is UNDEF.
16066 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16067 // Look for the following pattern: if
16068 // A = < float a0, float a1, float a2, float a3 >
16069 // B = < float b0, float b1, float b2, float b3 >
16071 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16072 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16073 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16074 // which is A horizontal-op B.
16076 // At least one of the operands should be a vector shuffle.
16077 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16078 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16081 EVT VT = LHS.getValueType();
16083 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16084 "Unsupported vector type for horizontal add/sub");
16086 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16087 // operate independently on 128-bit lanes.
16088 unsigned NumElts = VT.getVectorNumElements();
16089 unsigned NumLanes = VT.getSizeInBits()/128;
16090 unsigned NumLaneElts = NumElts / NumLanes;
16091 assert((NumLaneElts % 2 == 0) &&
16092 "Vector type should have an even number of elements in each lane");
16093 unsigned HalfLaneElts = NumLaneElts/2;
16095 // View LHS in the form
16096 // LHS = VECTOR_SHUFFLE A, B, LMask
16097 // If LHS is not a shuffle then pretend it is the shuffle
16098 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16099 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16102 SmallVector<int, 16> LMask(NumElts);
16103 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16104 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16105 A = LHS.getOperand(0);
16106 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16107 B = LHS.getOperand(1);
16108 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16109 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16111 if (LHS.getOpcode() != ISD::UNDEF)
16113 for (unsigned i = 0; i != NumElts; ++i)
16117 // Likewise, view RHS in the form
16118 // RHS = VECTOR_SHUFFLE C, D, RMask
16120 SmallVector<int, 16> RMask(NumElts);
16121 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16122 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16123 C = RHS.getOperand(0);
16124 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16125 D = RHS.getOperand(1);
16126 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16127 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16129 if (RHS.getOpcode() != ISD::UNDEF)
16131 for (unsigned i = 0; i != NumElts; ++i)
16135 // Check that the shuffles are both shuffling the same vectors.
16136 if (!(A == C && B == D) && !(A == D && B == C))
16139 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16140 if (!A.getNode() && !B.getNode())
16143 // If A and B occur in reverse order in RHS, then "swap" them (which means
16144 // rewriting the mask).
16146 CommuteVectorShuffleMask(RMask, NumElts);
16148 // At this point LHS and RHS are equivalent to
16149 // LHS = VECTOR_SHUFFLE A, B, LMask
16150 // RHS = VECTOR_SHUFFLE A, B, RMask
16151 // Check that the masks correspond to performing a horizontal operation.
16152 for (unsigned i = 0; i != NumElts; ++i) {
16153 int LIdx = LMask[i], RIdx = RMask[i];
16155 // Ignore any UNDEF components.
16156 if (LIdx < 0 || RIdx < 0 ||
16157 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16158 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16161 // Check that successive elements are being operated on. If not, this is
16162 // not a horizontal operation.
16163 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16164 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16165 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16166 if (!(LIdx == Index && RIdx == Index + 1) &&
16167 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16171 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16172 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16176 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16177 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16178 const X86Subtarget *Subtarget) {
16179 EVT VT = N->getValueType(0);
16180 SDValue LHS = N->getOperand(0);
16181 SDValue RHS = N->getOperand(1);
16183 // Try to synthesize horizontal adds from adds of shuffles.
16184 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16185 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16186 isHorizontalBinOp(LHS, RHS, true))
16187 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16191 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16192 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16193 const X86Subtarget *Subtarget) {
16194 EVT VT = N->getValueType(0);
16195 SDValue LHS = N->getOperand(0);
16196 SDValue RHS = N->getOperand(1);
16198 // Try to synthesize horizontal subs from subs of shuffles.
16199 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16200 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16201 isHorizontalBinOp(LHS, RHS, false))
16202 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16206 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16207 /// X86ISD::FXOR nodes.
16208 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16209 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16210 // F[X]OR(0.0, x) -> x
16211 // F[X]OR(x, 0.0) -> x
16212 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16213 if (C->getValueAPF().isPosZero())
16214 return N->getOperand(1);
16215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16216 if (C->getValueAPF().isPosZero())
16217 return N->getOperand(0);
16221 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16222 /// X86ISD::FMAX nodes.
16223 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16224 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16226 // Only perform optimizations if UnsafeMath is used.
16227 if (!DAG.getTarget().Options.UnsafeFPMath)
16230 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16231 // into FMINC and FMAXC, which are Commutative operations.
16232 unsigned NewOp = 0;
16233 switch (N->getOpcode()) {
16234 default: llvm_unreachable("unknown opcode");
16235 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16236 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16239 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16240 N->getOperand(0), N->getOperand(1));
16244 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16245 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16246 // FAND(0.0, x) -> 0.0
16247 // FAND(x, 0.0) -> 0.0
16248 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16249 if (C->getValueAPF().isPosZero())
16250 return N->getOperand(0);
16251 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16252 if (C->getValueAPF().isPosZero())
16253 return N->getOperand(1);
16257 static SDValue PerformBTCombine(SDNode *N,
16259 TargetLowering::DAGCombinerInfo &DCI) {
16260 // BT ignores high bits in the bit index operand.
16261 SDValue Op1 = N->getOperand(1);
16262 if (Op1.hasOneUse()) {
16263 unsigned BitWidth = Op1.getValueSizeInBits();
16264 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16265 APInt KnownZero, KnownOne;
16266 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16267 !DCI.isBeforeLegalizeOps());
16268 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16269 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
16270 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
16271 DCI.CommitTargetLoweringOpt(TLO);
16276 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
16277 SDValue Op = N->getOperand(0);
16278 if (Op.getOpcode() == ISD::BITCAST)
16279 Op = Op.getOperand(0);
16280 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
16281 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
16282 VT.getVectorElementType().getSizeInBits() ==
16283 OpVT.getVectorElementType().getSizeInBits()) {
16284 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
16289 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
16290 TargetLowering::DAGCombinerInfo &DCI,
16291 const X86Subtarget *Subtarget) {
16292 if (!DCI.isBeforeLegalizeOps())
16295 if (!Subtarget->hasAVX())
16298 EVT VT = N->getValueType(0);
16299 SDValue Op = N->getOperand(0);
16300 EVT OpVT = Op.getValueType();
16301 DebugLoc dl = N->getDebugLoc();
16303 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
16304 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
16306 if (Subtarget->hasAVX2())
16307 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
16309 // Optimize vectors in AVX mode
16310 // Sign extend v8i16 to v8i32 and
16313 // Divide input vector into two parts
16314 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
16315 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
16316 // concat the vectors to original VT
16318 unsigned NumElems = OpVT.getVectorNumElements();
16319 SDValue Undef = DAG.getUNDEF(OpVT);
16321 SmallVector<int,8> ShufMask1(NumElems, -1);
16322 for (unsigned i = 0; i != NumElems/2; ++i)
16325 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask1[0]);
16327 SmallVector<int,8> ShufMask2(NumElems, -1);
16328 for (unsigned i = 0; i != NumElems/2; ++i)
16329 ShufMask2[i] = i + NumElems/2;
16331 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, Undef, &ShufMask2[0]);
16333 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
16334 VT.getVectorNumElements()/2);
16336 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
16337 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
16339 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16344 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
16345 const X86Subtarget* Subtarget) {
16346 DebugLoc dl = N->getDebugLoc();
16347 EVT VT = N->getValueType(0);
16349 // Let legalize expand this if it isn't a legal type yet.
16350 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16353 EVT ScalarVT = VT.getScalarType();
16354 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
16355 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
16358 SDValue A = N->getOperand(0);
16359 SDValue B = N->getOperand(1);
16360 SDValue C = N->getOperand(2);
16362 bool NegA = (A.getOpcode() == ISD::FNEG);
16363 bool NegB = (B.getOpcode() == ISD::FNEG);
16364 bool NegC = (C.getOpcode() == ISD::FNEG);
16366 // Negative multiplication when NegA xor NegB
16367 bool NegMul = (NegA != NegB);
16369 A = A.getOperand(0);
16371 B = B.getOperand(0);
16373 C = C.getOperand(0);
16377 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
16379 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
16381 return DAG.getNode(Opcode, dl, VT, A, B, C);
16384 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
16385 TargetLowering::DAGCombinerInfo &DCI,
16386 const X86Subtarget *Subtarget) {
16387 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
16388 // (and (i32 x86isd::setcc_carry), 1)
16389 // This eliminates the zext. This transformation is necessary because
16390 // ISD::SETCC is always legalized to i8.
16391 DebugLoc dl = N->getDebugLoc();
16392 SDValue N0 = N->getOperand(0);
16393 EVT VT = N->getValueType(0);
16394 EVT OpVT = N0.getValueType();
16396 if (N0.getOpcode() == ISD::AND &&
16398 N0.getOperand(0).hasOneUse()) {
16399 SDValue N00 = N0.getOperand(0);
16400 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
16402 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
16403 if (!C || C->getZExtValue() != 1)
16405 return DAG.getNode(ISD::AND, dl, VT,
16406 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
16407 N00.getOperand(0), N00.getOperand(1)),
16408 DAG.getConstant(1, VT));
16411 // Optimize vectors in AVX mode:
16414 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
16415 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
16416 // Concat upper and lower parts.
16419 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
16420 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
16421 // Concat upper and lower parts.
16423 if (!DCI.isBeforeLegalizeOps())
16426 if (!Subtarget->hasAVX())
16429 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
16430 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
16432 if (Subtarget->hasAVX2())
16433 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
16435 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
16436 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
16437 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
16439 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
16440 VT.getVectorNumElements()/2);
16442 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
16443 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
16445 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
16451 // Optimize x == -y --> x+y == 0
16452 // x != -y --> x+y != 0
16453 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
16454 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16455 SDValue LHS = N->getOperand(0);
16456 SDValue RHS = N->getOperand(1);
16458 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
16459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
16460 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
16461 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16462 LHS.getValueType(), RHS, LHS.getOperand(1));
16463 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16464 addV, DAG.getConstant(0, addV.getValueType()), CC);
16466 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
16467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
16468 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
16469 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
16470 RHS.getValueType(), LHS, RHS.getOperand(1));
16471 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
16472 addV, DAG.getConstant(0, addV.getValueType()), CC);
16477 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
16478 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
16479 TargetLowering::DAGCombinerInfo &DCI,
16480 const X86Subtarget *Subtarget) {
16481 DebugLoc DL = N->getDebugLoc();
16482 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
16483 SDValue EFLAGS = N->getOperand(1);
16485 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
16486 // a zext and produces an all-ones bit which is more useful than 0/1 in some
16488 if (CC == X86::COND_B)
16489 return DAG.getNode(ISD::AND, DL, MVT::i8,
16490 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
16491 DAG.getConstant(CC, MVT::i8), EFLAGS),
16492 DAG.getConstant(1, MVT::i8));
16496 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16497 if (Flags.getNode()) {
16498 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16499 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
16505 // Optimize branch condition evaluation.
16507 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
16508 TargetLowering::DAGCombinerInfo &DCI,
16509 const X86Subtarget *Subtarget) {
16510 DebugLoc DL = N->getDebugLoc();
16511 SDValue Chain = N->getOperand(0);
16512 SDValue Dest = N->getOperand(1);
16513 SDValue EFLAGS = N->getOperand(3);
16514 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
16518 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
16519 if (Flags.getNode()) {
16520 SDValue Cond = DAG.getConstant(CC, MVT::i8);
16521 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
16528 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
16529 const X86TargetLowering *XTLI) {
16530 SDValue Op0 = N->getOperand(0);
16531 EVT InVT = Op0->getValueType(0);
16533 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
16534 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
16535 DebugLoc dl = N->getDebugLoc();
16536 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
16537 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
16538 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
16541 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
16542 // a 32-bit target where SSE doesn't support i64->FP operations.
16543 if (Op0.getOpcode() == ISD::LOAD) {
16544 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
16545 EVT VT = Ld->getValueType(0);
16546 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
16547 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
16548 !XTLI->getSubtarget()->is64Bit() &&
16549 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16550 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
16551 Ld->getChain(), Op0, DAG);
16552 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
16559 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
16560 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
16561 X86TargetLowering::DAGCombinerInfo &DCI) {
16562 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
16563 // the result is either zero or one (depending on the input carry bit).
16564 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
16565 if (X86::isZeroNode(N->getOperand(0)) &&
16566 X86::isZeroNode(N->getOperand(1)) &&
16567 // We don't have a good way to replace an EFLAGS use, so only do this when
16569 SDValue(N, 1).use_empty()) {
16570 DebugLoc DL = N->getDebugLoc();
16571 EVT VT = N->getValueType(0);
16572 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
16573 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
16574 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
16575 DAG.getConstant(X86::COND_B,MVT::i8),
16577 DAG.getConstant(1, VT));
16578 return DCI.CombineTo(N, Res1, CarryOut);
16584 // fold (add Y, (sete X, 0)) -> adc 0, Y
16585 // (add Y, (setne X, 0)) -> sbb -1, Y
16586 // (sub (sete X, 0), Y) -> sbb 0, Y
16587 // (sub (setne X, 0), Y) -> adc -1, Y
16588 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
16589 DebugLoc DL = N->getDebugLoc();
16591 // Look through ZExts.
16592 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
16593 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
16596 SDValue SetCC = Ext.getOperand(0);
16597 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
16600 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
16601 if (CC != X86::COND_E && CC != X86::COND_NE)
16604 SDValue Cmp = SetCC.getOperand(1);
16605 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
16606 !X86::isZeroNode(Cmp.getOperand(1)) ||
16607 !Cmp.getOperand(0).getValueType().isInteger())
16610 SDValue CmpOp0 = Cmp.getOperand(0);
16611 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
16612 DAG.getConstant(1, CmpOp0.getValueType()));
16614 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
16615 if (CC == X86::COND_NE)
16616 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
16617 DL, OtherVal.getValueType(), OtherVal,
16618 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
16619 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
16620 DL, OtherVal.getValueType(), OtherVal,
16621 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
16624 /// PerformADDCombine - Do target-specific dag combines on integer adds.
16625 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
16626 const X86Subtarget *Subtarget) {
16627 EVT VT = N->getValueType(0);
16628 SDValue Op0 = N->getOperand(0);
16629 SDValue Op1 = N->getOperand(1);
16631 // Try to synthesize horizontal adds from adds of shuffles.
16632 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16633 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16634 isHorizontalBinOp(Op0, Op1, true))
16635 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
16637 return OptimizeConditionalInDecrement(N, DAG);
16640 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
16641 const X86Subtarget *Subtarget) {
16642 SDValue Op0 = N->getOperand(0);
16643 SDValue Op1 = N->getOperand(1);
16645 // X86 can't encode an immediate LHS of a sub. See if we can push the
16646 // negation into a preceding instruction.
16647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
16648 // If the RHS of the sub is a XOR with one use and a constant, invert the
16649 // immediate. Then add one to the LHS of the sub so we can turn
16650 // X-Y -> X+~Y+1, saving one register.
16651 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
16652 isa<ConstantSDNode>(Op1.getOperand(1))) {
16653 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
16654 EVT VT = Op0.getValueType();
16655 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
16657 DAG.getConstant(~XorC, VT));
16658 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
16659 DAG.getConstant(C->getAPIntValue()+1, VT));
16663 // Try to synthesize horizontal adds from adds of shuffles.
16664 EVT VT = N->getValueType(0);
16665 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
16666 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
16667 isHorizontalBinOp(Op0, Op1, true))
16668 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
16670 return OptimizeConditionalInDecrement(N, DAG);
16673 /// performVZEXTCombine - Performs build vector combines
16674 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
16675 TargetLowering::DAGCombinerInfo &DCI,
16676 const X86Subtarget *Subtarget) {
16677 // (vzext (bitcast (vzext (x)) -> (vzext x)
16678 SDValue In = N->getOperand(0);
16679 while (In.getOpcode() == ISD::BITCAST)
16680 In = In.getOperand(0);
16682 if (In.getOpcode() != X86ISD::VZEXT)
16685 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
16688 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
16689 DAGCombinerInfo &DCI) const {
16690 SelectionDAG &DAG = DCI.DAG;
16691 switch (N->getOpcode()) {
16693 case ISD::EXTRACT_VECTOR_ELT:
16694 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
16696 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
16697 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
16698 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
16699 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
16700 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
16701 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
16704 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
16705 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
16706 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
16707 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
16708 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
16709 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
16710 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
16711 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
16712 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
16714 case X86ISD::FOR: return PerformFORCombine(N, DAG);
16716 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
16717 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
16718 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
16719 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
16720 case ISD::ANY_EXTEND:
16721 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
16722 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
16723 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
16724 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
16725 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
16726 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
16727 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
16728 case X86ISD::SHUFP: // Handle all target specific shuffles
16729 case X86ISD::PALIGN:
16730 case X86ISD::UNPCKH:
16731 case X86ISD::UNPCKL:
16732 case X86ISD::MOVHLPS:
16733 case X86ISD::MOVLHPS:
16734 case X86ISD::PSHUFD:
16735 case X86ISD::PSHUFHW:
16736 case X86ISD::PSHUFLW:
16737 case X86ISD::MOVSS:
16738 case X86ISD::MOVSD:
16739 case X86ISD::VPERMILP:
16740 case X86ISD::VPERM2X128:
16741 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
16742 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
16748 /// isTypeDesirableForOp - Return true if the target has native support for
16749 /// the specified value type and it is 'desirable' to use the type for the
16750 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
16751 /// instruction encodings are longer and some i16 instructions are slow.
16752 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
16753 if (!isTypeLegal(VT))
16755 if (VT != MVT::i16)
16762 case ISD::SIGN_EXTEND:
16763 case ISD::ZERO_EXTEND:
16764 case ISD::ANY_EXTEND:
16777 /// IsDesirableToPromoteOp - This method query the target whether it is
16778 /// beneficial for dag combiner to promote the specified node. If true, it
16779 /// should return the desired promotion type by reference.
16780 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
16781 EVT VT = Op.getValueType();
16782 if (VT != MVT::i16)
16785 bool Promote = false;
16786 bool Commute = false;
16787 switch (Op.getOpcode()) {
16790 LoadSDNode *LD = cast<LoadSDNode>(Op);
16791 // If the non-extending load has a single use and it's not live out, then it
16792 // might be folded.
16793 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
16794 Op.hasOneUse()*/) {
16795 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
16796 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
16797 // The only case where we'd want to promote LOAD (rather then it being
16798 // promoted as an operand is when it's only use is liveout.
16799 if (UI->getOpcode() != ISD::CopyToReg)
16806 case ISD::SIGN_EXTEND:
16807 case ISD::ZERO_EXTEND:
16808 case ISD::ANY_EXTEND:
16813 SDValue N0 = Op.getOperand(0);
16814 // Look out for (store (shl (load), x)).
16815 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
16828 SDValue N0 = Op.getOperand(0);
16829 SDValue N1 = Op.getOperand(1);
16830 if (!Commute && MayFoldLoad(N1))
16832 // Avoid disabling potential load folding opportunities.
16833 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
16835 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
16845 //===----------------------------------------------------------------------===//
16846 // X86 Inline Assembly Support
16847 //===----------------------------------------------------------------------===//
16850 // Helper to match a string separated by whitespace.
16851 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
16852 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
16854 for (unsigned i = 0, e = args.size(); i != e; ++i) {
16855 StringRef piece(*args[i]);
16856 if (!s.startswith(piece)) // Check if the piece matches.
16859 s = s.substr(piece.size());
16860 StringRef::size_type pos = s.find_first_not_of(" \t");
16861 if (pos == 0) // We matched a prefix.
16869 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
16872 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
16873 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
16875 std::string AsmStr = IA->getAsmString();
16877 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16878 if (!Ty || Ty->getBitWidth() % 16 != 0)
16881 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
16882 SmallVector<StringRef, 4> AsmPieces;
16883 SplitString(AsmStr, AsmPieces, ";\n");
16885 switch (AsmPieces.size()) {
16886 default: return false;
16888 // FIXME: this should verify that we are targeting a 486 or better. If not,
16889 // we will turn this bswap into something that will be lowered to logical
16890 // ops instead of emitting the bswap asm. For now, we don't support 486 or
16891 // lower so don't worry about this.
16893 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
16894 matchAsm(AsmPieces[0], "bswapl", "$0") ||
16895 matchAsm(AsmPieces[0], "bswapq", "$0") ||
16896 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
16897 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
16898 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
16899 // No need to check constraints, nothing other than the equivalent of
16900 // "=r,0" would be valid here.
16901 return IntrinsicLowering::LowerToByteSwap(CI);
16904 // rorw $$8, ${0:w} --> llvm.bswap.i16
16905 if (CI->getType()->isIntegerTy(16) &&
16906 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16907 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
16908 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
16910 const std::string &ConstraintsStr = IA->getConstraintString();
16911 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16912 std::sort(AsmPieces.begin(), AsmPieces.end());
16913 if (AsmPieces.size() == 4 &&
16914 AsmPieces[0] == "~{cc}" &&
16915 AsmPieces[1] == "~{dirflag}" &&
16916 AsmPieces[2] == "~{flags}" &&
16917 AsmPieces[3] == "~{fpsr}")
16918 return IntrinsicLowering::LowerToByteSwap(CI);
16922 if (CI->getType()->isIntegerTy(32) &&
16923 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
16924 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
16925 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
16926 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
16928 const std::string &ConstraintsStr = IA->getConstraintString();
16929 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
16930 std::sort(AsmPieces.begin(), AsmPieces.end());
16931 if (AsmPieces.size() == 4 &&
16932 AsmPieces[0] == "~{cc}" &&
16933 AsmPieces[1] == "~{dirflag}" &&
16934 AsmPieces[2] == "~{flags}" &&
16935 AsmPieces[3] == "~{fpsr}")
16936 return IntrinsicLowering::LowerToByteSwap(CI);
16939 if (CI->getType()->isIntegerTy(64)) {
16940 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
16941 if (Constraints.size() >= 2 &&
16942 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
16943 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
16944 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
16945 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
16946 matchAsm(AsmPieces[1], "bswap", "%edx") &&
16947 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
16948 return IntrinsicLowering::LowerToByteSwap(CI);
16958 /// getConstraintType - Given a constraint letter, return the type of
16959 /// constraint it is for this target.
16960 X86TargetLowering::ConstraintType
16961 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
16962 if (Constraint.size() == 1) {
16963 switch (Constraint[0]) {
16974 return C_RegisterClass;
16998 return TargetLowering::getConstraintType(Constraint);
17001 /// Examine constraint type and operand type and determine a weight value.
17002 /// This object must already have been set up with the operand type
17003 /// and the current alternative constraint selected.
17004 TargetLowering::ConstraintWeight
17005 X86TargetLowering::getSingleConstraintMatchWeight(
17006 AsmOperandInfo &info, const char *constraint) const {
17007 ConstraintWeight weight = CW_Invalid;
17008 Value *CallOperandVal = info.CallOperandVal;
17009 // If we don't have a value, we can't do a match,
17010 // but allow it at the lowest weight.
17011 if (CallOperandVal == NULL)
17013 Type *type = CallOperandVal->getType();
17014 // Look at the constraint type.
17015 switch (*constraint) {
17017 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17028 if (CallOperandVal->getType()->isIntegerTy())
17029 weight = CW_SpecificReg;
17034 if (type->isFloatingPointTy())
17035 weight = CW_SpecificReg;
17038 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17039 weight = CW_SpecificReg;
17043 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17044 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
17045 weight = CW_Register;
17048 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17049 if (C->getZExtValue() <= 31)
17050 weight = CW_Constant;
17054 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17055 if (C->getZExtValue() <= 63)
17056 weight = CW_Constant;
17060 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17061 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17062 weight = CW_Constant;
17066 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17067 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17068 weight = CW_Constant;
17072 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17073 if (C->getZExtValue() <= 3)
17074 weight = CW_Constant;
17078 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17079 if (C->getZExtValue() <= 0xff)
17080 weight = CW_Constant;
17085 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17086 weight = CW_Constant;
17090 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17091 if ((C->getSExtValue() >= -0x80000000LL) &&
17092 (C->getSExtValue() <= 0x7fffffffLL))
17093 weight = CW_Constant;
17097 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17098 if (C->getZExtValue() <= 0xffffffff)
17099 weight = CW_Constant;
17106 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17107 /// with another that has more specific requirements based on the type of the
17108 /// corresponding operand.
17109 const char *X86TargetLowering::
17110 LowerXConstraint(EVT ConstraintVT) const {
17111 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17112 // 'f' like normal targets.
17113 if (ConstraintVT.isFloatingPoint()) {
17114 if (Subtarget->hasSSE2())
17116 if (Subtarget->hasSSE1())
17120 return TargetLowering::LowerXConstraint(ConstraintVT);
17123 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17124 /// vector. If it is invalid, don't add anything to Ops.
17125 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17126 std::string &Constraint,
17127 std::vector<SDValue>&Ops,
17128 SelectionDAG &DAG) const {
17129 SDValue Result(0, 0);
17131 // Only support length 1 constraints for now.
17132 if (Constraint.length() > 1) return;
17134 char ConstraintLetter = Constraint[0];
17135 switch (ConstraintLetter) {
17138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17139 if (C->getZExtValue() <= 31) {
17140 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17147 if (C->getZExtValue() <= 63) {
17148 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17155 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
17156 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17162 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17163 if (C->getZExtValue() <= 255) {
17164 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17170 // 32-bit signed value
17171 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17172 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17173 C->getSExtValue())) {
17174 // Widen to 64 bits here to get it sign extended.
17175 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17178 // FIXME gcc accepts some relocatable values here too, but only in certain
17179 // memory models; it's complicated.
17184 // 32-bit unsigned value
17185 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17186 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17187 C->getZExtValue())) {
17188 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17192 // FIXME gcc accepts some relocatable values here too, but only in certain
17193 // memory models; it's complicated.
17197 // Literal immediates are always ok.
17198 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17199 // Widen to 64 bits here to get it sign extended.
17200 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17204 // In any sort of PIC mode addresses need to be computed at runtime by
17205 // adding in a register or some sort of table lookup. These can't
17206 // be used as immediates.
17207 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17210 // If we are in non-pic codegen mode, we allow the address of a global (with
17211 // an optional displacement) to be used with 'i'.
17212 GlobalAddressSDNode *GA = 0;
17213 int64_t Offset = 0;
17215 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17217 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17218 Offset += GA->getOffset();
17220 } else if (Op.getOpcode() == ISD::ADD) {
17221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17222 Offset += C->getZExtValue();
17223 Op = Op.getOperand(0);
17226 } else if (Op.getOpcode() == ISD::SUB) {
17227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17228 Offset += -C->getZExtValue();
17229 Op = Op.getOperand(0);
17234 // Otherwise, this isn't something we can handle, reject it.
17238 const GlobalValue *GV = GA->getGlobal();
17239 // If we require an extra load to get this address, as in PIC mode, we
17240 // can't accept it.
17241 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17242 getTargetMachine())))
17245 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17246 GA->getValueType(0), Offset);
17251 if (Result.getNode()) {
17252 Ops.push_back(Result);
17255 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17258 std::pair<unsigned, const TargetRegisterClass*>
17259 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17261 // First, see if this is a constraint that directly corresponds to an LLVM
17263 if (Constraint.size() == 1) {
17264 // GCC Constraint Letters
17265 switch (Constraint[0]) {
17267 // TODO: Slight differences here in allocation order and leaving
17268 // RIP in the class. Do they matter any more here than they do
17269 // in the normal allocation?
17270 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17271 if (Subtarget->is64Bit()) {
17272 if (VT == MVT::i32 || VT == MVT::f32)
17273 return std::make_pair(0U, &X86::GR32RegClass);
17274 if (VT == MVT::i16)
17275 return std::make_pair(0U, &X86::GR16RegClass);
17276 if (VT == MVT::i8 || VT == MVT::i1)
17277 return std::make_pair(0U, &X86::GR8RegClass);
17278 if (VT == MVT::i64 || VT == MVT::f64)
17279 return std::make_pair(0U, &X86::GR64RegClass);
17282 // 32-bit fallthrough
17283 case 'Q': // Q_REGS
17284 if (VT == MVT::i32 || VT == MVT::f32)
17285 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17286 if (VT == MVT::i16)
17287 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17288 if (VT == MVT::i8 || VT == MVT::i1)
17289 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17290 if (VT == MVT::i64)
17291 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17293 case 'r': // GENERAL_REGS
17294 case 'l': // INDEX_REGS
17295 if (VT == MVT::i8 || VT == MVT::i1)
17296 return std::make_pair(0U, &X86::GR8RegClass);
17297 if (VT == MVT::i16)
17298 return std::make_pair(0U, &X86::GR16RegClass);
17299 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17300 return std::make_pair(0U, &X86::GR32RegClass);
17301 return std::make_pair(0U, &X86::GR64RegClass);
17302 case 'R': // LEGACY_REGS
17303 if (VT == MVT::i8 || VT == MVT::i1)
17304 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17305 if (VT == MVT::i16)
17306 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17307 if (VT == MVT::i32 || !Subtarget->is64Bit())
17308 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17309 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17310 case 'f': // FP Stack registers.
17311 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17312 // value to the correct fpstack register class.
17313 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17314 return std::make_pair(0U, &X86::RFP32RegClass);
17315 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
17316 return std::make_pair(0U, &X86::RFP64RegClass);
17317 return std::make_pair(0U, &X86::RFP80RegClass);
17318 case 'y': // MMX_REGS if MMX allowed.
17319 if (!Subtarget->hasMMX()) break;
17320 return std::make_pair(0U, &X86::VR64RegClass);
17321 case 'Y': // SSE_REGS if SSE2 allowed
17322 if (!Subtarget->hasSSE2()) break;
17324 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
17325 if (!Subtarget->hasSSE1()) break;
17327 switch (VT.getSimpleVT().SimpleTy) {
17329 // Scalar SSE types.
17332 return std::make_pair(0U, &X86::FR32RegClass);
17335 return std::make_pair(0U, &X86::FR64RegClass);
17343 return std::make_pair(0U, &X86::VR128RegClass);
17351 return std::make_pair(0U, &X86::VR256RegClass);
17357 // Use the default implementation in TargetLowering to convert the register
17358 // constraint into a member of a register class.
17359 std::pair<unsigned, const TargetRegisterClass*> Res;
17360 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
17362 // Not found as a standard register?
17363 if (Res.second == 0) {
17364 // Map st(0) -> st(7) -> ST0
17365 if (Constraint.size() == 7 && Constraint[0] == '{' &&
17366 tolower(Constraint[1]) == 's' &&
17367 tolower(Constraint[2]) == 't' &&
17368 Constraint[3] == '(' &&
17369 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
17370 Constraint[5] == ')' &&
17371 Constraint[6] == '}') {
17373 Res.first = X86::ST0+Constraint[4]-'0';
17374 Res.second = &X86::RFP80RegClass;
17378 // GCC allows "st(0)" to be called just plain "st".
17379 if (StringRef("{st}").equals_lower(Constraint)) {
17380 Res.first = X86::ST0;
17381 Res.second = &X86::RFP80RegClass;
17386 if (StringRef("{flags}").equals_lower(Constraint)) {
17387 Res.first = X86::EFLAGS;
17388 Res.second = &X86::CCRRegClass;
17392 // 'A' means EAX + EDX.
17393 if (Constraint == "A") {
17394 Res.first = X86::EAX;
17395 Res.second = &X86::GR32_ADRegClass;
17401 // Otherwise, check to see if this is a register class of the wrong value
17402 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
17403 // turn into {ax},{dx}.
17404 if (Res.second->hasType(VT))
17405 return Res; // Correct type already, nothing to do.
17407 // All of the single-register GCC register classes map their values onto
17408 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
17409 // really want an 8-bit or 32-bit register, map to the appropriate register
17410 // class and return the appropriate register.
17411 if (Res.second == &X86::GR16RegClass) {
17412 if (VT == MVT::i8) {
17413 unsigned DestReg = 0;
17414 switch (Res.first) {
17416 case X86::AX: DestReg = X86::AL; break;
17417 case X86::DX: DestReg = X86::DL; break;
17418 case X86::CX: DestReg = X86::CL; break;
17419 case X86::BX: DestReg = X86::BL; break;
17422 Res.first = DestReg;
17423 Res.second = &X86::GR8RegClass;
17425 } else if (VT == MVT::i32) {
17426 unsigned DestReg = 0;
17427 switch (Res.first) {
17429 case X86::AX: DestReg = X86::EAX; break;
17430 case X86::DX: DestReg = X86::EDX; break;
17431 case X86::CX: DestReg = X86::ECX; break;
17432 case X86::BX: DestReg = X86::EBX; break;
17433 case X86::SI: DestReg = X86::ESI; break;
17434 case X86::DI: DestReg = X86::EDI; break;
17435 case X86::BP: DestReg = X86::EBP; break;
17436 case X86::SP: DestReg = X86::ESP; break;
17439 Res.first = DestReg;
17440 Res.second = &X86::GR32RegClass;
17442 } else if (VT == MVT::i64) {
17443 unsigned DestReg = 0;
17444 switch (Res.first) {
17446 case X86::AX: DestReg = X86::RAX; break;
17447 case X86::DX: DestReg = X86::RDX; break;
17448 case X86::CX: DestReg = X86::RCX; break;
17449 case X86::BX: DestReg = X86::RBX; break;
17450 case X86::SI: DestReg = X86::RSI; break;
17451 case X86::DI: DestReg = X86::RDI; break;
17452 case X86::BP: DestReg = X86::RBP; break;
17453 case X86::SP: DestReg = X86::RSP; break;
17456 Res.first = DestReg;
17457 Res.second = &X86::GR64RegClass;
17460 } else if (Res.second == &X86::FR32RegClass ||
17461 Res.second == &X86::FR64RegClass ||
17462 Res.second == &X86::VR128RegClass) {
17463 // Handle references to XMM physical registers that got mapped into the
17464 // wrong class. This can happen with constraints like {xmm0} where the
17465 // target independent register mapper will just pick the first match it can
17466 // find, ignoring the required type.
17468 if (VT == MVT::f32 || VT == MVT::i32)
17469 Res.second = &X86::FR32RegClass;
17470 else if (VT == MVT::f64 || VT == MVT::i64)
17471 Res.second = &X86::FR64RegClass;
17472 else if (X86::VR128RegClass.hasType(VT))
17473 Res.second = &X86::VR128RegClass;
17474 else if (X86::VR256RegClass.hasType(VT))
17475 Res.second = &X86::VR256RegClass;