1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
17 #include "Utils/X86ShuffleDecode.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
55 STATISTIC(NumTailCalls, "Number of tail calls");
57 // Forward declarations.
58 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
62 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
63 /// simple subregister reference. Idx is an index in the 128 bits we
64 /// want. It need not be aligned to a 128-bit bounday. That makes
65 /// lowering EXTRACT_VECTOR_ELT operations easier.
66 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
67 SelectionDAG &DAG, DebugLoc dl) {
68 EVT VT = Vec.getValueType();
69 assert(VT.is256BitVector() && "Unexpected vector size!");
70 EVT ElVT = VT.getVectorElementType();
71 unsigned Factor = VT.getSizeInBits()/128;
72 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
73 VT.getVectorNumElements()/Factor);
75 // Extract from UNDEF is UNDEF.
76 if (Vec.getOpcode() == ISD::UNDEF)
77 return DAG.getUNDEF(ResultVT);
79 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
80 // we can match to VEXTRACTF128.
81 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
83 // This is the index of the first element of the 128-bit chunk
85 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
88 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
89 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
96 /// sets things up to match to an AVX VINSERTF128 instruction or a
97 /// simple superregister reference. Idx is an index in the 128 bits
98 /// we want. It need not be aligned to a 128-bit bounday. That makes
99 /// lowering INSERT_VECTOR_ELT operations easier.
100 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
101 unsigned IdxVal, SelectionDAG &DAG,
103 // Inserting UNDEF is Result
104 if (Vec.getOpcode() == ISD::UNDEF)
107 EVT VT = Vec.getValueType();
108 assert(VT.is128BitVector() && "Unexpected vector size!");
110 EVT ElVT = VT.getVectorElementType();
111 EVT ResultVT = Result.getValueType();
113 // Insert the relevant 128 bits.
114 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
116 // This is the index of the first element of the 128-bit chunk
118 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
121 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
122 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
126 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
127 /// instructions. This is used because creating CONCAT_VECTOR nodes of
128 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
129 /// large BUILD_VECTORS.
130 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
131 unsigned NumElems, SelectionDAG &DAG,
133 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
134 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
137 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
138 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
139 bool is64Bit = Subtarget->is64Bit();
141 if (Subtarget->isTargetEnvMacho()) {
143 return new X86_64MachoTargetObjectFile();
144 return new TargetLoweringObjectFileMachO();
147 if (Subtarget->isTargetLinux())
148 return new X86LinuxTargetObjectFile();
149 if (Subtarget->isTargetELF())
150 return new TargetLoweringObjectFileELF();
151 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
152 return new TargetLoweringObjectFileCOFF();
153 llvm_unreachable("unknown subtarget type");
156 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
157 : TargetLowering(TM, createTLOF(TM)) {
158 Subtarget = &TM.getSubtarget<X86Subtarget>();
159 X86ScalarSSEf64 = Subtarget->hasSSE2();
160 X86ScalarSSEf32 = Subtarget->hasSSE1();
162 RegInfo = TM.getRegisterInfo();
163 TD = getDataLayout();
165 // Set up the TargetLowering object.
166 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
168 // X86 is weird, it always uses i8 for shift amounts and setcc results.
169 setBooleanContents(ZeroOrOneBooleanContent);
170 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
171 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173 // For 64-bit since we have so many registers use the ILP scheduler, for
174 // 32-bit code use the register pressure specific scheduling.
175 // For Atom, always use ILP scheduling.
176 if (Subtarget->isAtom())
177 setSchedulingPreference(Sched::ILP);
178 else if (Subtarget->is64Bit())
179 setSchedulingPreference(Sched::ILP);
181 setSchedulingPreference(Sched::RegPressure);
182 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
184 // Bypass i32 with i8 on Atom when compiling with O2
185 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default)
186 addBypassSlowDiv(32, 8);
188 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
189 // Setup Windows compiler runtime calls.
190 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
191 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
192 setLibcallName(RTLIB::SREM_I64, "_allrem");
193 setLibcallName(RTLIB::UREM_I64, "_aullrem");
194 setLibcallName(RTLIB::MUL_I64, "_allmul");
195 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
196 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
197 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
198 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
199 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
201 // The _ftol2 runtime function has an unusual calling conv, which
202 // is modeled by a special pseudo-instruction.
203 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
204 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
205 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
206 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
209 if (Subtarget->isTargetDarwin()) {
210 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
211 setUseUnderscoreSetJmp(false);
212 setUseUnderscoreLongJmp(false);
213 } else if (Subtarget->isTargetMingw()) {
214 // MS runtime is weird: it exports _setjmp, but longjmp!
215 setUseUnderscoreSetJmp(true);
216 setUseUnderscoreLongJmp(false);
218 setUseUnderscoreSetJmp(true);
219 setUseUnderscoreLongJmp(true);
222 // Set up the register classes.
223 addRegisterClass(MVT::i8, &X86::GR8RegClass);
224 addRegisterClass(MVT::i16, &X86::GR16RegClass);
225 addRegisterClass(MVT::i32, &X86::GR32RegClass);
226 if (Subtarget->is64Bit())
227 addRegisterClass(MVT::i64, &X86::GR64RegClass);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // We don't accept any truncstore of integer registers.
232 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
233 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
234 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
235 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
236 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
237 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
239 // SETOEQ and SETUNE require checking two conditions.
240 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
241 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
242 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
243 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
244 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
245 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
247 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
249 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
250 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
251 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
255 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
256 } else if (!TM.Options.UseSoftFloat) {
257 // We have an algorithm for SSE2->double, and we turn this into a
258 // 64-bit FILD followed by conditional FADD for other targets.
259 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
260 // We have an algorithm for SSE2, and we turn this into a 64-bit
261 // FILD for other targets.
262 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
265 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
267 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
270 if (!TM.Options.UseSoftFloat) {
271 // SSE has no i16 to fp conversion, only i32
272 if (X86ScalarSSEf32) {
273 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
274 // f32 and f64 cases are Legal, f80 case is not
275 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
277 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
278 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
281 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
282 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
285 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
286 // are Legal, f80 is custom lowered.
287 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
288 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
290 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
292 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
293 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
295 if (X86ScalarSSEf32) {
296 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
297 // f32 and f64 cases are Legal, f80 case is not
298 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
300 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
301 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
304 // Handle FP_TO_UINT by promoting the destination to a larger signed
306 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
307 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
308 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
310 if (Subtarget->is64Bit()) {
311 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
312 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
313 } else if (!TM.Options.UseSoftFloat) {
314 // Since AVX is a superset of SSE3, only check for SSE here.
315 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
316 // Expand FP_TO_UINT into a select.
317 // FIXME: We would like to use a Custom expander here eventually to do
318 // the optimal thing for SSE vs. the default expansion in the legalizer.
319 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
321 // With SSE3 we can use fisttpll to convert to a signed i64; without
322 // SSE, we're stuck with a fistpll.
323 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
326 if (isTargetFTOL()) {
327 // Use the _ftol2 runtime function, which has a pseudo-instruction
328 // to handle its weird calling convention.
329 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
332 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
333 if (!X86ScalarSSEf64) {
334 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
335 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
338 // Without SSE, i64->f64 goes through memory.
339 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
343 // Scalar integer divide and remainder are lowered to use operations that
344 // produce two results, to match the available instructions. This exposes
345 // the two-result form to trivial CSE, which is able to combine x/y and x%y
346 // into a single instruction.
348 // Scalar integer multiply-high is also lowered to use two-result
349 // operations, to match the available instructions. However, plain multiply
350 // (low) operations are left as Legal, as there are single-result
351 // instructions for this in x86. Using the two-result multiply instructions
352 // when both high and low results are needed must be arranged by dagcombine.
353 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
355 setOperationAction(ISD::MULHS, VT, Expand);
356 setOperationAction(ISD::MULHU, VT, Expand);
357 setOperationAction(ISD::SDIV, VT, Expand);
358 setOperationAction(ISD::UDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UREM, VT, Expand);
362 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
363 setOperationAction(ISD::ADDC, VT, Custom);
364 setOperationAction(ISD::ADDE, VT, Custom);
365 setOperationAction(ISD::SUBC, VT, Custom);
366 setOperationAction(ISD::SUBE, VT, Custom);
369 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
370 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
371 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
372 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
378 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
379 setOperationAction(ISD::FREM , MVT::f32 , Expand);
380 setOperationAction(ISD::FREM , MVT::f64 , Expand);
381 setOperationAction(ISD::FREM , MVT::f80 , Expand);
382 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
384 // Promote the i8 variants and force them on up to i32 which has a shorter
386 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
387 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
389 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
390 if (Subtarget->hasBMI()) {
391 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
393 if (Subtarget->is64Bit())
394 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
396 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
397 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
398 if (Subtarget->is64Bit())
399 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
402 if (Subtarget->hasLZCNT()) {
403 // When promoting the i8 variants, force them to i32 for a shorter
405 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
406 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
408 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
411 if (Subtarget->is64Bit())
412 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
415 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
416 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
418 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
419 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
420 if (Subtarget->is64Bit()) {
421 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
426 if (Subtarget->hasPOPCNT()) {
427 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
429 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
430 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
431 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
436 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
437 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
439 // These should be promoted to a larger select which is supported.
440 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
441 // X86 wants to expand cmov itself.
442 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
443 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
444 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
445 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
446 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
447 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
448 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
449 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
450 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
451 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
452 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
453 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
454 if (Subtarget->is64Bit()) {
455 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
456 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
458 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
459 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
460 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
461 // support continuation, user-level threading, and etc.. As a result, no
462 // other SjLj exception interfaces are implemented and please don't build
463 // your own exception handling based on them.
464 // LLVM/Clang supports zero-cost DWARF exception handling.
465 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
466 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
469 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
470 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
471 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
472 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
473 if (Subtarget->is64Bit())
474 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
475 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
476 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
477 if (Subtarget->is64Bit()) {
478 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
479 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
480 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
481 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
482 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
484 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
485 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
486 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
487 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
488 if (Subtarget->is64Bit()) {
489 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
490 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
491 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
494 if (Subtarget->hasSSE1())
495 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
497 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
498 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
500 // On X86 and X86-64, atomic operations are lowered to locked instructions.
501 // Locked instructions, in turn, have implicit fence semantics (all memory
502 // operations are flushed before issuing the locked instruction, and they
503 // are not buffered), so we can fold away the common pattern of
504 // fence-atomic-fence.
505 setShouldFoldAtomicFences(true);
507 // Expand certain atomics
508 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
511 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
512 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
515 if (!Subtarget->is64Bit()) {
516 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
517 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
518 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
519 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
520 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
521 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
522 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
523 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
524 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
525 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
526 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
527 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
530 if (Subtarget->hasCmpxchg16b()) {
531 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
534 // FIXME - use subtarget debug flags
535 if (!Subtarget->isTargetDarwin() &&
536 !Subtarget->isTargetELF() &&
537 !Subtarget->isTargetCygMing()) {
538 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
541 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
542 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
543 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
544 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
545 if (Subtarget->is64Bit()) {
546 setExceptionPointerRegister(X86::RAX);
547 setExceptionSelectorRegister(X86::RDX);
549 setExceptionPointerRegister(X86::EAX);
550 setExceptionSelectorRegister(X86::EDX);
552 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
553 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
555 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
556 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
558 setOperationAction(ISD::TRAP, MVT::Other, Legal);
559 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
561 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
562 setOperationAction(ISD::VASTART , MVT::Other, Custom);
563 setOperationAction(ISD::VAEND , MVT::Other, Expand);
564 if (Subtarget->is64Bit()) {
565 setOperationAction(ISD::VAARG , MVT::Other, Custom);
566 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
568 setOperationAction(ISD::VAARG , MVT::Other, Expand);
569 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
572 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
573 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
575 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
576 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
577 MVT::i64 : MVT::i32, Custom);
578 else if (TM.Options.EnableSegmentedStacks)
579 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
580 MVT::i64 : MVT::i32, Custom);
582 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
583 MVT::i64 : MVT::i32, Expand);
585 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
586 // f32 and f64 use SSE.
587 // Set up the FP register classes.
588 addRegisterClass(MVT::f32, &X86::FR32RegClass);
589 addRegisterClass(MVT::f64, &X86::FR64RegClass);
591 // Use ANDPD to simulate FABS.
592 setOperationAction(ISD::FABS , MVT::f64, Custom);
593 setOperationAction(ISD::FABS , MVT::f32, Custom);
595 // Use XORP to simulate FNEG.
596 setOperationAction(ISD::FNEG , MVT::f64, Custom);
597 setOperationAction(ISD::FNEG , MVT::f32, Custom);
599 // Use ANDPD and ORPD to simulate FCOPYSIGN.
600 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
601 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
603 // Lower this to FGETSIGNx86 plus an AND.
604 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
605 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
607 // We don't support sin/cos/fmod
608 setOperationAction(ISD::FSIN , MVT::f64, Expand);
609 setOperationAction(ISD::FCOS , MVT::f64, Expand);
610 setOperationAction(ISD::FSIN , MVT::f32, Expand);
611 setOperationAction(ISD::FCOS , MVT::f32, Expand);
613 // Expand FP immediates into loads from the stack, except for the special
615 addLegalFPImmediate(APFloat(+0.0)); // xorpd
616 addLegalFPImmediate(APFloat(+0.0f)); // xorps
617 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
618 // Use SSE for f32, x87 for f64.
619 // Set up the FP register classes.
620 addRegisterClass(MVT::f32, &X86::FR32RegClass);
621 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
623 // Use ANDPS to simulate FABS.
624 setOperationAction(ISD::FABS , MVT::f32, Custom);
626 // Use XORP to simulate FNEG.
627 setOperationAction(ISD::FNEG , MVT::f32, Custom);
629 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
631 // Use ANDPS and ORPS to simulate FCOPYSIGN.
632 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
633 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
635 // We don't support sin/cos/fmod
636 setOperationAction(ISD::FSIN , MVT::f32, Expand);
637 setOperationAction(ISD::FCOS , MVT::f32, Expand);
639 // Special cases we handle for FP constants.
640 addLegalFPImmediate(APFloat(+0.0f)); // xorps
641 addLegalFPImmediate(APFloat(+0.0)); // FLD0
642 addLegalFPImmediate(APFloat(+1.0)); // FLD1
643 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
644 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
646 if (!TM.Options.UnsafeFPMath) {
647 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
648 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
650 } else if (!TM.Options.UseSoftFloat) {
651 // f32 and f64 in x87.
652 // Set up the FP register classes.
653 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
654 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
656 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
657 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
658 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
661 if (!TM.Options.UnsafeFPMath) {
662 setOperationAction(ISD::FSIN , MVT::f32 , Expand);
663 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
664 setOperationAction(ISD::FCOS , MVT::f32 , Expand);
665 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
667 addLegalFPImmediate(APFloat(+0.0)); // FLD0
668 addLegalFPImmediate(APFloat(+1.0)); // FLD1
669 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
672 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
673 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
674 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
677 // We don't support FMA.
678 setOperationAction(ISD::FMA, MVT::f64, Expand);
679 setOperationAction(ISD::FMA, MVT::f32, Expand);
681 // Long double always uses X87.
682 if (!TM.Options.UseSoftFloat) {
683 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
684 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
685 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
687 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
688 addLegalFPImmediate(TmpFlt); // FLD0
690 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
693 APFloat TmpFlt2(+1.0);
694 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
696 addLegalFPImmediate(TmpFlt2); // FLD1
697 TmpFlt2.changeSign();
698 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
701 if (!TM.Options.UnsafeFPMath) {
702 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
703 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
706 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
707 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
708 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
709 setOperationAction(ISD::FRINT, MVT::f80, Expand);
710 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
711 setOperationAction(ISD::FMA, MVT::f80, Expand);
714 // Always use a library call for pow.
715 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
716 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
717 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
719 setOperationAction(ISD::FLOG, MVT::f80, Expand);
720 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
721 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
722 setOperationAction(ISD::FEXP, MVT::f80, Expand);
723 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
725 // First set operation action for all vector types to either promote
726 // (for widening) or expand (for scalarization). Then we will selectively
727 // turn on ones that can be effectively codegen'd.
728 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
729 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
730 MVT VT = (MVT::SimpleValueType)i;
731 setOperationAction(ISD::ADD , VT, Expand);
732 setOperationAction(ISD::SUB , VT, Expand);
733 setOperationAction(ISD::FADD, VT, Expand);
734 setOperationAction(ISD::FNEG, VT, Expand);
735 setOperationAction(ISD::FSUB, VT, Expand);
736 setOperationAction(ISD::MUL , VT, Expand);
737 setOperationAction(ISD::FMUL, VT, Expand);
738 setOperationAction(ISD::SDIV, VT, Expand);
739 setOperationAction(ISD::UDIV, VT, Expand);
740 setOperationAction(ISD::FDIV, VT, Expand);
741 setOperationAction(ISD::SREM, VT, Expand);
742 setOperationAction(ISD::UREM, VT, Expand);
743 setOperationAction(ISD::LOAD, VT, Expand);
744 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
745 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
746 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
747 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
748 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
749 setOperationAction(ISD::FABS, VT, Expand);
750 setOperationAction(ISD::FSIN, VT, Expand);
751 setOperationAction(ISD::FCOS, VT, Expand);
752 setOperationAction(ISD::FREM, VT, Expand);
753 setOperationAction(ISD::FMA, VT, Expand);
754 setOperationAction(ISD::FPOWI, VT, Expand);
755 setOperationAction(ISD::FSQRT, VT, Expand);
756 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
757 setOperationAction(ISD::FFLOOR, VT, Expand);
758 setOperationAction(ISD::FCEIL, VT, Expand);
759 setOperationAction(ISD::FTRUNC, VT, Expand);
760 setOperationAction(ISD::FRINT, VT, Expand);
761 setOperationAction(ISD::FNEARBYINT, VT, Expand);
762 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
763 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
764 setOperationAction(ISD::SDIVREM, VT, Expand);
765 setOperationAction(ISD::UDIVREM, VT, Expand);
766 setOperationAction(ISD::FPOW, VT, Expand);
767 setOperationAction(ISD::CTPOP, VT, Expand);
768 setOperationAction(ISD::CTTZ, VT, Expand);
769 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
770 setOperationAction(ISD::CTLZ, VT, Expand);
771 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
772 setOperationAction(ISD::SHL, VT, Expand);
773 setOperationAction(ISD::SRA, VT, Expand);
774 setOperationAction(ISD::SRL, VT, Expand);
775 setOperationAction(ISD::ROTL, VT, Expand);
776 setOperationAction(ISD::ROTR, VT, Expand);
777 setOperationAction(ISD::BSWAP, VT, Expand);
778 setOperationAction(ISD::SETCC, VT, Expand);
779 setOperationAction(ISD::FLOG, VT, Expand);
780 setOperationAction(ISD::FLOG2, VT, Expand);
781 setOperationAction(ISD::FLOG10, VT, Expand);
782 setOperationAction(ISD::FEXP, VT, Expand);
783 setOperationAction(ISD::FEXP2, VT, Expand);
784 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
785 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
786 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
787 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
788 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
789 setOperationAction(ISD::TRUNCATE, VT, Expand);
790 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
791 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
792 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
793 setOperationAction(ISD::VSELECT, VT, Expand);
794 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
795 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
796 setTruncStoreAction(VT,
797 (MVT::SimpleValueType)InnerVT, Expand);
798 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
799 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
800 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
803 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
804 // with -msoft-float, disable use of MMX as well.
805 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
806 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
807 // No operations on x86mmx supported, everything uses intrinsics.
810 // MMX-sized vectors (other than x86mmx) are expected to be expanded
811 // into smaller operations.
812 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
813 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
814 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
815 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
816 setOperationAction(ISD::AND, MVT::v8i8, Expand);
817 setOperationAction(ISD::AND, MVT::v4i16, Expand);
818 setOperationAction(ISD::AND, MVT::v2i32, Expand);
819 setOperationAction(ISD::AND, MVT::v1i64, Expand);
820 setOperationAction(ISD::OR, MVT::v8i8, Expand);
821 setOperationAction(ISD::OR, MVT::v4i16, Expand);
822 setOperationAction(ISD::OR, MVT::v2i32, Expand);
823 setOperationAction(ISD::OR, MVT::v1i64, Expand);
824 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
825 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
826 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
827 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
828 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
829 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
830 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
831 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
833 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
834 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
835 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
836 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
837 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
838 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
839 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
840 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
842 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
843 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
845 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
851 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
852 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
853 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
854 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
859 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
860 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
862 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
863 // registers cannot be used even for integer operations.
864 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
865 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
866 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
867 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
869 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
870 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
871 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
872 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
873 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
874 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
875 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
876 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
877 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
878 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
879 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
880 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
881 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
882 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
883 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
884 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
885 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
886 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
888 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
889 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
890 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
891 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
893 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
894 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
895 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
899 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
900 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
901 MVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
905 // Do not attempt to custom lower non-128-bit vectors
906 if (!VT.is128BitVector())
908 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
909 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
913 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
914 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
915 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
916 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
917 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
918 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
920 if (Subtarget->is64Bit()) {
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
925 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
926 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
927 MVT VT = (MVT::SimpleValueType)i;
929 // Do not attempt to promote non-128-bit vectors
930 if (!VT.is128BitVector())
933 setOperationAction(ISD::AND, VT, Promote);
934 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
935 setOperationAction(ISD::OR, VT, Promote);
936 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
937 setOperationAction(ISD::XOR, VT, Promote);
938 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
939 setOperationAction(ISD::LOAD, VT, Promote);
940 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
941 setOperationAction(ISD::SELECT, VT, Promote);
942 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
945 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
947 // Custom lower v2i64 and v2f64 selects.
948 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
949 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
950 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
951 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
953 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
954 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
956 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
957 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
958 // As there is no 64-bit GPR available, we need build a special custom
959 // sequence to convert from v2i32 to v2f32.
960 if (!Subtarget->is64Bit())
961 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
963 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
964 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
966 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
969 if (Subtarget->hasSSE41()) {
970 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
971 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
972 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
973 setOperationAction(ISD::FRINT, MVT::f32, Legal);
974 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
975 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
976 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
977 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
978 setOperationAction(ISD::FRINT, MVT::f64, Legal);
979 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
981 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
982 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
983 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
984 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
985 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
986 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
987 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
988 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
989 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
990 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
992 // FIXME: Do we need to handle scalar-to-vector here?
993 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
995 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
996 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
997 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
998 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
999 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1001 // i8 and i16 vectors are custom , because the source register and source
1002 // source memory operand types are not the same width. f32 vectors are
1003 // custom since the immediate controlling the insert encodes additional
1005 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1006 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1008 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1012 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1015 // FIXME: these should be Legal but thats only for the case where
1016 // the index is constant. For now custom expand to deal with that.
1017 if (Subtarget->is64Bit()) {
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1023 if (Subtarget->hasSSE2()) {
1024 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1025 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1027 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1028 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1030 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1031 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1033 if (Subtarget->hasInt256()) {
1034 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1035 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
1037 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1038 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
1042 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1043 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1045 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1046 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1048 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1050 setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
1051 setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
1054 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1055 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1056 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1057 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1058 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1059 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1060 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1062 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1063 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1064 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1066 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1067 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1068 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1069 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1070 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1071 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1072 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1073 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1074 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1075 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1076 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1077 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1079 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1080 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1081 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1082 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1083 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1084 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1085 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1086 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1087 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1088 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1089 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1090 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1092 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1093 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1095 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
1097 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1098 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1099 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1101 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1102 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1103 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1105 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1107 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1108 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1110 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1111 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1113 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1114 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1116 setOperationAction(ISD::SDIV, MVT::v16i16, Custom);
1118 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1119 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1120 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1121 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1123 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1124 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1125 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1127 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1128 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1129 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1130 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1132 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1133 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1134 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1135 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1136 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1137 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1139 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1140 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1142 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1143 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1144 setOperationAction(ISD::FMA, MVT::f32, Legal);
1145 setOperationAction(ISD::FMA, MVT::f64, Legal);
1148 if (Subtarget->hasInt256()) {
1149 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1150 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1151 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1152 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1154 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1155 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1156 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1157 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1159 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1160 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1161 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1162 // Don't lower v32i8 because there is no 128-bit byte mul
1164 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1166 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1167 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1169 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1170 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1172 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1174 setOperationAction(ISD::SDIV, MVT::v8i32, Custom);
1176 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1177 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1178 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1179 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1182 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1183 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1184 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1186 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1187 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1188 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1189 // Don't lower v32i8 because there is no 128-bit byte mul
1191 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1192 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1194 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1195 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1197 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1200 // Custom lower several nodes for 256-bit types.
1201 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1202 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1203 MVT VT = (MVT::SimpleValueType)i;
1205 // Extract subvector is special because the value type
1206 // (result) is 128-bit but the source is 256-bit wide.
1207 if (VT.is128BitVector())
1208 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1210 // Do not attempt to custom lower other non-256-bit vectors
1211 if (!VT.is256BitVector())
1214 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1215 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1216 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1217 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1218 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1219 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1220 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1223 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1224 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1225 MVT VT = (MVT::SimpleValueType)i;
1227 // Do not attempt to promote non-256-bit vectors
1228 if (!VT.is256BitVector())
1231 setOperationAction(ISD::AND, VT, Promote);
1232 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1233 setOperationAction(ISD::OR, VT, Promote);
1234 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1235 setOperationAction(ISD::XOR, VT, Promote);
1236 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1237 setOperationAction(ISD::LOAD, VT, Promote);
1238 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1239 setOperationAction(ISD::SELECT, VT, Promote);
1240 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1244 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1245 // of this type with custom code.
1246 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1247 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1248 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1252 // We want to custom lower some of our intrinsics.
1253 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1254 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1256 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1257 // handle type legalization for these operations here.
1259 // FIXME: We really should do custom legalization for addition and
1260 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1261 // than generic legalization for 64-bit multiplication-with-overflow, though.
1262 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1263 // Add/Sub/Mul with overflow operations are custom lowered.
1265 setOperationAction(ISD::SADDO, VT, Custom);
1266 setOperationAction(ISD::UADDO, VT, Custom);
1267 setOperationAction(ISD::SSUBO, VT, Custom);
1268 setOperationAction(ISD::USUBO, VT, Custom);
1269 setOperationAction(ISD::SMULO, VT, Custom);
1270 setOperationAction(ISD::UMULO, VT, Custom);
1273 // There are no 8-bit 3-address imul/mul instructions
1274 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1275 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1277 if (!Subtarget->is64Bit()) {
1278 // These libcalls are not available in 32-bit.
1279 setLibcallName(RTLIB::SHL_I128, 0);
1280 setLibcallName(RTLIB::SRL_I128, 0);
1281 setLibcallName(RTLIB::SRA_I128, 0);
1284 // We have target-specific dag combine patterns for the following nodes:
1285 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1286 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1287 setTargetDAGCombine(ISD::VSELECT);
1288 setTargetDAGCombine(ISD::SELECT);
1289 setTargetDAGCombine(ISD::SHL);
1290 setTargetDAGCombine(ISD::SRA);
1291 setTargetDAGCombine(ISD::SRL);
1292 setTargetDAGCombine(ISD::OR);
1293 setTargetDAGCombine(ISD::AND);
1294 setTargetDAGCombine(ISD::ADD);
1295 setTargetDAGCombine(ISD::FADD);
1296 setTargetDAGCombine(ISD::FSUB);
1297 setTargetDAGCombine(ISD::FMA);
1298 setTargetDAGCombine(ISD::SUB);
1299 setTargetDAGCombine(ISD::LOAD);
1300 setTargetDAGCombine(ISD::STORE);
1301 setTargetDAGCombine(ISD::ZERO_EXTEND);
1302 setTargetDAGCombine(ISD::ANY_EXTEND);
1303 setTargetDAGCombine(ISD::SIGN_EXTEND);
1304 setTargetDAGCombine(ISD::TRUNCATE);
1305 setTargetDAGCombine(ISD::SINT_TO_FP);
1306 setTargetDAGCombine(ISD::SETCC);
1307 if (Subtarget->is64Bit())
1308 setTargetDAGCombine(ISD::MUL);
1309 setTargetDAGCombine(ISD::XOR);
1311 computeRegisterProperties();
1313 // On Darwin, -Os means optimize for size without hurting performance,
1314 // do not reduce the limit.
1315 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1316 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1317 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1318 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1319 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1320 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1321 setPrefLoopAlignment(4); // 2^4 bytes.
1322 benefitFromCodePlacementOpt = true;
1324 // Predictable cmov don't hurt on atom because it's in-order.
1325 predictableSelectIsExpensive = !Subtarget->isAtom();
1327 setPrefFunctionAlignment(4); // 2^4 bytes.
1330 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1331 if (!VT.isVector()) return MVT::i8;
1332 return VT.changeVectorElementTypeToInteger();
1335 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1336 /// the desired ByVal argument alignment.
1337 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1340 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1341 if (VTy->getBitWidth() == 128)
1343 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1344 unsigned EltAlign = 0;
1345 getMaxByValAlign(ATy->getElementType(), EltAlign);
1346 if (EltAlign > MaxAlign)
1347 MaxAlign = EltAlign;
1348 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1349 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1350 unsigned EltAlign = 0;
1351 getMaxByValAlign(STy->getElementType(i), EltAlign);
1352 if (EltAlign > MaxAlign)
1353 MaxAlign = EltAlign;
1360 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1361 /// function arguments in the caller parameter area. For X86, aggregates
1362 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1363 /// are at 4-byte boundaries.
1364 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1365 if (Subtarget->is64Bit()) {
1366 // Max of 8 and alignment of type.
1367 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1374 if (Subtarget->hasSSE1())
1375 getMaxByValAlign(Ty, Align);
1379 /// getOptimalMemOpType - Returns the target specific optimal type for load
1380 /// and store operations as a result of memset, memcpy, and memmove
1381 /// lowering. If DstAlign is zero that means it's safe to destination
1382 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1383 /// means there isn't a need to check it against alignment requirement,
1384 /// probably because the source does not need to be loaded. If 'IsMemset' is
1385 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1386 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1387 /// source is constant so it does not need to be loaded.
1388 /// It returns EVT::Other if the type should be determined using generic
1389 /// target-independent logic.
1391 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1392 unsigned DstAlign, unsigned SrcAlign,
1393 bool IsMemset, bool ZeroMemset,
1395 MachineFunction &MF) const {
1396 const Function *F = MF.getFunction();
1397 if ((!IsMemset || ZeroMemset) &&
1398 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1399 Attribute::NoImplicitFloat)) {
1401 (Subtarget->isUnalignedMemAccessFast() ||
1402 ((DstAlign == 0 || DstAlign >= 16) &&
1403 (SrcAlign == 0 || SrcAlign >= 16)))) {
1405 if (Subtarget->hasInt256())
1407 if (Subtarget->hasFp256())
1410 if (Subtarget->hasSSE2())
1412 if (Subtarget->hasSSE1())
1414 } else if (!MemcpyStrSrc && Size >= 8 &&
1415 !Subtarget->is64Bit() &&
1416 Subtarget->hasSSE2()) {
1417 // Do not use f64 to lower memcpy if source is string constant. It's
1418 // better to use i32 to avoid the loads.
1422 if (Subtarget->is64Bit() && Size >= 8)
1427 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1429 return X86ScalarSSEf32;
1430 else if (VT == MVT::f64)
1431 return X86ScalarSSEf64;
1436 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1438 *Fast = Subtarget->isUnalignedMemAccessFast();
1442 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1443 /// current function. The returned value is a member of the
1444 /// MachineJumpTableInfo::JTEntryKind enum.
1445 unsigned X86TargetLowering::getJumpTableEncoding() const {
1446 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1448 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1449 Subtarget->isPICStyleGOT())
1450 return MachineJumpTableInfo::EK_Custom32;
1452 // Otherwise, use the normal jump table encoding heuristics.
1453 return TargetLowering::getJumpTableEncoding();
1457 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1458 const MachineBasicBlock *MBB,
1459 unsigned uid,MCContext &Ctx) const{
1460 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1461 Subtarget->isPICStyleGOT());
1462 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1464 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1465 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1468 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1470 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1471 SelectionDAG &DAG) const {
1472 if (!Subtarget->is64Bit())
1473 // This doesn't have DebugLoc associated with it, but is not really the
1474 // same as a Register.
1475 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1479 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1480 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1482 const MCExpr *X86TargetLowering::
1483 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1484 MCContext &Ctx) const {
1485 // X86-64 uses RIP relative addressing based on the jump table label.
1486 if (Subtarget->isPICStyleRIPRel())
1487 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1489 // Otherwise, the reference is relative to the PIC base.
1490 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1493 // FIXME: Why this routine is here? Move to RegInfo!
1494 std::pair<const TargetRegisterClass*, uint8_t>
1495 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1496 const TargetRegisterClass *RRC = 0;
1498 switch (VT.SimpleTy) {
1500 return TargetLowering::findRepresentativeClass(VT);
1501 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1502 RRC = Subtarget->is64Bit() ?
1503 (const TargetRegisterClass*)&X86::GR64RegClass :
1504 (const TargetRegisterClass*)&X86::GR32RegClass;
1507 RRC = &X86::VR64RegClass;
1509 case MVT::f32: case MVT::f64:
1510 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1511 case MVT::v4f32: case MVT::v2f64:
1512 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1514 RRC = &X86::VR128RegClass;
1517 return std::make_pair(RRC, Cost);
1520 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1521 unsigned &Offset) const {
1522 if (!Subtarget->isTargetLinux())
1525 if (Subtarget->is64Bit()) {
1526 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1528 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1540 //===----------------------------------------------------------------------===//
1541 // Return Value Calling Convention Implementation
1542 //===----------------------------------------------------------------------===//
1544 #include "X86GenCallingConv.inc"
1547 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1548 MachineFunction &MF, bool isVarArg,
1549 const SmallVectorImpl<ISD::OutputArg> &Outs,
1550 LLVMContext &Context) const {
1551 SmallVector<CCValAssign, 16> RVLocs;
1552 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1554 return CCInfo.CheckReturn(Outs, RetCC_X86);
1558 X86TargetLowering::LowerReturn(SDValue Chain,
1559 CallingConv::ID CallConv, bool isVarArg,
1560 const SmallVectorImpl<ISD::OutputArg> &Outs,
1561 const SmallVectorImpl<SDValue> &OutVals,
1562 DebugLoc dl, SelectionDAG &DAG) const {
1563 MachineFunction &MF = DAG.getMachineFunction();
1564 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1566 SmallVector<CCValAssign, 16> RVLocs;
1567 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1568 RVLocs, *DAG.getContext());
1569 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1571 // Add the regs to the liveout set for the function.
1572 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1573 for (unsigned i = 0; i != RVLocs.size(); ++i)
1574 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1575 MRI.addLiveOut(RVLocs[i].getLocReg());
1579 SmallVector<SDValue, 6> RetOps;
1580 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1581 // Operand #1 = Bytes To Pop
1582 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1585 // Copy the result values into the output registers.
1586 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1587 CCValAssign &VA = RVLocs[i];
1588 assert(VA.isRegLoc() && "Can only return in registers!");
1589 SDValue ValToCopy = OutVals[i];
1590 EVT ValVT = ValToCopy.getValueType();
1592 // Promote values to the appropriate types
1593 if (VA.getLocInfo() == CCValAssign::SExt)
1594 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1595 else if (VA.getLocInfo() == CCValAssign::ZExt)
1596 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1597 else if (VA.getLocInfo() == CCValAssign::AExt)
1598 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1599 else if (VA.getLocInfo() == CCValAssign::BCvt)
1600 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1602 // If this is x86-64, and we disabled SSE, we can't return FP values,
1603 // or SSE or MMX vectors.
1604 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1605 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1606 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1607 report_fatal_error("SSE register return with SSE disabled");
1609 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1610 // llvm-gcc has never done it right and no one has noticed, so this
1611 // should be OK for now.
1612 if (ValVT == MVT::f64 &&
1613 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1614 report_fatal_error("SSE2 register return with SSE2 disabled");
1616 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1617 // the RET instruction and handled by the FP Stackifier.
1618 if (VA.getLocReg() == X86::ST0 ||
1619 VA.getLocReg() == X86::ST1) {
1620 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1621 // change the value to the FP stack register class.
1622 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1623 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1624 RetOps.push_back(ValToCopy);
1625 // Don't emit a copytoreg.
1629 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1630 // which is returned in RAX / RDX.
1631 if (Subtarget->is64Bit()) {
1632 if (ValVT == MVT::x86mmx) {
1633 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1634 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1635 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1637 // If we don't have SSE2 available, convert to v4f32 so the generated
1638 // register is legal.
1639 if (!Subtarget->hasSSE2())
1640 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1645 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1646 Flag = Chain.getValue(1);
1649 // The x86-64 ABIs require that for returning structs by value we copy
1650 // the sret argument into %rax/%eax (depending on ABI) for the return.
1651 // We saved the argument into a virtual register in the entry block,
1652 // so now we copy the value out and into %rax/%eax.
1653 if (Subtarget->is64Bit() &&
1654 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1655 MachineFunction &MF = DAG.getMachineFunction();
1656 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1657 unsigned Reg = FuncInfo->getSRetReturnReg();
1659 "SRetReturnReg should have been set in LowerFormalArguments().");
1660 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1662 unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1663 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1664 Flag = Chain.getValue(1);
1666 // RAX/EAX now acts like a return value.
1667 MRI.addLiveOut(RetValReg);
1670 RetOps[0] = Chain; // Update chain.
1672 // Add the flag if we have it.
1674 RetOps.push_back(Flag);
1676 return DAG.getNode(X86ISD::RET_FLAG, dl,
1677 MVT::Other, &RetOps[0], RetOps.size());
1680 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1681 if (N->getNumValues() != 1)
1683 if (!N->hasNUsesOfValue(1, 0))
1686 SDValue TCChain = Chain;
1687 SDNode *Copy = *N->use_begin();
1688 if (Copy->getOpcode() == ISD::CopyToReg) {
1689 // If the copy has a glue operand, we conservatively assume it isn't safe to
1690 // perform a tail call.
1691 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1693 TCChain = Copy->getOperand(0);
1694 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1697 bool HasRet = false;
1698 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1700 if (UI->getOpcode() != X86ISD::RET_FLAG)
1713 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1714 ISD::NodeType ExtendKind) const {
1716 // TODO: Is this also valid on 32-bit?
1717 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1718 ReturnMVT = MVT::i8;
1720 ReturnMVT = MVT::i32;
1722 MVT MinVT = getRegisterType(ReturnMVT);
1723 return VT.bitsLT(MinVT) ? MinVT : VT;
1726 /// LowerCallResult - Lower the result values of a call into the
1727 /// appropriate copies out of appropriate physical registers.
1730 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1731 CallingConv::ID CallConv, bool isVarArg,
1732 const SmallVectorImpl<ISD::InputArg> &Ins,
1733 DebugLoc dl, SelectionDAG &DAG,
1734 SmallVectorImpl<SDValue> &InVals) const {
1736 // Assign locations to each value returned by this call.
1737 SmallVector<CCValAssign, 16> RVLocs;
1738 bool Is64Bit = Subtarget->is64Bit();
1739 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1740 getTargetMachine(), RVLocs, *DAG.getContext());
1741 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1743 // Copy all of the result registers out of their specified physreg.
1744 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1745 CCValAssign &VA = RVLocs[i];
1746 EVT CopyVT = VA.getValVT();
1748 // If this is x86-64, and we disabled SSE, we can't return FP values
1749 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1750 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1751 report_fatal_error("SSE register return with SSE disabled");
1756 // If this is a call to a function that returns an fp value on the floating
1757 // point stack, we must guarantee the value is popped from the stack, so
1758 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1759 // if the return value is not used. We use the FpPOP_RETVAL instruction
1761 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1762 // If we prefer to use the value in xmm registers, copy it out as f80 and
1763 // use a truncate to move it from fp stack reg to xmm reg.
1764 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1765 SDValue Ops[] = { Chain, InFlag };
1766 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1767 MVT::Other, MVT::Glue, Ops, 2), 1);
1768 Val = Chain.getValue(0);
1770 // Round the f80 to the right size, which also moves it to the appropriate
1772 if (CopyVT != VA.getValVT())
1773 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1774 // This truncation won't change the value.
1775 DAG.getIntPtrConstant(1));
1777 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1778 CopyVT, InFlag).getValue(1);
1779 Val = Chain.getValue(0);
1781 InFlag = Chain.getValue(2);
1782 InVals.push_back(Val);
1788 //===----------------------------------------------------------------------===//
1789 // C & StdCall & Fast Calling Convention implementation
1790 //===----------------------------------------------------------------------===//
1791 // StdCall calling convention seems to be standard for many Windows' API
1792 // routines and around. It differs from C calling convention just a little:
1793 // callee should clean up the stack, not caller. Symbols should be also
1794 // decorated in some fancy way :) It doesn't support any vector arguments.
1795 // For info on fast calling convention see Fast Calling Convention (tail call)
1796 // implementation LowerX86_32FastCCCallTo.
1798 /// CallIsStructReturn - Determines whether a call uses struct return
1800 enum StructReturnType {
1805 static StructReturnType
1806 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1808 return NotStructReturn;
1810 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1811 if (!Flags.isSRet())
1812 return NotStructReturn;
1813 if (Flags.isInReg())
1814 return RegStructReturn;
1815 return StackStructReturn;
1818 /// ArgsAreStructReturn - Determines whether a function uses struct
1819 /// return semantics.
1820 static StructReturnType
1821 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1823 return NotStructReturn;
1825 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1826 if (!Flags.isSRet())
1827 return NotStructReturn;
1828 if (Flags.isInReg())
1829 return RegStructReturn;
1830 return StackStructReturn;
1833 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1834 /// by "Src" to address "Dst" with size and alignment information specified by
1835 /// the specific parameter attribute. The copy will be passed as a byval
1836 /// function parameter.
1838 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1839 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1841 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1843 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1844 /*isVolatile*/false, /*AlwaysInline=*/true,
1845 MachinePointerInfo(), MachinePointerInfo());
1848 /// IsTailCallConvention - Return true if the calling convention is one that
1849 /// supports tail call optimization.
1850 static bool IsTailCallConvention(CallingConv::ID CC) {
1851 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1852 CC == CallingConv::HiPE);
1855 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1856 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1860 CallingConv::ID CalleeCC = CS.getCallingConv();
1861 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1867 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1868 /// a tailcall target by changing its ABI.
1869 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1870 bool GuaranteedTailCallOpt) {
1871 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1875 X86TargetLowering::LowerMemArgument(SDValue Chain,
1876 CallingConv::ID CallConv,
1877 const SmallVectorImpl<ISD::InputArg> &Ins,
1878 DebugLoc dl, SelectionDAG &DAG,
1879 const CCValAssign &VA,
1880 MachineFrameInfo *MFI,
1882 // Create the nodes corresponding to a load from this parameter slot.
1883 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1884 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1885 getTargetMachine().Options.GuaranteedTailCallOpt);
1886 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1889 // If value is passed by pointer we have address passed instead of the value
1891 if (VA.getLocInfo() == CCValAssign::Indirect)
1892 ValVT = VA.getLocVT();
1894 ValVT = VA.getValVT();
1896 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1897 // changed with more analysis.
1898 // In case of tail call optimization mark all arguments mutable. Since they
1899 // could be overwritten by lowering of arguments in case of a tail call.
1900 if (Flags.isByVal()) {
1901 unsigned Bytes = Flags.getByValSize();
1902 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1903 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1904 return DAG.getFrameIndex(FI, getPointerTy());
1906 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1907 VA.getLocMemOffset(), isImmutable);
1908 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1909 return DAG.getLoad(ValVT, dl, Chain, FIN,
1910 MachinePointerInfo::getFixedStack(FI),
1911 false, false, false, 0);
1916 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1917 CallingConv::ID CallConv,
1919 const SmallVectorImpl<ISD::InputArg> &Ins,
1922 SmallVectorImpl<SDValue> &InVals)
1924 MachineFunction &MF = DAG.getMachineFunction();
1925 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1927 const Function* Fn = MF.getFunction();
1928 if (Fn->hasExternalLinkage() &&
1929 Subtarget->isTargetCygMing() &&
1930 Fn->getName() == "main")
1931 FuncInfo->setForceFramePointer(true);
1933 MachineFrameInfo *MFI = MF.getFrameInfo();
1934 bool Is64Bit = Subtarget->is64Bit();
1935 bool IsWindows = Subtarget->isTargetWindows();
1936 bool IsWin64 = Subtarget->isTargetWin64();
1938 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1939 "Var args not supported with calling convention fastcc, ghc or hipe");
1941 // Assign locations to all of the incoming arguments.
1942 SmallVector<CCValAssign, 16> ArgLocs;
1943 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1944 ArgLocs, *DAG.getContext());
1946 // Allocate shadow area for Win64
1948 CCInfo.AllocateStack(32, 8);
1951 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1953 unsigned LastVal = ~0U;
1955 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1956 CCValAssign &VA = ArgLocs[i];
1957 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1959 assert(VA.getValNo() != LastVal &&
1960 "Don't support value assigned to multiple locs yet");
1962 LastVal = VA.getValNo();
1964 if (VA.isRegLoc()) {
1965 EVT RegVT = VA.getLocVT();
1966 const TargetRegisterClass *RC;
1967 if (RegVT == MVT::i32)
1968 RC = &X86::GR32RegClass;
1969 else if (Is64Bit && RegVT == MVT::i64)
1970 RC = &X86::GR64RegClass;
1971 else if (RegVT == MVT::f32)
1972 RC = &X86::FR32RegClass;
1973 else if (RegVT == MVT::f64)
1974 RC = &X86::FR64RegClass;
1975 else if (RegVT.is256BitVector())
1976 RC = &X86::VR256RegClass;
1977 else if (RegVT.is128BitVector())
1978 RC = &X86::VR128RegClass;
1979 else if (RegVT == MVT::x86mmx)
1980 RC = &X86::VR64RegClass;
1982 llvm_unreachable("Unknown argument type!");
1984 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1985 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1987 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1988 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1990 if (VA.getLocInfo() == CCValAssign::SExt)
1991 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1992 DAG.getValueType(VA.getValVT()));
1993 else if (VA.getLocInfo() == CCValAssign::ZExt)
1994 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1995 DAG.getValueType(VA.getValVT()));
1996 else if (VA.getLocInfo() == CCValAssign::BCvt)
1997 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1999 if (VA.isExtInLoc()) {
2000 // Handle MMX values passed in XMM regs.
2001 if (RegVT.isVector())
2002 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2004 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2007 assert(VA.isMemLoc());
2008 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2011 // If value is passed via pointer - do a load.
2012 if (VA.getLocInfo() == CCValAssign::Indirect)
2013 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2014 MachinePointerInfo(), false, false, false, 0);
2016 InVals.push_back(ArgValue);
2019 // The x86-64 ABIs require that for returning structs by value we copy
2020 // the sret argument into %rax/%eax (depending on ABI) for the return.
2021 // Save the argument into a virtual register so that we can access it
2022 // from the return points.
2023 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2024 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2025 unsigned Reg = FuncInfo->getSRetReturnReg();
2027 MVT PtrTy = getPointerTy();
2028 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2029 FuncInfo->setSRetReturnReg(Reg);
2031 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2032 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2035 unsigned StackSize = CCInfo.getNextStackOffset();
2036 // Align stack specially for tail calls.
2037 if (FuncIsMadeTailCallSafe(CallConv,
2038 MF.getTarget().Options.GuaranteedTailCallOpt))
2039 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2041 // If the function takes variable number of arguments, make a frame index for
2042 // the start of the first vararg value... for expansion of llvm.va_start.
2044 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2045 CallConv != CallingConv::X86_ThisCall)) {
2046 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2049 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2051 // FIXME: We should really autogenerate these arrays
2052 static const uint16_t GPR64ArgRegsWin64[] = {
2053 X86::RCX, X86::RDX, X86::R8, X86::R9
2055 static const uint16_t GPR64ArgRegs64Bit[] = {
2056 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2058 static const uint16_t XMMArgRegs64Bit[] = {
2059 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2060 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2062 const uint16_t *GPR64ArgRegs;
2063 unsigned NumXMMRegs = 0;
2066 // The XMM registers which might contain var arg parameters are shadowed
2067 // in their paired GPR. So we only need to save the GPR to their home
2069 TotalNumIntRegs = 4;
2070 GPR64ArgRegs = GPR64ArgRegsWin64;
2072 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2073 GPR64ArgRegs = GPR64ArgRegs64Bit;
2075 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2078 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2081 bool NoImplicitFloatOps = Fn->getAttributes().
2082 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2083 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2084 "SSE register cannot be used when SSE is disabled!");
2085 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2086 NoImplicitFloatOps) &&
2087 "SSE register cannot be used when SSE is disabled!");
2088 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2089 !Subtarget->hasSSE1())
2090 // Kernel mode asks for SSE to be disabled, so don't push them
2092 TotalNumXMMRegs = 0;
2095 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2096 // Get to the caller-allocated home save location. Add 8 to account
2097 // for the return address.
2098 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2099 FuncInfo->setRegSaveFrameIndex(
2100 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2101 // Fixup to set vararg frame on shadow area (4 x i64).
2103 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2105 // For X86-64, if there are vararg parameters that are passed via
2106 // registers, then we must store them to their spots on the stack so
2107 // they may be loaded by deferencing the result of va_next.
2108 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2109 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2110 FuncInfo->setRegSaveFrameIndex(
2111 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2115 // Store the integer parameter registers.
2116 SmallVector<SDValue, 8> MemOps;
2117 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2119 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2120 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2121 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2122 DAG.getIntPtrConstant(Offset));
2123 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2124 &X86::GR64RegClass);
2125 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2127 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2128 MachinePointerInfo::getFixedStack(
2129 FuncInfo->getRegSaveFrameIndex(), Offset),
2131 MemOps.push_back(Store);
2135 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2136 // Now store the XMM (fp + vector) parameter registers.
2137 SmallVector<SDValue, 11> SaveXMMOps;
2138 SaveXMMOps.push_back(Chain);
2140 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2141 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2142 SaveXMMOps.push_back(ALVal);
2144 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2145 FuncInfo->getRegSaveFrameIndex()));
2146 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2147 FuncInfo->getVarArgsFPOffset()));
2149 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2150 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2151 &X86::VR128RegClass);
2152 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2153 SaveXMMOps.push_back(Val);
2155 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2157 &SaveXMMOps[0], SaveXMMOps.size()));
2160 if (!MemOps.empty())
2161 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2162 &MemOps[0], MemOps.size());
2166 // Some CCs need callee pop.
2167 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2168 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2169 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2171 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2172 // If this is an sret function, the return should pop the hidden pointer.
2173 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2174 argsAreStructReturn(Ins) == StackStructReturn)
2175 FuncInfo->setBytesToPopOnReturn(4);
2179 // RegSaveFrameIndex is X86-64 only.
2180 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2181 if (CallConv == CallingConv::X86_FastCall ||
2182 CallConv == CallingConv::X86_ThisCall)
2183 // fastcc functions can't have varargs.
2184 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2187 FuncInfo->setArgumentStackSize(StackSize);
2193 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2194 SDValue StackPtr, SDValue Arg,
2195 DebugLoc dl, SelectionDAG &DAG,
2196 const CCValAssign &VA,
2197 ISD::ArgFlagsTy Flags) const {
2198 unsigned LocMemOffset = VA.getLocMemOffset();
2199 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2200 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2201 if (Flags.isByVal())
2202 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2204 return DAG.getStore(Chain, dl, Arg, PtrOff,
2205 MachinePointerInfo::getStack(LocMemOffset),
2209 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2210 /// optimization is performed and it is required.
2212 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2213 SDValue &OutRetAddr, SDValue Chain,
2214 bool IsTailCall, bool Is64Bit,
2215 int FPDiff, DebugLoc dl) const {
2216 // Adjust the Return address stack slot.
2217 EVT VT = getPointerTy();
2218 OutRetAddr = getReturnAddressFrameIndex(DAG);
2220 // Load the "old" Return address.
2221 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2222 false, false, false, 0);
2223 return SDValue(OutRetAddr.getNode(), 1);
2226 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2227 /// optimization is performed and it is required (FPDiff!=0).
2229 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2230 SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2231 unsigned SlotSize, int FPDiff, DebugLoc dl) {
2232 // Store the return address to the appropriate stack slot.
2233 if (!FPDiff) return Chain;
2234 // Calculate the new stack slot for the return address.
2235 int NewReturnAddrFI =
2236 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2237 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2238 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2239 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2245 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2246 SmallVectorImpl<SDValue> &InVals) const {
2247 SelectionDAG &DAG = CLI.DAG;
2248 DebugLoc &dl = CLI.DL;
2249 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2250 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2251 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2252 SDValue Chain = CLI.Chain;
2253 SDValue Callee = CLI.Callee;
2254 CallingConv::ID CallConv = CLI.CallConv;
2255 bool &isTailCall = CLI.IsTailCall;
2256 bool isVarArg = CLI.IsVarArg;
2258 MachineFunction &MF = DAG.getMachineFunction();
2259 bool Is64Bit = Subtarget->is64Bit();
2260 bool IsWin64 = Subtarget->isTargetWin64();
2261 bool IsWindows = Subtarget->isTargetWindows();
2262 StructReturnType SR = callIsStructReturn(Outs);
2263 bool IsSibcall = false;
2265 if (MF.getTarget().Options.DisableTailCalls)
2269 // Check if it's really possible to do a tail call.
2270 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2271 isVarArg, SR != NotStructReturn,
2272 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2273 Outs, OutVals, Ins, DAG);
2275 // Sibcalls are automatically detected tailcalls which do not require
2277 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2284 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2285 "Var args not supported with calling convention fastcc, ghc or hipe");
2287 // Analyze operands of the call, assigning locations to each operand.
2288 SmallVector<CCValAssign, 16> ArgLocs;
2289 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2290 ArgLocs, *DAG.getContext());
2292 // Allocate shadow area for Win64
2294 CCInfo.AllocateStack(32, 8);
2297 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2299 // Get a count of how many bytes are to be pushed on the stack.
2300 unsigned NumBytes = CCInfo.getNextStackOffset();
2302 // This is a sibcall. The memory operands are available in caller's
2303 // own caller's stack.
2305 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2306 IsTailCallConvention(CallConv))
2307 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2310 if (isTailCall && !IsSibcall) {
2311 // Lower arguments at fp - stackoffset + fpdiff.
2312 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2313 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2315 FPDiff = NumBytesCallerPushed - NumBytes;
2317 // Set the delta of movement of the returnaddr stackslot.
2318 // But only set if delta is greater than previous delta.
2319 if (FPDiff < X86Info->getTCReturnAddrDelta())
2320 X86Info->setTCReturnAddrDelta(FPDiff);
2324 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2326 SDValue RetAddrFrIdx;
2327 // Load return address for tail calls.
2328 if (isTailCall && FPDiff)
2329 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2330 Is64Bit, FPDiff, dl);
2332 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2333 SmallVector<SDValue, 8> MemOpChains;
2336 // Walk the register/memloc assignments, inserting copies/loads. In the case
2337 // of tail call optimization arguments are handle later.
2338 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339 CCValAssign &VA = ArgLocs[i];
2340 EVT RegVT = VA.getLocVT();
2341 SDValue Arg = OutVals[i];
2342 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2343 bool isByVal = Flags.isByVal();
2345 // Promote the value if needed.
2346 switch (VA.getLocInfo()) {
2347 default: llvm_unreachable("Unknown loc info!");
2348 case CCValAssign::Full: break;
2349 case CCValAssign::SExt:
2350 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2352 case CCValAssign::ZExt:
2353 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2355 case CCValAssign::AExt:
2356 if (RegVT.is128BitVector()) {
2357 // Special case: passing MMX values in XMM registers.
2358 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2359 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2360 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2362 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2364 case CCValAssign::BCvt:
2365 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2367 case CCValAssign::Indirect: {
2368 // Store the argument.
2369 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2370 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2371 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2372 MachinePointerInfo::getFixedStack(FI),
2379 if (VA.isRegLoc()) {
2380 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2381 if (isVarArg && IsWin64) {
2382 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2383 // shadow reg if callee is a varargs function.
2384 unsigned ShadowReg = 0;
2385 switch (VA.getLocReg()) {
2386 case X86::XMM0: ShadowReg = X86::RCX; break;
2387 case X86::XMM1: ShadowReg = X86::RDX; break;
2388 case X86::XMM2: ShadowReg = X86::R8; break;
2389 case X86::XMM3: ShadowReg = X86::R9; break;
2392 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2394 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2395 assert(VA.isMemLoc());
2396 if (StackPtr.getNode() == 0)
2397 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2399 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2400 dl, DAG, VA, Flags));
2404 if (!MemOpChains.empty())
2405 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2406 &MemOpChains[0], MemOpChains.size());
2408 if (Subtarget->isPICStyleGOT()) {
2409 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2412 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2413 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2415 // If we are tail calling and generating PIC/GOT style code load the
2416 // address of the callee into ECX. The value in ecx is used as target of
2417 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2418 // for tail calls on PIC/GOT architectures. Normally we would just put the
2419 // address of GOT into ebx and then call target@PLT. But for tail calls
2420 // ebx would be restored (since ebx is callee saved) before jumping to the
2423 // Note: The actual moving to ECX is done further down.
2424 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2425 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2426 !G->getGlobal()->hasProtectedVisibility())
2427 Callee = LowerGlobalAddress(Callee, DAG);
2428 else if (isa<ExternalSymbolSDNode>(Callee))
2429 Callee = LowerExternalSymbol(Callee, DAG);
2433 if (Is64Bit && isVarArg && !IsWin64) {
2434 // From AMD64 ABI document:
2435 // For calls that may call functions that use varargs or stdargs
2436 // (prototype-less calls or calls to functions containing ellipsis (...) in
2437 // the declaration) %al is used as hidden argument to specify the number
2438 // of SSE registers used. The contents of %al do not need to match exactly
2439 // the number of registers, but must be an ubound on the number of SSE
2440 // registers used and is in the range 0 - 8 inclusive.
2442 // Count the number of XMM registers allocated.
2443 static const uint16_t XMMArgRegs[] = {
2444 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2445 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2447 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2448 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2449 && "SSE registers cannot be used when SSE is disabled");
2451 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2452 DAG.getConstant(NumXMMRegs, MVT::i8)));
2455 // For tail calls lower the arguments to the 'real' stack slot.
2457 // Force all the incoming stack arguments to be loaded from the stack
2458 // before any new outgoing arguments are stored to the stack, because the
2459 // outgoing stack slots may alias the incoming argument stack slots, and
2460 // the alias isn't otherwise explicit. This is slightly more conservative
2461 // than necessary, because it means that each store effectively depends
2462 // on every argument instead of just those arguments it would clobber.
2463 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2465 SmallVector<SDValue, 8> MemOpChains2;
2468 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2470 CCValAssign &VA = ArgLocs[i];
2473 assert(VA.isMemLoc());
2474 SDValue Arg = OutVals[i];
2475 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2476 // Create frame index.
2477 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2478 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2479 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2480 FIN = DAG.getFrameIndex(FI, getPointerTy());
2482 if (Flags.isByVal()) {
2483 // Copy relative to framepointer.
2484 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2485 if (StackPtr.getNode() == 0)
2486 StackPtr = DAG.getCopyFromReg(Chain, dl,
2487 RegInfo->getStackRegister(),
2489 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2491 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2495 // Store relative to framepointer.
2496 MemOpChains2.push_back(
2497 DAG.getStore(ArgChain, dl, Arg, FIN,
2498 MachinePointerInfo::getFixedStack(FI),
2504 if (!MemOpChains2.empty())
2505 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2506 &MemOpChains2[0], MemOpChains2.size());
2508 // Store the return address to the appropriate stack slot.
2509 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2510 getPointerTy(), RegInfo->getSlotSize(),
2514 // Build a sequence of copy-to-reg nodes chained together with token chain
2515 // and flag operands which copy the outgoing args into registers.
2517 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2518 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2519 RegsToPass[i].second, InFlag);
2520 InFlag = Chain.getValue(1);
2523 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2524 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2525 // In the 64-bit large code model, we have to make all calls
2526 // through a register, since the call instruction's 32-bit
2527 // pc-relative offset may not be large enough to hold the whole
2529 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2530 // If the callee is a GlobalAddress node (quite common, every direct call
2531 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2534 // We should use extra load for direct calls to dllimported functions in
2536 const GlobalValue *GV = G->getGlobal();
2537 if (!GV->hasDLLImportLinkage()) {
2538 unsigned char OpFlags = 0;
2539 bool ExtraLoad = false;
2540 unsigned WrapperKind = ISD::DELETED_NODE;
2542 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2543 // external symbols most go through the PLT in PIC mode. If the symbol
2544 // has hidden or protected visibility, or if it is static or local, then
2545 // we don't need to use the PLT - we can directly call it.
2546 if (Subtarget->isTargetELF() &&
2547 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2548 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2549 OpFlags = X86II::MO_PLT;
2550 } else if (Subtarget->isPICStyleStubAny() &&
2551 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2552 (!Subtarget->getTargetTriple().isMacOSX() ||
2553 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2554 // PC-relative references to external symbols should go through $stub,
2555 // unless we're building with the leopard linker or later, which
2556 // automatically synthesizes these stubs.
2557 OpFlags = X86II::MO_DARWIN_STUB;
2558 } else if (Subtarget->isPICStyleRIPRel() &&
2559 isa<Function>(GV) &&
2560 cast<Function>(GV)->getAttributes().
2561 hasAttribute(AttributeSet::FunctionIndex,
2562 Attribute::NonLazyBind)) {
2563 // If the function is marked as non-lazy, generate an indirect call
2564 // which loads from the GOT directly. This avoids runtime overhead
2565 // at the cost of eager binding (and one extra byte of encoding).
2566 OpFlags = X86II::MO_GOTPCREL;
2567 WrapperKind = X86ISD::WrapperRIP;
2571 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2572 G->getOffset(), OpFlags);
2574 // Add a wrapper if needed.
2575 if (WrapperKind != ISD::DELETED_NODE)
2576 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2577 // Add extra indirection if needed.
2579 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2580 MachinePointerInfo::getGOT(),
2581 false, false, false, 0);
2583 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2584 unsigned char OpFlags = 0;
2586 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2587 // external symbols should go through the PLT.
2588 if (Subtarget->isTargetELF() &&
2589 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2590 OpFlags = X86II::MO_PLT;
2591 } else if (Subtarget->isPICStyleStubAny() &&
2592 (!Subtarget->getTargetTriple().isMacOSX() ||
2593 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2594 // PC-relative references to external symbols should go through $stub,
2595 // unless we're building with the leopard linker or later, which
2596 // automatically synthesizes these stubs.
2597 OpFlags = X86II::MO_DARWIN_STUB;
2600 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2604 // Returns a chain & a flag for retval copy to use.
2605 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2606 SmallVector<SDValue, 8> Ops;
2608 if (!IsSibcall && isTailCall) {
2609 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2610 DAG.getIntPtrConstant(0, true), InFlag);
2611 InFlag = Chain.getValue(1);
2614 Ops.push_back(Chain);
2615 Ops.push_back(Callee);
2618 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2620 // Add argument registers to the end of the list so that they are known live
2622 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2623 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2624 RegsToPass[i].second.getValueType()));
2626 // Add a register mask operand representing the call-preserved registers.
2627 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2628 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2629 assert(Mask && "Missing call preserved mask for calling convention");
2630 Ops.push_back(DAG.getRegisterMask(Mask));
2632 if (InFlag.getNode())
2633 Ops.push_back(InFlag);
2637 //// If this is the first return lowered for this function, add the regs
2638 //// to the liveout set for the function.
2639 // This isn't right, although it's probably harmless on x86; liveouts
2640 // should be computed from returns not tail calls. Consider a void
2641 // function making a tail call to a function returning int.
2642 return DAG.getNode(X86ISD::TC_RETURN, dl,
2643 NodeTys, &Ops[0], Ops.size());
2646 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2647 InFlag = Chain.getValue(1);
2649 // Create the CALLSEQ_END node.
2650 unsigned NumBytesForCalleeToPush;
2651 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2652 getTargetMachine().Options.GuaranteedTailCallOpt))
2653 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2654 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2655 SR == StackStructReturn)
2656 // If this is a call to a struct-return function, the callee
2657 // pops the hidden struct pointer, so we have to push it back.
2658 // This is common for Darwin/X86, Linux & Mingw32 targets.
2659 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2660 NumBytesForCalleeToPush = 4;
2662 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2664 // Returns a flag for retval copy to use.
2666 Chain = DAG.getCALLSEQ_END(Chain,
2667 DAG.getIntPtrConstant(NumBytes, true),
2668 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2671 InFlag = Chain.getValue(1);
2674 // Handle result values, copying them out of physregs into vregs that we
2676 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2677 Ins, dl, DAG, InVals);
2680 //===----------------------------------------------------------------------===//
2681 // Fast Calling Convention (tail call) implementation
2682 //===----------------------------------------------------------------------===//
2684 // Like std call, callee cleans arguments, convention except that ECX is
2685 // reserved for storing the tail called function address. Only 2 registers are
2686 // free for argument passing (inreg). Tail call optimization is performed
2688 // * tailcallopt is enabled
2689 // * caller/callee are fastcc
2690 // On X86_64 architecture with GOT-style position independent code only local
2691 // (within module) calls are supported at the moment.
2692 // To keep the stack aligned according to platform abi the function
2693 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2694 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2695 // If a tail called function callee has more arguments than the caller the
2696 // caller needs to make sure that there is room to move the RETADDR to. This is
2697 // achieved by reserving an area the size of the argument delta right after the
2698 // original REtADDR, but before the saved framepointer or the spilled registers
2699 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2711 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2712 /// for a 16 byte align requirement.
2714 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2715 SelectionDAG& DAG) const {
2716 MachineFunction &MF = DAG.getMachineFunction();
2717 const TargetMachine &TM = MF.getTarget();
2718 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2719 unsigned StackAlignment = TFI.getStackAlignment();
2720 uint64_t AlignMask = StackAlignment - 1;
2721 int64_t Offset = StackSize;
2722 unsigned SlotSize = RegInfo->getSlotSize();
2723 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2724 // Number smaller than 12 so just add the difference.
2725 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2727 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2728 Offset = ((~AlignMask) & Offset) + StackAlignment +
2729 (StackAlignment-SlotSize);
2734 /// MatchingStackOffset - Return true if the given stack call argument is
2735 /// already available in the same position (relatively) of the caller's
2736 /// incoming argument stack.
2738 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2739 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2740 const X86InstrInfo *TII) {
2741 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2743 if (Arg.getOpcode() == ISD::CopyFromReg) {
2744 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2745 if (!TargetRegisterInfo::isVirtualRegister(VR))
2747 MachineInstr *Def = MRI->getVRegDef(VR);
2750 if (!Flags.isByVal()) {
2751 if (!TII->isLoadFromStackSlot(Def, FI))
2754 unsigned Opcode = Def->getOpcode();
2755 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2756 Def->getOperand(1).isFI()) {
2757 FI = Def->getOperand(1).getIndex();
2758 Bytes = Flags.getByValSize();
2762 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2763 if (Flags.isByVal())
2764 // ByVal argument is passed in as a pointer but it's now being
2765 // dereferenced. e.g.
2766 // define @foo(%struct.X* %A) {
2767 // tail call @bar(%struct.X* byval %A)
2770 SDValue Ptr = Ld->getBasePtr();
2771 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2774 FI = FINode->getIndex();
2775 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2776 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2777 FI = FINode->getIndex();
2778 Bytes = Flags.getByValSize();
2782 assert(FI != INT_MAX);
2783 if (!MFI->isFixedObjectIndex(FI))
2785 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2788 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2789 /// for tail call optimization. Targets which want to do tail call
2790 /// optimization should implement this function.
2792 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2793 CallingConv::ID CalleeCC,
2795 bool isCalleeStructRet,
2796 bool isCallerStructRet,
2798 const SmallVectorImpl<ISD::OutputArg> &Outs,
2799 const SmallVectorImpl<SDValue> &OutVals,
2800 const SmallVectorImpl<ISD::InputArg> &Ins,
2801 SelectionDAG& DAG) const {
2802 if (!IsTailCallConvention(CalleeCC) &&
2803 CalleeCC != CallingConv::C)
2806 // If -tailcallopt is specified, make fastcc functions tail-callable.
2807 const MachineFunction &MF = DAG.getMachineFunction();
2808 const Function *CallerF = DAG.getMachineFunction().getFunction();
2810 // If the function return type is x86_fp80 and the callee return type is not,
2811 // then the FP_EXTEND of the call result is not a nop. It's not safe to
2812 // perform a tailcall optimization here.
2813 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2816 CallingConv::ID CallerCC = CallerF->getCallingConv();
2817 bool CCMatch = CallerCC == CalleeCC;
2819 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2820 if (IsTailCallConvention(CalleeCC) && CCMatch)
2825 // Look for obvious safe cases to perform tail call optimization that do not
2826 // require ABI changes. This is what gcc calls sibcall.
2828 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2829 // emit a special epilogue.
2830 if (RegInfo->needsStackRealignment(MF))
2833 // Also avoid sibcall optimization if either caller or callee uses struct
2834 // return semantics.
2835 if (isCalleeStructRet || isCallerStructRet)
2838 // An stdcall caller is expected to clean up its arguments; the callee
2839 // isn't going to do that.
2840 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2843 // Do not sibcall optimize vararg calls unless all arguments are passed via
2845 if (isVarArg && !Outs.empty()) {
2847 // Optimizing for varargs on Win64 is unlikely to be safe without
2848 // additional testing.
2849 if (Subtarget->isTargetWin64())
2852 SmallVector<CCValAssign, 16> ArgLocs;
2853 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2854 getTargetMachine(), ArgLocs, *DAG.getContext());
2856 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2857 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2858 if (!ArgLocs[i].isRegLoc())
2862 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2863 // stack. Therefore, if it's not used by the call it is not safe to optimize
2864 // this into a sibcall.
2865 bool Unused = false;
2866 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2873 SmallVector<CCValAssign, 16> RVLocs;
2874 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2875 getTargetMachine(), RVLocs, *DAG.getContext());
2876 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2877 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2878 CCValAssign &VA = RVLocs[i];
2879 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2884 // If the calling conventions do not match, then we'd better make sure the
2885 // results are returned in the same way as what the caller expects.
2887 SmallVector<CCValAssign, 16> RVLocs1;
2888 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2889 getTargetMachine(), RVLocs1, *DAG.getContext());
2890 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2892 SmallVector<CCValAssign, 16> RVLocs2;
2893 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2894 getTargetMachine(), RVLocs2, *DAG.getContext());
2895 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2897 if (RVLocs1.size() != RVLocs2.size())
2899 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2900 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2902 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2904 if (RVLocs1[i].isRegLoc()) {
2905 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2908 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2914 // If the callee takes no arguments then go on to check the results of the
2916 if (!Outs.empty()) {
2917 // Check if stack adjustment is needed. For now, do not do this if any
2918 // argument is passed on the stack.
2919 SmallVector<CCValAssign, 16> ArgLocs;
2920 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2921 getTargetMachine(), ArgLocs, *DAG.getContext());
2923 // Allocate shadow area for Win64
2924 if (Subtarget->isTargetWin64()) {
2925 CCInfo.AllocateStack(32, 8);
2928 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2929 if (CCInfo.getNextStackOffset()) {
2930 MachineFunction &MF = DAG.getMachineFunction();
2931 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2934 // Check if the arguments are already laid out in the right way as
2935 // the caller's fixed stack objects.
2936 MachineFrameInfo *MFI = MF.getFrameInfo();
2937 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2938 const X86InstrInfo *TII =
2939 ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2940 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941 CCValAssign &VA = ArgLocs[i];
2942 SDValue Arg = OutVals[i];
2943 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2944 if (VA.getLocInfo() == CCValAssign::Indirect)
2946 if (!VA.isRegLoc()) {
2947 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2954 // If the tailcall address may be in a register, then make sure it's
2955 // possible to register allocate for it. In 32-bit, the call address can
2956 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2957 // callee-saved registers are restored. These happen to be the same
2958 // registers used to pass 'inreg' arguments so watch out for those.
2959 if (!Subtarget->is64Bit() &&
2960 !isa<GlobalAddressSDNode>(Callee) &&
2961 !isa<ExternalSymbolSDNode>(Callee)) {
2962 unsigned NumInRegs = 0;
2963 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2964 CCValAssign &VA = ArgLocs[i];
2967 unsigned Reg = VA.getLocReg();
2970 case X86::EAX: case X86::EDX: case X86::ECX:
2971 if (++NumInRegs == 3)
2983 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
2984 const TargetLibraryInfo *libInfo) const {
2985 return X86::createFastISel(funcInfo, libInfo);
2988 //===----------------------------------------------------------------------===//
2989 // Other Lowering Hooks
2990 //===----------------------------------------------------------------------===//
2992 static bool MayFoldLoad(SDValue Op) {
2993 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2996 static bool MayFoldIntoStore(SDValue Op) {
2997 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3000 static bool isTargetShuffle(unsigned Opcode) {
3002 default: return false;
3003 case X86ISD::PSHUFD:
3004 case X86ISD::PSHUFHW:
3005 case X86ISD::PSHUFLW:
3007 case X86ISD::PALIGN:
3008 case X86ISD::MOVLHPS:
3009 case X86ISD::MOVLHPD:
3010 case X86ISD::MOVHLPS:
3011 case X86ISD::MOVLPS:
3012 case X86ISD::MOVLPD:
3013 case X86ISD::MOVSHDUP:
3014 case X86ISD::MOVSLDUP:
3015 case X86ISD::MOVDDUP:
3018 case X86ISD::UNPCKL:
3019 case X86ISD::UNPCKH:
3020 case X86ISD::VPERMILP:
3021 case X86ISD::VPERM2X128:
3022 case X86ISD::VPERMI:
3027 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3028 SDValue V1, SelectionDAG &DAG) {
3030 default: llvm_unreachable("Unknown x86 shuffle node");
3031 case X86ISD::MOVSHDUP:
3032 case X86ISD::MOVSLDUP:
3033 case X86ISD::MOVDDUP:
3034 return DAG.getNode(Opc, dl, VT, V1);
3038 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3039 SDValue V1, unsigned TargetMask,
3040 SelectionDAG &DAG) {
3042 default: llvm_unreachable("Unknown x86 shuffle node");
3043 case X86ISD::PSHUFD:
3044 case X86ISD::PSHUFHW:
3045 case X86ISD::PSHUFLW:
3046 case X86ISD::VPERMILP:
3047 case X86ISD::VPERMI:
3048 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3052 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3053 SDValue V1, SDValue V2, unsigned TargetMask,
3054 SelectionDAG &DAG) {
3056 default: llvm_unreachable("Unknown x86 shuffle node");
3057 case X86ISD::PALIGN:
3059 case X86ISD::VPERM2X128:
3060 return DAG.getNode(Opc, dl, VT, V1, V2,
3061 DAG.getConstant(TargetMask, MVT::i8));
3065 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3066 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3068 default: llvm_unreachable("Unknown x86 shuffle node");
3069 case X86ISD::MOVLHPS:
3070 case X86ISD::MOVLHPD:
3071 case X86ISD::MOVHLPS:
3072 case X86ISD::MOVLPS:
3073 case X86ISD::MOVLPD:
3076 case X86ISD::UNPCKL:
3077 case X86ISD::UNPCKH:
3078 return DAG.getNode(Opc, dl, VT, V1, V2);
3082 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3083 MachineFunction &MF = DAG.getMachineFunction();
3084 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3085 int ReturnAddrIndex = FuncInfo->getRAIndex();
3087 if (ReturnAddrIndex == 0) {
3088 // Set up a frame object for the return address.
3089 unsigned SlotSize = RegInfo->getSlotSize();
3090 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3092 FuncInfo->setRAIndex(ReturnAddrIndex);
3095 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3098 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3099 bool hasSymbolicDisplacement) {
3100 // Offset should fit into 32 bit immediate field.
3101 if (!isInt<32>(Offset))
3104 // If we don't have a symbolic displacement - we don't have any extra
3106 if (!hasSymbolicDisplacement)
3109 // FIXME: Some tweaks might be needed for medium code model.
3110 if (M != CodeModel::Small && M != CodeModel::Kernel)
3113 // For small code model we assume that latest object is 16MB before end of 31
3114 // bits boundary. We may also accept pretty large negative constants knowing
3115 // that all objects are in the positive half of address space.
3116 if (M == CodeModel::Small && Offset < 16*1024*1024)
3119 // For kernel code model we know that all object resist in the negative half
3120 // of 32bits address space. We may not accept negative offsets, since they may
3121 // be just off and we may accept pretty large positive ones.
3122 if (M == CodeModel::Kernel && Offset > 0)
3128 /// isCalleePop - Determines whether the callee is required to pop its
3129 /// own arguments. Callee pop is necessary to support tail calls.
3130 bool X86::isCalleePop(CallingConv::ID CallingConv,
3131 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3135 switch (CallingConv) {
3138 case CallingConv::X86_StdCall:
3140 case CallingConv::X86_FastCall:
3142 case CallingConv::X86_ThisCall:
3144 case CallingConv::Fast:
3146 case CallingConv::GHC:
3148 case CallingConv::HiPE:
3153 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3154 /// specific condition code, returning the condition code and the LHS/RHS of the
3155 /// comparison to make.
3156 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3157 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3159 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3160 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3161 // X > -1 -> X == 0, jump !sign.
3162 RHS = DAG.getConstant(0, RHS.getValueType());
3163 return X86::COND_NS;
3165 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3166 // X < 0 -> X == 0, jump on sign.
3169 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3171 RHS = DAG.getConstant(0, RHS.getValueType());
3172 return X86::COND_LE;
3176 switch (SetCCOpcode) {
3177 default: llvm_unreachable("Invalid integer condition!");
3178 case ISD::SETEQ: return X86::COND_E;
3179 case ISD::SETGT: return X86::COND_G;
3180 case ISD::SETGE: return X86::COND_GE;
3181 case ISD::SETLT: return X86::COND_L;
3182 case ISD::SETLE: return X86::COND_LE;
3183 case ISD::SETNE: return X86::COND_NE;
3184 case ISD::SETULT: return X86::COND_B;
3185 case ISD::SETUGT: return X86::COND_A;
3186 case ISD::SETULE: return X86::COND_BE;
3187 case ISD::SETUGE: return X86::COND_AE;
3191 // First determine if it is required or is profitable to flip the operands.
3193 // If LHS is a foldable load, but RHS is not, flip the condition.
3194 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3195 !ISD::isNON_EXTLoad(RHS.getNode())) {
3196 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3197 std::swap(LHS, RHS);
3200 switch (SetCCOpcode) {
3206 std::swap(LHS, RHS);
3210 // On a floating point condition, the flags are set as follows:
3212 // 0 | 0 | 0 | X > Y
3213 // 0 | 0 | 1 | X < Y
3214 // 1 | 0 | 0 | X == Y
3215 // 1 | 1 | 1 | unordered
3216 switch (SetCCOpcode) {
3217 default: llvm_unreachable("Condcode should be pre-legalized away");
3219 case ISD::SETEQ: return X86::COND_E;
3220 case ISD::SETOLT: // flipped
3222 case ISD::SETGT: return X86::COND_A;
3223 case ISD::SETOLE: // flipped
3225 case ISD::SETGE: return X86::COND_AE;
3226 case ISD::SETUGT: // flipped
3228 case ISD::SETLT: return X86::COND_B;
3229 case ISD::SETUGE: // flipped
3231 case ISD::SETLE: return X86::COND_BE;
3233 case ISD::SETNE: return X86::COND_NE;
3234 case ISD::SETUO: return X86::COND_P;
3235 case ISD::SETO: return X86::COND_NP;
3237 case ISD::SETUNE: return X86::COND_INVALID;
3241 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3242 /// code. Current x86 isa includes the following FP cmov instructions:
3243 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3244 static bool hasFPCMov(unsigned X86CC) {
3260 /// isFPImmLegal - Returns true if the target can instruction select the
3261 /// specified FP immediate natively. If false, the legalizer will
3262 /// materialize the FP immediate as a load from a constant pool.
3263 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3264 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3265 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3271 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3272 /// the specified range (L, H].
3273 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3274 return (Val < 0) || (Val >= Low && Val < Hi);
3277 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3278 /// specified value.
3279 static bool isUndefOrEqual(int Val, int CmpVal) {
3280 return (Val < 0 || Val == CmpVal);
3283 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3284 /// from position Pos and ending in Pos+Size, falls within the specified
3285 /// sequential range (L, L+Pos]. or is undef.
3286 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3287 unsigned Pos, unsigned Size, int Low) {
3288 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3289 if (!isUndefOrEqual(Mask[i], Low))
3294 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3295 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3296 /// the second operand.
3297 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3298 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3299 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3300 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3301 return (Mask[0] < 2 && Mask[1] < 2);
3305 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3306 /// is suitable for input to PSHUFHW.
3307 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3308 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3311 // Lower quadword copied in order or undef.
3312 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3315 // Upper quadword shuffled.
3316 for (unsigned i = 4; i != 8; ++i)
3317 if (!isUndefOrInRange(Mask[i], 4, 8))
3320 if (VT == MVT::v16i16) {
3321 // Lower quadword copied in order or undef.
3322 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3325 // Upper quadword shuffled.
3326 for (unsigned i = 12; i != 16; ++i)
3327 if (!isUndefOrInRange(Mask[i], 12, 16))
3334 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3335 /// is suitable for input to PSHUFLW.
3336 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3337 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3340 // Upper quadword copied in order.
3341 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3344 // Lower quadword shuffled.
3345 for (unsigned i = 0; i != 4; ++i)
3346 if (!isUndefOrInRange(Mask[i], 0, 4))
3349 if (VT == MVT::v16i16) {
3350 // Upper quadword copied in order.
3351 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3354 // Lower quadword shuffled.
3355 for (unsigned i = 8; i != 12; ++i)
3356 if (!isUndefOrInRange(Mask[i], 8, 12))
3363 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3364 /// is suitable for input to PALIGNR.
3365 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3366 const X86Subtarget *Subtarget) {
3367 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3368 (VT.is256BitVector() && !Subtarget->hasInt256()))
3371 unsigned NumElts = VT.getVectorNumElements();
3372 unsigned NumLanes = VT.getSizeInBits()/128;
3373 unsigned NumLaneElts = NumElts/NumLanes;
3375 // Do not handle 64-bit element shuffles with palignr.
3376 if (NumLaneElts == 2)
3379 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3381 for (i = 0; i != NumLaneElts; ++i) {
3386 // Lane is all undef, go to next lane
3387 if (i == NumLaneElts)
3390 int Start = Mask[i+l];
3392 // Make sure its in this lane in one of the sources
3393 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3394 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3397 // If not lane 0, then we must match lane 0
3398 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3401 // Correct second source to be contiguous with first source
3402 if (Start >= (int)NumElts)
3403 Start -= NumElts - NumLaneElts;
3405 // Make sure we're shifting in the right direction.
3406 if (Start <= (int)(i+l))
3411 // Check the rest of the elements to see if they are consecutive.
3412 for (++i; i != NumLaneElts; ++i) {
3413 int Idx = Mask[i+l];
3415 // Make sure its in this lane
3416 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3417 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3420 // If not lane 0, then we must match lane 0
3421 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3424 if (Idx >= (int)NumElts)
3425 Idx -= NumElts - NumLaneElts;
3427 if (!isUndefOrEqual(Idx, Start+i))
3436 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3437 /// the two vector operands have swapped position.
3438 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3439 unsigned NumElems) {
3440 for (unsigned i = 0; i != NumElems; ++i) {
3444 else if (idx < (int)NumElems)
3445 Mask[i] = idx + NumElems;
3447 Mask[i] = idx - NumElems;
3451 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3452 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3453 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3454 /// reverse of what x86 shuffles want.
3455 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3456 bool Commuted = false) {
3457 if (!HasFp256 && VT.is256BitVector())
3460 unsigned NumElems = VT.getVectorNumElements();
3461 unsigned NumLanes = VT.getSizeInBits()/128;
3462 unsigned NumLaneElems = NumElems/NumLanes;
3464 if (NumLaneElems != 2 && NumLaneElems != 4)
3467 // VSHUFPSY divides the resulting vector into 4 chunks.
3468 // The sources are also splitted into 4 chunks, and each destination
3469 // chunk must come from a different source chunk.
3471 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3472 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3474 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3475 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3477 // VSHUFPDY divides the resulting vector into 4 chunks.
3478 // The sources are also splitted into 4 chunks, and each destination
3479 // chunk must come from a different source chunk.
3481 // SRC1 => X3 X2 X1 X0
3482 // SRC2 => Y3 Y2 Y1 Y0
3484 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3486 unsigned HalfLaneElems = NumLaneElems/2;
3487 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3488 for (unsigned i = 0; i != NumLaneElems; ++i) {
3489 int Idx = Mask[i+l];
3490 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3491 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3493 // For VSHUFPSY, the mask of the second half must be the same as the
3494 // first but with the appropriate offsets. This works in the same way as
3495 // VPERMILPS works with masks.
3496 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3498 if (!isUndefOrEqual(Idx, Mask[i]+l))
3506 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3507 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3508 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3509 if (!VT.is128BitVector())
3512 unsigned NumElems = VT.getVectorNumElements();
3517 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3518 return isUndefOrEqual(Mask[0], 6) &&
3519 isUndefOrEqual(Mask[1], 7) &&
3520 isUndefOrEqual(Mask[2], 2) &&
3521 isUndefOrEqual(Mask[3], 3);
3524 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3525 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3527 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3528 if (!VT.is128BitVector())
3531 unsigned NumElems = VT.getVectorNumElements();
3536 return isUndefOrEqual(Mask[0], 2) &&
3537 isUndefOrEqual(Mask[1], 3) &&
3538 isUndefOrEqual(Mask[2], 2) &&
3539 isUndefOrEqual(Mask[3], 3);
3542 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3543 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3544 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3545 if (!VT.is128BitVector())
3548 unsigned NumElems = VT.getVectorNumElements();
3550 if (NumElems != 2 && NumElems != 4)
3553 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3554 if (!isUndefOrEqual(Mask[i], i + NumElems))
3557 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3558 if (!isUndefOrEqual(Mask[i], i))
3564 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3565 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3566 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3567 if (!VT.is128BitVector())
3570 unsigned NumElems = VT.getVectorNumElements();
3572 if (NumElems != 2 && NumElems != 4)
3575 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3576 if (!isUndefOrEqual(Mask[i], i))
3579 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3580 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3587 // Some special combinations that can be optimized.
3590 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3591 SelectionDAG &DAG) {
3592 MVT VT = SVOp->getValueType(0).getSimpleVT();
3593 DebugLoc dl = SVOp->getDebugLoc();
3595 if (VT != MVT::v8i32 && VT != MVT::v8f32)
3598 ArrayRef<int> Mask = SVOp->getMask();
3600 // These are the special masks that may be optimized.
3601 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3602 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
3603 bool MatchEvenMask = true;
3604 bool MatchOddMask = true;
3605 for (int i=0; i<8; ++i) {
3606 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3607 MatchEvenMask = false;
3608 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3609 MatchOddMask = false;
3612 if (!MatchEvenMask && !MatchOddMask)
3615 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3617 SDValue Op0 = SVOp->getOperand(0);
3618 SDValue Op1 = SVOp->getOperand(1);
3620 if (MatchEvenMask) {
3621 // Shift the second operand right to 32 bits.
3622 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3623 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3625 // Shift the first operand left to 32 bits.
3626 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3627 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3629 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3630 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3633 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3634 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3635 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3636 bool HasInt256, bool V2IsSplat = false) {
3637 unsigned NumElts = VT.getVectorNumElements();
3639 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3640 "Unsupported vector type for unpckh");
3642 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3643 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3646 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3647 // independently on 128-bit lanes.
3648 unsigned NumLanes = VT.getSizeInBits()/128;
3649 unsigned NumLaneElts = NumElts/NumLanes;
3651 for (unsigned l = 0; l != NumLanes; ++l) {
3652 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3653 i != (l+1)*NumLaneElts;
3656 int BitI1 = Mask[i+1];
3657 if (!isUndefOrEqual(BitI, j))
3660 if (!isUndefOrEqual(BitI1, NumElts))
3663 if (!isUndefOrEqual(BitI1, j + NumElts))
3672 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3673 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3674 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3675 bool HasInt256, bool V2IsSplat = false) {
3676 unsigned NumElts = VT.getVectorNumElements();
3678 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3679 "Unsupported vector type for unpckh");
3681 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3682 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3685 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3686 // independently on 128-bit lanes.
3687 unsigned NumLanes = VT.getSizeInBits()/128;
3688 unsigned NumLaneElts = NumElts/NumLanes;
3690 for (unsigned l = 0; l != NumLanes; ++l) {
3691 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3692 i != (l+1)*NumLaneElts; i += 2, ++j) {
3694 int BitI1 = Mask[i+1];
3695 if (!isUndefOrEqual(BitI, j))
3698 if (isUndefOrEqual(BitI1, NumElts))
3701 if (!isUndefOrEqual(BitI1, j+NumElts))
3709 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3710 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3712 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3713 unsigned NumElts = VT.getVectorNumElements();
3714 bool Is256BitVec = VT.is256BitVector();
3716 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3717 "Unsupported vector type for unpckh");
3719 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3720 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3723 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3724 // FIXME: Need a better way to get rid of this, there's no latency difference
3725 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3726 // the former later. We should also remove the "_undef" special mask.
3727 if (NumElts == 4 && Is256BitVec)
3730 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3731 // independently on 128-bit lanes.
3732 unsigned NumLanes = VT.getSizeInBits()/128;
3733 unsigned NumLaneElts = NumElts/NumLanes;
3735 for (unsigned l = 0; l != NumLanes; ++l) {
3736 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3737 i != (l+1)*NumLaneElts;
3740 int BitI1 = Mask[i+1];
3742 if (!isUndefOrEqual(BitI, j))
3744 if (!isUndefOrEqual(BitI1, j))
3752 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3753 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3755 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3756 unsigned NumElts = VT.getVectorNumElements();
3758 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3759 "Unsupported vector type for unpckh");
3761 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3762 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3765 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3766 // independently on 128-bit lanes.
3767 unsigned NumLanes = VT.getSizeInBits()/128;
3768 unsigned NumLaneElts = NumElts/NumLanes;
3770 for (unsigned l = 0; l != NumLanes; ++l) {
3771 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3772 i != (l+1)*NumLaneElts; i += 2, ++j) {
3774 int BitI1 = Mask[i+1];
3775 if (!isUndefOrEqual(BitI, j))
3777 if (!isUndefOrEqual(BitI1, j))
3784 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3785 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3786 /// MOVSD, and MOVD, i.e. setting the lowest element.
3787 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3788 if (VT.getVectorElementType().getSizeInBits() < 32)
3790 if (!VT.is128BitVector())
3793 unsigned NumElts = VT.getVectorNumElements();
3795 if (!isUndefOrEqual(Mask[0], NumElts))
3798 for (unsigned i = 1; i != NumElts; ++i)
3799 if (!isUndefOrEqual(Mask[i], i))
3805 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3806 /// as permutations between 128-bit chunks or halves. As an example: this
3808 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3809 /// The first half comes from the second half of V1 and the second half from the
3810 /// the second half of V2.
3811 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3812 if (!HasFp256 || !VT.is256BitVector())
3815 // The shuffle result is divided into half A and half B. In total the two
3816 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3817 // B must come from C, D, E or F.
3818 unsigned HalfSize = VT.getVectorNumElements()/2;
3819 bool MatchA = false, MatchB = false;
3821 // Check if A comes from one of C, D, E, F.
3822 for (unsigned Half = 0; Half != 4; ++Half) {
3823 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3829 // Check if B comes from one of C, D, E, F.
3830 for (unsigned Half = 0; Half != 4; ++Half) {
3831 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3837 return MatchA && MatchB;
3840 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3841 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3842 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3843 MVT VT = SVOp->getValueType(0).getSimpleVT();
3845 unsigned HalfSize = VT.getVectorNumElements()/2;
3847 unsigned FstHalf = 0, SndHalf = 0;
3848 for (unsigned i = 0; i < HalfSize; ++i) {
3849 if (SVOp->getMaskElt(i) > 0) {
3850 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3854 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3855 if (SVOp->getMaskElt(i) > 0) {
3856 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3861 return (FstHalf | (SndHalf << 4));
3864 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3865 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3866 /// Note that VPERMIL mask matching is different depending whether theunderlying
3867 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3868 /// to the same elements of the low, but to the higher half of the source.
3869 /// In VPERMILPD the two lanes could be shuffled independently of each other
3870 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3871 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3875 unsigned NumElts = VT.getVectorNumElements();
3876 // Only match 256-bit with 32/64-bit types
3877 if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3880 unsigned NumLanes = VT.getSizeInBits()/128;
3881 unsigned LaneSize = NumElts/NumLanes;
3882 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3883 for (unsigned i = 0; i != LaneSize; ++i) {
3884 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3886 if (NumElts != 8 || l == 0)
3888 // VPERMILPS handling
3891 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3899 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3900 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3901 /// element of vector 2 and the other elements to come from vector 1 in order.
3902 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3903 bool V2IsSplat = false, bool V2IsUndef = false) {
3904 if (!VT.is128BitVector())
3907 unsigned NumOps = VT.getVectorNumElements();
3908 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3911 if (!isUndefOrEqual(Mask[0], 0))
3914 for (unsigned i = 1; i != NumOps; ++i)
3915 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3916 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3917 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3923 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3925 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3926 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3927 const X86Subtarget *Subtarget) {
3928 if (!Subtarget->hasSSE3())
3931 unsigned NumElems = VT.getVectorNumElements();
3933 if ((VT.is128BitVector() && NumElems != 4) ||
3934 (VT.is256BitVector() && NumElems != 8))
3937 // "i+1" is the value the indexed mask element must have
3938 for (unsigned i = 0; i != NumElems; i += 2)
3939 if (!isUndefOrEqual(Mask[i], i+1) ||
3940 !isUndefOrEqual(Mask[i+1], i+1))
3946 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3947 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3948 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3949 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3950 const X86Subtarget *Subtarget) {
3951 if (!Subtarget->hasSSE3())
3954 unsigned NumElems = VT.getVectorNumElements();
3956 if ((VT.is128BitVector() && NumElems != 4) ||
3957 (VT.is256BitVector() && NumElems != 8))
3960 // "i" is the value the indexed mask element must have
3961 for (unsigned i = 0; i != NumElems; i += 2)
3962 if (!isUndefOrEqual(Mask[i], i) ||
3963 !isUndefOrEqual(Mask[i+1], i))
3969 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to 256-bit
3971 /// version of MOVDDUP.
3972 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3973 if (!HasFp256 || !VT.is256BitVector())
3976 unsigned NumElts = VT.getVectorNumElements();
3980 for (unsigned i = 0; i != NumElts/2; ++i)
3981 if (!isUndefOrEqual(Mask[i], 0))
3983 for (unsigned i = NumElts/2; i != NumElts; ++i)
3984 if (!isUndefOrEqual(Mask[i], NumElts/2))
3989 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3990 /// specifies a shuffle of elements that is suitable for input to 128-bit
3991 /// version of MOVDDUP.
3992 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3993 if (!VT.is128BitVector())
3996 unsigned e = VT.getVectorNumElements() / 2;
3997 for (unsigned i = 0; i != e; ++i)
3998 if (!isUndefOrEqual(Mask[i], i))
4000 for (unsigned i = 0; i != e; ++i)
4001 if (!isUndefOrEqual(Mask[e+i], i))
4006 /// isVEXTRACTF128Index - Return true if the specified
4007 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4008 /// suitable for input to VEXTRACTF128.
4009 bool X86::isVEXTRACTF128Index(SDNode *N) {
4010 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4013 // The index should be aligned on a 128-bit boundary.
4015 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4017 MVT VT = N->getValueType(0).getSimpleVT();
4018 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4019 bool Result = (Index * ElSize) % 128 == 0;
4024 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4027 bool X86::isVINSERTF128Index(SDNode *N) {
4028 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4031 // The index should be aligned on a 128-bit boundary.
4033 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4035 MVT VT = N->getValueType(0).getSimpleVT();
4036 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4037 bool Result = (Index * ElSize) % 128 == 0;
4042 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4043 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4044 /// Handles 128-bit and 256-bit.
4045 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4046 MVT VT = N->getValueType(0).getSimpleVT();
4048 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4049 "Unsupported vector type for PSHUF/SHUFP");
4051 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4052 // independently on 128-bit lanes.
4053 unsigned NumElts = VT.getVectorNumElements();
4054 unsigned NumLanes = VT.getSizeInBits()/128;
4055 unsigned NumLaneElts = NumElts/NumLanes;
4057 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4058 "Only supports 2 or 4 elements per lane");
4060 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4062 for (unsigned i = 0; i != NumElts; ++i) {
4063 int Elt = N->getMaskElt(i);
4064 if (Elt < 0) continue;
4065 Elt &= NumLaneElts - 1;
4066 unsigned ShAmt = (i << Shift) % 8;
4067 Mask |= Elt << ShAmt;
4073 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4074 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4075 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4076 MVT VT = N->getValueType(0).getSimpleVT();
4078 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4079 "Unsupported vector type for PSHUFHW");
4081 unsigned NumElts = VT.getVectorNumElements();
4084 for (unsigned l = 0; l != NumElts; l += 8) {
4085 // 8 nodes per lane, but we only care about the last 4.
4086 for (unsigned i = 0; i < 4; ++i) {
4087 int Elt = N->getMaskElt(l+i+4);
4088 if (Elt < 0) continue;
4089 Elt &= 0x3; // only 2-bits.
4090 Mask |= Elt << (i * 2);
4097 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4098 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4099 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4100 MVT VT = N->getValueType(0).getSimpleVT();
4102 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4103 "Unsupported vector type for PSHUFHW");
4105 unsigned NumElts = VT.getVectorNumElements();
4108 for (unsigned l = 0; l != NumElts; l += 8) {
4109 // 8 nodes per lane, but we only care about the first 4.
4110 for (unsigned i = 0; i < 4; ++i) {
4111 int Elt = N->getMaskElt(l+i);
4112 if (Elt < 0) continue;
4113 Elt &= 0x3; // only 2-bits
4114 Mask |= Elt << (i * 2);
4121 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4122 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4123 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4124 MVT VT = SVOp->getValueType(0).getSimpleVT();
4125 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4127 unsigned NumElts = VT.getVectorNumElements();
4128 unsigned NumLanes = VT.getSizeInBits()/128;
4129 unsigned NumLaneElts = NumElts/NumLanes;
4133 for (i = 0; i != NumElts; ++i) {
4134 Val = SVOp->getMaskElt(i);
4138 if (Val >= (int)NumElts)
4139 Val -= NumElts - NumLaneElts;
4141 assert(Val - i > 0 && "PALIGNR imm should be positive");
4142 return (Val - i) * EltSize;
4145 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4146 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4148 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4149 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4150 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4153 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4155 MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4156 MVT ElVT = VecVT.getVectorElementType();
4158 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4159 return Index / NumElemsPerChunk;
4162 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4163 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4165 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4166 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4167 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4170 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4172 MVT VecVT = N->getValueType(0).getSimpleVT();
4173 MVT ElVT = VecVT.getVectorElementType();
4175 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4176 return Index / NumElemsPerChunk;
4179 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4180 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4181 /// Handles 256-bit.
4182 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4183 MVT VT = N->getValueType(0).getSimpleVT();
4185 unsigned NumElts = VT.getVectorNumElements();
4187 assert((VT.is256BitVector() && NumElts == 4) &&
4188 "Unsupported vector type for VPERMQ/VPERMPD");
4191 for (unsigned i = 0; i != NumElts; ++i) {
4192 int Elt = N->getMaskElt(i);
4195 Mask |= Elt << (i*2);
4200 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4202 bool X86::isZeroNode(SDValue Elt) {
4203 return ((isa<ConstantSDNode>(Elt) &&
4204 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4205 (isa<ConstantFPSDNode>(Elt) &&
4206 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4209 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4210 /// their permute mask.
4211 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4212 SelectionDAG &DAG) {
4213 MVT VT = SVOp->getValueType(0).getSimpleVT();
4214 unsigned NumElems = VT.getVectorNumElements();
4215 SmallVector<int, 8> MaskVec;
4217 for (unsigned i = 0; i != NumElems; ++i) {
4218 int Idx = SVOp->getMaskElt(i);
4220 if (Idx < (int)NumElems)
4225 MaskVec.push_back(Idx);
4227 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4228 SVOp->getOperand(0), &MaskVec[0]);
4231 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4232 /// match movhlps. The lower half elements should come from upper half of
4233 /// V1 (and in order), and the upper half elements should come from the upper
4234 /// half of V2 (and in order).
4235 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4236 if (!VT.is128BitVector())
4238 if (VT.getVectorNumElements() != 4)
4240 for (unsigned i = 0, e = 2; i != e; ++i)
4241 if (!isUndefOrEqual(Mask[i], i+2))
4243 for (unsigned i = 2; i != 4; ++i)
4244 if (!isUndefOrEqual(Mask[i], i+4))
4249 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4250 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4252 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4253 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4255 N = N->getOperand(0).getNode();
4256 if (!ISD::isNON_EXTLoad(N))
4259 *LD = cast<LoadSDNode>(N);
4263 // Test whether the given value is a vector value which will be legalized
4265 static bool WillBeConstantPoolLoad(SDNode *N) {
4266 if (N->getOpcode() != ISD::BUILD_VECTOR)
4269 // Check for any non-constant elements.
4270 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4271 switch (N->getOperand(i).getNode()->getOpcode()) {
4273 case ISD::ConstantFP:
4280 // Vectors of all-zeros and all-ones are materialized with special
4281 // instructions rather than being loaded.
4282 return !ISD::isBuildVectorAllZeros(N) &&
4283 !ISD::isBuildVectorAllOnes(N);
4286 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4287 /// match movlp{s|d}. The lower half elements should come from lower half of
4288 /// V1 (and in order), and the upper half elements should come from the upper
4289 /// half of V2 (and in order). And since V1 will become the source of the
4290 /// MOVLP, it must be either a vector load or a scalar load to vector.
4291 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4292 ArrayRef<int> Mask, EVT VT) {
4293 if (!VT.is128BitVector())
4296 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4298 // Is V2 is a vector load, don't do this transformation. We will try to use
4299 // load folding shufps op.
4300 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4303 unsigned NumElems = VT.getVectorNumElements();
4305 if (NumElems != 2 && NumElems != 4)
4307 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4308 if (!isUndefOrEqual(Mask[i], i))
4310 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4311 if (!isUndefOrEqual(Mask[i], i+NumElems))
4316 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4318 static bool isSplatVector(SDNode *N) {
4319 if (N->getOpcode() != ISD::BUILD_VECTOR)
4322 SDValue SplatValue = N->getOperand(0);
4323 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4324 if (N->getOperand(i) != SplatValue)
4329 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4330 /// to an zero vector.
4331 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4332 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4333 SDValue V1 = N->getOperand(0);
4334 SDValue V2 = N->getOperand(1);
4335 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4336 for (unsigned i = 0; i != NumElems; ++i) {
4337 int Idx = N->getMaskElt(i);
4338 if (Idx >= (int)NumElems) {
4339 unsigned Opc = V2.getOpcode();
4340 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4342 if (Opc != ISD::BUILD_VECTOR ||
4343 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4345 } else if (Idx >= 0) {
4346 unsigned Opc = V1.getOpcode();
4347 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4349 if (Opc != ISD::BUILD_VECTOR ||
4350 !X86::isZeroNode(V1.getOperand(Idx)))
4357 /// getZeroVector - Returns a vector of specified type with all zero elements.
4359 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4360 SelectionDAG &DAG, DebugLoc dl) {
4361 assert(VT.isVector() && "Expected a vector type");
4363 // Always build SSE zero vectors as <4 x i32> bitcasted
4364 // to their dest type. This ensures they get CSE'd.
4366 if (VT.is128BitVector()) { // SSE
4367 if (Subtarget->hasSSE2()) { // SSE2
4368 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4369 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4371 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4372 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4374 } else if (VT.is256BitVector()) { // AVX
4375 if (Subtarget->hasInt256()) { // AVX2
4376 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4377 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4378 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4380 // 256-bit logic and arithmetic instructions in AVX are all
4381 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4382 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4383 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4384 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4387 llvm_unreachable("Unexpected vector type");
4389 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4392 /// getOnesVector - Returns a vector of specified type with all bits set.
4393 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4394 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4395 /// Then bitcast to their original type, ensuring they get CSE'd.
4396 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4398 assert(VT.isVector() && "Expected a vector type");
4400 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4402 if (VT.is256BitVector()) {
4403 if (HasInt256) { // AVX2
4404 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4405 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4407 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4408 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4410 } else if (VT.is128BitVector()) {
4411 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4413 llvm_unreachable("Unexpected vector type");
4415 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4418 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4419 /// that point to V2 points to its first element.
4420 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4421 for (unsigned i = 0; i != NumElems; ++i) {
4422 if (Mask[i] > (int)NumElems) {
4428 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4429 /// operation of specified width.
4430 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4432 unsigned NumElems = VT.getVectorNumElements();
4433 SmallVector<int, 8> Mask;
4434 Mask.push_back(NumElems);
4435 for (unsigned i = 1; i != NumElems; ++i)
4437 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4440 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4441 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4443 unsigned NumElems = VT.getVectorNumElements();
4444 SmallVector<int, 8> Mask;
4445 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4447 Mask.push_back(i + NumElems);
4449 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4452 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4453 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4455 unsigned NumElems = VT.getVectorNumElements();
4456 SmallVector<int, 8> Mask;
4457 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4458 Mask.push_back(i + Half);
4459 Mask.push_back(i + NumElems + Half);
4461 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4464 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4465 // a generic shuffle instruction because the target has no such instructions.
4466 // Generate shuffles which repeat i16 and i8 several times until they can be
4467 // represented by v4f32 and then be manipulated by target suported shuffles.
4468 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4469 EVT VT = V.getValueType();
4470 int NumElems = VT.getVectorNumElements();
4471 DebugLoc dl = V.getDebugLoc();
4473 while (NumElems > 4) {
4474 if (EltNo < NumElems/2) {
4475 V = getUnpackl(DAG, dl, VT, V, V);
4477 V = getUnpackh(DAG, dl, VT, V, V);
4478 EltNo -= NumElems/2;
4485 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4486 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4487 EVT VT = V.getValueType();
4488 DebugLoc dl = V.getDebugLoc();
4490 if (VT.is128BitVector()) {
4491 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4492 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4493 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4495 } else if (VT.is256BitVector()) {
4496 // To use VPERMILPS to splat scalars, the second half of indicies must
4497 // refer to the higher part, which is a duplication of the lower one,
4498 // because VPERMILPS can only handle in-lane permutations.
4499 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4500 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4502 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4503 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4506 llvm_unreachable("Vector size not supported");
4508 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4511 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4512 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4513 EVT SrcVT = SV->getValueType(0);
4514 SDValue V1 = SV->getOperand(0);
4515 DebugLoc dl = SV->getDebugLoc();
4517 int EltNo = SV->getSplatIndex();
4518 int NumElems = SrcVT.getVectorNumElements();
4519 bool Is256BitVec = SrcVT.is256BitVector();
4521 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4522 "Unknown how to promote splat for type");
4524 // Extract the 128-bit part containing the splat element and update
4525 // the splat element index when it refers to the higher register.
4527 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4528 if (EltNo >= NumElems/2)
4529 EltNo -= NumElems/2;
4532 // All i16 and i8 vector types can't be used directly by a generic shuffle
4533 // instruction because the target has no such instruction. Generate shuffles
4534 // which repeat i16 and i8 several times until they fit in i32, and then can
4535 // be manipulated by target suported shuffles.
4536 EVT EltVT = SrcVT.getVectorElementType();
4537 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4538 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4540 // Recreate the 256-bit vector and place the same 128-bit vector
4541 // into the low and high part. This is necessary because we want
4542 // to use VPERM* to shuffle the vectors
4544 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4547 return getLegalSplat(DAG, V1, EltNo);
4550 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4551 /// vector of zero or undef vector. This produces a shuffle where the low
4552 /// element of V2 is swizzled into the zero/undef vector, landing at element
4553 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4554 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4556 const X86Subtarget *Subtarget,
4557 SelectionDAG &DAG) {
4558 EVT VT = V2.getValueType();
4560 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4561 unsigned NumElems = VT.getVectorNumElements();
4562 SmallVector<int, 16> MaskVec;
4563 for (unsigned i = 0; i != NumElems; ++i)
4564 // If this is the insertion idx, put the low elt of V2 here.
4565 MaskVec.push_back(i == Idx ? NumElems : i);
4566 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4569 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4570 /// target specific opcode. Returns true if the Mask could be calculated.
4571 /// Sets IsUnary to true if only uses one source.
4572 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4573 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4574 unsigned NumElems = VT.getVectorNumElements();
4578 switch(N->getOpcode()) {
4580 ImmN = N->getOperand(N->getNumOperands()-1);
4581 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4583 case X86ISD::UNPCKH:
4584 DecodeUNPCKHMask(VT, Mask);
4586 case X86ISD::UNPCKL:
4587 DecodeUNPCKLMask(VT, Mask);
4589 case X86ISD::MOVHLPS:
4590 DecodeMOVHLPSMask(NumElems, Mask);
4592 case X86ISD::MOVLHPS:
4593 DecodeMOVLHPSMask(NumElems, Mask);
4595 case X86ISD::PSHUFD:
4596 case X86ISD::VPERMILP:
4597 ImmN = N->getOperand(N->getNumOperands()-1);
4598 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601 case X86ISD::PSHUFHW:
4602 ImmN = N->getOperand(N->getNumOperands()-1);
4603 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606 case X86ISD::PSHUFLW:
4607 ImmN = N->getOperand(N->getNumOperands()-1);
4608 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4611 case X86ISD::VPERMI:
4612 ImmN = N->getOperand(N->getNumOperands()-1);
4613 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4617 case X86ISD::MOVSD: {
4618 // The index 0 always comes from the first element of the second source,
4619 // this is why MOVSS and MOVSD are used in the first place. The other
4620 // elements come from the other positions of the first source vector
4621 Mask.push_back(NumElems);
4622 for (unsigned i = 1; i != NumElems; ++i) {
4627 case X86ISD::VPERM2X128:
4628 ImmN = N->getOperand(N->getNumOperands()-1);
4629 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4630 if (Mask.empty()) return false;
4632 case X86ISD::MOVDDUP:
4633 case X86ISD::MOVLHPD:
4634 case X86ISD::MOVLPD:
4635 case X86ISD::MOVLPS:
4636 case X86ISD::MOVSHDUP:
4637 case X86ISD::MOVSLDUP:
4638 case X86ISD::PALIGN:
4639 // Not yet implemented
4641 default: llvm_unreachable("unknown target shuffle node");
4647 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4648 /// element of the result of the vector shuffle.
4649 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4652 return SDValue(); // Limit search depth.
4654 SDValue V = SDValue(N, 0);
4655 EVT VT = V.getValueType();
4656 unsigned Opcode = V.getOpcode();
4658 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4659 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4660 int Elt = SV->getMaskElt(Index);
4663 return DAG.getUNDEF(VT.getVectorElementType());
4665 unsigned NumElems = VT.getVectorNumElements();
4666 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4667 : SV->getOperand(1);
4668 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4671 // Recurse into target specific vector shuffles to find scalars.
4672 if (isTargetShuffle(Opcode)) {
4673 MVT ShufVT = V.getValueType().getSimpleVT();
4674 unsigned NumElems = ShufVT.getVectorNumElements();
4675 SmallVector<int, 16> ShuffleMask;
4678 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4681 int Elt = ShuffleMask[Index];
4683 return DAG.getUNDEF(ShufVT.getVectorElementType());
4685 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4687 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4691 // Actual nodes that may contain scalar elements
4692 if (Opcode == ISD::BITCAST) {
4693 V = V.getOperand(0);
4694 EVT SrcVT = V.getValueType();
4695 unsigned NumElems = VT.getVectorNumElements();
4697 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4701 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4702 return (Index == 0) ? V.getOperand(0)
4703 : DAG.getUNDEF(VT.getVectorElementType());
4705 if (V.getOpcode() == ISD::BUILD_VECTOR)
4706 return V.getOperand(Index);
4711 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4712 /// shuffle operation which come from a consecutively from a zero. The
4713 /// search can start in two different directions, from left or right.
4715 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4716 bool ZerosFromLeft, SelectionDAG &DAG) {
4718 for (i = 0; i != NumElems; ++i) {
4719 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4720 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4721 if (!(Elt.getNode() &&
4722 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4729 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4730 /// correspond consecutively to elements from one of the vector operands,
4731 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4733 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4734 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4735 unsigned NumElems, unsigned &OpNum) {
4736 bool SeenV1 = false;
4737 bool SeenV2 = false;
4739 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4740 int Idx = SVOp->getMaskElt(i);
4741 // Ignore undef indicies
4745 if (Idx < (int)NumElems)
4750 // Only accept consecutive elements from the same vector
4751 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4755 OpNum = SeenV1 ? 0 : 1;
4759 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4760 /// logical left shift of a vector.
4761 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4762 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4763 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4764 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4765 false /* check zeros from right */, DAG);
4771 // Considering the elements in the mask that are not consecutive zeros,
4772 // check if they consecutively come from only one of the source vectors.
4774 // V1 = {X, A, B, C} 0
4776 // vector_shuffle V1, V2 <1, 2, 3, X>
4778 if (!isShuffleMaskConsecutive(SVOp,
4779 0, // Mask Start Index
4780 NumElems-NumZeros, // Mask End Index(exclusive)
4781 NumZeros, // Where to start looking in the src vector
4782 NumElems, // Number of elements in vector
4783 OpSrc)) // Which source operand ?
4788 ShVal = SVOp->getOperand(OpSrc);
4792 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4793 /// logical left shift of a vector.
4794 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4795 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4796 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4797 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4798 true /* check zeros from left */, DAG);
4804 // Considering the elements in the mask that are not consecutive zeros,
4805 // check if they consecutively come from only one of the source vectors.
4807 // 0 { A, B, X, X } = V2
4809 // vector_shuffle V1, V2 <X, X, 4, 5>
4811 if (!isShuffleMaskConsecutive(SVOp,
4812 NumZeros, // Mask Start Index
4813 NumElems, // Mask End Index(exclusive)
4814 0, // Where to start looking in the src vector
4815 NumElems, // Number of elements in vector
4816 OpSrc)) // Which source operand ?
4821 ShVal = SVOp->getOperand(OpSrc);
4825 /// isVectorShift - Returns true if the shuffle can be implemented as a
4826 /// logical left or right shift of a vector.
4827 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4828 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4829 // Although the logic below support any bitwidth size, there are no
4830 // shift instructions which handle more than 128-bit vectors.
4831 if (!SVOp->getValueType(0).is128BitVector())
4834 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4835 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4841 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4843 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4844 unsigned NumNonZero, unsigned NumZero,
4846 const X86Subtarget* Subtarget,
4847 const TargetLowering &TLI) {
4851 DebugLoc dl = Op.getDebugLoc();
4854 for (unsigned i = 0; i < 16; ++i) {
4855 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4856 if (ThisIsNonZero && First) {
4858 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4860 V = DAG.getUNDEF(MVT::v8i16);
4865 SDValue ThisElt(0, 0), LastElt(0, 0);
4866 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4867 if (LastIsNonZero) {
4868 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4869 MVT::i16, Op.getOperand(i-1));
4871 if (ThisIsNonZero) {
4872 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4873 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4874 ThisElt, DAG.getConstant(8, MVT::i8));
4876 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4880 if (ThisElt.getNode())
4881 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4882 DAG.getIntPtrConstant(i/2));
4886 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4889 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4891 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4892 unsigned NumNonZero, unsigned NumZero,
4894 const X86Subtarget* Subtarget,
4895 const TargetLowering &TLI) {
4899 DebugLoc dl = Op.getDebugLoc();
4902 for (unsigned i = 0; i < 8; ++i) {
4903 bool isNonZero = (NonZeros & (1 << i)) != 0;
4907 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4909 V = DAG.getUNDEF(MVT::v8i16);
4912 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4913 MVT::v8i16, V, Op.getOperand(i),
4914 DAG.getIntPtrConstant(i));
4921 /// getVShift - Return a vector logical shift node.
4923 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4924 unsigned NumBits, SelectionDAG &DAG,
4925 const TargetLowering &TLI, DebugLoc dl) {
4926 assert(VT.is128BitVector() && "Unknown type for VShift");
4927 EVT ShVT = MVT::v2i64;
4928 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4929 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4930 return DAG.getNode(ISD::BITCAST, dl, VT,
4931 DAG.getNode(Opc, dl, ShVT, SrcOp,
4932 DAG.getConstant(NumBits,
4933 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4937 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4938 SelectionDAG &DAG) const {
4940 // Check if the scalar load can be widened into a vector load. And if
4941 // the address is "base + cst" see if the cst can be "absorbed" into
4942 // the shuffle mask.
4943 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4944 SDValue Ptr = LD->getBasePtr();
4945 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4947 EVT PVT = LD->getValueType(0);
4948 if (PVT != MVT::i32 && PVT != MVT::f32)
4953 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4954 FI = FINode->getIndex();
4956 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4957 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4958 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4959 Offset = Ptr.getConstantOperandVal(1);
4960 Ptr = Ptr.getOperand(0);
4965 // FIXME: 256-bit vector instructions don't require a strict alignment,
4966 // improve this code to support it better.
4967 unsigned RequiredAlign = VT.getSizeInBits()/8;
4968 SDValue Chain = LD->getChain();
4969 // Make sure the stack object alignment is at least 16 or 32.
4970 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4971 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4972 if (MFI->isFixedObjectIndex(FI)) {
4973 // Can't change the alignment. FIXME: It's possible to compute
4974 // the exact stack offset and reference FI + adjust offset instead.
4975 // If someone *really* cares about this. That's the way to implement it.
4978 MFI->setObjectAlignment(FI, RequiredAlign);
4982 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4983 // Ptr + (Offset & ~15).
4986 if ((Offset % RequiredAlign) & 3)
4988 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4990 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4991 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4993 int EltNo = (Offset - StartOffset) >> 2;
4994 unsigned NumElems = VT.getVectorNumElements();
4996 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4997 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4998 LD->getPointerInfo().getWithOffset(StartOffset),
4999 false, false, false, 0);
5001 SmallVector<int, 8> Mask;
5002 for (unsigned i = 0; i != NumElems; ++i)
5003 Mask.push_back(EltNo);
5005 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5011 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5012 /// vector of type 'VT', see if the elements can be replaced by a single large
5013 /// load which has the same value as a build_vector whose operands are 'elts'.
5015 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5017 /// FIXME: we'd also like to handle the case where the last elements are zero
5018 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5019 /// There's even a handy isZeroNode for that purpose.
5020 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5021 DebugLoc &DL, SelectionDAG &DAG) {
5022 EVT EltVT = VT.getVectorElementType();
5023 unsigned NumElems = Elts.size();
5025 LoadSDNode *LDBase = NULL;
5026 unsigned LastLoadedElt = -1U;
5028 // For each element in the initializer, see if we've found a load or an undef.
5029 // If we don't find an initial load element, or later load elements are
5030 // non-consecutive, bail out.
5031 for (unsigned i = 0; i < NumElems; ++i) {
5032 SDValue Elt = Elts[i];
5034 if (!Elt.getNode() ||
5035 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5038 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5040 LDBase = cast<LoadSDNode>(Elt.getNode());
5044 if (Elt.getOpcode() == ISD::UNDEF)
5047 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5048 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5053 // If we have found an entire vector of loads and undefs, then return a large
5054 // load of the entire vector width starting at the base pointer. If we found
5055 // consecutive loads for the low half, generate a vzext_load node.
5056 if (LastLoadedElt == NumElems - 1) {
5057 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5058 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5059 LDBase->getPointerInfo(),
5060 LDBase->isVolatile(), LDBase->isNonTemporal(),
5061 LDBase->isInvariant(), 0);
5062 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5063 LDBase->getPointerInfo(),
5064 LDBase->isVolatile(), LDBase->isNonTemporal(),
5065 LDBase->isInvariant(), LDBase->getAlignment());
5067 if (NumElems == 4 && LastLoadedElt == 1 &&
5068 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5069 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5070 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5072 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5073 LDBase->getPointerInfo(),
5074 LDBase->getAlignment(),
5075 false/*isVolatile*/, true/*ReadMem*/,
5078 // Make sure the newly-created LOAD is in the same position as LDBase in
5079 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5080 // update uses of LDBase's output chain to use the TokenFactor.
5081 if (LDBase->hasAnyUseOfValue(1)) {
5082 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5083 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5084 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5085 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5086 SDValue(ResNode.getNode(), 1));
5089 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5094 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5095 /// to generate a splat value for the following cases:
5096 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5097 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5098 /// a scalar load, or a constant.
5099 /// The VBROADCAST node is returned when a pattern is found,
5100 /// or SDValue() otherwise.
5102 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5103 if (!Subtarget->hasFp256())
5106 MVT VT = Op.getValueType().getSimpleVT();
5107 DebugLoc dl = Op.getDebugLoc();
5109 assert((VT.is128BitVector() || VT.is256BitVector()) &&
5110 "Unsupported vector type for broadcast.");
5115 switch (Op.getOpcode()) {
5117 // Unknown pattern found.
5120 case ISD::BUILD_VECTOR: {
5121 // The BUILD_VECTOR node must be a splat.
5122 if (!isSplatVector(Op.getNode()))
5125 Ld = Op.getOperand(0);
5126 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5127 Ld.getOpcode() == ISD::ConstantFP);
5129 // The suspected load node has several users. Make sure that all
5130 // of its users are from the BUILD_VECTOR node.
5131 // Constants may have multiple users.
5132 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5137 case ISD::VECTOR_SHUFFLE: {
5138 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5140 // Shuffles must have a splat mask where the first element is
5142 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5145 SDValue Sc = Op.getOperand(0);
5146 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5147 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5149 if (!Subtarget->hasInt256())
5152 // Use the register form of the broadcast instruction available on AVX2.
5153 if (VT.is256BitVector())
5154 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5155 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5158 Ld = Sc.getOperand(0);
5159 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5160 Ld.getOpcode() == ISD::ConstantFP);
5162 // The scalar_to_vector node and the suspected
5163 // load node must have exactly one user.
5164 // Constants may have multiple users.
5165 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5171 bool Is256 = VT.is256BitVector();
5173 // Handle the broadcasting a single constant scalar from the constant pool
5174 // into a vector. On Sandybridge it is still better to load a constant vector
5175 // from the constant pool and not to broadcast it from a scalar.
5176 if (ConstSplatVal && Subtarget->hasInt256()) {
5177 EVT CVT = Ld.getValueType();
5178 assert(!CVT.isVector() && "Must not broadcast a vector type");
5179 unsigned ScalarSize = CVT.getSizeInBits();
5181 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5182 const Constant *C = 0;
5183 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5184 C = CI->getConstantIntValue();
5185 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5186 C = CF->getConstantFPValue();
5188 assert(C && "Invalid constant type");
5190 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5191 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5192 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5193 MachinePointerInfo::getConstantPool(),
5194 false, false, false, Alignment);
5196 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5200 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5201 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5203 // Handle AVX2 in-register broadcasts.
5204 if (!IsLoad && Subtarget->hasInt256() &&
5205 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5206 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5208 // The scalar source must be a normal load.
5212 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5213 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5215 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5216 // double since there is no vbroadcastsd xmm
5217 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5218 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5219 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5222 // Unsupported broadcast.
5227 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5228 EVT VT = Op.getValueType();
5230 // Skip if insert_vec_elt is not supported.
5231 if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5234 DebugLoc DL = Op.getDebugLoc();
5235 unsigned NumElems = Op.getNumOperands();
5239 SmallVector<unsigned, 4> InsertIndices;
5240 SmallVector<int, 8> Mask(NumElems, -1);
5242 for (unsigned i = 0; i != NumElems; ++i) {
5243 unsigned Opc = Op.getOperand(i).getOpcode();
5245 if (Opc == ISD::UNDEF)
5248 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5249 // Quit if more than 1 elements need inserting.
5250 if (InsertIndices.size() > 1)
5253 InsertIndices.push_back(i);
5257 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5258 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5260 // Quit if extracted from vector of different type.
5261 if (ExtractedFromVec.getValueType() != VT)
5264 // Quit if non-constant index.
5265 if (!isa<ConstantSDNode>(ExtIdx))
5268 if (VecIn1.getNode() == 0)
5269 VecIn1 = ExtractedFromVec;
5270 else if (VecIn1 != ExtractedFromVec) {
5271 if (VecIn2.getNode() == 0)
5272 VecIn2 = ExtractedFromVec;
5273 else if (VecIn2 != ExtractedFromVec)
5274 // Quit if more than 2 vectors to shuffle
5278 unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5280 if (ExtractedFromVec == VecIn1)
5282 else if (ExtractedFromVec == VecIn2)
5283 Mask[i] = Idx + NumElems;
5286 if (VecIn1.getNode() == 0)
5289 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5290 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5291 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5292 unsigned Idx = InsertIndices[i];
5293 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5294 DAG.getIntPtrConstant(Idx));
5301 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5302 DebugLoc dl = Op.getDebugLoc();
5304 MVT VT = Op.getValueType().getSimpleVT();
5305 MVT ExtVT = VT.getVectorElementType();
5306 unsigned NumElems = Op.getNumOperands();
5308 // Vectors containing all zeros can be matched by pxor and xorps later
5309 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5310 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5311 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5312 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5315 return getZeroVector(VT, Subtarget, DAG, dl);
5318 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5319 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5320 // vpcmpeqd on 256-bit vectors.
5321 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5322 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5325 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5328 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5329 if (Broadcast.getNode())
5332 unsigned EVTBits = ExtVT.getSizeInBits();
5334 unsigned NumZero = 0;
5335 unsigned NumNonZero = 0;
5336 unsigned NonZeros = 0;
5337 bool IsAllConstants = true;
5338 SmallSet<SDValue, 8> Values;
5339 for (unsigned i = 0; i < NumElems; ++i) {
5340 SDValue Elt = Op.getOperand(i);
5341 if (Elt.getOpcode() == ISD::UNDEF)
5344 if (Elt.getOpcode() != ISD::Constant &&
5345 Elt.getOpcode() != ISD::ConstantFP)
5346 IsAllConstants = false;
5347 if (X86::isZeroNode(Elt))
5350 NonZeros |= (1 << i);
5355 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5356 if (NumNonZero == 0)
5357 return DAG.getUNDEF(VT);
5359 // Special case for single non-zero, non-undef, element.
5360 if (NumNonZero == 1) {
5361 unsigned Idx = CountTrailingZeros_32(NonZeros);
5362 SDValue Item = Op.getOperand(Idx);
5364 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5365 // the value are obviously zero, truncate the value to i32 and do the
5366 // insertion that way. Only do this if the value is non-constant or if the
5367 // value is a constant being inserted into element 0. It is cheaper to do
5368 // a constant pool load than it is to do a movd + shuffle.
5369 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5370 (!IsAllConstants || Idx == 0)) {
5371 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5373 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5374 EVT VecVT = MVT::v4i32;
5375 unsigned VecElts = 4;
5377 // Truncate the value (which may itself be a constant) to i32, and
5378 // convert it to a vector with movd (S2V+shuffle to zero extend).
5379 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5380 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5381 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5383 // Now we have our 32-bit value zero extended in the low element of
5384 // a vector. If Idx != 0, swizzle it into place.
5386 SmallVector<int, 4> Mask;
5387 Mask.push_back(Idx);
5388 for (unsigned i = 1; i != VecElts; ++i)
5390 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5393 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5397 // If we have a constant or non-constant insertion into the low element of
5398 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5399 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5400 // depending on what the source datatype is.
5403 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5405 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5406 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5407 if (VT.is256BitVector()) {
5408 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5409 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5410 Item, DAG.getIntPtrConstant(0));
5412 assert(VT.is128BitVector() && "Expected an SSE value type!");
5413 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5414 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5415 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5418 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5419 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5420 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5421 if (VT.is256BitVector()) {
5422 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5423 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5425 assert(VT.is128BitVector() && "Expected an SSE value type!");
5426 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5428 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5432 // Is it a vector logical left shift?
5433 if (NumElems == 2 && Idx == 1 &&
5434 X86::isZeroNode(Op.getOperand(0)) &&
5435 !X86::isZeroNode(Op.getOperand(1))) {
5436 unsigned NumBits = VT.getSizeInBits();
5437 return getVShift(true, VT,
5438 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5439 VT, Op.getOperand(1)),
5440 NumBits/2, DAG, *this, dl);
5443 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5446 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5447 // is a non-constant being inserted into an element other than the low one,
5448 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5449 // movd/movss) to move this into the low element, then shuffle it into
5451 if (EVTBits == 32) {
5452 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5454 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5455 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5456 SmallVector<int, 8> MaskVec;
5457 for (unsigned i = 0; i != NumElems; ++i)
5458 MaskVec.push_back(i == Idx ? 0 : 1);
5459 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5463 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5464 if (Values.size() == 1) {
5465 if (EVTBits == 32) {
5466 // Instead of a shuffle like this:
5467 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5468 // Check if it's possible to issue this instead.
5469 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5470 unsigned Idx = CountTrailingZeros_32(NonZeros);
5471 SDValue Item = Op.getOperand(Idx);
5472 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5473 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5478 // A vector full of immediates; various special cases are already
5479 // handled, so this is best done with a single constant-pool load.
5483 // For AVX-length vectors, build the individual 128-bit pieces and use
5484 // shuffles to put them in place.
5485 if (VT.is256BitVector()) {
5486 SmallVector<SDValue, 32> V;
5487 for (unsigned i = 0; i != NumElems; ++i)
5488 V.push_back(Op.getOperand(i));
5490 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5492 // Build both the lower and upper subvector.
5493 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5494 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5497 // Recreate the wider vector with the lower and upper part.
5498 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5501 // Let legalizer expand 2-wide build_vectors.
5502 if (EVTBits == 64) {
5503 if (NumNonZero == 1) {
5504 // One half is zero or undef.
5505 unsigned Idx = CountTrailingZeros_32(NonZeros);
5506 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5507 Op.getOperand(Idx));
5508 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5513 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5514 if (EVTBits == 8 && NumElems == 16) {
5515 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5517 if (V.getNode()) return V;
5520 if (EVTBits == 16 && NumElems == 8) {
5521 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5523 if (V.getNode()) return V;
5526 // If element VT is == 32 bits, turn it into a number of shuffles.
5527 SmallVector<SDValue, 8> V(NumElems);
5528 if (NumElems == 4 && NumZero > 0) {
5529 for (unsigned i = 0; i < 4; ++i) {
5530 bool isZero = !(NonZeros & (1 << i));
5532 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5534 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5537 for (unsigned i = 0; i < 2; ++i) {
5538 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5541 V[i] = V[i*2]; // Must be a zero vector.
5544 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5547 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5550 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5555 bool Reverse1 = (NonZeros & 0x3) == 2;
5556 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5560 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5561 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5563 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5566 if (Values.size() > 1 && VT.is128BitVector()) {
5567 // Check for a build vector of consecutive loads.
5568 for (unsigned i = 0; i < NumElems; ++i)
5569 V[i] = Op.getOperand(i);
5571 // Check for elements which are consecutive loads.
5572 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5576 // Check for a build vector from mostly shuffle plus few inserting.
5577 SDValue Sh = buildFromShuffleMostly(Op, DAG);
5581 // For SSE 4.1, use insertps to put the high elements into the low element.
5582 if (getSubtarget()->hasSSE41()) {
5584 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5585 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5587 Result = DAG.getUNDEF(VT);
5589 for (unsigned i = 1; i < NumElems; ++i) {
5590 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5591 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5592 Op.getOperand(i), DAG.getIntPtrConstant(i));
5597 // Otherwise, expand into a number of unpckl*, start by extending each of
5598 // our (non-undef) elements to the full vector width with the element in the
5599 // bottom slot of the vector (which generates no code for SSE).
5600 for (unsigned i = 0; i < NumElems; ++i) {
5601 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5602 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5604 V[i] = DAG.getUNDEF(VT);
5607 // Next, we iteratively mix elements, e.g. for v4f32:
5608 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5609 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5610 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5611 unsigned EltStride = NumElems >> 1;
5612 while (EltStride != 0) {
5613 for (unsigned i = 0; i < EltStride; ++i) {
5614 // If V[i+EltStride] is undef and this is the first round of mixing,
5615 // then it is safe to just drop this shuffle: V[i] is already in the
5616 // right place, the one element (since it's the first round) being
5617 // inserted as undef can be dropped. This isn't safe for successive
5618 // rounds because they will permute elements within both vectors.
5619 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5620 EltStride == NumElems/2)
5623 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5632 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5633 // to create 256-bit vectors from two other 128-bit ones.
5634 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5635 DebugLoc dl = Op.getDebugLoc();
5636 MVT ResVT = Op.getValueType().getSimpleVT();
5638 assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5640 SDValue V1 = Op.getOperand(0);
5641 SDValue V2 = Op.getOperand(1);
5642 unsigned NumElems = ResVT.getVectorNumElements();
5644 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5647 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5648 assert(Op.getNumOperands() == 2);
5650 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5651 // from two other 128-bit ones.
5652 return LowerAVXCONCAT_VECTORS(Op, DAG);
5655 // Try to lower a shuffle node into a simple blend instruction.
5657 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5658 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5659 SDValue V1 = SVOp->getOperand(0);
5660 SDValue V2 = SVOp->getOperand(1);
5661 DebugLoc dl = SVOp->getDebugLoc();
5662 MVT VT = SVOp->getValueType(0).getSimpleVT();
5663 MVT EltVT = VT.getVectorElementType();
5664 unsigned NumElems = VT.getVectorNumElements();
5666 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5668 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5671 // Check the mask for BLEND and build the value.
5672 unsigned MaskValue = 0;
5673 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5674 unsigned NumLanes = (NumElems-1)/8 + 1;
5675 unsigned NumElemsInLane = NumElems / NumLanes;
5677 // Blend for v16i16 should be symetric for the both lanes.
5678 for (unsigned i = 0; i < NumElemsInLane; ++i) {
5680 int SndLaneEltIdx = (NumLanes == 2) ?
5681 SVOp->getMaskElt(i + NumElemsInLane) : -1;
5682 int EltIdx = SVOp->getMaskElt(i);
5684 if ((EltIdx < 0 || EltIdx == (int)i) &&
5685 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5688 if (((unsigned)EltIdx == (i + NumElems)) &&
5689 (SndLaneEltIdx < 0 ||
5690 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5691 MaskValue |= (1<<i);
5696 // Convert i32 vectors to floating point if it is not AVX2.
5697 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5699 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5700 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5702 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5703 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5706 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5707 DAG.getConstant(MaskValue, MVT::i32));
5708 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5711 // v8i16 shuffles - Prefer shuffles in the following order:
5712 // 1. [all] pshuflw, pshufhw, optional move
5713 // 2. [ssse3] 1 x pshufb
5714 // 3. [ssse3] 2 x pshufb + 1 x por
5715 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5717 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5718 SelectionDAG &DAG) {
5719 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5720 SDValue V1 = SVOp->getOperand(0);
5721 SDValue V2 = SVOp->getOperand(1);
5722 DebugLoc dl = SVOp->getDebugLoc();
5723 SmallVector<int, 8> MaskVals;
5725 // Determine if more than 1 of the words in each of the low and high quadwords
5726 // of the result come from the same quadword of one of the two inputs. Undef
5727 // mask values count as coming from any quadword, for better codegen.
5728 unsigned LoQuad[] = { 0, 0, 0, 0 };
5729 unsigned HiQuad[] = { 0, 0, 0, 0 };
5730 std::bitset<4> InputQuads;
5731 for (unsigned i = 0; i < 8; ++i) {
5732 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5733 int EltIdx = SVOp->getMaskElt(i);
5734 MaskVals.push_back(EltIdx);
5743 InputQuads.set(EltIdx / 4);
5746 int BestLoQuad = -1;
5747 unsigned MaxQuad = 1;
5748 for (unsigned i = 0; i < 4; ++i) {
5749 if (LoQuad[i] > MaxQuad) {
5751 MaxQuad = LoQuad[i];
5755 int BestHiQuad = -1;
5757 for (unsigned i = 0; i < 4; ++i) {
5758 if (HiQuad[i] > MaxQuad) {
5760 MaxQuad = HiQuad[i];
5764 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5765 // of the two input vectors, shuffle them into one input vector so only a
5766 // single pshufb instruction is necessary. If There are more than 2 input
5767 // quads, disable the next transformation since it does not help SSSE3.
5768 bool V1Used = InputQuads[0] || InputQuads[1];
5769 bool V2Used = InputQuads[2] || InputQuads[3];
5770 if (Subtarget->hasSSSE3()) {
5771 if (InputQuads.count() == 2 && V1Used && V2Used) {
5772 BestLoQuad = InputQuads[0] ? 0 : 1;
5773 BestHiQuad = InputQuads[2] ? 2 : 3;
5775 if (InputQuads.count() > 2) {
5781 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5782 // the shuffle mask. If a quad is scored as -1, that means that it contains
5783 // words from all 4 input quadwords.
5785 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5787 BestLoQuad < 0 ? 0 : BestLoQuad,
5788 BestHiQuad < 0 ? 1 : BestHiQuad
5790 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5791 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5792 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5793 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5795 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5796 // source words for the shuffle, to aid later transformations.
5797 bool AllWordsInNewV = true;
5798 bool InOrder[2] = { true, true };
5799 for (unsigned i = 0; i != 8; ++i) {
5800 int idx = MaskVals[i];
5802 InOrder[i/4] = false;
5803 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5805 AllWordsInNewV = false;
5809 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5810 if (AllWordsInNewV) {
5811 for (int i = 0; i != 8; ++i) {
5812 int idx = MaskVals[i];
5815 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5816 if ((idx != i) && idx < 4)
5818 if ((idx != i) && idx > 3)
5827 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5828 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5829 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5830 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5831 unsigned TargetMask = 0;
5832 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5833 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5834 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5835 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5836 getShufflePSHUFLWImmediate(SVOp);
5837 V1 = NewV.getOperand(0);
5838 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5842 // If we have SSSE3, and all words of the result are from 1 input vector,
5843 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5844 // is present, fall back to case 4.
5845 if (Subtarget->hasSSSE3()) {
5846 SmallVector<SDValue,16> pshufbMask;
5848 // If we have elements from both input vectors, set the high bit of the
5849 // shuffle mask element to zero out elements that come from V2 in the V1
5850 // mask, and elements that come from V1 in the V2 mask, so that the two
5851 // results can be OR'd together.
5852 bool TwoInputs = V1Used && V2Used;
5853 for (unsigned i = 0; i != 8; ++i) {
5854 int EltIdx = MaskVals[i] * 2;
5855 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5856 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5857 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5858 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5860 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5861 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5862 DAG.getNode(ISD::BUILD_VECTOR, dl,
5863 MVT::v16i8, &pshufbMask[0], 16));
5865 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5867 // Calculate the shuffle mask for the second input, shuffle it, and
5868 // OR it with the first shuffled input.
5870 for (unsigned i = 0; i != 8; ++i) {
5871 int EltIdx = MaskVals[i] * 2;
5872 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5873 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5874 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5875 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5877 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5878 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5879 DAG.getNode(ISD::BUILD_VECTOR, dl,
5880 MVT::v16i8, &pshufbMask[0], 16));
5881 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5882 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5885 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5886 // and update MaskVals with new element order.
5887 std::bitset<8> InOrder;
5888 if (BestLoQuad >= 0) {
5889 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5890 for (int i = 0; i != 4; ++i) {
5891 int idx = MaskVals[i];
5894 } else if ((idx / 4) == BestLoQuad) {
5899 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5902 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5903 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5904 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5906 getShufflePSHUFLWImmediate(SVOp), DAG);
5910 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5911 // and update MaskVals with the new element order.
5912 if (BestHiQuad >= 0) {
5913 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5914 for (unsigned i = 4; i != 8; ++i) {
5915 int idx = MaskVals[i];
5918 } else if ((idx / 4) == BestHiQuad) {
5919 MaskV[i] = (idx & 3) + 4;
5923 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5926 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5927 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5928 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5930 getShufflePSHUFHWImmediate(SVOp), DAG);
5934 // In case BestHi & BestLo were both -1, which means each quadword has a word
5935 // from each of the four input quadwords, calculate the InOrder bitvector now
5936 // before falling through to the insert/extract cleanup.
5937 if (BestLoQuad == -1 && BestHiQuad == -1) {
5939 for (int i = 0; i != 8; ++i)
5940 if (MaskVals[i] < 0 || MaskVals[i] == i)
5944 // The other elements are put in the right place using pextrw and pinsrw.
5945 for (unsigned i = 0; i != 8; ++i) {
5948 int EltIdx = MaskVals[i];
5951 SDValue ExtOp = (EltIdx < 8) ?
5952 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5953 DAG.getIntPtrConstant(EltIdx)) :
5954 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5955 DAG.getIntPtrConstant(EltIdx - 8));
5956 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5957 DAG.getIntPtrConstant(i));
5962 // v16i8 shuffles - Prefer shuffles in the following order:
5963 // 1. [ssse3] 1 x pshufb
5964 // 2. [ssse3] 2 x pshufb + 1 x por
5965 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5967 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5969 const X86TargetLowering &TLI) {
5970 SDValue V1 = SVOp->getOperand(0);
5971 SDValue V2 = SVOp->getOperand(1);
5972 DebugLoc dl = SVOp->getDebugLoc();
5973 ArrayRef<int> MaskVals = SVOp->getMask();
5975 // If we have SSSE3, case 1 is generated when all result bytes come from
5976 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5977 // present, fall back to case 3.
5979 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5980 if (TLI.getSubtarget()->hasSSSE3()) {
5981 SmallVector<SDValue,16> pshufbMask;
5983 // If all result elements are from one input vector, then only translate
5984 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5986 // Otherwise, we have elements from both input vectors, and must zero out
5987 // elements that come from V2 in the first mask, and V1 in the second mask
5988 // so that we can OR them together.
5989 for (unsigned i = 0; i != 16; ++i) {
5990 int EltIdx = MaskVals[i];
5991 if (EltIdx < 0 || EltIdx >= 16)
5993 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5995 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5996 DAG.getNode(ISD::BUILD_VECTOR, dl,
5997 MVT::v16i8, &pshufbMask[0], 16));
5999 // As PSHUFB will zero elements with negative indices, it's safe to ignore
6000 // the 2nd operand if it's undefined or zero.
6001 if (V2.getOpcode() == ISD::UNDEF ||
6002 ISD::isBuildVectorAllZeros(V2.getNode()))
6005 // Calculate the shuffle mask for the second input, shuffle it, and
6006 // OR it with the first shuffled input.
6008 for (unsigned i = 0; i != 16; ++i) {
6009 int EltIdx = MaskVals[i];
6010 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6011 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6013 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6014 DAG.getNode(ISD::BUILD_VECTOR, dl,
6015 MVT::v16i8, &pshufbMask[0], 16));
6016 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6019 // No SSSE3 - Calculate in place words and then fix all out of place words
6020 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
6021 // the 16 different words that comprise the two doublequadword input vectors.
6022 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6023 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6025 for (int i = 0; i != 8; ++i) {
6026 int Elt0 = MaskVals[i*2];
6027 int Elt1 = MaskVals[i*2+1];
6029 // This word of the result is all undef, skip it.
6030 if (Elt0 < 0 && Elt1 < 0)
6033 // This word of the result is already in the correct place, skip it.
6034 if ((Elt0 == i*2) && (Elt1 == i*2+1))
6037 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6038 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6041 // If Elt0 and Elt1 are defined, are consecutive, and can be load
6042 // using a single extract together, load it and store it.
6043 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6044 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6045 DAG.getIntPtrConstant(Elt1 / 2));
6046 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6047 DAG.getIntPtrConstant(i));
6051 // If Elt1 is defined, extract it from the appropriate source. If the
6052 // source byte is not also odd, shift the extracted word left 8 bits
6053 // otherwise clear the bottom 8 bits if we need to do an or.
6055 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6056 DAG.getIntPtrConstant(Elt1 / 2));
6057 if ((Elt1 & 1) == 0)
6058 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6060 TLI.getShiftAmountTy(InsElt.getValueType())));
6062 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6063 DAG.getConstant(0xFF00, MVT::i16));
6065 // If Elt0 is defined, extract it from the appropriate source. If the
6066 // source byte is not also even, shift the extracted word right 8 bits. If
6067 // Elt1 was also defined, OR the extracted values together before
6068 // inserting them in the result.
6070 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6071 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6072 if ((Elt0 & 1) != 0)
6073 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6075 TLI.getShiftAmountTy(InsElt0.getValueType())));
6077 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6078 DAG.getConstant(0x00FF, MVT::i16));
6079 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6082 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6083 DAG.getIntPtrConstant(i));
6085 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6088 // v32i8 shuffles - Translate to VPSHUFB if possible.
6090 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6091 const X86Subtarget *Subtarget,
6092 SelectionDAG &DAG) {
6093 MVT VT = SVOp->getValueType(0).getSimpleVT();
6094 SDValue V1 = SVOp->getOperand(0);
6095 SDValue V2 = SVOp->getOperand(1);
6096 DebugLoc dl = SVOp->getDebugLoc();
6097 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6099 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6100 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6101 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6103 // VPSHUFB may be generated if
6104 // (1) one of input vector is undefined or zeroinitializer.
6105 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6106 // And (2) the mask indexes don't cross the 128-bit lane.
6107 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6108 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6111 if (V1IsAllZero && !V2IsAllZero) {
6112 CommuteVectorShuffleMask(MaskVals, 32);
6115 SmallVector<SDValue, 32> pshufbMask;
6116 for (unsigned i = 0; i != 32; i++) {
6117 int EltIdx = MaskVals[i];
6118 if (EltIdx < 0 || EltIdx >= 32)
6121 if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6122 // Cross lane is not allowed.
6126 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6128 return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6129 DAG.getNode(ISD::BUILD_VECTOR, dl,
6130 MVT::v32i8, &pshufbMask[0], 32));
6133 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6134 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6135 /// done when every pair / quad of shuffle mask elements point to elements in
6136 /// the right sequence. e.g.
6137 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6139 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6140 SelectionDAG &DAG) {
6141 MVT VT = SVOp->getValueType(0).getSimpleVT();
6142 DebugLoc dl = SVOp->getDebugLoc();
6143 unsigned NumElems = VT.getVectorNumElements();
6146 switch (VT.SimpleTy) {
6147 default: llvm_unreachable("Unexpected!");
6148 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
6149 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
6150 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
6151 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
6152 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6153 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
6156 SmallVector<int, 8> MaskVec;
6157 for (unsigned i = 0; i != NumElems; i += Scale) {
6159 for (unsigned j = 0; j != Scale; ++j) {
6160 int EltIdx = SVOp->getMaskElt(i+j);
6164 StartIdx = (EltIdx / Scale);
6165 if (EltIdx != (int)(StartIdx*Scale + j))
6168 MaskVec.push_back(StartIdx);
6171 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6172 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6173 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6176 /// getVZextMovL - Return a zero-extending vector move low node.
6178 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6179 SDValue SrcOp, SelectionDAG &DAG,
6180 const X86Subtarget *Subtarget, DebugLoc dl) {
6181 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6182 LoadSDNode *LD = NULL;
6183 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6184 LD = dyn_cast<LoadSDNode>(SrcOp);
6186 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6188 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6189 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6190 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6191 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6192 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6194 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6195 return DAG.getNode(ISD::BITCAST, dl, VT,
6196 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6197 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6205 return DAG.getNode(ISD::BITCAST, dl, VT,
6206 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6207 DAG.getNode(ISD::BITCAST, dl,
6211 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6212 /// which could not be matched by any known target speficic shuffle
6214 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6216 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6217 if (NewOp.getNode())
6220 MVT VT = SVOp->getValueType(0).getSimpleVT();
6222 unsigned NumElems = VT.getVectorNumElements();
6223 unsigned NumLaneElems = NumElems / 2;
6225 DebugLoc dl = SVOp->getDebugLoc();
6226 MVT EltVT = VT.getVectorElementType();
6227 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6230 SmallVector<int, 16> Mask;
6231 for (unsigned l = 0; l < 2; ++l) {
6232 // Build a shuffle mask for the output, discovering on the fly which
6233 // input vectors to use as shuffle operands (recorded in InputUsed).
6234 // If building a suitable shuffle vector proves too hard, then bail
6235 // out with UseBuildVector set.
6236 bool UseBuildVector = false;
6237 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6238 unsigned LaneStart = l * NumLaneElems;
6239 for (unsigned i = 0; i != NumLaneElems; ++i) {
6240 // The mask element. This indexes into the input.
6241 int Idx = SVOp->getMaskElt(i+LaneStart);
6243 // the mask element does not index into any input vector.
6248 // The input vector this mask element indexes into.
6249 int Input = Idx / NumLaneElems;
6251 // Turn the index into an offset from the start of the input vector.
6252 Idx -= Input * NumLaneElems;
6254 // Find or create a shuffle vector operand to hold this input.
6256 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6257 if (InputUsed[OpNo] == Input)
6258 // This input vector is already an operand.
6260 if (InputUsed[OpNo] < 0) {
6261 // Create a new operand for this input vector.
6262 InputUsed[OpNo] = Input;
6267 if (OpNo >= array_lengthof(InputUsed)) {
6268 // More than two input vectors used! Give up on trying to create a
6269 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6270 UseBuildVector = true;
6274 // Add the mask index for the new shuffle vector.
6275 Mask.push_back(Idx + OpNo * NumLaneElems);
6278 if (UseBuildVector) {
6279 SmallVector<SDValue, 16> SVOps;
6280 for (unsigned i = 0; i != NumLaneElems; ++i) {
6281 // The mask element. This indexes into the input.
6282 int Idx = SVOp->getMaskElt(i+LaneStart);
6284 SVOps.push_back(DAG.getUNDEF(EltVT));
6288 // The input vector this mask element indexes into.
6289 int Input = Idx / NumElems;
6291 // Turn the index into an offset from the start of the input vector.
6292 Idx -= Input * NumElems;
6294 // Extract the vector element by hand.
6295 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6296 SVOp->getOperand(Input),
6297 DAG.getIntPtrConstant(Idx)));
6300 // Construct the output using a BUILD_VECTOR.
6301 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6303 } else if (InputUsed[0] < 0) {
6304 // No input vectors were used! The result is undefined.
6305 Output[l] = DAG.getUNDEF(NVT);
6307 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6308 (InputUsed[0] % 2) * NumLaneElems,
6310 // If only one input was used, use an undefined vector for the other.
6311 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6312 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6313 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6314 // At least one input vector was used. Create a new shuffle vector.
6315 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6321 // Concatenate the result back
6322 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6325 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6326 /// 4 elements, and match them with several different shuffle types.
6328 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6329 SDValue V1 = SVOp->getOperand(0);
6330 SDValue V2 = SVOp->getOperand(1);
6331 DebugLoc dl = SVOp->getDebugLoc();
6332 MVT VT = SVOp->getValueType(0).getSimpleVT();
6334 assert(VT.is128BitVector() && "Unsupported vector size");
6336 std::pair<int, int> Locs[4];
6337 int Mask1[] = { -1, -1, -1, -1 };
6338 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6342 for (unsigned i = 0; i != 4; ++i) {
6343 int Idx = PermMask[i];
6345 Locs[i] = std::make_pair(-1, -1);
6347 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6349 Locs[i] = std::make_pair(0, NumLo);
6353 Locs[i] = std::make_pair(1, NumHi);
6355 Mask1[2+NumHi] = Idx;
6361 if (NumLo <= 2 && NumHi <= 2) {
6362 // If no more than two elements come from either vector. This can be
6363 // implemented with two shuffles. First shuffle gather the elements.
6364 // The second shuffle, which takes the first shuffle as both of its
6365 // vector operands, put the elements into the right order.
6366 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6368 int Mask2[] = { -1, -1, -1, -1 };
6370 for (unsigned i = 0; i != 4; ++i)
6371 if (Locs[i].first != -1) {
6372 unsigned Idx = (i < 2) ? 0 : 4;
6373 Idx += Locs[i].first * 2 + Locs[i].second;
6377 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6380 if (NumLo == 3 || NumHi == 3) {
6381 // Otherwise, we must have three elements from one vector, call it X, and
6382 // one element from the other, call it Y. First, use a shufps to build an
6383 // intermediate vector with the one element from Y and the element from X
6384 // that will be in the same half in the final destination (the indexes don't
6385 // matter). Then, use a shufps to build the final vector, taking the half
6386 // containing the element from Y from the intermediate, and the other half
6389 // Normalize it so the 3 elements come from V1.
6390 CommuteVectorShuffleMask(PermMask, 4);
6394 // Find the element from V2.
6396 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6397 int Val = PermMask[HiIndex];
6404 Mask1[0] = PermMask[HiIndex];
6406 Mask1[2] = PermMask[HiIndex^1];
6408 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6411 Mask1[0] = PermMask[0];
6412 Mask1[1] = PermMask[1];
6413 Mask1[2] = HiIndex & 1 ? 6 : 4;
6414 Mask1[3] = HiIndex & 1 ? 4 : 6;
6415 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6418 Mask1[0] = HiIndex & 1 ? 2 : 0;
6419 Mask1[1] = HiIndex & 1 ? 0 : 2;
6420 Mask1[2] = PermMask[2];
6421 Mask1[3] = PermMask[3];
6426 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6429 // Break it into (shuffle shuffle_hi, shuffle_lo).
6430 int LoMask[] = { -1, -1, -1, -1 };
6431 int HiMask[] = { -1, -1, -1, -1 };
6433 int *MaskPtr = LoMask;
6434 unsigned MaskIdx = 0;
6437 for (unsigned i = 0; i != 4; ++i) {
6444 int Idx = PermMask[i];
6446 Locs[i] = std::make_pair(-1, -1);
6447 } else if (Idx < 4) {
6448 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6449 MaskPtr[LoIdx] = Idx;
6452 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6453 MaskPtr[HiIdx] = Idx;
6458 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6459 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6460 int MaskOps[] = { -1, -1, -1, -1 };
6461 for (unsigned i = 0; i != 4; ++i)
6462 if (Locs[i].first != -1)
6463 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6464 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6467 static bool MayFoldVectorLoad(SDValue V) {
6468 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6469 V = V.getOperand(0);
6471 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6472 V = V.getOperand(0);
6473 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6474 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6475 // BUILD_VECTOR (load), undef
6476 V = V.getOperand(0);
6478 return MayFoldLoad(V);
6482 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6483 EVT VT = Op.getValueType();
6485 // Canonizalize to v2f64.
6486 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6487 return DAG.getNode(ISD::BITCAST, dl, VT,
6488 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6493 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6495 SDValue V1 = Op.getOperand(0);
6496 SDValue V2 = Op.getOperand(1);
6497 EVT VT = Op.getValueType();
6499 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6501 if (HasSSE2 && VT == MVT::v2f64)
6502 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6504 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6505 return DAG.getNode(ISD::BITCAST, dl, VT,
6506 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6507 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6508 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6512 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6513 SDValue V1 = Op.getOperand(0);
6514 SDValue V2 = Op.getOperand(1);
6515 EVT VT = Op.getValueType();
6517 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6518 "unsupported shuffle type");
6520 if (V2.getOpcode() == ISD::UNDEF)
6524 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6528 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6529 SDValue V1 = Op.getOperand(0);
6530 SDValue V2 = Op.getOperand(1);
6531 EVT VT = Op.getValueType();
6532 unsigned NumElems = VT.getVectorNumElements();
6534 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6535 // operand of these instructions is only memory, so check if there's a
6536 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6538 bool CanFoldLoad = false;
6540 // Trivial case, when V2 comes from a load.
6541 if (MayFoldVectorLoad(V2))
6544 // When V1 is a load, it can be folded later into a store in isel, example:
6545 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6547 // (MOVLPSmr addr:$src1, VR128:$src2)
6548 // So, recognize this potential and also use MOVLPS or MOVLPD
6549 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6552 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6554 if (HasSSE2 && NumElems == 2)
6555 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6558 // If we don't care about the second element, proceed to use movss.
6559 if (SVOp->getMaskElt(1) != -1)
6560 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6563 // movl and movlp will both match v2i64, but v2i64 is never matched by
6564 // movl earlier because we make it strict to avoid messing with the movlp load
6565 // folding logic (see the code above getMOVLP call). Match it here then,
6566 // this is horrible, but will stay like this until we move all shuffle
6567 // matching to x86 specific nodes. Note that for the 1st condition all
6568 // types are matched with movsd.
6570 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6571 // as to remove this logic from here, as much as possible
6572 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6573 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6574 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6577 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6579 // Invert the operand order and use SHUFPS to match it.
6580 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6581 getShuffleSHUFImmediate(SVOp), DAG);
6584 // Reduce a vector shuffle to zext.
6586 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6587 // PMOVZX is only available from SSE41.
6588 if (!Subtarget->hasSSE41())
6591 EVT VT = Op.getValueType();
6593 // Only AVX2 support 256-bit vector integer extending.
6594 if (!Subtarget->hasInt256() && VT.is256BitVector())
6597 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6598 DebugLoc DL = Op.getDebugLoc();
6599 SDValue V1 = Op.getOperand(0);
6600 SDValue V2 = Op.getOperand(1);
6601 unsigned NumElems = VT.getVectorNumElements();
6603 // Extending is an unary operation and the element type of the source vector
6604 // won't be equal to or larger than i64.
6605 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6606 VT.getVectorElementType() == MVT::i64)
6609 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6610 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6611 while ((1U << Shift) < NumElems) {
6612 if (SVOp->getMaskElt(1U << Shift) == 1)
6615 // The maximal ratio is 8, i.e. from i8 to i64.
6620 // Check the shuffle mask.
6621 unsigned Mask = (1U << Shift) - 1;
6622 for (unsigned i = 0; i != NumElems; ++i) {
6623 int EltIdx = SVOp->getMaskElt(i);
6624 if ((i & Mask) != 0 && EltIdx != -1)
6626 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6630 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6631 EVT NeVT = EVT::getIntegerVT(*DAG.getContext(), NBits);
6632 EVT NVT = EVT::getVectorVT(*DAG.getContext(), NeVT, NumElems >> Shift);
6634 if (!isTypeLegal(NVT))
6637 // Simplify the operand as it's prepared to be fed into shuffle.
6638 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6639 if (V1.getOpcode() == ISD::BITCAST &&
6640 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6641 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6643 .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6644 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6645 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6646 ConstantSDNode *CIdx =
6647 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6648 // If it's foldable, i.e. normal load with single use, we will let code
6649 // selection to fold it. Otherwise, we will short the conversion sequence.
6650 if (CIdx && CIdx->getZExtValue() == 0 &&
6651 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse()))
6652 V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6655 return DAG.getNode(ISD::BITCAST, DL, VT,
6656 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6660 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6661 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6662 MVT VT = Op.getValueType().getSimpleVT();
6663 DebugLoc dl = Op.getDebugLoc();
6664 SDValue V1 = Op.getOperand(0);
6665 SDValue V2 = Op.getOperand(1);
6667 if (isZeroShuffle(SVOp))
6668 return getZeroVector(VT, Subtarget, DAG, dl);
6670 // Handle splat operations
6671 if (SVOp->isSplat()) {
6672 unsigned NumElem = VT.getVectorNumElements();
6674 // Use vbroadcast whenever the splat comes from a foldable load
6675 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6676 if (Broadcast.getNode())
6679 // Handle splats by matching through known shuffle masks
6680 if ((VT.is128BitVector() && NumElem <= 4) ||
6681 (VT.is256BitVector() && NumElem <= 8))
6684 // All remaning splats are promoted to target supported vector shuffles.
6685 return PromoteSplat(SVOp, DAG);
6688 // Check integer expanding shuffles.
6689 SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6690 if (NewOp.getNode())
6693 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6695 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6696 VT == MVT::v16i16 || VT == MVT::v32i8) {
6697 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6698 if (NewOp.getNode())
6699 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6700 } else if ((VT == MVT::v4i32 ||
6701 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6702 // FIXME: Figure out a cleaner way to do this.
6703 // Try to make use of movq to zero out the top part.
6704 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6705 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6706 if (NewOp.getNode()) {
6707 MVT NewVT = NewOp.getValueType().getSimpleVT();
6708 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6709 NewVT, true, false))
6710 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6711 DAG, Subtarget, dl);
6713 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6714 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6715 if (NewOp.getNode()) {
6716 MVT NewVT = NewOp.getValueType().getSimpleVT();
6717 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6718 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6719 DAG, Subtarget, dl);
6727 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6728 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6729 SDValue V1 = Op.getOperand(0);
6730 SDValue V2 = Op.getOperand(1);
6731 MVT VT = Op.getValueType().getSimpleVT();
6732 DebugLoc dl = Op.getDebugLoc();
6733 unsigned NumElems = VT.getVectorNumElements();
6734 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6735 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6736 bool V1IsSplat = false;
6737 bool V2IsSplat = false;
6738 bool HasSSE2 = Subtarget->hasSSE2();
6739 bool HasFp256 = Subtarget->hasFp256();
6740 bool HasInt256 = Subtarget->hasInt256();
6741 MachineFunction &MF = DAG.getMachineFunction();
6742 bool OptForSize = MF.getFunction()->getAttributes().
6743 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6745 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6747 if (V1IsUndef && V2IsUndef)
6748 return DAG.getUNDEF(VT);
6750 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6752 // Vector shuffle lowering takes 3 steps:
6754 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6755 // narrowing and commutation of operands should be handled.
6756 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6758 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6759 // so the shuffle can be broken into other shuffles and the legalizer can
6760 // try the lowering again.
6762 // The general idea is that no vector_shuffle operation should be left to
6763 // be matched during isel, all of them must be converted to a target specific
6766 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6767 // narrowing and commutation of operands should be handled. The actual code
6768 // doesn't include all of those, work in progress...
6769 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6770 if (NewOp.getNode())
6773 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6775 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6776 // unpckh_undef). Only use pshufd if speed is more important than size.
6777 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6778 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6779 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6780 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6782 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6783 V2IsUndef && MayFoldVectorLoad(V1))
6784 return getMOVDDup(Op, dl, V1, DAG);
6786 if (isMOVHLPS_v_undef_Mask(M, VT))
6787 return getMOVHighToLow(Op, dl, DAG);
6789 // Use to match splats
6790 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6791 (VT == MVT::v2f64 || VT == MVT::v2i64))
6792 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6794 if (isPSHUFDMask(M, VT)) {
6795 // The actual implementation will match the mask in the if above and then
6796 // during isel it can match several different instructions, not only pshufd
6797 // as its name says, sad but true, emulate the behavior for now...
6798 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6799 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6801 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6803 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6804 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6806 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6807 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6810 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6814 // Check if this can be converted into a logical shift.
6815 bool isLeft = false;
6818 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6819 if (isShift && ShVal.hasOneUse()) {
6820 // If the shifted value has multiple uses, it may be cheaper to use
6821 // v_set0 + movlhps or movhlps, etc.
6822 MVT EltVT = VT.getVectorElementType();
6823 ShAmt *= EltVT.getSizeInBits();
6824 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6827 if (isMOVLMask(M, VT)) {
6828 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6829 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6830 if (!isMOVLPMask(M, VT)) {
6831 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6832 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6834 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6835 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6839 // FIXME: fold these into legal mask.
6840 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6841 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6843 if (isMOVHLPSMask(M, VT))
6844 return getMOVHighToLow(Op, dl, DAG);
6846 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6847 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6849 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6850 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6852 if (isMOVLPMask(M, VT))
6853 return getMOVLP(Op, dl, DAG, HasSSE2);
6855 if (ShouldXformToMOVHLPS(M, VT) ||
6856 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6857 return CommuteVectorShuffle(SVOp, DAG);
6860 // No better options. Use a vshldq / vsrldq.
6861 MVT EltVT = VT.getVectorElementType();
6862 ShAmt *= EltVT.getSizeInBits();
6863 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6866 bool Commuted = false;
6867 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6868 // 1,1,1,1 -> v8i16 though.
6869 V1IsSplat = isSplatVector(V1.getNode());
6870 V2IsSplat = isSplatVector(V2.getNode());
6872 // Canonicalize the splat or undef, if present, to be on the RHS.
6873 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6874 CommuteVectorShuffleMask(M, NumElems);
6876 std::swap(V1IsSplat, V2IsSplat);
6880 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6881 // Shuffling low element of v1 into undef, just return v1.
6884 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6885 // the instruction selector will not match, so get a canonical MOVL with
6886 // swapped operands to undo the commute.
6887 return getMOVL(DAG, dl, VT, V2, V1);
6890 if (isUNPCKLMask(M, VT, HasInt256))
6891 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6893 if (isUNPCKHMask(M, VT, HasInt256))
6894 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6897 // Normalize mask so all entries that point to V2 points to its first
6898 // element then try to match unpck{h|l} again. If match, return a
6899 // new vector_shuffle with the corrected mask.p
6900 SmallVector<int, 8> NewMask(M.begin(), M.end());
6901 NormalizeMask(NewMask, NumElems);
6902 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6903 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6904 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6905 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6909 // Commute is back and try unpck* again.
6910 // FIXME: this seems wrong.
6911 CommuteVectorShuffleMask(M, NumElems);
6913 std::swap(V1IsSplat, V2IsSplat);
6916 if (isUNPCKLMask(M, VT, HasInt256))
6917 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6919 if (isUNPCKHMask(M, VT, HasInt256))
6920 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6923 // Normalize the node to match x86 shuffle ops if needed
6924 if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6925 return CommuteVectorShuffle(SVOp, DAG);
6927 // The checks below are all present in isShuffleMaskLegal, but they are
6928 // inlined here right now to enable us to directly emit target specific
6929 // nodes, and remove one by one until they don't return Op anymore.
6931 if (isPALIGNRMask(M, VT, Subtarget))
6932 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6933 getShufflePALIGNRImmediate(SVOp),
6936 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6937 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6938 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6939 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6942 if (isPSHUFHWMask(M, VT, HasInt256))
6943 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6944 getShufflePSHUFHWImmediate(SVOp),
6947 if (isPSHUFLWMask(M, VT, HasInt256))
6948 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6949 getShufflePSHUFLWImmediate(SVOp),
6952 if (isSHUFPMask(M, VT, HasFp256))
6953 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6954 getShuffleSHUFImmediate(SVOp), DAG);
6956 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6957 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6958 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6959 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6961 //===--------------------------------------------------------------------===//
6962 // Generate target specific nodes for 128 or 256-bit shuffles only
6963 // supported in the AVX instruction set.
6966 // Handle VMOVDDUPY permutations
6967 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
6968 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6970 // Handle VPERMILPS/D* permutations
6971 if (isVPERMILPMask(M, VT, HasFp256)) {
6972 if (HasInt256 && VT == MVT::v8i32)
6973 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6974 getShuffleSHUFImmediate(SVOp), DAG);
6975 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6976 getShuffleSHUFImmediate(SVOp), DAG);
6979 // Handle VPERM2F128/VPERM2I128 permutations
6980 if (isVPERM2X128Mask(M, VT, HasFp256))
6981 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6982 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6984 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6985 if (BlendOp.getNode())
6988 if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6989 SmallVector<SDValue, 8> permclMask;
6990 for (unsigned i = 0; i != 8; ++i) {
6991 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6993 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6995 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6996 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6997 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7000 if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7001 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7002 getShuffleCLImmediate(SVOp), DAG);
7004 //===--------------------------------------------------------------------===//
7005 // Since no target specific shuffle was selected for this generic one,
7006 // lower it into other known shuffles. FIXME: this isn't true yet, but
7007 // this is the plan.
7010 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7011 if (VT == MVT::v8i16) {
7012 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7013 if (NewOp.getNode())
7017 if (VT == MVT::v16i8) {
7018 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7019 if (NewOp.getNode())
7023 if (VT == MVT::v32i8) {
7024 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7025 if (NewOp.getNode())
7029 // Handle all 128-bit wide vectors with 4 elements, and match them with
7030 // several different shuffle types.
7031 if (NumElems == 4 && VT.is128BitVector())
7032 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7034 // Handle general 256-bit shuffles
7035 if (VT.is256BitVector())
7036 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7041 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7042 MVT VT = Op.getValueType().getSimpleVT();
7043 DebugLoc dl = Op.getDebugLoc();
7045 if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7048 if (VT.getSizeInBits() == 8) {
7049 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7050 Op.getOperand(0), Op.getOperand(1));
7051 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7052 DAG.getValueType(VT));
7053 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7056 if (VT.getSizeInBits() == 16) {
7057 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7058 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7060 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7061 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7062 DAG.getNode(ISD::BITCAST, dl,
7066 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7067 Op.getOperand(0), Op.getOperand(1));
7068 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7069 DAG.getValueType(VT));
7070 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7073 if (VT == MVT::f32) {
7074 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7075 // the result back to FR32 register. It's only worth matching if the
7076 // result has a single use which is a store or a bitcast to i32. And in
7077 // the case of a store, it's not worth it if the index is a constant 0,
7078 // because a MOVSSmr can be used instead, which is smaller and faster.
7079 if (!Op.hasOneUse())
7081 SDNode *User = *Op.getNode()->use_begin();
7082 if ((User->getOpcode() != ISD::STORE ||
7083 (isa<ConstantSDNode>(Op.getOperand(1)) &&
7084 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7085 (User->getOpcode() != ISD::BITCAST ||
7086 User->getValueType(0) != MVT::i32))
7088 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7089 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7092 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7095 if (VT == MVT::i32 || VT == MVT::i64) {
7096 // ExtractPS/pextrq works with constant index.
7097 if (isa<ConstantSDNode>(Op.getOperand(1)))
7104 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7105 SelectionDAG &DAG) const {
7106 if (!isa<ConstantSDNode>(Op.getOperand(1)))
7109 SDValue Vec = Op.getOperand(0);
7110 MVT VecVT = Vec.getValueType().getSimpleVT();
7112 // If this is a 256-bit vector result, first extract the 128-bit vector and
7113 // then extract the element from the 128-bit vector.
7114 if (VecVT.is256BitVector()) {
7115 DebugLoc dl = Op.getNode()->getDebugLoc();
7116 unsigned NumElems = VecVT.getVectorNumElements();
7117 SDValue Idx = Op.getOperand(1);
7118 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7120 // Get the 128-bit vector.
7121 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7123 if (IdxVal >= NumElems/2)
7124 IdxVal -= NumElems/2;
7125 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7126 DAG.getConstant(IdxVal, MVT::i32));
7129 assert(VecVT.is128BitVector() && "Unexpected vector length");
7131 if (Subtarget->hasSSE41()) {
7132 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7137 MVT VT = Op.getValueType().getSimpleVT();
7138 DebugLoc dl = Op.getDebugLoc();
7139 // TODO: handle v16i8.
7140 if (VT.getSizeInBits() == 16) {
7141 SDValue Vec = Op.getOperand(0);
7142 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7144 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7145 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7146 DAG.getNode(ISD::BITCAST, dl,
7149 // Transform it so it match pextrw which produces a 32-bit result.
7150 MVT EltVT = MVT::i32;
7151 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7152 Op.getOperand(0), Op.getOperand(1));
7153 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7154 DAG.getValueType(VT));
7155 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7158 if (VT.getSizeInBits() == 32) {
7159 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7163 // SHUFPS the element to the lowest double word, then movss.
7164 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7165 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7166 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7167 DAG.getUNDEF(VVT), Mask);
7168 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7169 DAG.getIntPtrConstant(0));
7172 if (VT.getSizeInBits() == 64) {
7173 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7174 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7175 // to match extract_elt for f64.
7176 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7180 // UNPCKHPD the element to the lowest double word, then movsd.
7181 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7182 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7183 int Mask[2] = { 1, -1 };
7184 MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7185 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7186 DAG.getUNDEF(VVT), Mask);
7187 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7188 DAG.getIntPtrConstant(0));
7194 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7195 MVT VT = Op.getValueType().getSimpleVT();
7196 MVT EltVT = VT.getVectorElementType();
7197 DebugLoc dl = Op.getDebugLoc();
7199 SDValue N0 = Op.getOperand(0);
7200 SDValue N1 = Op.getOperand(1);
7201 SDValue N2 = Op.getOperand(2);
7203 if (!VT.is128BitVector())
7206 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7207 isa<ConstantSDNode>(N2)) {
7209 if (VT == MVT::v8i16)
7210 Opc = X86ISD::PINSRW;
7211 else if (VT == MVT::v16i8)
7212 Opc = X86ISD::PINSRB;
7214 Opc = X86ISD::PINSRB;
7216 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7218 if (N1.getValueType() != MVT::i32)
7219 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7220 if (N2.getValueType() != MVT::i32)
7221 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7222 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7225 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7226 // Bits [7:6] of the constant are the source select. This will always be
7227 // zero here. The DAG Combiner may combine an extract_elt index into these
7228 // bits. For example (insert (extract, 3), 2) could be matched by putting
7229 // the '3' into bits [7:6] of X86ISD::INSERTPS.
7230 // Bits [5:4] of the constant are the destination select. This is the
7231 // value of the incoming immediate.
7232 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
7233 // combine either bitwise AND or insert of float 0.0 to set these bits.
7234 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7235 // Create this as a scalar to vector..
7236 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7237 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7240 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7241 // PINSR* works with constant index.
7248 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7249 MVT VT = Op.getValueType().getSimpleVT();
7250 MVT EltVT = VT.getVectorElementType();
7252 DebugLoc dl = Op.getDebugLoc();
7253 SDValue N0 = Op.getOperand(0);
7254 SDValue N1 = Op.getOperand(1);
7255 SDValue N2 = Op.getOperand(2);
7257 // If this is a 256-bit vector result, first extract the 128-bit vector,
7258 // insert the element into the extracted half and then place it back.
7259 if (VT.is256BitVector()) {
7260 if (!isa<ConstantSDNode>(N2))
7263 // Get the desired 128-bit vector half.
7264 unsigned NumElems = VT.getVectorNumElements();
7265 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7266 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7268 // Insert the element into the desired half.
7269 bool Upper = IdxVal >= NumElems/2;
7270 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7271 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7273 // Insert the changed part back to the 256-bit vector
7274 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7277 if (Subtarget->hasSSE41())
7278 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7280 if (EltVT == MVT::i8)
7283 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7284 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7285 // as its second argument.
7286 if (N1.getValueType() != MVT::i32)
7287 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7288 if (N2.getValueType() != MVT::i32)
7289 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7290 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7295 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7296 LLVMContext *Context = DAG.getContext();
7297 DebugLoc dl = Op.getDebugLoc();
7298 MVT OpVT = Op.getValueType().getSimpleVT();
7300 // If this is a 256-bit vector result, first insert into a 128-bit
7301 // vector and then insert into the 256-bit vector.
7302 if (!OpVT.is128BitVector()) {
7303 // Insert into a 128-bit vector.
7304 EVT VT128 = EVT::getVectorVT(*Context,
7305 OpVT.getVectorElementType(),
7306 OpVT.getVectorNumElements() / 2);
7308 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7310 // Insert the 128-bit vector.
7311 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7314 if (OpVT == MVT::v1i64 &&
7315 Op.getOperand(0).getValueType() == MVT::i64)
7316 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7318 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7319 assert(OpVT.is128BitVector() && "Expected an SSE type!");
7320 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7321 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7324 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7325 // a simple subregister reference or explicit instructions to grab
7326 // upper bits of a vector.
7327 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7328 SelectionDAG &DAG) {
7329 if (Subtarget->hasFp256()) {
7330 DebugLoc dl = Op.getNode()->getDebugLoc();
7331 SDValue Vec = Op.getNode()->getOperand(0);
7332 SDValue Idx = Op.getNode()->getOperand(1);
7334 if (Op.getNode()->getValueType(0).is128BitVector() &&
7335 Vec.getNode()->getValueType(0).is256BitVector() &&
7336 isa<ConstantSDNode>(Idx)) {
7337 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7338 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7344 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7345 // simple superregister reference or explicit instructions to insert
7346 // the upper bits of a vector.
7347 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7348 SelectionDAG &DAG) {
7349 if (Subtarget->hasFp256()) {
7350 DebugLoc dl = Op.getNode()->getDebugLoc();
7351 SDValue Vec = Op.getNode()->getOperand(0);
7352 SDValue SubVec = Op.getNode()->getOperand(1);
7353 SDValue Idx = Op.getNode()->getOperand(2);
7355 if (Op.getNode()->getValueType(0).is256BitVector() &&
7356 SubVec.getNode()->getValueType(0).is128BitVector() &&
7357 isa<ConstantSDNode>(Idx)) {
7358 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7359 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7365 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7366 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7367 // one of the above mentioned nodes. It has to be wrapped because otherwise
7368 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7369 // be used to form addressing mode. These wrapped nodes will be selected
7372 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7373 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7375 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7377 unsigned char OpFlag = 0;
7378 unsigned WrapperKind = X86ISD::Wrapper;
7379 CodeModel::Model M = getTargetMachine().getCodeModel();
7381 if (Subtarget->isPICStyleRIPRel() &&
7382 (M == CodeModel::Small || M == CodeModel::Kernel))
7383 WrapperKind = X86ISD::WrapperRIP;
7384 else if (Subtarget->isPICStyleGOT())
7385 OpFlag = X86II::MO_GOTOFF;
7386 else if (Subtarget->isPICStyleStubPIC())
7387 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7389 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7391 CP->getOffset(), OpFlag);
7392 DebugLoc DL = CP->getDebugLoc();
7393 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7394 // With PIC, the address is actually $g + Offset.
7396 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7397 DAG.getNode(X86ISD::GlobalBaseReg,
7398 DebugLoc(), getPointerTy()),
7405 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7406 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7408 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7410 unsigned char OpFlag = 0;
7411 unsigned WrapperKind = X86ISD::Wrapper;
7412 CodeModel::Model M = getTargetMachine().getCodeModel();
7414 if (Subtarget->isPICStyleRIPRel() &&
7415 (M == CodeModel::Small || M == CodeModel::Kernel))
7416 WrapperKind = X86ISD::WrapperRIP;
7417 else if (Subtarget->isPICStyleGOT())
7418 OpFlag = X86II::MO_GOTOFF;
7419 else if (Subtarget->isPICStyleStubPIC())
7420 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7422 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7424 DebugLoc DL = JT->getDebugLoc();
7425 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7427 // With PIC, the address is actually $g + Offset.
7429 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7430 DAG.getNode(X86ISD::GlobalBaseReg,
7431 DebugLoc(), getPointerTy()),
7438 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7439 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7441 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7443 unsigned char OpFlag = 0;
7444 unsigned WrapperKind = X86ISD::Wrapper;
7445 CodeModel::Model M = getTargetMachine().getCodeModel();
7447 if (Subtarget->isPICStyleRIPRel() &&
7448 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7449 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7450 OpFlag = X86II::MO_GOTPCREL;
7451 WrapperKind = X86ISD::WrapperRIP;
7452 } else if (Subtarget->isPICStyleGOT()) {
7453 OpFlag = X86II::MO_GOT;
7454 } else if (Subtarget->isPICStyleStubPIC()) {
7455 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7456 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7457 OpFlag = X86II::MO_DARWIN_NONLAZY;
7460 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7462 DebugLoc DL = Op.getDebugLoc();
7463 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7465 // With PIC, the address is actually $g + Offset.
7466 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7467 !Subtarget->is64Bit()) {
7468 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7469 DAG.getNode(X86ISD::GlobalBaseReg,
7470 DebugLoc(), getPointerTy()),
7474 // For symbols that require a load from a stub to get the address, emit the
7476 if (isGlobalStubReference(OpFlag))
7477 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7478 MachinePointerInfo::getGOT(), false, false, false, 0);
7484 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7485 // Create the TargetBlockAddressAddress node.
7486 unsigned char OpFlags =
7487 Subtarget->ClassifyBlockAddressReference();
7488 CodeModel::Model M = getTargetMachine().getCodeModel();
7489 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7490 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7491 DebugLoc dl = Op.getDebugLoc();
7492 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7495 if (Subtarget->isPICStyleRIPRel() &&
7496 (M == CodeModel::Small || M == CodeModel::Kernel))
7497 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7499 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7501 // With PIC, the address is actually $g + Offset.
7502 if (isGlobalRelativeToPICBase(OpFlags)) {
7503 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7504 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7512 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7513 int64_t Offset, SelectionDAG &DAG) const {
7514 // Create the TargetGlobalAddress node, folding in the constant
7515 // offset if it is legal.
7516 unsigned char OpFlags =
7517 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7518 CodeModel::Model M = getTargetMachine().getCodeModel();
7520 if (OpFlags == X86II::MO_NO_FLAG &&
7521 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7522 // A direct static reference to a global.
7523 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7526 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7529 if (Subtarget->isPICStyleRIPRel() &&
7530 (M == CodeModel::Small || M == CodeModel::Kernel))
7531 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7533 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7535 // With PIC, the address is actually $g + Offset.
7536 if (isGlobalRelativeToPICBase(OpFlags)) {
7537 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7538 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7542 // For globals that require a load from a stub to get the address, emit the
7544 if (isGlobalStubReference(OpFlags))
7545 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7546 MachinePointerInfo::getGOT(), false, false, false, 0);
7548 // If there was a non-zero offset that we didn't fold, create an explicit
7551 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7552 DAG.getConstant(Offset, getPointerTy()));
7558 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7559 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7560 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7561 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7565 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7566 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7567 unsigned char OperandFlags, bool LocalDynamic = false) {
7568 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7569 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7570 DebugLoc dl = GA->getDebugLoc();
7571 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7572 GA->getValueType(0),
7576 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7580 SDValue Ops[] = { Chain, TGA, *InFlag };
7581 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7583 SDValue Ops[] = { Chain, TGA };
7584 Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7587 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7588 MFI->setAdjustsStack(true);
7590 SDValue Flag = Chain.getValue(1);
7591 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7594 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7596 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7599 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7600 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7601 DAG.getNode(X86ISD::GlobalBaseReg,
7602 DebugLoc(), PtrVT), InFlag);
7603 InFlag = Chain.getValue(1);
7605 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7608 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7610 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7612 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7613 X86::RAX, X86II::MO_TLSGD);
7616 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7620 DebugLoc dl = GA->getDebugLoc();
7622 // Get the start address of the TLS block for this module.
7623 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7624 .getInfo<X86MachineFunctionInfo>();
7625 MFI->incNumLocalDynamicTLSAccesses();
7629 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7630 X86II::MO_TLSLD, /*LocalDynamic=*/true);
7633 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7634 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7635 InFlag = Chain.getValue(1);
7636 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7637 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7640 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7644 unsigned char OperandFlags = X86II::MO_DTPOFF;
7645 unsigned WrapperKind = X86ISD::Wrapper;
7646 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7647 GA->getValueType(0),
7648 GA->getOffset(), OperandFlags);
7649 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7651 // Add x@dtpoff with the base.
7652 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7655 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7656 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7657 const EVT PtrVT, TLSModel::Model model,
7658 bool is64Bit, bool isPIC) {
7659 DebugLoc dl = GA->getDebugLoc();
7661 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7662 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7663 is64Bit ? 257 : 256));
7665 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7666 DAG.getIntPtrConstant(0),
7667 MachinePointerInfo(Ptr),
7668 false, false, false, 0);
7670 unsigned char OperandFlags = 0;
7671 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7673 unsigned WrapperKind = X86ISD::Wrapper;
7674 if (model == TLSModel::LocalExec) {
7675 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7676 } else if (model == TLSModel::InitialExec) {
7678 OperandFlags = X86II::MO_GOTTPOFF;
7679 WrapperKind = X86ISD::WrapperRIP;
7681 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7684 llvm_unreachable("Unexpected model");
7687 // emit "addl x@ntpoff,%eax" (local exec)
7688 // or "addl x@indntpoff,%eax" (initial exec)
7689 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7690 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7691 GA->getValueType(0),
7692 GA->getOffset(), OperandFlags);
7693 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7695 if (model == TLSModel::InitialExec) {
7696 if (isPIC && !is64Bit) {
7697 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7698 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7702 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7703 MachinePointerInfo::getGOT(), false, false, false,
7707 // The address of the thread local variable is the add of the thread
7708 // pointer with the offset of the variable.
7709 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7713 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7715 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7716 const GlobalValue *GV = GA->getGlobal();
7718 if (Subtarget->isTargetELF()) {
7719 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7722 case TLSModel::GeneralDynamic:
7723 if (Subtarget->is64Bit())
7724 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7725 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7726 case TLSModel::LocalDynamic:
7727 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7728 Subtarget->is64Bit());
7729 case TLSModel::InitialExec:
7730 case TLSModel::LocalExec:
7731 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7732 Subtarget->is64Bit(),
7733 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7735 llvm_unreachable("Unknown TLS model.");
7738 if (Subtarget->isTargetDarwin()) {
7739 // Darwin only has one model of TLS. Lower to that.
7740 unsigned char OpFlag = 0;
7741 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7742 X86ISD::WrapperRIP : X86ISD::Wrapper;
7744 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7746 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7747 !Subtarget->is64Bit();
7749 OpFlag = X86II::MO_TLVP_PIC_BASE;
7751 OpFlag = X86II::MO_TLVP;
7752 DebugLoc DL = Op.getDebugLoc();
7753 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7754 GA->getValueType(0),
7755 GA->getOffset(), OpFlag);
7756 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7758 // With PIC32, the address is actually $g + Offset.
7760 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7761 DAG.getNode(X86ISD::GlobalBaseReg,
7762 DebugLoc(), getPointerTy()),
7765 // Lowering the machine isd will make sure everything is in the right
7767 SDValue Chain = DAG.getEntryNode();
7768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7769 SDValue Args[] = { Chain, Offset };
7770 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7772 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7773 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7774 MFI->setAdjustsStack(true);
7776 // And our return value (tls address) is in the standard call return value
7778 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7779 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7783 if (Subtarget->isTargetWindows()) {
7784 // Just use the implicit TLS architecture
7785 // Need to generate someting similar to:
7786 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7788 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7789 // mov rcx, qword [rdx+rcx*8]
7790 // mov eax, .tls$:tlsvar
7791 // [rax+rcx] contains the address
7792 // Windows 64bit: gs:0x58
7793 // Windows 32bit: fs:__tls_array
7795 // If GV is an alias then use the aliasee for determining
7796 // thread-localness.
7797 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7798 GV = GA->resolveAliasedGlobal(false);
7799 DebugLoc dl = GA->getDebugLoc();
7800 SDValue Chain = DAG.getEntryNode();
7802 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7803 // %gs:0x58 (64-bit).
7804 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7805 ? Type::getInt8PtrTy(*DAG.getContext(),
7807 : Type::getInt32PtrTy(*DAG.getContext(),
7810 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7811 Subtarget->is64Bit()
7812 ? DAG.getIntPtrConstant(0x58)
7813 : DAG.getExternalSymbol("_tls_array",
7815 MachinePointerInfo(Ptr),
7816 false, false, false, 0);
7818 // Load the _tls_index variable
7819 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7820 if (Subtarget->is64Bit())
7821 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7822 IDX, MachinePointerInfo(), MVT::i32,
7825 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7826 false, false, false, 0);
7828 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7830 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7832 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7833 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7834 false, false, false, 0);
7836 // Get the offset of start of .tls section
7837 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7838 GA->getValueType(0),
7839 GA->getOffset(), X86II::MO_SECREL);
7840 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7842 // The address of the thread local variable is the add of the thread
7843 // pointer with the offset of the variable.
7844 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7847 llvm_unreachable("TLS not implemented for this target.");
7850 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7851 /// and take a 2 x i32 value to shift plus a shift amount.
7852 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7853 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7854 EVT VT = Op.getValueType();
7855 unsigned VTBits = VT.getSizeInBits();
7856 DebugLoc dl = Op.getDebugLoc();
7857 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7858 SDValue ShOpLo = Op.getOperand(0);
7859 SDValue ShOpHi = Op.getOperand(1);
7860 SDValue ShAmt = Op.getOperand(2);
7861 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7862 DAG.getConstant(VTBits - 1, MVT::i8))
7863 : DAG.getConstant(0, VT);
7866 if (Op.getOpcode() == ISD::SHL_PARTS) {
7867 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7868 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7870 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7871 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7874 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7875 DAG.getConstant(VTBits, MVT::i8));
7876 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7877 AndNode, DAG.getConstant(0, MVT::i8));
7880 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7881 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7882 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7884 if (Op.getOpcode() == ISD::SHL_PARTS) {
7885 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7886 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7888 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7889 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7892 SDValue Ops[2] = { Lo, Hi };
7893 return DAG.getMergeValues(Ops, 2, dl);
7896 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7897 SelectionDAG &DAG) const {
7898 EVT SrcVT = Op.getOperand(0).getValueType();
7900 if (SrcVT.isVector())
7903 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7904 "Unknown SINT_TO_FP to lower!");
7906 // These are really Legal; return the operand so the caller accepts it as
7908 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7910 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7911 Subtarget->is64Bit()) {
7915 DebugLoc dl = Op.getDebugLoc();
7916 unsigned Size = SrcVT.getSizeInBits()/8;
7917 MachineFunction &MF = DAG.getMachineFunction();
7918 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7919 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7920 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7922 MachinePointerInfo::getFixedStack(SSFI),
7924 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7927 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7929 SelectionDAG &DAG) const {
7931 DebugLoc DL = Op.getDebugLoc();
7933 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7935 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7937 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7939 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7941 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7942 MachineMemOperand *MMO;
7944 int SSFI = FI->getIndex();
7946 DAG.getMachineFunction()
7947 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7948 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7950 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7951 StackSlot = StackSlot.getOperand(1);
7953 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7954 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7956 Tys, Ops, array_lengthof(Ops),
7960 Chain = Result.getValue(1);
7961 SDValue InFlag = Result.getValue(2);
7963 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7964 // shouldn't be necessary except that RFP cannot be live across
7965 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7966 MachineFunction &MF = DAG.getMachineFunction();
7967 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7968 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7969 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7970 Tys = DAG.getVTList(MVT::Other);
7972 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7974 MachineMemOperand *MMO =
7975 DAG.getMachineFunction()
7976 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7977 MachineMemOperand::MOStore, SSFISize, SSFISize);
7979 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7980 Ops, array_lengthof(Ops),
7981 Op.getValueType(), MMO);
7982 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7983 MachinePointerInfo::getFixedStack(SSFI),
7984 false, false, false, 0);
7990 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7991 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7992 SelectionDAG &DAG) const {
7993 // This algorithm is not obvious. Here it is what we're trying to output:
7996 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7997 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8001 pshufd $0x4e, %xmm0, %xmm1
8006 DebugLoc dl = Op.getDebugLoc();
8007 LLVMContext *Context = DAG.getContext();
8009 // Build some magic constants.
8010 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8011 Constant *C0 = ConstantDataVector::get(*Context, CV0);
8012 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8014 SmallVector<Constant*,2> CV1;
8016 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8017 APInt(64, 0x4330000000000000ULL))));
8019 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8020 APInt(64, 0x4530000000000000ULL))));
8021 Constant *C1 = ConstantVector::get(CV1);
8022 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8024 // Load the 64-bit value into an XMM register.
8025 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8027 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8028 MachinePointerInfo::getConstantPool(),
8029 false, false, false, 16);
8030 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8031 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8034 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8035 MachinePointerInfo::getConstantPool(),
8036 false, false, false, 16);
8037 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8038 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8041 if (Subtarget->hasSSE3()) {
8042 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8043 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8045 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8046 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8048 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8049 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8053 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8054 DAG.getIntPtrConstant(0));
8057 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8058 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8059 SelectionDAG &DAG) const {
8060 DebugLoc dl = Op.getDebugLoc();
8061 // FP constant to bias correct the final result.
8062 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8065 // Load the 32-bit value into an XMM register.
8066 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8069 // Zero out the upper parts of the register.
8070 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8072 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8073 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8074 DAG.getIntPtrConstant(0));
8076 // Or the load with the bias.
8077 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8078 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8079 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8081 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8082 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8083 MVT::v2f64, Bias)));
8084 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8085 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8086 DAG.getIntPtrConstant(0));
8088 // Subtract the bias.
8089 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8091 // Handle final rounding.
8092 EVT DestVT = Op.getValueType();
8094 if (DestVT.bitsLT(MVT::f64))
8095 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8096 DAG.getIntPtrConstant(0));
8097 if (DestVT.bitsGT(MVT::f64))
8098 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8100 // Handle final rounding.
8104 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8105 SelectionDAG &DAG) const {
8106 SDValue N0 = Op.getOperand(0);
8107 EVT SVT = N0.getValueType();
8108 DebugLoc dl = Op.getDebugLoc();
8110 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8111 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8112 "Custom UINT_TO_FP is not supported!");
8114 EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8115 SVT.getVectorNumElements());
8116 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8117 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8120 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8121 SelectionDAG &DAG) const {
8122 SDValue N0 = Op.getOperand(0);
8123 DebugLoc dl = Op.getDebugLoc();
8125 if (Op.getValueType().isVector())
8126 return lowerUINT_TO_FP_vec(Op, DAG);
8128 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8129 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8130 // the optimization here.
8131 if (DAG.SignBitIsZero(N0))
8132 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8134 EVT SrcVT = N0.getValueType();
8135 EVT DstVT = Op.getValueType();
8136 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8137 return LowerUINT_TO_FP_i64(Op, DAG);
8138 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8139 return LowerUINT_TO_FP_i32(Op, DAG);
8140 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8143 // Make a 64-bit buffer, and use it to build an FILD.
8144 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8145 if (SrcVT == MVT::i32) {
8146 SDValue WordOff = DAG.getConstant(4, getPointerTy());
8147 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8148 getPointerTy(), StackSlot, WordOff);
8149 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8150 StackSlot, MachinePointerInfo(),
8152 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8153 OffsetSlot, MachinePointerInfo(),
8155 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8159 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8160 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8161 StackSlot, MachinePointerInfo(),
8163 // For i64 source, we need to add the appropriate power of 2 if the input
8164 // was negative. This is the same as the optimization in
8165 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8166 // we must be careful to do the computation in x87 extended precision, not
8167 // in SSE. (The generic code can't know it's OK to do this, or how to.)
8168 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8169 MachineMemOperand *MMO =
8170 DAG.getMachineFunction()
8171 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8172 MachineMemOperand::MOLoad, 8, 8);
8174 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8175 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8176 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8179 APInt FF(32, 0x5F800000ULL);
8181 // Check whether the sign bit is set.
8182 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8183 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8186 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8187 SDValue FudgePtr = DAG.getConstantPool(
8188 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8191 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8192 SDValue Zero = DAG.getIntPtrConstant(0);
8193 SDValue Four = DAG.getIntPtrConstant(4);
8194 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8196 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8198 // Load the value out, extending it from f32 to f80.
8199 // FIXME: Avoid the extend by constructing the right constant pool?
8200 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8201 FudgePtr, MachinePointerInfo::getConstantPool(),
8202 MVT::f32, false, false, 4);
8203 // Extend everything to 80 bits to force it to be done on x87.
8204 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8205 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8208 std::pair<SDValue,SDValue>
8209 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8210 bool IsSigned, bool IsReplace) const {
8211 DebugLoc DL = Op.getDebugLoc();
8213 EVT DstTy = Op.getValueType();
8215 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8216 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8220 assert(DstTy.getSimpleVT() <= MVT::i64 &&
8221 DstTy.getSimpleVT() >= MVT::i16 &&
8222 "Unknown FP_TO_INT to lower!");
8224 // These are really Legal.
8225 if (DstTy == MVT::i32 &&
8226 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8227 return std::make_pair(SDValue(), SDValue());
8228 if (Subtarget->is64Bit() &&
8229 DstTy == MVT::i64 &&
8230 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8231 return std::make_pair(SDValue(), SDValue());
8233 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8234 // stack slot, or into the FTOL runtime function.
8235 MachineFunction &MF = DAG.getMachineFunction();
8236 unsigned MemSize = DstTy.getSizeInBits()/8;
8237 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8238 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8241 if (!IsSigned && isIntegerTypeFTOL(DstTy))
8242 Opc = X86ISD::WIN_FTOL;
8244 switch (DstTy.getSimpleVT().SimpleTy) {
8245 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8246 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8247 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8248 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8251 SDValue Chain = DAG.getEntryNode();
8252 SDValue Value = Op.getOperand(0);
8253 EVT TheVT = Op.getOperand(0).getValueType();
8254 // FIXME This causes a redundant load/store if the SSE-class value is already
8255 // in memory, such as if it is on the callstack.
8256 if (isScalarFPTypeInSSEReg(TheVT)) {
8257 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8258 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8259 MachinePointerInfo::getFixedStack(SSFI),
8261 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8263 Chain, StackSlot, DAG.getValueType(TheVT)
8266 MachineMemOperand *MMO =
8267 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8268 MachineMemOperand::MOLoad, MemSize, MemSize);
8269 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8271 Chain = Value.getValue(1);
8272 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8273 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8276 MachineMemOperand *MMO =
8277 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8278 MachineMemOperand::MOStore, MemSize, MemSize);
8280 if (Opc != X86ISD::WIN_FTOL) {
8281 // Build the FP_TO_INT*_IN_MEM
8282 SDValue Ops[] = { Chain, Value, StackSlot };
8283 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8284 Ops, 3, DstTy, MMO);
8285 return std::make_pair(FIST, StackSlot);
8287 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8288 DAG.getVTList(MVT::Other, MVT::Glue),
8290 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8291 MVT::i32, ftol.getValue(1));
8292 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8293 MVT::i32, eax.getValue(2));
8294 SDValue Ops[] = { eax, edx };
8295 SDValue pair = IsReplace
8296 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8297 : DAG.getMergeValues(Ops, 2, DL);
8298 return std::make_pair(pair, SDValue());
8302 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8303 const X86Subtarget *Subtarget) {
8304 MVT VT = Op->getValueType(0).getSimpleVT();
8305 SDValue In = Op->getOperand(0);
8306 MVT InVT = In.getValueType().getSimpleVT();
8307 DebugLoc dl = Op->getDebugLoc();
8309 // Optimize vectors in AVX mode:
8312 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
8313 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
8314 // Concat upper and lower parts.
8317 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
8318 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
8319 // Concat upper and lower parts.
8322 if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8323 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8326 if (Subtarget->hasInt256())
8327 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8329 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8330 SDValue Undef = DAG.getUNDEF(InVT);
8331 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8332 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8333 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8335 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8336 VT.getVectorNumElements()/2);
8338 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8339 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8341 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8344 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8345 SelectionDAG &DAG) const {
8346 if (Subtarget->hasFp256()) {
8347 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8354 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8355 SelectionDAG &DAG) const {
8356 DebugLoc DL = Op.getDebugLoc();
8357 MVT VT = Op.getValueType().getSimpleVT();
8358 SDValue In = Op.getOperand(0);
8359 MVT SVT = In.getValueType().getSimpleVT();
8361 if (Subtarget->hasFp256()) {
8362 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8367 if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8368 VT.getVectorNumElements() != SVT.getVectorNumElements())
8371 assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8373 // AVX2 has better support of integer extending.
8374 if (Subtarget->hasInt256())
8375 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8377 SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8378 static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8379 SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8380 DAG.getVectorShuffle(MVT::v8i16, DL, In,
8381 DAG.getUNDEF(MVT::v8i16),
8384 return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8387 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8388 DebugLoc DL = Op.getDebugLoc();
8389 MVT VT = Op.getValueType().getSimpleVT();
8390 SDValue In = Op.getOperand(0);
8391 MVT SVT = In.getValueType().getSimpleVT();
8393 if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8394 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8395 if (Subtarget->hasInt256()) {
8396 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8397 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8398 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8400 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8401 DAG.getIntPtrConstant(0));
8404 // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8405 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8406 DAG.getIntPtrConstant(0));
8407 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8408 DAG.getIntPtrConstant(2));
8410 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8411 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8414 static const int ShufMask1[] = {0, 2, 0, 0};
8415 SDValue Undef = DAG.getUNDEF(VT);
8416 OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8417 OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8419 // The MOVLHPS mask:
8420 static const int ShufMask2[] = {0, 1, 4, 5};
8421 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8424 if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8425 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8426 if (Subtarget->hasInt256()) {
8427 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8429 SmallVector<SDValue,32> pshufbMask;
8430 for (unsigned i = 0; i < 2; ++i) {
8431 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8432 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8433 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8434 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8435 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8436 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8437 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8438 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8439 for (unsigned j = 0; j < 8; ++j)
8440 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8442 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8443 &pshufbMask[0], 32);
8444 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8445 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8447 static const int ShufMask[] = {0, 2, -1, -1};
8448 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
8450 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8451 DAG.getIntPtrConstant(0));
8452 return DAG.getNode(ISD::BITCAST, DL, VT, In);
8455 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8456 DAG.getIntPtrConstant(0));
8458 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8459 DAG.getIntPtrConstant(4));
8461 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8462 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8465 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
8466 -1, -1, -1, -1, -1, -1, -1, -1};
8468 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8469 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8470 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8472 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8473 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8475 // The MOVLHPS Mask:
8476 static const int ShufMask2[] = {0, 1, 4, 5};
8477 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8478 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8481 // Handle truncation of V256 to V128 using shuffles.
8482 if (!VT.is128BitVector() || !SVT.is256BitVector())
8485 assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8487 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8489 unsigned NumElems = VT.getVectorNumElements();
8490 EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8493 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8494 // Prepare truncation shuffle mask
8495 for (unsigned i = 0; i != NumElems; ++i)
8497 SDValue V = DAG.getVectorShuffle(NVT, DL,
8498 DAG.getNode(ISD::BITCAST, DL, NVT, In),
8499 DAG.getUNDEF(NVT), &MaskVec[0]);
8500 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8501 DAG.getIntPtrConstant(0));
8504 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8505 SelectionDAG &DAG) const {
8506 MVT VT = Op.getValueType().getSimpleVT();
8507 if (VT.isVector()) {
8508 if (VT == MVT::v8i16)
8509 return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8510 DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8511 MVT::v8i32, Op.getOperand(0)));
8515 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8516 /*IsSigned=*/ true, /*IsReplace=*/ false);
8517 SDValue FIST = Vals.first, StackSlot = Vals.second;
8518 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8519 if (FIST.getNode() == 0) return Op;
8521 if (StackSlot.getNode())
8523 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8524 FIST, StackSlot, MachinePointerInfo(),
8525 false, false, false, 0);
8527 // The node is the result.
8531 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8532 SelectionDAG &DAG) const {
8533 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8534 /*IsSigned=*/ false, /*IsReplace=*/ false);
8535 SDValue FIST = Vals.first, StackSlot = Vals.second;
8536 assert(FIST.getNode() && "Unexpected failure");
8538 if (StackSlot.getNode())
8540 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8541 FIST, StackSlot, MachinePointerInfo(),
8542 false, false, false, 0);
8544 // The node is the result.
8548 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8549 DebugLoc DL = Op.getDebugLoc();
8550 MVT VT = Op.getValueType().getSimpleVT();
8551 SDValue In = Op.getOperand(0);
8552 MVT SVT = In.getValueType().getSimpleVT();
8554 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8556 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8557 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8558 In, DAG.getUNDEF(SVT)));
8561 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8562 LLVMContext *Context = DAG.getContext();
8563 DebugLoc dl = Op.getDebugLoc();
8564 MVT VT = Op.getValueType().getSimpleVT();
8566 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8567 if (VT.isVector()) {
8568 EltVT = VT.getVectorElementType();
8569 NumElts = VT.getVectorNumElements();
8572 if (EltVT == MVT::f64)
8573 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8574 APInt(64, ~(1ULL << 63))));
8576 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8577 APInt(32, ~(1U << 31))));
8578 C = ConstantVector::getSplat(NumElts, C);
8579 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8580 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8581 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8582 MachinePointerInfo::getConstantPool(),
8583 false, false, false, Alignment);
8584 if (VT.isVector()) {
8585 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8586 return DAG.getNode(ISD::BITCAST, dl, VT,
8587 DAG.getNode(ISD::AND, dl, ANDVT,
8588 DAG.getNode(ISD::BITCAST, dl, ANDVT,
8590 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8592 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8595 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8596 LLVMContext *Context = DAG.getContext();
8597 DebugLoc dl = Op.getDebugLoc();
8598 MVT VT = Op.getValueType().getSimpleVT();
8600 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8601 if (VT.isVector()) {
8602 EltVT = VT.getVectorElementType();
8603 NumElts = VT.getVectorNumElements();
8606 if (EltVT == MVT::f64)
8607 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8608 APInt(64, 1ULL << 63)));
8610 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8611 APInt(32, 1U << 31)));
8612 C = ConstantVector::getSplat(NumElts, C);
8613 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8614 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8615 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8616 MachinePointerInfo::getConstantPool(),
8617 false, false, false, Alignment);
8618 if (VT.isVector()) {
8619 MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8620 return DAG.getNode(ISD::BITCAST, dl, VT,
8621 DAG.getNode(ISD::XOR, dl, XORVT,
8622 DAG.getNode(ISD::BITCAST, dl, XORVT,
8624 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8627 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8630 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8631 LLVMContext *Context = DAG.getContext();
8632 SDValue Op0 = Op.getOperand(0);
8633 SDValue Op1 = Op.getOperand(1);
8634 DebugLoc dl = Op.getDebugLoc();
8635 MVT VT = Op.getValueType().getSimpleVT();
8636 MVT SrcVT = Op1.getValueType().getSimpleVT();
8638 // If second operand is smaller, extend it first.
8639 if (SrcVT.bitsLT(VT)) {
8640 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8643 // And if it is bigger, shrink it first.
8644 if (SrcVT.bitsGT(VT)) {
8645 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8649 // At this point the operands and the result should have the same
8650 // type, and that won't be f80 since that is not custom lowered.
8652 // First get the sign bit of second operand.
8653 SmallVector<Constant*,4> CV;
8654 if (SrcVT == MVT::f64) {
8655 const fltSemantics &Sem = APFloat::IEEEdouble;
8656 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8657 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8659 const fltSemantics &Sem = APFloat::IEEEsingle;
8660 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8661 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8662 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8663 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8665 Constant *C = ConstantVector::get(CV);
8666 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8667 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8668 MachinePointerInfo::getConstantPool(),
8669 false, false, false, 16);
8670 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8672 // Shift sign bit right or left if the two operands have different types.
8673 if (SrcVT.bitsGT(VT)) {
8674 // Op0 is MVT::f32, Op1 is MVT::f64.
8675 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8676 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8677 DAG.getConstant(32, MVT::i32));
8678 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8679 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8680 DAG.getIntPtrConstant(0));
8683 // Clear first operand sign bit.
8685 if (VT == MVT::f64) {
8686 const fltSemantics &Sem = APFloat::IEEEdouble;
8687 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8688 APInt(64, ~(1ULL << 63)))));
8689 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8691 const fltSemantics &Sem = APFloat::IEEEsingle;
8692 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8693 APInt(32, ~(1U << 31)))));
8694 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8695 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8696 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8698 C = ConstantVector::get(CV);
8699 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8700 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8701 MachinePointerInfo::getConstantPool(),
8702 false, false, false, 16);
8703 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8705 // Or the value with the sign bit.
8706 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8709 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8710 SDValue N0 = Op.getOperand(0);
8711 DebugLoc dl = Op.getDebugLoc();
8712 MVT VT = Op.getValueType().getSimpleVT();
8714 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8715 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8716 DAG.getConstant(1, VT));
8717 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8720 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8722 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8723 SelectionDAG &DAG) const {
8724 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8726 if (!Subtarget->hasSSE41())
8729 if (!Op->hasOneUse())
8732 SDNode *N = Op.getNode();
8733 DebugLoc DL = N->getDebugLoc();
8735 SmallVector<SDValue, 8> Opnds;
8736 DenseMap<SDValue, unsigned> VecInMap;
8737 EVT VT = MVT::Other;
8739 // Recognize a special case where a vector is casted into wide integer to
8741 Opnds.push_back(N->getOperand(0));
8742 Opnds.push_back(N->getOperand(1));
8744 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8745 SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8746 // BFS traverse all OR'd operands.
8747 if (I->getOpcode() == ISD::OR) {
8748 Opnds.push_back(I->getOperand(0));
8749 Opnds.push_back(I->getOperand(1));
8750 // Re-evaluate the number of nodes to be traversed.
8751 e += 2; // 2 more nodes (LHS and RHS) are pushed.
8755 // Quit if a non-EXTRACT_VECTOR_ELT
8756 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8759 // Quit if without a constant index.
8760 SDValue Idx = I->getOperand(1);
8761 if (!isa<ConstantSDNode>(Idx))
8764 SDValue ExtractedFromVec = I->getOperand(0);
8765 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8766 if (M == VecInMap.end()) {
8767 VT = ExtractedFromVec.getValueType();
8768 // Quit if not 128/256-bit vector.
8769 if (!VT.is128BitVector() && !VT.is256BitVector())
8771 // Quit if not the same type.
8772 if (VecInMap.begin() != VecInMap.end() &&
8773 VT != VecInMap.begin()->first.getValueType())
8775 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8777 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8780 assert((VT.is128BitVector() || VT.is256BitVector()) &&
8781 "Not extracted from 128-/256-bit vector.");
8783 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8784 SmallVector<SDValue, 8> VecIns;
8786 for (DenseMap<SDValue, unsigned>::const_iterator
8787 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8788 // Quit if not all elements are used.
8789 if (I->second != FullMask)
8791 VecIns.push_back(I->first);
8794 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8796 // Cast all vectors into TestVT for PTEST.
8797 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8798 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8800 // If more than one full vectors are evaluated, OR them first before PTEST.
8801 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8802 // Each iteration will OR 2 nodes and append the result until there is only
8803 // 1 node left, i.e. the final OR'd value of all vectors.
8804 SDValue LHS = VecIns[Slot];
8805 SDValue RHS = VecIns[Slot + 1];
8806 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8809 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8810 VecIns.back(), VecIns.back());
8813 /// Emit nodes that will be selected as "test Op0,Op0", or something
8815 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8816 SelectionDAG &DAG) const {
8817 DebugLoc dl = Op.getDebugLoc();
8819 // CF and OF aren't always set the way we want. Determine which
8820 // of these we need.
8821 bool NeedCF = false;
8822 bool NeedOF = false;
8825 case X86::COND_A: case X86::COND_AE:
8826 case X86::COND_B: case X86::COND_BE:
8829 case X86::COND_G: case X86::COND_GE:
8830 case X86::COND_L: case X86::COND_LE:
8831 case X86::COND_O: case X86::COND_NO:
8836 // See if we can use the EFLAGS value from the operand instead of
8837 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8838 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8839 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8840 // Emit a CMP with 0, which is the TEST pattern.
8841 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8842 DAG.getConstant(0, Op.getValueType()));
8844 unsigned Opcode = 0;
8845 unsigned NumOperands = 0;
8847 // Truncate operations may prevent the merge of the SETCC instruction
8848 // and the arithmetic intruction before it. Attempt to truncate the operands
8849 // of the arithmetic instruction and use a reduced bit-width instruction.
8850 bool NeedTruncation = false;
8851 SDValue ArithOp = Op;
8852 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8853 SDValue Arith = Op->getOperand(0);
8854 // Both the trunc and the arithmetic op need to have one user each.
8855 if (Arith->hasOneUse())
8856 switch (Arith.getOpcode()) {
8863 NeedTruncation = true;
8869 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8870 // which may be the result of a CAST. We use the variable 'Op', which is the
8871 // non-casted variable when we check for possible users.
8872 switch (ArithOp.getOpcode()) {
8874 // Due to an isel shortcoming, be conservative if this add is likely to be
8875 // selected as part of a load-modify-store instruction. When the root node
8876 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8877 // uses of other nodes in the match, such as the ADD in this case. This
8878 // leads to the ADD being left around and reselected, with the result being
8879 // two adds in the output. Alas, even if none our users are stores, that
8880 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8881 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8882 // climbing the DAG back to the root, and it doesn't seem to be worth the
8884 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8885 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8886 if (UI->getOpcode() != ISD::CopyToReg &&
8887 UI->getOpcode() != ISD::SETCC &&
8888 UI->getOpcode() != ISD::STORE)
8891 if (ConstantSDNode *C =
8892 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8893 // An add of one will be selected as an INC.
8894 if (C->getAPIntValue() == 1) {
8895 Opcode = X86ISD::INC;
8900 // An add of negative one (subtract of one) will be selected as a DEC.
8901 if (C->getAPIntValue().isAllOnesValue()) {
8902 Opcode = X86ISD::DEC;
8908 // Otherwise use a regular EFLAGS-setting add.
8909 Opcode = X86ISD::ADD;
8913 // If the primary and result isn't used, don't bother using X86ISD::AND,
8914 // because a TEST instruction will be better.
8915 bool NonFlagUse = false;
8916 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8917 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8919 unsigned UOpNo = UI.getOperandNo();
8920 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8921 // Look pass truncate.
8922 UOpNo = User->use_begin().getOperandNo();
8923 User = *User->use_begin();
8926 if (User->getOpcode() != ISD::BRCOND &&
8927 User->getOpcode() != ISD::SETCC &&
8928 !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8941 // Due to the ISEL shortcoming noted above, be conservative if this op is
8942 // likely to be selected as part of a load-modify-store instruction.
8943 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8944 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8945 if (UI->getOpcode() == ISD::STORE)
8948 // Otherwise use a regular EFLAGS-setting instruction.
8949 switch (ArithOp.getOpcode()) {
8950 default: llvm_unreachable("unexpected operator!");
8951 case ISD::SUB: Opcode = X86ISD::SUB; break;
8952 case ISD::XOR: Opcode = X86ISD::XOR; break;
8953 case ISD::AND: Opcode = X86ISD::AND; break;
8955 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8956 SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8957 if (EFLAGS.getNode())
8960 Opcode = X86ISD::OR;
8974 return SDValue(Op.getNode(), 1);
8980 // If we found that truncation is beneficial, perform the truncation and
8982 if (NeedTruncation) {
8983 EVT VT = Op.getValueType();
8984 SDValue WideVal = Op->getOperand(0);
8985 EVT WideVT = WideVal.getValueType();
8986 unsigned ConvertedOp = 0;
8987 // Use a target machine opcode to prevent further DAGCombine
8988 // optimizations that may separate the arithmetic operations
8989 // from the setcc node.
8990 switch (WideVal.getOpcode()) {
8992 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
8993 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
8994 case ISD::AND: ConvertedOp = X86ISD::AND; break;
8995 case ISD::OR: ConvertedOp = X86ISD::OR; break;
8996 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9000 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9001 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9002 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9003 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9004 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9010 // Emit a CMP with 0, which is the TEST pattern.
9011 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9012 DAG.getConstant(0, Op.getValueType()));
9014 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9015 SmallVector<SDValue, 4> Ops;
9016 for (unsigned i = 0; i != NumOperands; ++i)
9017 Ops.push_back(Op.getOperand(i));
9019 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9020 DAG.ReplaceAllUsesWith(Op, New);
9021 return SDValue(New.getNode(), 1);
9024 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9026 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9027 SelectionDAG &DAG) const {
9028 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9029 if (C->getAPIntValue() == 0)
9030 return EmitTest(Op0, X86CC, DAG);
9032 DebugLoc dl = Op0.getDebugLoc();
9033 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9034 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9035 // Use SUB instead of CMP to enable CSE between SUB and CMP.
9036 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9037 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9039 return SDValue(Sub.getNode(), 1);
9041 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9044 /// Convert a comparison if required by the subtarget.
9045 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9046 SelectionDAG &DAG) const {
9047 // If the subtarget does not support the FUCOMI instruction, floating-point
9048 // comparisons have to be converted.
9049 if (Subtarget->hasCMov() ||
9050 Cmp.getOpcode() != X86ISD::CMP ||
9051 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9052 !Cmp.getOperand(1).getValueType().isFloatingPoint())
9055 // The instruction selector will select an FUCOM instruction instead of
9056 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9057 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9058 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9059 DebugLoc dl = Cmp.getDebugLoc();
9060 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9061 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9062 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9063 DAG.getConstant(8, MVT::i8));
9064 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9065 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9068 static bool isAllOnes(SDValue V) {
9069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9070 return C && C->isAllOnesValue();
9073 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9074 /// if it's possible.
9075 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9076 DebugLoc dl, SelectionDAG &DAG) const {
9077 SDValue Op0 = And.getOperand(0);
9078 SDValue Op1 = And.getOperand(1);
9079 if (Op0.getOpcode() == ISD::TRUNCATE)
9080 Op0 = Op0.getOperand(0);
9081 if (Op1.getOpcode() == ISD::TRUNCATE)
9082 Op1 = Op1.getOperand(0);
9085 if (Op1.getOpcode() == ISD::SHL)
9086 std::swap(Op0, Op1);
9087 if (Op0.getOpcode() == ISD::SHL) {
9088 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9089 if (And00C->getZExtValue() == 1) {
9090 // If we looked past a truncate, check that it's only truncating away
9092 unsigned BitWidth = Op0.getValueSizeInBits();
9093 unsigned AndBitWidth = And.getValueSizeInBits();
9094 if (BitWidth > AndBitWidth) {
9096 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9097 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9101 RHS = Op0.getOperand(1);
9103 } else if (Op1.getOpcode() == ISD::Constant) {
9104 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9105 uint64_t AndRHSVal = AndRHS->getZExtValue();
9106 SDValue AndLHS = Op0;
9108 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9109 LHS = AndLHS.getOperand(0);
9110 RHS = AndLHS.getOperand(1);
9113 // Use BT if the immediate can't be encoded in a TEST instruction.
9114 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9116 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9120 if (LHS.getNode()) {
9121 // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9122 // the condition code later.
9123 bool Invert = false;
9124 if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9126 LHS = LHS.getOperand(0);
9129 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
9130 // instruction. Since the shift amount is in-range-or-undefined, we know
9131 // that doing a bittest on the i32 value is ok. We extend to i32 because
9132 // the encoding for the i16 version is larger than the i32 version.
9133 // Also promote i16 to i32 for performance / code size reason.
9134 if (LHS.getValueType() == MVT::i8 ||
9135 LHS.getValueType() == MVT::i16)
9136 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9138 // If the operand types disagree, extend the shift amount to match. Since
9139 // BT ignores high bits (like shifts) we can use anyextend.
9140 if (LHS.getValueType() != RHS.getValueType())
9141 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9143 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9144 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9145 // Flip the condition if the LHS was a not instruction
9147 Cond = X86::GetOppositeBranchCondition(Cond);
9148 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9149 DAG.getConstant(Cond, MVT::i8), BT);
9155 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9156 // ones, and then concatenate the result back.
9157 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9158 MVT VT = Op.getValueType().getSimpleVT();
9160 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9161 "Unsupported value type for operation");
9163 unsigned NumElems = VT.getVectorNumElements();
9164 DebugLoc dl = Op.getDebugLoc();
9165 SDValue CC = Op.getOperand(2);
9167 // Extract the LHS vectors
9168 SDValue LHS = Op.getOperand(0);
9169 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9170 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9172 // Extract the RHS vectors
9173 SDValue RHS = Op.getOperand(1);
9174 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9175 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9177 // Issue the operation on the smaller types and concatenate the result back
9178 MVT EltVT = VT.getVectorElementType();
9179 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9180 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9181 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9182 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9185 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9186 SelectionDAG &DAG) {
9188 SDValue Op0 = Op.getOperand(0);
9189 SDValue Op1 = Op.getOperand(1);
9190 SDValue CC = Op.getOperand(2);
9191 MVT VT = Op.getValueType().getSimpleVT();
9192 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9193 bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9194 DebugLoc dl = Op.getDebugLoc();
9198 MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9199 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9205 // SSE Condition code mapping:
9214 switch (SetCCOpcode) {
9215 default: llvm_unreachable("Unexpected SETCC condition");
9217 case ISD::SETEQ: SSECC = 0; break;
9219 case ISD::SETGT: Swap = true; // Fallthrough
9221 case ISD::SETOLT: SSECC = 1; break;
9223 case ISD::SETGE: Swap = true; // Fallthrough
9225 case ISD::SETOLE: SSECC = 2; break;
9226 case ISD::SETUO: SSECC = 3; break;
9228 case ISD::SETNE: SSECC = 4; break;
9229 case ISD::SETULE: Swap = true; // Fallthrough
9230 case ISD::SETUGE: SSECC = 5; break;
9231 case ISD::SETULT: Swap = true; // Fallthrough
9232 case ISD::SETUGT: SSECC = 6; break;
9233 case ISD::SETO: SSECC = 7; break;
9235 case ISD::SETONE: SSECC = 8; break;
9238 std::swap(Op0, Op1);
9240 // In the two special cases we can't handle, emit two comparisons.
9243 unsigned CombineOpc;
9244 if (SetCCOpcode == ISD::SETUEQ) {
9245 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9247 assert(SetCCOpcode == ISD::SETONE);
9248 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9251 SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9252 DAG.getConstant(CC0, MVT::i8));
9253 SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9254 DAG.getConstant(CC1, MVT::i8));
9255 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9257 // Handle all other FP comparisons here.
9258 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9259 DAG.getConstant(SSECC, MVT::i8));
9262 // Break 256-bit integer vector compare into smaller ones.
9263 if (VT.is256BitVector() && !Subtarget->hasInt256())
9264 return Lower256IntVSETCC(Op, DAG);
9266 // We are handling one of the integer comparisons here. Since SSE only has
9267 // GT and EQ comparisons for integer, swapping operands and multiple
9268 // operations may be required for some comparisons.
9270 bool Swap = false, Invert = false, FlipSigns = false;
9272 switch (SetCCOpcode) {
9273 default: llvm_unreachable("Unexpected SETCC condition");
9274 case ISD::SETNE: Invert = true;
9275 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
9276 case ISD::SETLT: Swap = true;
9277 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
9278 case ISD::SETGE: Swap = true;
9279 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
9280 case ISD::SETULT: Swap = true;
9281 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9282 case ISD::SETUGE: Swap = true;
9283 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9286 std::swap(Op0, Op1);
9288 // Check that the operation in question is available (most are plain SSE2,
9289 // but PCMPGTQ and PCMPEQQ have different requirements).
9290 if (VT == MVT::v2i64) {
9291 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9293 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9294 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9295 // pcmpeqd + pshufd + pand.
9296 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9298 // First cast everything to the right type,
9299 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9300 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9303 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9305 // Make sure the lower and upper halves are both all-ones.
9306 const int Mask[] = { 1, 0, 3, 2 };
9307 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9308 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9311 Result = DAG.getNOT(dl, Result, MVT::v4i32);
9313 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9317 // Since SSE has no unsigned integer comparisons, we need to flip the sign
9318 // bits of the inputs before performing those operations.
9320 EVT EltVT = VT.getVectorElementType();
9321 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9323 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9324 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9326 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9327 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9330 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9332 // If the logical-not of the result is required, perform that now.
9334 Result = DAG.getNOT(dl, Result, VT);
9339 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9341 MVT VT = Op.getValueType().getSimpleVT();
9343 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9345 assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9346 SDValue Op0 = Op.getOperand(0);
9347 SDValue Op1 = Op.getOperand(1);
9348 DebugLoc dl = Op.getDebugLoc();
9349 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9351 // Optimize to BT if possible.
9352 // Lower (X & (1 << N)) == 0 to BT(X, N).
9353 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9354 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9355 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9356 Op1.getOpcode() == ISD::Constant &&
9357 cast<ConstantSDNode>(Op1)->isNullValue() &&
9358 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9359 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9360 if (NewSetCC.getNode())
9364 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
9366 if (Op1.getOpcode() == ISD::Constant &&
9367 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9368 cast<ConstantSDNode>(Op1)->isNullValue()) &&
9369 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9371 // If the input is a setcc, then reuse the input setcc or use a new one with
9372 // the inverted condition.
9373 if (Op0.getOpcode() == X86ISD::SETCC) {
9374 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9375 bool Invert = (CC == ISD::SETNE) ^
9376 cast<ConstantSDNode>(Op1)->isNullValue();
9377 if (!Invert) return Op0;
9379 CCode = X86::GetOppositeBranchCondition(CCode);
9380 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9381 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9385 bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9386 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9387 if (X86CC == X86::COND_INVALID)
9390 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9391 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9392 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9393 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9396 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9397 static bool isX86LogicalCmp(SDValue Op) {
9398 unsigned Opc = Op.getNode()->getOpcode();
9399 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9400 Opc == X86ISD::SAHF)
9402 if (Op.getResNo() == 1 &&
9403 (Opc == X86ISD::ADD ||
9404 Opc == X86ISD::SUB ||
9405 Opc == X86ISD::ADC ||
9406 Opc == X86ISD::SBB ||
9407 Opc == X86ISD::SMUL ||
9408 Opc == X86ISD::UMUL ||
9409 Opc == X86ISD::INC ||
9410 Opc == X86ISD::DEC ||
9411 Opc == X86ISD::OR ||
9412 Opc == X86ISD::XOR ||
9413 Opc == X86ISD::AND))
9416 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9422 static bool isZero(SDValue V) {
9423 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9424 return C && C->isNullValue();
9427 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9428 if (V.getOpcode() != ISD::TRUNCATE)
9431 SDValue VOp0 = V.getOperand(0);
9432 unsigned InBits = VOp0.getValueSizeInBits();
9433 unsigned Bits = V.getValueSizeInBits();
9434 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9437 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9438 bool addTest = true;
9439 SDValue Cond = Op.getOperand(0);
9440 SDValue Op1 = Op.getOperand(1);
9441 SDValue Op2 = Op.getOperand(2);
9442 DebugLoc DL = Op.getDebugLoc();
9445 if (Cond.getOpcode() == ISD::SETCC) {
9446 SDValue NewCond = LowerSETCC(Cond, DAG);
9447 if (NewCond.getNode())
9451 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9452 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9453 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9454 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9455 if (Cond.getOpcode() == X86ISD::SETCC &&
9456 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9457 isZero(Cond.getOperand(1).getOperand(1))) {
9458 SDValue Cmp = Cond.getOperand(1);
9460 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9462 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9463 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9464 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9466 SDValue CmpOp0 = Cmp.getOperand(0);
9467 // Apply further optimizations for special cases
9468 // (select (x != 0), -1, 0) -> neg & sbb
9469 // (select (x == 0), 0, -1) -> neg & sbb
9470 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9471 if (YC->isNullValue() &&
9472 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9473 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9474 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9475 DAG.getConstant(0, CmpOp0.getValueType()),
9477 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9478 DAG.getConstant(X86::COND_B, MVT::i8),
9479 SDValue(Neg.getNode(), 1));
9483 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9484 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9485 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9487 SDValue Res = // Res = 0 or -1.
9488 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9489 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9491 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9492 Res = DAG.getNOT(DL, Res, Res.getValueType());
9494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9495 if (N2C == 0 || !N2C->isNullValue())
9496 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9501 // Look past (and (setcc_carry (cmp ...)), 1).
9502 if (Cond.getOpcode() == ISD::AND &&
9503 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9504 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9505 if (C && C->getAPIntValue() == 1)
9506 Cond = Cond.getOperand(0);
9509 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9510 // setting operand in place of the X86ISD::SETCC.
9511 unsigned CondOpcode = Cond.getOpcode();
9512 if (CondOpcode == X86ISD::SETCC ||
9513 CondOpcode == X86ISD::SETCC_CARRY) {
9514 CC = Cond.getOperand(0);
9516 SDValue Cmp = Cond.getOperand(1);
9517 unsigned Opc = Cmp.getOpcode();
9518 MVT VT = Op.getValueType().getSimpleVT();
9520 bool IllegalFPCMov = false;
9521 if (VT.isFloatingPoint() && !VT.isVector() &&
9522 !isScalarFPTypeInSSEReg(VT)) // FPStack?
9523 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9525 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9526 Opc == X86ISD::BT) { // FIXME
9530 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9531 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9532 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9533 Cond.getOperand(0).getValueType() != MVT::i8)) {
9534 SDValue LHS = Cond.getOperand(0);
9535 SDValue RHS = Cond.getOperand(1);
9539 switch (CondOpcode) {
9540 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9541 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9542 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9543 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9544 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9545 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9546 default: llvm_unreachable("unexpected overflowing operator");
9548 if (CondOpcode == ISD::UMULO)
9549 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9552 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9554 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9556 if (CondOpcode == ISD::UMULO)
9557 Cond = X86Op.getValue(2);
9559 Cond = X86Op.getValue(1);
9561 CC = DAG.getConstant(X86Cond, MVT::i8);
9566 // Look pass the truncate if the high bits are known zero.
9567 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9568 Cond = Cond.getOperand(0);
9570 // We know the result of AND is compared against zero. Try to match
9572 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9573 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9574 if (NewSetCC.getNode()) {
9575 CC = NewSetCC.getOperand(0);
9576 Cond = NewSetCC.getOperand(1);
9583 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9584 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9587 // a < b ? -1 : 0 -> RES = ~setcc_carry
9588 // a < b ? 0 : -1 -> RES = setcc_carry
9589 // a >= b ? -1 : 0 -> RES = setcc_carry
9590 // a >= b ? 0 : -1 -> RES = ~setcc_carry
9591 if (Cond.getOpcode() == X86ISD::SUB) {
9592 Cond = ConvertCmpIfNecessary(Cond, DAG);
9593 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9595 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9596 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9597 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9598 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9599 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9600 return DAG.getNOT(DL, Res, Res.getValueType());
9605 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9606 // widen the cmov and push the truncate through. This avoids introducing a new
9607 // branch during isel and doesn't add any extensions.
9608 if (Op.getValueType() == MVT::i8 &&
9609 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9610 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9611 if (T1.getValueType() == T2.getValueType() &&
9612 // Blacklist CopyFromReg to avoid partial register stalls.
9613 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9614 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9615 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9616 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9620 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9621 // condition is true.
9622 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9623 SDValue Ops[] = { Op2, Op1, CC, Cond };
9624 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9627 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9628 SelectionDAG &DAG) const {
9629 MVT VT = Op->getValueType(0).getSimpleVT();
9630 SDValue In = Op->getOperand(0);
9631 MVT InVT = In.getValueType().getSimpleVT();
9632 DebugLoc dl = Op->getDebugLoc();
9634 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9635 (VT != MVT::v8i32 || InVT != MVT::v8i16))
9638 if (Subtarget->hasInt256())
9639 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9641 // Optimize vectors in AVX mode
9642 // Sign extend v8i16 to v8i32 and
9645 // Divide input vector into two parts
9646 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9647 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9648 // concat the vectors to original VT
9650 unsigned NumElems = InVT.getVectorNumElements();
9651 SDValue Undef = DAG.getUNDEF(InVT);
9653 SmallVector<int,8> ShufMask1(NumElems, -1);
9654 for (unsigned i = 0; i != NumElems/2; ++i)
9657 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9659 SmallVector<int,8> ShufMask2(NumElems, -1);
9660 for (unsigned i = 0; i != NumElems/2; ++i)
9661 ShufMask2[i] = i + NumElems/2;
9663 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9665 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9666 VT.getVectorNumElements()/2);
9668 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9669 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9671 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9674 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9675 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9676 // from the AND / OR.
9677 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9678 Opc = Op.getOpcode();
9679 if (Opc != ISD::OR && Opc != ISD::AND)
9681 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9682 Op.getOperand(0).hasOneUse() &&
9683 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9684 Op.getOperand(1).hasOneUse());
9687 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9688 // 1 and that the SETCC node has a single use.
9689 static bool isXor1OfSetCC(SDValue Op) {
9690 if (Op.getOpcode() != ISD::XOR)
9692 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9693 if (N1C && N1C->getAPIntValue() == 1) {
9694 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9695 Op.getOperand(0).hasOneUse();
9700 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9701 bool addTest = true;
9702 SDValue Chain = Op.getOperand(0);
9703 SDValue Cond = Op.getOperand(1);
9704 SDValue Dest = Op.getOperand(2);
9705 DebugLoc dl = Op.getDebugLoc();
9707 bool Inverted = false;
9709 if (Cond.getOpcode() == ISD::SETCC) {
9710 // Check for setcc([su]{add,sub,mul}o == 0).
9711 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9712 isa<ConstantSDNode>(Cond.getOperand(1)) &&
9713 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9714 Cond.getOperand(0).getResNo() == 1 &&
9715 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9716 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9717 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9718 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9719 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9720 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9722 Cond = Cond.getOperand(0);
9724 SDValue NewCond = LowerSETCC(Cond, DAG);
9725 if (NewCond.getNode())
9730 // FIXME: LowerXALUO doesn't handle these!!
9731 else if (Cond.getOpcode() == X86ISD::ADD ||
9732 Cond.getOpcode() == X86ISD::SUB ||
9733 Cond.getOpcode() == X86ISD::SMUL ||
9734 Cond.getOpcode() == X86ISD::UMUL)
9735 Cond = LowerXALUO(Cond, DAG);
9738 // Look pass (and (setcc_carry (cmp ...)), 1).
9739 if (Cond.getOpcode() == ISD::AND &&
9740 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9741 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9742 if (C && C->getAPIntValue() == 1)
9743 Cond = Cond.getOperand(0);
9746 // If condition flag is set by a X86ISD::CMP, then use it as the condition
9747 // setting operand in place of the X86ISD::SETCC.
9748 unsigned CondOpcode = Cond.getOpcode();
9749 if (CondOpcode == X86ISD::SETCC ||
9750 CondOpcode == X86ISD::SETCC_CARRY) {
9751 CC = Cond.getOperand(0);
9753 SDValue Cmp = Cond.getOperand(1);
9754 unsigned Opc = Cmp.getOpcode();
9755 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9756 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9760 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9764 // These can only come from an arithmetic instruction with overflow,
9765 // e.g. SADDO, UADDO.
9766 Cond = Cond.getNode()->getOperand(1);
9772 CondOpcode = Cond.getOpcode();
9773 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9774 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9775 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9776 Cond.getOperand(0).getValueType() != MVT::i8)) {
9777 SDValue LHS = Cond.getOperand(0);
9778 SDValue RHS = Cond.getOperand(1);
9782 switch (CondOpcode) {
9783 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9784 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9785 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9786 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9787 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9788 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9789 default: llvm_unreachable("unexpected overflowing operator");
9792 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9793 if (CondOpcode == ISD::UMULO)
9794 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9797 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9799 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9801 if (CondOpcode == ISD::UMULO)
9802 Cond = X86Op.getValue(2);
9804 Cond = X86Op.getValue(1);
9806 CC = DAG.getConstant(X86Cond, MVT::i8);
9810 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9811 SDValue Cmp = Cond.getOperand(0).getOperand(1);
9812 if (CondOpc == ISD::OR) {
9813 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9814 // two branches instead of an explicit OR instruction with a
9816 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9817 isX86LogicalCmp(Cmp)) {
9818 CC = Cond.getOperand(0).getOperand(0);
9819 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9820 Chain, Dest, CC, Cmp);
9821 CC = Cond.getOperand(1).getOperand(0);
9825 } else { // ISD::AND
9826 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9827 // two branches instead of an explicit AND instruction with a
9828 // separate test. However, we only do this if this block doesn't
9829 // have a fall-through edge, because this requires an explicit
9830 // jmp when the condition is false.
9831 if (Cmp == Cond.getOperand(1).getOperand(1) &&
9832 isX86LogicalCmp(Cmp) &&
9833 Op.getNode()->hasOneUse()) {
9834 X86::CondCode CCode =
9835 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9836 CCode = X86::GetOppositeBranchCondition(CCode);
9837 CC = DAG.getConstant(CCode, MVT::i8);
9838 SDNode *User = *Op.getNode()->use_begin();
9839 // Look for an unconditional branch following this conditional branch.
9840 // We need this because we need to reverse the successors in order
9841 // to implement FCMP_OEQ.
9842 if (User->getOpcode() == ISD::BR) {
9843 SDValue FalseBB = User->getOperand(1);
9845 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9846 assert(NewBR == User);
9850 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9851 Chain, Dest, CC, Cmp);
9852 X86::CondCode CCode =
9853 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9854 CCode = X86::GetOppositeBranchCondition(CCode);
9855 CC = DAG.getConstant(CCode, MVT::i8);
9861 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9862 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9863 // It should be transformed during dag combiner except when the condition
9864 // is set by a arithmetics with overflow node.
9865 X86::CondCode CCode =
9866 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9867 CCode = X86::GetOppositeBranchCondition(CCode);
9868 CC = DAG.getConstant(CCode, MVT::i8);
9869 Cond = Cond.getOperand(0).getOperand(1);
9871 } else if (Cond.getOpcode() == ISD::SETCC &&
9872 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9873 // For FCMP_OEQ, we can emit
9874 // two branches instead of an explicit AND instruction with a
9875 // separate test. However, we only do this if this block doesn't
9876 // have a fall-through edge, because this requires an explicit
9877 // jmp when the condition is false.
9878 if (Op.getNode()->hasOneUse()) {
9879 SDNode *User = *Op.getNode()->use_begin();
9880 // Look for an unconditional branch following this conditional branch.
9881 // We need this because we need to reverse the successors in order
9882 // to implement FCMP_OEQ.
9883 if (User->getOpcode() == ISD::BR) {
9884 SDValue FalseBB = User->getOperand(1);
9886 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9887 assert(NewBR == User);
9891 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9892 Cond.getOperand(0), Cond.getOperand(1));
9893 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9894 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9895 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9896 Chain, Dest, CC, Cmp);
9897 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9902 } else if (Cond.getOpcode() == ISD::SETCC &&
9903 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9904 // For FCMP_UNE, we can emit
9905 // two branches instead of an explicit AND instruction with a
9906 // separate test. However, we only do this if this block doesn't
9907 // have a fall-through edge, because this requires an explicit
9908 // jmp when the condition is false.
9909 if (Op.getNode()->hasOneUse()) {
9910 SDNode *User = *Op.getNode()->use_begin();
9911 // Look for an unconditional branch following this conditional branch.
9912 // We need this because we need to reverse the successors in order
9913 // to implement FCMP_UNE.
9914 if (User->getOpcode() == ISD::BR) {
9915 SDValue FalseBB = User->getOperand(1);
9917 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9918 assert(NewBR == User);
9921 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9922 Cond.getOperand(0), Cond.getOperand(1));
9923 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9924 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9925 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9926 Chain, Dest, CC, Cmp);
9927 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9937 // Look pass the truncate if the high bits are known zero.
9938 if (isTruncWithZeroHighBitsInput(Cond, DAG))
9939 Cond = Cond.getOperand(0);
9941 // We know the result of AND is compared against zero. Try to match
9943 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9944 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9945 if (NewSetCC.getNode()) {
9946 CC = NewSetCC.getOperand(0);
9947 Cond = NewSetCC.getOperand(1);
9954 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9955 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9957 Cond = ConvertCmpIfNecessary(Cond, DAG);
9958 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9959 Chain, Dest, CC, Cond);
9962 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9963 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9964 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9965 // that the guard pages used by the OS virtual memory manager are allocated in
9966 // correct sequence.
9968 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9969 SelectionDAG &DAG) const {
9970 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9971 getTargetMachine().Options.EnableSegmentedStacks) &&
9972 "This should be used only on Windows targets or when segmented stacks "
9974 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9975 DebugLoc dl = Op.getDebugLoc();
9978 SDValue Chain = Op.getOperand(0);
9979 SDValue Size = Op.getOperand(1);
9980 // FIXME: Ensure alignment here
9982 bool Is64Bit = Subtarget->is64Bit();
9983 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9985 if (getTargetMachine().Options.EnableSegmentedStacks) {
9986 MachineFunction &MF = DAG.getMachineFunction();
9987 MachineRegisterInfo &MRI = MF.getRegInfo();
9990 // The 64 bit implementation of segmented stacks needs to clobber both r10
9991 // r11. This makes it impossible to use it along with nested parameters.
9992 const Function *F = MF.getFunction();
9994 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9996 if (I->hasNestAttr())
9997 report_fatal_error("Cannot use segmented stacks with functions that "
9998 "have nested arguments.");
10001 const TargetRegisterClass *AddrRegClass =
10002 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10003 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10004 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10005 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10006 DAG.getRegister(Vreg, SPTy));
10007 SDValue Ops1[2] = { Value, Chain };
10008 return DAG.getMergeValues(Ops1, 2, dl);
10011 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10013 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10014 Flag = Chain.getValue(1);
10015 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10017 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10018 Flag = Chain.getValue(1);
10020 Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10023 SDValue Ops1[2] = { Chain.getValue(0), Chain };
10024 return DAG.getMergeValues(Ops1, 2, dl);
10028 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10029 MachineFunction &MF = DAG.getMachineFunction();
10030 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10032 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10033 DebugLoc DL = Op.getDebugLoc();
10035 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10036 // vastart just stores the address of the VarArgsFrameIndex slot into the
10037 // memory location argument.
10038 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10040 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10041 MachinePointerInfo(SV), false, false, 0);
10045 // gp_offset (0 - 6 * 8)
10046 // fp_offset (48 - 48 + 8 * 16)
10047 // overflow_arg_area (point to parameters coming in memory).
10049 SmallVector<SDValue, 8> MemOps;
10050 SDValue FIN = Op.getOperand(1);
10052 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10053 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10055 FIN, MachinePointerInfo(SV), false, false, 0);
10056 MemOps.push_back(Store);
10059 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10060 FIN, DAG.getIntPtrConstant(4));
10061 Store = DAG.getStore(Op.getOperand(0), DL,
10062 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10064 FIN, MachinePointerInfo(SV, 4), false, false, 0);
10065 MemOps.push_back(Store);
10067 // Store ptr to overflow_arg_area
10068 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10069 FIN, DAG.getIntPtrConstant(4));
10070 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10072 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10073 MachinePointerInfo(SV, 8),
10075 MemOps.push_back(Store);
10077 // Store ptr to reg_save_area.
10078 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10079 FIN, DAG.getIntPtrConstant(8));
10080 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10082 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10083 MachinePointerInfo(SV, 16), false, false, 0);
10084 MemOps.push_back(Store);
10085 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10086 &MemOps[0], MemOps.size());
10089 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10090 assert(Subtarget->is64Bit() &&
10091 "LowerVAARG only handles 64-bit va_arg!");
10092 assert((Subtarget->isTargetLinux() ||
10093 Subtarget->isTargetDarwin()) &&
10094 "Unhandled target in LowerVAARG");
10095 assert(Op.getNode()->getNumOperands() == 4);
10096 SDValue Chain = Op.getOperand(0);
10097 SDValue SrcPtr = Op.getOperand(1);
10098 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10099 unsigned Align = Op.getConstantOperandVal(3);
10100 DebugLoc dl = Op.getDebugLoc();
10102 EVT ArgVT = Op.getNode()->getValueType(0);
10103 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10104 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10107 // Decide which area this value should be read from.
10108 // TODO: Implement the AMD64 ABI in its entirety. This simple
10109 // selection mechanism works only for the basic types.
10110 if (ArgVT == MVT::f80) {
10111 llvm_unreachable("va_arg for f80 not yet implemented");
10112 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10113 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
10114 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10115 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
10117 llvm_unreachable("Unhandled argument type in LowerVAARG");
10120 if (ArgMode == 2) {
10121 // Sanity Check: Make sure using fp_offset makes sense.
10122 assert(!getTargetMachine().Options.UseSoftFloat &&
10123 !(DAG.getMachineFunction()
10124 .getFunction()->getAttributes()
10125 .hasAttribute(AttributeSet::FunctionIndex,
10126 Attribute::NoImplicitFloat)) &&
10127 Subtarget->hasSSE1());
10130 // Insert VAARG_64 node into the DAG
10131 // VAARG_64 returns two values: Variable Argument Address, Chain
10132 SmallVector<SDValue, 11> InstOps;
10133 InstOps.push_back(Chain);
10134 InstOps.push_back(SrcPtr);
10135 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10136 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10137 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10138 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10139 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10140 VTs, &InstOps[0], InstOps.size(),
10142 MachinePointerInfo(SV),
10144 /*Volatile=*/false,
10146 /*WriteMem=*/true);
10147 Chain = VAARG.getValue(1);
10149 // Load the next argument and return it
10150 return DAG.getLoad(ArgVT, dl,
10153 MachinePointerInfo(),
10154 false, false, false, 0);
10157 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10158 SelectionDAG &DAG) {
10159 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10160 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10161 SDValue Chain = Op.getOperand(0);
10162 SDValue DstPtr = Op.getOperand(1);
10163 SDValue SrcPtr = Op.getOperand(2);
10164 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10165 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10166 DebugLoc DL = Op.getDebugLoc();
10168 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10169 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10171 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10174 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
10175 // may or may not be a constant. Takes immediate version of shift as input.
10176 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10177 SDValue SrcOp, SDValue ShAmt,
10178 SelectionDAG &DAG) {
10179 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10181 if (isa<ConstantSDNode>(ShAmt)) {
10182 // Constant may be a TargetConstant. Use a regular constant.
10183 uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10185 default: llvm_unreachable("Unknown target vector shift node");
10186 case X86ISD::VSHLI:
10187 case X86ISD::VSRLI:
10188 case X86ISD::VSRAI:
10189 return DAG.getNode(Opc, dl, VT, SrcOp,
10190 DAG.getConstant(ShiftAmt, MVT::i32));
10194 // Change opcode to non-immediate version
10196 default: llvm_unreachable("Unknown target vector shift node");
10197 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10198 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10199 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10202 // Need to build a vector containing shift amount
10203 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10206 ShOps[1] = DAG.getConstant(0, MVT::i32);
10207 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10208 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10210 // The return type has to be a 128-bit type with the same element
10211 // type as the input type.
10212 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10213 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10215 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10216 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10219 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10220 DebugLoc dl = Op.getDebugLoc();
10221 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10223 default: return SDValue(); // Don't custom lower most intrinsics.
10224 // Comparison intrinsics.
10225 case Intrinsic::x86_sse_comieq_ss:
10226 case Intrinsic::x86_sse_comilt_ss:
10227 case Intrinsic::x86_sse_comile_ss:
10228 case Intrinsic::x86_sse_comigt_ss:
10229 case Intrinsic::x86_sse_comige_ss:
10230 case Intrinsic::x86_sse_comineq_ss:
10231 case Intrinsic::x86_sse_ucomieq_ss:
10232 case Intrinsic::x86_sse_ucomilt_ss:
10233 case Intrinsic::x86_sse_ucomile_ss:
10234 case Intrinsic::x86_sse_ucomigt_ss:
10235 case Intrinsic::x86_sse_ucomige_ss:
10236 case Intrinsic::x86_sse_ucomineq_ss:
10237 case Intrinsic::x86_sse2_comieq_sd:
10238 case Intrinsic::x86_sse2_comilt_sd:
10239 case Intrinsic::x86_sse2_comile_sd:
10240 case Intrinsic::x86_sse2_comigt_sd:
10241 case Intrinsic::x86_sse2_comige_sd:
10242 case Intrinsic::x86_sse2_comineq_sd:
10243 case Intrinsic::x86_sse2_ucomieq_sd:
10244 case Intrinsic::x86_sse2_ucomilt_sd:
10245 case Intrinsic::x86_sse2_ucomile_sd:
10246 case Intrinsic::x86_sse2_ucomigt_sd:
10247 case Intrinsic::x86_sse2_ucomige_sd:
10248 case Intrinsic::x86_sse2_ucomineq_sd: {
10252 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10253 case Intrinsic::x86_sse_comieq_ss:
10254 case Intrinsic::x86_sse2_comieq_sd:
10255 Opc = X86ISD::COMI;
10258 case Intrinsic::x86_sse_comilt_ss:
10259 case Intrinsic::x86_sse2_comilt_sd:
10260 Opc = X86ISD::COMI;
10263 case Intrinsic::x86_sse_comile_ss:
10264 case Intrinsic::x86_sse2_comile_sd:
10265 Opc = X86ISD::COMI;
10268 case Intrinsic::x86_sse_comigt_ss:
10269 case Intrinsic::x86_sse2_comigt_sd:
10270 Opc = X86ISD::COMI;
10273 case Intrinsic::x86_sse_comige_ss:
10274 case Intrinsic::x86_sse2_comige_sd:
10275 Opc = X86ISD::COMI;
10278 case Intrinsic::x86_sse_comineq_ss:
10279 case Intrinsic::x86_sse2_comineq_sd:
10280 Opc = X86ISD::COMI;
10283 case Intrinsic::x86_sse_ucomieq_ss:
10284 case Intrinsic::x86_sse2_ucomieq_sd:
10285 Opc = X86ISD::UCOMI;
10288 case Intrinsic::x86_sse_ucomilt_ss:
10289 case Intrinsic::x86_sse2_ucomilt_sd:
10290 Opc = X86ISD::UCOMI;
10293 case Intrinsic::x86_sse_ucomile_ss:
10294 case Intrinsic::x86_sse2_ucomile_sd:
10295 Opc = X86ISD::UCOMI;
10298 case Intrinsic::x86_sse_ucomigt_ss:
10299 case Intrinsic::x86_sse2_ucomigt_sd:
10300 Opc = X86ISD::UCOMI;
10303 case Intrinsic::x86_sse_ucomige_ss:
10304 case Intrinsic::x86_sse2_ucomige_sd:
10305 Opc = X86ISD::UCOMI;
10308 case Intrinsic::x86_sse_ucomineq_ss:
10309 case Intrinsic::x86_sse2_ucomineq_sd:
10310 Opc = X86ISD::UCOMI;
10315 SDValue LHS = Op.getOperand(1);
10316 SDValue RHS = Op.getOperand(2);
10317 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10318 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10319 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10320 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10321 DAG.getConstant(X86CC, MVT::i8), Cond);
10322 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10325 // Arithmetic intrinsics.
10326 case Intrinsic::x86_sse2_pmulu_dq:
10327 case Intrinsic::x86_avx2_pmulu_dq:
10328 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10329 Op.getOperand(1), Op.getOperand(2));
10331 // SSE2/AVX2 sub with unsigned saturation intrinsics
10332 case Intrinsic::x86_sse2_psubus_b:
10333 case Intrinsic::x86_sse2_psubus_w:
10334 case Intrinsic::x86_avx2_psubus_b:
10335 case Intrinsic::x86_avx2_psubus_w:
10336 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10337 Op.getOperand(1), Op.getOperand(2));
10339 // SSE3/AVX horizontal add/sub intrinsics
10340 case Intrinsic::x86_sse3_hadd_ps:
10341 case Intrinsic::x86_sse3_hadd_pd:
10342 case Intrinsic::x86_avx_hadd_ps_256:
10343 case Intrinsic::x86_avx_hadd_pd_256:
10344 case Intrinsic::x86_sse3_hsub_ps:
10345 case Intrinsic::x86_sse3_hsub_pd:
10346 case Intrinsic::x86_avx_hsub_ps_256:
10347 case Intrinsic::x86_avx_hsub_pd_256:
10348 case Intrinsic::x86_ssse3_phadd_w_128:
10349 case Intrinsic::x86_ssse3_phadd_d_128:
10350 case Intrinsic::x86_avx2_phadd_w:
10351 case Intrinsic::x86_avx2_phadd_d:
10352 case Intrinsic::x86_ssse3_phsub_w_128:
10353 case Intrinsic::x86_ssse3_phsub_d_128:
10354 case Intrinsic::x86_avx2_phsub_w:
10355 case Intrinsic::x86_avx2_phsub_d: {
10358 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10359 case Intrinsic::x86_sse3_hadd_ps:
10360 case Intrinsic::x86_sse3_hadd_pd:
10361 case Intrinsic::x86_avx_hadd_ps_256:
10362 case Intrinsic::x86_avx_hadd_pd_256:
10363 Opcode = X86ISD::FHADD;
10365 case Intrinsic::x86_sse3_hsub_ps:
10366 case Intrinsic::x86_sse3_hsub_pd:
10367 case Intrinsic::x86_avx_hsub_ps_256:
10368 case Intrinsic::x86_avx_hsub_pd_256:
10369 Opcode = X86ISD::FHSUB;
10371 case Intrinsic::x86_ssse3_phadd_w_128:
10372 case Intrinsic::x86_ssse3_phadd_d_128:
10373 case Intrinsic::x86_avx2_phadd_w:
10374 case Intrinsic::x86_avx2_phadd_d:
10375 Opcode = X86ISD::HADD;
10377 case Intrinsic::x86_ssse3_phsub_w_128:
10378 case Intrinsic::x86_ssse3_phsub_d_128:
10379 case Intrinsic::x86_avx2_phsub_w:
10380 case Intrinsic::x86_avx2_phsub_d:
10381 Opcode = X86ISD::HSUB;
10384 return DAG.getNode(Opcode, dl, Op.getValueType(),
10385 Op.getOperand(1), Op.getOperand(2));
10388 // SSE2/SSE41/AVX2 integer max/min intrinsics.
10389 case Intrinsic::x86_sse2_pmaxu_b:
10390 case Intrinsic::x86_sse41_pmaxuw:
10391 case Intrinsic::x86_sse41_pmaxud:
10392 case Intrinsic::x86_avx2_pmaxu_b:
10393 case Intrinsic::x86_avx2_pmaxu_w:
10394 case Intrinsic::x86_avx2_pmaxu_d:
10395 case Intrinsic::x86_sse2_pminu_b:
10396 case Intrinsic::x86_sse41_pminuw:
10397 case Intrinsic::x86_sse41_pminud:
10398 case Intrinsic::x86_avx2_pminu_b:
10399 case Intrinsic::x86_avx2_pminu_w:
10400 case Intrinsic::x86_avx2_pminu_d:
10401 case Intrinsic::x86_sse41_pmaxsb:
10402 case Intrinsic::x86_sse2_pmaxs_w:
10403 case Intrinsic::x86_sse41_pmaxsd:
10404 case Intrinsic::x86_avx2_pmaxs_b:
10405 case Intrinsic::x86_avx2_pmaxs_w:
10406 case Intrinsic::x86_avx2_pmaxs_d:
10407 case Intrinsic::x86_sse41_pminsb:
10408 case Intrinsic::x86_sse2_pmins_w:
10409 case Intrinsic::x86_sse41_pminsd:
10410 case Intrinsic::x86_avx2_pmins_b:
10411 case Intrinsic::x86_avx2_pmins_w:
10412 case Intrinsic::x86_avx2_pmins_d: {
10415 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10416 case Intrinsic::x86_sse2_pmaxu_b:
10417 case Intrinsic::x86_sse41_pmaxuw:
10418 case Intrinsic::x86_sse41_pmaxud:
10419 case Intrinsic::x86_avx2_pmaxu_b:
10420 case Intrinsic::x86_avx2_pmaxu_w:
10421 case Intrinsic::x86_avx2_pmaxu_d:
10422 Opcode = X86ISD::UMAX;
10424 case Intrinsic::x86_sse2_pminu_b:
10425 case Intrinsic::x86_sse41_pminuw:
10426 case Intrinsic::x86_sse41_pminud:
10427 case Intrinsic::x86_avx2_pminu_b:
10428 case Intrinsic::x86_avx2_pminu_w:
10429 case Intrinsic::x86_avx2_pminu_d:
10430 Opcode = X86ISD::UMIN;
10432 case Intrinsic::x86_sse41_pmaxsb:
10433 case Intrinsic::x86_sse2_pmaxs_w:
10434 case Intrinsic::x86_sse41_pmaxsd:
10435 case Intrinsic::x86_avx2_pmaxs_b:
10436 case Intrinsic::x86_avx2_pmaxs_w:
10437 case Intrinsic::x86_avx2_pmaxs_d:
10438 Opcode = X86ISD::SMAX;
10440 case Intrinsic::x86_sse41_pminsb:
10441 case Intrinsic::x86_sse2_pmins_w:
10442 case Intrinsic::x86_sse41_pminsd:
10443 case Intrinsic::x86_avx2_pmins_b:
10444 case Intrinsic::x86_avx2_pmins_w:
10445 case Intrinsic::x86_avx2_pmins_d:
10446 Opcode = X86ISD::SMIN;
10449 return DAG.getNode(Opcode, dl, Op.getValueType(),
10450 Op.getOperand(1), Op.getOperand(2));
10453 // SSE/SSE2/AVX floating point max/min intrinsics.
10454 case Intrinsic::x86_sse_max_ps:
10455 case Intrinsic::x86_sse2_max_pd:
10456 case Intrinsic::x86_avx_max_ps_256:
10457 case Intrinsic::x86_avx_max_pd_256:
10458 case Intrinsic::x86_sse_min_ps:
10459 case Intrinsic::x86_sse2_min_pd:
10460 case Intrinsic::x86_avx_min_ps_256:
10461 case Intrinsic::x86_avx_min_pd_256: {
10464 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10465 case Intrinsic::x86_sse_max_ps:
10466 case Intrinsic::x86_sse2_max_pd:
10467 case Intrinsic::x86_avx_max_ps_256:
10468 case Intrinsic::x86_avx_max_pd_256:
10469 Opcode = X86ISD::FMAX;
10471 case Intrinsic::x86_sse_min_ps:
10472 case Intrinsic::x86_sse2_min_pd:
10473 case Intrinsic::x86_avx_min_ps_256:
10474 case Intrinsic::x86_avx_min_pd_256:
10475 Opcode = X86ISD::FMIN;
10478 return DAG.getNode(Opcode, dl, Op.getValueType(),
10479 Op.getOperand(1), Op.getOperand(2));
10482 // AVX2 variable shift intrinsics
10483 case Intrinsic::x86_avx2_psllv_d:
10484 case Intrinsic::x86_avx2_psllv_q:
10485 case Intrinsic::x86_avx2_psllv_d_256:
10486 case Intrinsic::x86_avx2_psllv_q_256:
10487 case Intrinsic::x86_avx2_psrlv_d:
10488 case Intrinsic::x86_avx2_psrlv_q:
10489 case Intrinsic::x86_avx2_psrlv_d_256:
10490 case Intrinsic::x86_avx2_psrlv_q_256:
10491 case Intrinsic::x86_avx2_psrav_d:
10492 case Intrinsic::x86_avx2_psrav_d_256: {
10495 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10496 case Intrinsic::x86_avx2_psllv_d:
10497 case Intrinsic::x86_avx2_psllv_q:
10498 case Intrinsic::x86_avx2_psllv_d_256:
10499 case Intrinsic::x86_avx2_psllv_q_256:
10502 case Intrinsic::x86_avx2_psrlv_d:
10503 case Intrinsic::x86_avx2_psrlv_q:
10504 case Intrinsic::x86_avx2_psrlv_d_256:
10505 case Intrinsic::x86_avx2_psrlv_q_256:
10508 case Intrinsic::x86_avx2_psrav_d:
10509 case Intrinsic::x86_avx2_psrav_d_256:
10513 return DAG.getNode(Opcode, dl, Op.getValueType(),
10514 Op.getOperand(1), Op.getOperand(2));
10517 case Intrinsic::x86_ssse3_pshuf_b_128:
10518 case Intrinsic::x86_avx2_pshuf_b:
10519 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10520 Op.getOperand(1), Op.getOperand(2));
10522 case Intrinsic::x86_ssse3_psign_b_128:
10523 case Intrinsic::x86_ssse3_psign_w_128:
10524 case Intrinsic::x86_ssse3_psign_d_128:
10525 case Intrinsic::x86_avx2_psign_b:
10526 case Intrinsic::x86_avx2_psign_w:
10527 case Intrinsic::x86_avx2_psign_d:
10528 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10529 Op.getOperand(1), Op.getOperand(2));
10531 case Intrinsic::x86_sse41_insertps:
10532 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10533 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10535 case Intrinsic::x86_avx_vperm2f128_ps_256:
10536 case Intrinsic::x86_avx_vperm2f128_pd_256:
10537 case Intrinsic::x86_avx_vperm2f128_si_256:
10538 case Intrinsic::x86_avx2_vperm2i128:
10539 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10540 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10542 case Intrinsic::x86_avx2_permd:
10543 case Intrinsic::x86_avx2_permps:
10544 // Operands intentionally swapped. Mask is last operand to intrinsic,
10545 // but second operand for node/intruction.
10546 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10547 Op.getOperand(2), Op.getOperand(1));
10549 case Intrinsic::x86_sse_sqrt_ps:
10550 case Intrinsic::x86_sse2_sqrt_pd:
10551 case Intrinsic::x86_avx_sqrt_ps_256:
10552 case Intrinsic::x86_avx_sqrt_pd_256:
10553 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10555 // ptest and testp intrinsics. The intrinsic these come from are designed to
10556 // return an integer value, not just an instruction so lower it to the ptest
10557 // or testp pattern and a setcc for the result.
10558 case Intrinsic::x86_sse41_ptestz:
10559 case Intrinsic::x86_sse41_ptestc:
10560 case Intrinsic::x86_sse41_ptestnzc:
10561 case Intrinsic::x86_avx_ptestz_256:
10562 case Intrinsic::x86_avx_ptestc_256:
10563 case Intrinsic::x86_avx_ptestnzc_256:
10564 case Intrinsic::x86_avx_vtestz_ps:
10565 case Intrinsic::x86_avx_vtestc_ps:
10566 case Intrinsic::x86_avx_vtestnzc_ps:
10567 case Intrinsic::x86_avx_vtestz_pd:
10568 case Intrinsic::x86_avx_vtestc_pd:
10569 case Intrinsic::x86_avx_vtestnzc_pd:
10570 case Intrinsic::x86_avx_vtestz_ps_256:
10571 case Intrinsic::x86_avx_vtestc_ps_256:
10572 case Intrinsic::x86_avx_vtestnzc_ps_256:
10573 case Intrinsic::x86_avx_vtestz_pd_256:
10574 case Intrinsic::x86_avx_vtestc_pd_256:
10575 case Intrinsic::x86_avx_vtestnzc_pd_256: {
10576 bool IsTestPacked = false;
10579 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10580 case Intrinsic::x86_avx_vtestz_ps:
10581 case Intrinsic::x86_avx_vtestz_pd:
10582 case Intrinsic::x86_avx_vtestz_ps_256:
10583 case Intrinsic::x86_avx_vtestz_pd_256:
10584 IsTestPacked = true; // Fallthrough
10585 case Intrinsic::x86_sse41_ptestz:
10586 case Intrinsic::x86_avx_ptestz_256:
10588 X86CC = X86::COND_E;
10590 case Intrinsic::x86_avx_vtestc_ps:
10591 case Intrinsic::x86_avx_vtestc_pd:
10592 case Intrinsic::x86_avx_vtestc_ps_256:
10593 case Intrinsic::x86_avx_vtestc_pd_256:
10594 IsTestPacked = true; // Fallthrough
10595 case Intrinsic::x86_sse41_ptestc:
10596 case Intrinsic::x86_avx_ptestc_256:
10598 X86CC = X86::COND_B;
10600 case Intrinsic::x86_avx_vtestnzc_ps:
10601 case Intrinsic::x86_avx_vtestnzc_pd:
10602 case Intrinsic::x86_avx_vtestnzc_ps_256:
10603 case Intrinsic::x86_avx_vtestnzc_pd_256:
10604 IsTestPacked = true; // Fallthrough
10605 case Intrinsic::x86_sse41_ptestnzc:
10606 case Intrinsic::x86_avx_ptestnzc_256:
10608 X86CC = X86::COND_A;
10612 SDValue LHS = Op.getOperand(1);
10613 SDValue RHS = Op.getOperand(2);
10614 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10615 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10616 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10617 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10618 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10621 // SSE/AVX shift intrinsics
10622 case Intrinsic::x86_sse2_psll_w:
10623 case Intrinsic::x86_sse2_psll_d:
10624 case Intrinsic::x86_sse2_psll_q:
10625 case Intrinsic::x86_avx2_psll_w:
10626 case Intrinsic::x86_avx2_psll_d:
10627 case Intrinsic::x86_avx2_psll_q:
10628 case Intrinsic::x86_sse2_psrl_w:
10629 case Intrinsic::x86_sse2_psrl_d:
10630 case Intrinsic::x86_sse2_psrl_q:
10631 case Intrinsic::x86_avx2_psrl_w:
10632 case Intrinsic::x86_avx2_psrl_d:
10633 case Intrinsic::x86_avx2_psrl_q:
10634 case Intrinsic::x86_sse2_psra_w:
10635 case Intrinsic::x86_sse2_psra_d:
10636 case Intrinsic::x86_avx2_psra_w:
10637 case Intrinsic::x86_avx2_psra_d: {
10640 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10641 case Intrinsic::x86_sse2_psll_w:
10642 case Intrinsic::x86_sse2_psll_d:
10643 case Intrinsic::x86_sse2_psll_q:
10644 case Intrinsic::x86_avx2_psll_w:
10645 case Intrinsic::x86_avx2_psll_d:
10646 case Intrinsic::x86_avx2_psll_q:
10647 Opcode = X86ISD::VSHL;
10649 case Intrinsic::x86_sse2_psrl_w:
10650 case Intrinsic::x86_sse2_psrl_d:
10651 case Intrinsic::x86_sse2_psrl_q:
10652 case Intrinsic::x86_avx2_psrl_w:
10653 case Intrinsic::x86_avx2_psrl_d:
10654 case Intrinsic::x86_avx2_psrl_q:
10655 Opcode = X86ISD::VSRL;
10657 case Intrinsic::x86_sse2_psra_w:
10658 case Intrinsic::x86_sse2_psra_d:
10659 case Intrinsic::x86_avx2_psra_w:
10660 case Intrinsic::x86_avx2_psra_d:
10661 Opcode = X86ISD::VSRA;
10664 return DAG.getNode(Opcode, dl, Op.getValueType(),
10665 Op.getOperand(1), Op.getOperand(2));
10668 // SSE/AVX immediate shift intrinsics
10669 case Intrinsic::x86_sse2_pslli_w:
10670 case Intrinsic::x86_sse2_pslli_d:
10671 case Intrinsic::x86_sse2_pslli_q:
10672 case Intrinsic::x86_avx2_pslli_w:
10673 case Intrinsic::x86_avx2_pslli_d:
10674 case Intrinsic::x86_avx2_pslli_q:
10675 case Intrinsic::x86_sse2_psrli_w:
10676 case Intrinsic::x86_sse2_psrli_d:
10677 case Intrinsic::x86_sse2_psrli_q:
10678 case Intrinsic::x86_avx2_psrli_w:
10679 case Intrinsic::x86_avx2_psrli_d:
10680 case Intrinsic::x86_avx2_psrli_q:
10681 case Intrinsic::x86_sse2_psrai_w:
10682 case Intrinsic::x86_sse2_psrai_d:
10683 case Intrinsic::x86_avx2_psrai_w:
10684 case Intrinsic::x86_avx2_psrai_d: {
10687 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10688 case Intrinsic::x86_sse2_pslli_w:
10689 case Intrinsic::x86_sse2_pslli_d:
10690 case Intrinsic::x86_sse2_pslli_q:
10691 case Intrinsic::x86_avx2_pslli_w:
10692 case Intrinsic::x86_avx2_pslli_d:
10693 case Intrinsic::x86_avx2_pslli_q:
10694 Opcode = X86ISD::VSHLI;
10696 case Intrinsic::x86_sse2_psrli_w:
10697 case Intrinsic::x86_sse2_psrli_d:
10698 case Intrinsic::x86_sse2_psrli_q:
10699 case Intrinsic::x86_avx2_psrli_w:
10700 case Intrinsic::x86_avx2_psrli_d:
10701 case Intrinsic::x86_avx2_psrli_q:
10702 Opcode = X86ISD::VSRLI;
10704 case Intrinsic::x86_sse2_psrai_w:
10705 case Intrinsic::x86_sse2_psrai_d:
10706 case Intrinsic::x86_avx2_psrai_w:
10707 case Intrinsic::x86_avx2_psrai_d:
10708 Opcode = X86ISD::VSRAI;
10711 return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10712 Op.getOperand(1), Op.getOperand(2), DAG);
10715 case Intrinsic::x86_sse42_pcmpistria128:
10716 case Intrinsic::x86_sse42_pcmpestria128:
10717 case Intrinsic::x86_sse42_pcmpistric128:
10718 case Intrinsic::x86_sse42_pcmpestric128:
10719 case Intrinsic::x86_sse42_pcmpistrio128:
10720 case Intrinsic::x86_sse42_pcmpestrio128:
10721 case Intrinsic::x86_sse42_pcmpistris128:
10722 case Intrinsic::x86_sse42_pcmpestris128:
10723 case Intrinsic::x86_sse42_pcmpistriz128:
10724 case Intrinsic::x86_sse42_pcmpestriz128: {
10728 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10729 case Intrinsic::x86_sse42_pcmpistria128:
10730 Opcode = X86ISD::PCMPISTRI;
10731 X86CC = X86::COND_A;
10733 case Intrinsic::x86_sse42_pcmpestria128:
10734 Opcode = X86ISD::PCMPESTRI;
10735 X86CC = X86::COND_A;
10737 case Intrinsic::x86_sse42_pcmpistric128:
10738 Opcode = X86ISD::PCMPISTRI;
10739 X86CC = X86::COND_B;
10741 case Intrinsic::x86_sse42_pcmpestric128:
10742 Opcode = X86ISD::PCMPESTRI;
10743 X86CC = X86::COND_B;
10745 case Intrinsic::x86_sse42_pcmpistrio128:
10746 Opcode = X86ISD::PCMPISTRI;
10747 X86CC = X86::COND_O;
10749 case Intrinsic::x86_sse42_pcmpestrio128:
10750 Opcode = X86ISD::PCMPESTRI;
10751 X86CC = X86::COND_O;
10753 case Intrinsic::x86_sse42_pcmpistris128:
10754 Opcode = X86ISD::PCMPISTRI;
10755 X86CC = X86::COND_S;
10757 case Intrinsic::x86_sse42_pcmpestris128:
10758 Opcode = X86ISD::PCMPESTRI;
10759 X86CC = X86::COND_S;
10761 case Intrinsic::x86_sse42_pcmpistriz128:
10762 Opcode = X86ISD::PCMPISTRI;
10763 X86CC = X86::COND_E;
10765 case Intrinsic::x86_sse42_pcmpestriz128:
10766 Opcode = X86ISD::PCMPESTRI;
10767 X86CC = X86::COND_E;
10770 SmallVector<SDValue, 5> NewOps;
10771 NewOps.append(Op->op_begin()+1, Op->op_end());
10772 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10773 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10774 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10775 DAG.getConstant(X86CC, MVT::i8),
10776 SDValue(PCMP.getNode(), 1));
10777 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10780 case Intrinsic::x86_sse42_pcmpistri128:
10781 case Intrinsic::x86_sse42_pcmpestri128: {
10783 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10784 Opcode = X86ISD::PCMPISTRI;
10786 Opcode = X86ISD::PCMPESTRI;
10788 SmallVector<SDValue, 5> NewOps;
10789 NewOps.append(Op->op_begin()+1, Op->op_end());
10790 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10791 return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10793 case Intrinsic::x86_fma_vfmadd_ps:
10794 case Intrinsic::x86_fma_vfmadd_pd:
10795 case Intrinsic::x86_fma_vfmsub_ps:
10796 case Intrinsic::x86_fma_vfmsub_pd:
10797 case Intrinsic::x86_fma_vfnmadd_ps:
10798 case Intrinsic::x86_fma_vfnmadd_pd:
10799 case Intrinsic::x86_fma_vfnmsub_ps:
10800 case Intrinsic::x86_fma_vfnmsub_pd:
10801 case Intrinsic::x86_fma_vfmaddsub_ps:
10802 case Intrinsic::x86_fma_vfmaddsub_pd:
10803 case Intrinsic::x86_fma_vfmsubadd_ps:
10804 case Intrinsic::x86_fma_vfmsubadd_pd:
10805 case Intrinsic::x86_fma_vfmadd_ps_256:
10806 case Intrinsic::x86_fma_vfmadd_pd_256:
10807 case Intrinsic::x86_fma_vfmsub_ps_256:
10808 case Intrinsic::x86_fma_vfmsub_pd_256:
10809 case Intrinsic::x86_fma_vfnmadd_ps_256:
10810 case Intrinsic::x86_fma_vfnmadd_pd_256:
10811 case Intrinsic::x86_fma_vfnmsub_ps_256:
10812 case Intrinsic::x86_fma_vfnmsub_pd_256:
10813 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10814 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10815 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10816 case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10819 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
10820 case Intrinsic::x86_fma_vfmadd_ps:
10821 case Intrinsic::x86_fma_vfmadd_pd:
10822 case Intrinsic::x86_fma_vfmadd_ps_256:
10823 case Intrinsic::x86_fma_vfmadd_pd_256:
10824 Opc = X86ISD::FMADD;
10826 case Intrinsic::x86_fma_vfmsub_ps:
10827 case Intrinsic::x86_fma_vfmsub_pd:
10828 case Intrinsic::x86_fma_vfmsub_ps_256:
10829 case Intrinsic::x86_fma_vfmsub_pd_256:
10830 Opc = X86ISD::FMSUB;
10832 case Intrinsic::x86_fma_vfnmadd_ps:
10833 case Intrinsic::x86_fma_vfnmadd_pd:
10834 case Intrinsic::x86_fma_vfnmadd_ps_256:
10835 case Intrinsic::x86_fma_vfnmadd_pd_256:
10836 Opc = X86ISD::FNMADD;
10838 case Intrinsic::x86_fma_vfnmsub_ps:
10839 case Intrinsic::x86_fma_vfnmsub_pd:
10840 case Intrinsic::x86_fma_vfnmsub_ps_256:
10841 case Intrinsic::x86_fma_vfnmsub_pd_256:
10842 Opc = X86ISD::FNMSUB;
10844 case Intrinsic::x86_fma_vfmaddsub_ps:
10845 case Intrinsic::x86_fma_vfmaddsub_pd:
10846 case Intrinsic::x86_fma_vfmaddsub_ps_256:
10847 case Intrinsic::x86_fma_vfmaddsub_pd_256:
10848 Opc = X86ISD::FMADDSUB;
10850 case Intrinsic::x86_fma_vfmsubadd_ps:
10851 case Intrinsic::x86_fma_vfmsubadd_pd:
10852 case Intrinsic::x86_fma_vfmsubadd_ps_256:
10853 case Intrinsic::x86_fma_vfmsubadd_pd_256:
10854 Opc = X86ISD::FMSUBADD;
10858 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10859 Op.getOperand(2), Op.getOperand(3));
10864 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10865 DebugLoc dl = Op.getDebugLoc();
10866 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10868 default: return SDValue(); // Don't custom lower most intrinsics.
10870 // RDRAND intrinsics.
10871 case Intrinsic::x86_rdrand_16:
10872 case Intrinsic::x86_rdrand_32:
10873 case Intrinsic::x86_rdrand_64: {
10874 // Emit the node with the right value type.
10875 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10876 SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10878 // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10879 // return the value from Rand, which is always 0, casted to i32.
10880 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10881 DAG.getConstant(1, Op->getValueType(1)),
10882 DAG.getConstant(X86::COND_B, MVT::i32),
10883 SDValue(Result.getNode(), 1) };
10884 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10885 DAG.getVTList(Op->getValueType(1), MVT::Glue),
10888 // Return { result, isValid, chain }.
10889 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10890 SDValue(Result.getNode(), 2));
10895 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10896 SelectionDAG &DAG) const {
10897 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10898 MFI->setReturnAddressIsTaken(true);
10900 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10901 DebugLoc dl = Op.getDebugLoc();
10902 EVT PtrVT = getPointerTy();
10905 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10907 DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10908 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10909 DAG.getNode(ISD::ADD, dl, PtrVT,
10910 FrameAddr, Offset),
10911 MachinePointerInfo(), false, false, false, 0);
10914 // Just load the return address.
10915 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10916 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10917 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10920 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10921 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10922 MFI->setFrameAddressIsTaken(true);
10924 EVT VT = Op.getValueType();
10925 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
10926 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10927 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10928 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10930 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10931 MachinePointerInfo(),
10932 false, false, false, 0);
10936 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10937 SelectionDAG &DAG) const {
10938 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10941 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10942 SDValue Chain = Op.getOperand(0);
10943 SDValue Offset = Op.getOperand(1);
10944 SDValue Handler = Op.getOperand(2);
10945 DebugLoc dl = Op.getDebugLoc();
10947 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10948 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10950 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10952 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10953 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10954 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10955 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10957 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
10959 return DAG.getNode(X86ISD::EH_RETURN, dl,
10961 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
10964 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
10965 SelectionDAG &DAG) const {
10966 DebugLoc DL = Op.getDebugLoc();
10967 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
10968 DAG.getVTList(MVT::i32, MVT::Other),
10969 Op.getOperand(0), Op.getOperand(1));
10972 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
10973 SelectionDAG &DAG) const {
10974 DebugLoc DL = Op.getDebugLoc();
10975 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
10976 Op.getOperand(0), Op.getOperand(1));
10979 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
10980 return Op.getOperand(0);
10983 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
10984 SelectionDAG &DAG) const {
10985 SDValue Root = Op.getOperand(0);
10986 SDValue Trmp = Op.getOperand(1); // trampoline
10987 SDValue FPtr = Op.getOperand(2); // nested function
10988 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
10989 DebugLoc dl = Op.getDebugLoc();
10991 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10992 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
10994 if (Subtarget->is64Bit()) {
10995 SDValue OutChains[6];
10997 // Large code-model.
10998 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
10999 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11001 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11002 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11004 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11006 // Load the pointer to the nested function into R11.
11007 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11008 SDValue Addr = Trmp;
11009 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11010 Addr, MachinePointerInfo(TrmpAddr),
11013 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11014 DAG.getConstant(2, MVT::i64));
11015 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11016 MachinePointerInfo(TrmpAddr, 2),
11019 // Load the 'nest' parameter value into R10.
11020 // R10 is specified in X86CallingConv.td
11021 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11022 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11023 DAG.getConstant(10, MVT::i64));
11024 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11025 Addr, MachinePointerInfo(TrmpAddr, 10),
11028 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11029 DAG.getConstant(12, MVT::i64));
11030 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11031 MachinePointerInfo(TrmpAddr, 12),
11034 // Jump to the nested function.
11035 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11036 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11037 DAG.getConstant(20, MVT::i64));
11038 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11039 Addr, MachinePointerInfo(TrmpAddr, 20),
11042 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11043 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11044 DAG.getConstant(22, MVT::i64));
11045 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11046 MachinePointerInfo(TrmpAddr, 22),
11049 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11051 const Function *Func =
11052 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11053 CallingConv::ID CC = Func->getCallingConv();
11058 llvm_unreachable("Unsupported calling convention");
11059 case CallingConv::C:
11060 case CallingConv::X86_StdCall: {
11061 // Pass 'nest' parameter in ECX.
11062 // Must be kept in sync with X86CallingConv.td
11063 NestReg = X86::ECX;
11065 // Check that ECX wasn't needed by an 'inreg' parameter.
11066 FunctionType *FTy = Func->getFunctionType();
11067 const AttributeSet &Attrs = Func->getAttributes();
11069 if (!Attrs.isEmpty() && !Func->isVarArg()) {
11070 unsigned InRegCount = 0;
11073 for (FunctionType::param_iterator I = FTy->param_begin(),
11074 E = FTy->param_end(); I != E; ++I, ++Idx)
11075 if (Attrs.hasAttribute(Idx, Attribute::InReg))
11076 // FIXME: should only count parameters that are lowered to integers.
11077 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11079 if (InRegCount > 2) {
11080 report_fatal_error("Nest register in use - reduce number of inreg"
11086 case CallingConv::X86_FastCall:
11087 case CallingConv::X86_ThisCall:
11088 case CallingConv::Fast:
11089 // Pass 'nest' parameter in EAX.
11090 // Must be kept in sync with X86CallingConv.td
11091 NestReg = X86::EAX;
11095 SDValue OutChains[4];
11096 SDValue Addr, Disp;
11098 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11099 DAG.getConstant(10, MVT::i32));
11100 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11102 // This is storing the opcode for MOV32ri.
11103 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11104 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11105 OutChains[0] = DAG.getStore(Root, dl,
11106 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11107 Trmp, MachinePointerInfo(TrmpAddr),
11110 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11111 DAG.getConstant(1, MVT::i32));
11112 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11113 MachinePointerInfo(TrmpAddr, 1),
11116 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11117 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11118 DAG.getConstant(5, MVT::i32));
11119 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11120 MachinePointerInfo(TrmpAddr, 5),
11123 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11124 DAG.getConstant(6, MVT::i32));
11125 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11126 MachinePointerInfo(TrmpAddr, 6),
11129 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11133 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11134 SelectionDAG &DAG) const {
11136 The rounding mode is in bits 11:10 of FPSR, and has the following
11138 00 Round to nearest
11143 FLT_ROUNDS, on the other hand, expects the following:
11150 To perform the conversion, we do:
11151 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11154 MachineFunction &MF = DAG.getMachineFunction();
11155 const TargetMachine &TM = MF.getTarget();
11156 const TargetFrameLowering &TFI = *TM.getFrameLowering();
11157 unsigned StackAlignment = TFI.getStackAlignment();
11158 EVT VT = Op.getValueType();
11159 DebugLoc DL = Op.getDebugLoc();
11161 // Save FP Control Word to stack slot
11162 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11163 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11165 MachineMemOperand *MMO =
11166 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11167 MachineMemOperand::MOStore, 2, 2);
11169 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11170 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11171 DAG.getVTList(MVT::Other),
11172 Ops, 2, MVT::i16, MMO);
11174 // Load FP Control Word from stack slot
11175 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11176 MachinePointerInfo(), false, false, false, 0);
11178 // Transform as necessary
11180 DAG.getNode(ISD::SRL, DL, MVT::i16,
11181 DAG.getNode(ISD::AND, DL, MVT::i16,
11182 CWD, DAG.getConstant(0x800, MVT::i16)),
11183 DAG.getConstant(11, MVT::i8));
11185 DAG.getNode(ISD::SRL, DL, MVT::i16,
11186 DAG.getNode(ISD::AND, DL, MVT::i16,
11187 CWD, DAG.getConstant(0x400, MVT::i16)),
11188 DAG.getConstant(9, MVT::i8));
11191 DAG.getNode(ISD::AND, DL, MVT::i16,
11192 DAG.getNode(ISD::ADD, DL, MVT::i16,
11193 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11194 DAG.getConstant(1, MVT::i16)),
11195 DAG.getConstant(3, MVT::i16));
11197 return DAG.getNode((VT.getSizeInBits() < 16 ?
11198 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11201 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11202 EVT VT = Op.getValueType();
11204 unsigned NumBits = VT.getSizeInBits();
11205 DebugLoc dl = Op.getDebugLoc();
11207 Op = Op.getOperand(0);
11208 if (VT == MVT::i8) {
11209 // Zero extend to i32 since there is not an i8 bsr.
11211 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11214 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11215 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11216 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11218 // If src is zero (i.e. bsr sets ZF), returns NumBits.
11221 DAG.getConstant(NumBits+NumBits-1, OpVT),
11222 DAG.getConstant(X86::COND_E, MVT::i8),
11225 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11227 // Finally xor with NumBits-1.
11228 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11231 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11235 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11236 EVT VT = Op.getValueType();
11238 unsigned NumBits = VT.getSizeInBits();
11239 DebugLoc dl = Op.getDebugLoc();
11241 Op = Op.getOperand(0);
11242 if (VT == MVT::i8) {
11243 // Zero extend to i32 since there is not an i8 bsr.
11245 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11248 // Issue a bsr (scan bits in reverse).
11249 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11250 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11252 // And xor with NumBits-1.
11253 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11256 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11260 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11261 EVT VT = Op.getValueType();
11262 unsigned NumBits = VT.getSizeInBits();
11263 DebugLoc dl = Op.getDebugLoc();
11264 Op = Op.getOperand(0);
11266 // Issue a bsf (scan bits forward) which also sets EFLAGS.
11267 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11268 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11270 // If src is zero (i.e. bsf sets ZF), returns NumBits.
11273 DAG.getConstant(NumBits, VT),
11274 DAG.getConstant(X86::COND_E, MVT::i8),
11277 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11280 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11281 // ones, and then concatenate the result back.
11282 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11283 EVT VT = Op.getValueType();
11285 assert(VT.is256BitVector() && VT.isInteger() &&
11286 "Unsupported value type for operation");
11288 unsigned NumElems = VT.getVectorNumElements();
11289 DebugLoc dl = Op.getDebugLoc();
11291 // Extract the LHS vectors
11292 SDValue LHS = Op.getOperand(0);
11293 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11294 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11296 // Extract the RHS vectors
11297 SDValue RHS = Op.getOperand(1);
11298 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11299 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11301 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11302 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11304 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11305 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11306 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11309 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11310 assert(Op.getValueType().is256BitVector() &&
11311 Op.getValueType().isInteger() &&
11312 "Only handle AVX 256-bit vector integer operation");
11313 return Lower256IntArith(Op, DAG);
11316 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11317 assert(Op.getValueType().is256BitVector() &&
11318 Op.getValueType().isInteger() &&
11319 "Only handle AVX 256-bit vector integer operation");
11320 return Lower256IntArith(Op, DAG);
11323 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11324 SelectionDAG &DAG) {
11325 DebugLoc dl = Op.getDebugLoc();
11326 EVT VT = Op.getValueType();
11328 // Decompose 256-bit ops into smaller 128-bit ops.
11329 if (VT.is256BitVector() && !Subtarget->hasInt256())
11330 return Lower256IntArith(Op, DAG);
11332 SDValue A = Op.getOperand(0);
11333 SDValue B = Op.getOperand(1);
11335 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11336 if (VT == MVT::v4i32) {
11337 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11338 "Should not custom lower when pmuldq is available!");
11340 // Extract the odd parts.
11341 const int UnpackMask[] = { 1, -1, 3, -1 };
11342 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11343 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11345 // Multiply the even parts.
11346 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11347 // Now multiply odd parts.
11348 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11350 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11351 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11353 // Merge the two vectors back together with a shuffle. This expands into 2
11355 const int ShufMask[] = { 0, 4, 2, 6 };
11356 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11359 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11360 "Only know how to lower V2I64/V4I64 multiply");
11362 // Ahi = psrlqi(a, 32);
11363 // Bhi = psrlqi(b, 32);
11365 // AloBlo = pmuludq(a, b);
11366 // AloBhi = pmuludq(a, Bhi);
11367 // AhiBlo = pmuludq(Ahi, b);
11369 // AloBhi = psllqi(AloBhi, 32);
11370 // AhiBlo = psllqi(AhiBlo, 32);
11371 // return AloBlo + AloBhi + AhiBlo;
11373 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11375 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11376 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11378 // Bit cast to 32-bit vectors for MULUDQ
11379 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11380 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11381 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11382 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11383 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11385 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11386 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11387 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11389 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11390 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11392 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11393 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11396 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11397 EVT VT = Op.getValueType();
11398 EVT EltTy = VT.getVectorElementType();
11399 unsigned NumElts = VT.getVectorNumElements();
11400 SDValue N0 = Op.getOperand(0);
11401 DebugLoc dl = Op.getDebugLoc();
11403 // Lower sdiv X, pow2-const.
11404 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11408 APInt SplatValue, SplatUndef;
11409 unsigned MinSplatBits;
11411 if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11414 if ((SplatValue != 0) &&
11415 (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11416 unsigned lg2 = SplatValue.countTrailingZeros();
11417 // Splat the sign bit.
11418 SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11419 SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11420 // Add (N0 < 0) ? abs2 - 1 : 0;
11421 SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11422 SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11423 SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11424 SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11425 SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11427 // If we're dividing by a positive value, we're done. Otherwise, we must
11428 // negate the result.
11429 if (SplatValue.isNonNegative())
11432 SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11433 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11434 return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11439 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11441 EVT VT = Op.getValueType();
11442 DebugLoc dl = Op.getDebugLoc();
11443 SDValue R = Op.getOperand(0);
11444 SDValue Amt = Op.getOperand(1);
11445 LLVMContext *Context = DAG.getContext();
11447 if (!Subtarget->hasSSE2())
11450 // Optimize shl/srl/sra with constant shift amount.
11451 if (isSplatVector(Amt.getNode())) {
11452 SDValue SclrAmt = Amt->getOperand(0);
11453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11454 uint64_t ShiftAmt = C->getZExtValue();
11456 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11457 (Subtarget->hasInt256() &&
11458 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11459 if (Op.getOpcode() == ISD::SHL)
11460 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11461 DAG.getConstant(ShiftAmt, MVT::i32));
11462 if (Op.getOpcode() == ISD::SRL)
11463 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11464 DAG.getConstant(ShiftAmt, MVT::i32));
11465 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11466 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11467 DAG.getConstant(ShiftAmt, MVT::i32));
11470 if (VT == MVT::v16i8) {
11471 if (Op.getOpcode() == ISD::SHL) {
11472 // Make a large shift.
11473 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11474 DAG.getConstant(ShiftAmt, MVT::i32));
11475 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11476 // Zero out the rightmost bits.
11477 SmallVector<SDValue, 16> V(16,
11478 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11480 return DAG.getNode(ISD::AND, dl, VT, SHL,
11481 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11483 if (Op.getOpcode() == ISD::SRL) {
11484 // Make a large shift.
11485 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11486 DAG.getConstant(ShiftAmt, MVT::i32));
11487 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11488 // Zero out the leftmost bits.
11489 SmallVector<SDValue, 16> V(16,
11490 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11492 return DAG.getNode(ISD::AND, dl, VT, SRL,
11493 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11495 if (Op.getOpcode() == ISD::SRA) {
11496 if (ShiftAmt == 7) {
11497 // R s>> 7 === R s< 0
11498 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11499 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11502 // R s>> a === ((R u>> a) ^ m) - m
11503 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11504 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11506 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11507 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11508 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11511 llvm_unreachable("Unknown shift opcode.");
11514 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11515 if (Op.getOpcode() == ISD::SHL) {
11516 // Make a large shift.
11517 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11518 DAG.getConstant(ShiftAmt, MVT::i32));
11519 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11520 // Zero out the rightmost bits.
11521 SmallVector<SDValue, 32> V(32,
11522 DAG.getConstant(uint8_t(-1U << ShiftAmt),
11524 return DAG.getNode(ISD::AND, dl, VT, SHL,
11525 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11527 if (Op.getOpcode() == ISD::SRL) {
11528 // Make a large shift.
11529 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11530 DAG.getConstant(ShiftAmt, MVT::i32));
11531 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11532 // Zero out the leftmost bits.
11533 SmallVector<SDValue, 32> V(32,
11534 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11536 return DAG.getNode(ISD::AND, dl, VT, SRL,
11537 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11539 if (Op.getOpcode() == ISD::SRA) {
11540 if (ShiftAmt == 7) {
11541 // R s>> 7 === R s< 0
11542 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11543 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11546 // R s>> a === ((R u>> a) ^ m) - m
11547 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11548 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11550 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11551 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11552 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11555 llvm_unreachable("Unknown shift opcode.");
11560 // Lower SHL with variable shift amount.
11561 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11562 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
11563 DAG.getConstant(23, MVT::i32));
11565 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
11566 Constant *C = ConstantDataVector::get(*Context, CV);
11567 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
11568 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11569 MachinePointerInfo::getConstantPool(),
11570 false, false, false, 16);
11572 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
11573 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11574 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11575 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11577 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11578 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11581 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
11582 DAG.getConstant(5, MVT::i32));
11583 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11585 // Turn 'a' into a mask suitable for VSELECT
11586 SDValue VSelM = DAG.getConstant(0x80, VT);
11587 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11588 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11590 SDValue CM1 = DAG.getConstant(0x0f, VT);
11591 SDValue CM2 = DAG.getConstant(0x3f, VT);
11593 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11594 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11595 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11596 DAG.getConstant(4, MVT::i32), DAG);
11597 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11598 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11601 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11602 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11603 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11605 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11606 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11607 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11608 DAG.getConstant(2, MVT::i32), DAG);
11609 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11610 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11613 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11614 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11615 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11617 // return VSELECT(r, r+r, a);
11618 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11619 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11623 // Decompose 256-bit shifts into smaller 128-bit shifts.
11624 if (VT.is256BitVector()) {
11625 unsigned NumElems = VT.getVectorNumElements();
11626 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11627 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11629 // Extract the two vectors
11630 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11631 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11633 // Recreate the shift amount vectors
11634 SDValue Amt1, Amt2;
11635 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11636 // Constant shift amount
11637 SmallVector<SDValue, 4> Amt1Csts;
11638 SmallVector<SDValue, 4> Amt2Csts;
11639 for (unsigned i = 0; i != NumElems/2; ++i)
11640 Amt1Csts.push_back(Amt->getOperand(i));
11641 for (unsigned i = NumElems/2; i != NumElems; ++i)
11642 Amt2Csts.push_back(Amt->getOperand(i));
11644 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11645 &Amt1Csts[0], NumElems/2);
11646 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11647 &Amt2Csts[0], NumElems/2);
11649 // Variable shift amount
11650 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11651 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11654 // Issue new vector shifts for the smaller types
11655 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11656 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11658 // Concatenate the result back
11659 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11665 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11666 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11667 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11668 // looks for this combo and may remove the "setcc" instruction if the "setcc"
11669 // has only one use.
11670 SDNode *N = Op.getNode();
11671 SDValue LHS = N->getOperand(0);
11672 SDValue RHS = N->getOperand(1);
11673 unsigned BaseOp = 0;
11675 DebugLoc DL = Op.getDebugLoc();
11676 switch (Op.getOpcode()) {
11677 default: llvm_unreachable("Unknown ovf instruction!");
11679 // A subtract of one will be selected as a INC. Note that INC doesn't
11680 // set CF, so we can't do this for UADDO.
11681 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11683 BaseOp = X86ISD::INC;
11684 Cond = X86::COND_O;
11687 BaseOp = X86ISD::ADD;
11688 Cond = X86::COND_O;
11691 BaseOp = X86ISD::ADD;
11692 Cond = X86::COND_B;
11695 // A subtract of one will be selected as a DEC. Note that DEC doesn't
11696 // set CF, so we can't do this for USUBO.
11697 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11699 BaseOp = X86ISD::DEC;
11700 Cond = X86::COND_O;
11703 BaseOp = X86ISD::SUB;
11704 Cond = X86::COND_O;
11707 BaseOp = X86ISD::SUB;
11708 Cond = X86::COND_B;
11711 BaseOp = X86ISD::SMUL;
11712 Cond = X86::COND_O;
11714 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11715 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11717 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11720 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11721 DAG.getConstant(X86::COND_O, MVT::i32),
11722 SDValue(Sum.getNode(), 2));
11724 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11728 // Also sets EFLAGS.
11729 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11730 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11733 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11734 DAG.getConstant(Cond, MVT::i32),
11735 SDValue(Sum.getNode(), 1));
11737 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11740 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11741 SelectionDAG &DAG) const {
11742 DebugLoc dl = Op.getDebugLoc();
11743 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11744 EVT VT = Op.getValueType();
11746 if (!Subtarget->hasSSE2() || !VT.isVector())
11749 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11750 ExtraVT.getScalarType().getSizeInBits();
11751 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11753 switch (VT.getSimpleVT().SimpleTy) {
11754 default: return SDValue();
11757 if (!Subtarget->hasFp256())
11759 if (!Subtarget->hasInt256()) {
11760 // needs to be split
11761 unsigned NumElems = VT.getVectorNumElements();
11763 // Extract the LHS vectors
11764 SDValue LHS = Op.getOperand(0);
11765 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11766 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11768 MVT EltVT = VT.getVectorElementType().getSimpleVT();
11769 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11771 EVT ExtraEltVT = ExtraVT.getVectorElementType();
11772 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11773 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11775 SDValue Extra = DAG.getValueType(ExtraVT);
11777 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11778 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11780 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11785 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11786 Op.getOperand(0), ShAmt, DAG);
11787 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11792 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11793 SelectionDAG &DAG) {
11794 DebugLoc dl = Op.getDebugLoc();
11796 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11797 // There isn't any reason to disable it if the target processor supports it.
11798 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11799 SDValue Chain = Op.getOperand(0);
11800 SDValue Zero = DAG.getConstant(0, MVT::i32);
11802 DAG.getRegister(X86::ESP, MVT::i32), // Base
11803 DAG.getTargetConstant(1, MVT::i8), // Scale
11804 DAG.getRegister(0, MVT::i32), // Index
11805 DAG.getTargetConstant(0, MVT::i32), // Disp
11806 DAG.getRegister(0, MVT::i32), // Segment.
11811 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11812 array_lengthof(Ops));
11813 return SDValue(Res, 0);
11816 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11818 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11820 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11821 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11822 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11823 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11825 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11826 if (!Op1 && !Op2 && !Op3 && Op4)
11827 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11829 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11830 if (Op1 && !Op2 && !Op3 && !Op4)
11831 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11833 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11835 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11838 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11839 SelectionDAG &DAG) {
11840 DebugLoc dl = Op.getDebugLoc();
11841 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11842 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11843 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11844 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11846 // The only fence that needs an instruction is a sequentially-consistent
11847 // cross-thread fence.
11848 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11849 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11850 // no-sse2). There isn't any reason to disable it if the target processor
11852 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11853 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11855 SDValue Chain = Op.getOperand(0);
11856 SDValue Zero = DAG.getConstant(0, MVT::i32);
11858 DAG.getRegister(X86::ESP, MVT::i32), // Base
11859 DAG.getTargetConstant(1, MVT::i8), // Scale
11860 DAG.getRegister(0, MVT::i32), // Index
11861 DAG.getTargetConstant(0, MVT::i32), // Disp
11862 DAG.getRegister(0, MVT::i32), // Segment.
11867 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11868 array_lengthof(Ops));
11869 return SDValue(Res, 0);
11872 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11873 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11876 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11877 SelectionDAG &DAG) {
11878 EVT T = Op.getValueType();
11879 DebugLoc DL = Op.getDebugLoc();
11882 switch(T.getSimpleVT().SimpleTy) {
11883 default: llvm_unreachable("Invalid value type!");
11884 case MVT::i8: Reg = X86::AL; size = 1; break;
11885 case MVT::i16: Reg = X86::AX; size = 2; break;
11886 case MVT::i32: Reg = X86::EAX; size = 4; break;
11888 assert(Subtarget->is64Bit() && "Node not type legal!");
11889 Reg = X86::RAX; size = 8;
11892 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11893 Op.getOperand(2), SDValue());
11894 SDValue Ops[] = { cpIn.getValue(0),
11897 DAG.getTargetConstant(size, MVT::i8),
11898 cpIn.getValue(1) };
11899 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11900 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11901 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11904 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11908 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11909 SelectionDAG &DAG) {
11910 assert(Subtarget->is64Bit() && "Result not type legalized?");
11911 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11912 SDValue TheChain = Op.getOperand(0);
11913 DebugLoc dl = Op.getDebugLoc();
11914 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11915 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11916 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11918 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11919 DAG.getConstant(32, MVT::i8));
11921 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11924 return DAG.getMergeValues(Ops, 2, dl);
11927 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11928 EVT SrcVT = Op.getOperand(0).getValueType();
11929 EVT DstVT = Op.getValueType();
11930 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11931 Subtarget->hasMMX() && "Unexpected custom BITCAST");
11932 assert((DstVT == MVT::i64 ||
11933 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11934 "Unexpected custom BITCAST");
11935 // i64 <=> MMX conversions are Legal.
11936 if (SrcVT==MVT::i64 && DstVT.isVector())
11938 if (DstVT==MVT::i64 && SrcVT.isVector())
11940 // MMX <=> MMX conversions are Legal.
11941 if (SrcVT.isVector() && DstVT.isVector())
11943 // All other conversions need to be expanded.
11947 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11948 SDNode *Node = Op.getNode();
11949 DebugLoc dl = Node->getDebugLoc();
11950 EVT T = Node->getValueType(0);
11951 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11952 DAG.getConstant(0, T), Node->getOperand(2));
11953 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11954 cast<AtomicSDNode>(Node)->getMemoryVT(),
11955 Node->getOperand(0),
11956 Node->getOperand(1), negOp,
11957 cast<AtomicSDNode>(Node)->getSrcValue(),
11958 cast<AtomicSDNode>(Node)->getAlignment(),
11959 cast<AtomicSDNode>(Node)->getOrdering(),
11960 cast<AtomicSDNode>(Node)->getSynchScope());
11963 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
11964 SDNode *Node = Op.getNode();
11965 DebugLoc dl = Node->getDebugLoc();
11966 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11968 // Convert seq_cst store -> xchg
11969 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
11970 // FIXME: On 32-bit, store -> fist or movq would be more efficient
11971 // (The only way to get a 16-byte store is cmpxchg16b)
11972 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
11973 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
11974 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11975 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
11976 cast<AtomicSDNode>(Node)->getMemoryVT(),
11977 Node->getOperand(0),
11978 Node->getOperand(1), Node->getOperand(2),
11979 cast<AtomicSDNode>(Node)->getMemOperand(),
11980 cast<AtomicSDNode>(Node)->getOrdering(),
11981 cast<AtomicSDNode>(Node)->getSynchScope());
11982 return Swap.getValue(1);
11984 // Other atomic stores have a simple pattern.
11988 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
11989 EVT VT = Op.getNode()->getValueType(0);
11991 // Let legalize expand this if it isn't a legal type yet.
11992 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11995 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11998 bool ExtraOp = false;
11999 switch (Op.getOpcode()) {
12000 default: llvm_unreachable("Invalid code");
12001 case ISD::ADDC: Opc = X86ISD::ADD; break;
12002 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12003 case ISD::SUBC: Opc = X86ISD::SUB; break;
12004 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12008 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12010 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12011 Op.getOperand(1), Op.getOperand(2));
12014 /// LowerOperation - Provide custom lowering hooks for some operations.
12016 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12017 switch (Op.getOpcode()) {
12018 default: llvm_unreachable("Should not custom lower this!");
12019 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
12020 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, Subtarget, DAG);
12021 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12022 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op, Subtarget, DAG);
12023 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
12024 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
12025 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
12026 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
12027 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
12028 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12029 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
12030 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12031 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12032 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
12033 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
12034 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
12035 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
12036 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
12037 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
12038 case ISD::SHL_PARTS:
12039 case ISD::SRA_PARTS:
12040 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
12041 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
12042 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
12043 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
12044 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, DAG);
12045 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, DAG);
12046 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, DAG);
12047 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
12048 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
12049 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
12050 case ISD::FABS: return LowerFABS(Op, DAG);
12051 case ISD::FNEG: return LowerFNEG(Op, DAG);
12052 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
12053 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
12054 case ISD::SETCC: return LowerSETCC(Op, DAG);
12055 case ISD::SELECT: return LowerSELECT(Op, DAG);
12056 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
12057 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
12058 case ISD::VASTART: return LowerVASTART(Op, DAG);
12059 case ISD::VAARG: return LowerVAARG(Op, DAG);
12060 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
12061 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12062 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
12063 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
12064 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
12065 case ISD::FRAME_TO_ARGS_OFFSET:
12066 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12067 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12068 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
12069 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
12070 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
12071 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
12072 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
12073 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
12074 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
12075 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12076 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
12077 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
12080 case ISD::SHL: return LowerShift(Op, DAG);
12086 case ISD::UMULO: return LowerXALUO(Op, DAG);
12087 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12088 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
12092 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12093 case ISD::ADD: return LowerADD(Op, DAG);
12094 case ISD::SUB: return LowerSUB(Op, DAG);
12095 case ISD::SDIV: return LowerSDIV(Op, DAG);
12099 static void ReplaceATOMIC_LOAD(SDNode *Node,
12100 SmallVectorImpl<SDValue> &Results,
12101 SelectionDAG &DAG) {
12102 DebugLoc dl = Node->getDebugLoc();
12103 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12105 // Convert wide load -> cmpxchg8b/cmpxchg16b
12106 // FIXME: On 32-bit, load -> fild or movq would be more efficient
12107 // (The only way to get a 16-byte load is cmpxchg16b)
12108 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12109 SDValue Zero = DAG.getConstant(0, VT);
12110 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12111 Node->getOperand(0),
12112 Node->getOperand(1), Zero, Zero,
12113 cast<AtomicSDNode>(Node)->getMemOperand(),
12114 cast<AtomicSDNode>(Node)->getOrdering(),
12115 cast<AtomicSDNode>(Node)->getSynchScope());
12116 Results.push_back(Swap.getValue(0));
12117 Results.push_back(Swap.getValue(1));
12121 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12122 SelectionDAG &DAG, unsigned NewOp) {
12123 DebugLoc dl = Node->getDebugLoc();
12124 assert (Node->getValueType(0) == MVT::i64 &&
12125 "Only know how to expand i64 atomics");
12127 SDValue Chain = Node->getOperand(0);
12128 SDValue In1 = Node->getOperand(1);
12129 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12130 Node->getOperand(2), DAG.getIntPtrConstant(0));
12131 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12132 Node->getOperand(2), DAG.getIntPtrConstant(1));
12133 SDValue Ops[] = { Chain, In1, In2L, In2H };
12134 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12136 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12137 cast<MemSDNode>(Node)->getMemOperand());
12138 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12139 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12140 Results.push_back(Result.getValue(2));
12143 /// ReplaceNodeResults - Replace a node with an illegal result type
12144 /// with a new node built out of custom code.
12145 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12146 SmallVectorImpl<SDValue>&Results,
12147 SelectionDAG &DAG) const {
12148 DebugLoc dl = N->getDebugLoc();
12149 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12150 switch (N->getOpcode()) {
12152 llvm_unreachable("Do not know how to custom type legalize this operation!");
12153 case ISD::SIGN_EXTEND_INREG:
12158 // We don't want to expand or promote these.
12160 case ISD::FP_TO_SINT:
12161 case ISD::FP_TO_UINT: {
12162 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12164 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12167 std::pair<SDValue,SDValue> Vals =
12168 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12169 SDValue FIST = Vals.first, StackSlot = Vals.second;
12170 if (FIST.getNode() != 0) {
12171 EVT VT = N->getValueType(0);
12172 // Return a load from the stack slot.
12173 if (StackSlot.getNode() != 0)
12174 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12175 MachinePointerInfo(),
12176 false, false, false, 0));
12178 Results.push_back(FIST);
12182 case ISD::UINT_TO_FP: {
12183 if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12184 N->getValueType(0) != MVT::v2f32)
12186 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12188 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12190 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12191 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12192 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12193 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12194 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12195 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12198 case ISD::FP_ROUND: {
12199 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12201 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12202 Results.push_back(V);
12205 case ISD::READCYCLECOUNTER: {
12206 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12207 SDValue TheChain = N->getOperand(0);
12208 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12209 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12211 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12213 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12214 SDValue Ops[] = { eax, edx };
12215 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12216 Results.push_back(edx.getValue(1));
12219 case ISD::ATOMIC_CMP_SWAP: {
12220 EVT T = N->getValueType(0);
12221 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12222 bool Regs64bit = T == MVT::i128;
12223 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12224 SDValue cpInL, cpInH;
12225 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12226 DAG.getConstant(0, HalfT));
12227 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12228 DAG.getConstant(1, HalfT));
12229 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12230 Regs64bit ? X86::RAX : X86::EAX,
12232 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12233 Regs64bit ? X86::RDX : X86::EDX,
12234 cpInH, cpInL.getValue(1));
12235 SDValue swapInL, swapInH;
12236 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12237 DAG.getConstant(0, HalfT));
12238 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12239 DAG.getConstant(1, HalfT));
12240 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12241 Regs64bit ? X86::RBX : X86::EBX,
12242 swapInL, cpInH.getValue(1));
12243 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12244 Regs64bit ? X86::RCX : X86::ECX,
12245 swapInH, swapInL.getValue(1));
12246 SDValue Ops[] = { swapInH.getValue(0),
12248 swapInH.getValue(1) };
12249 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12250 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12251 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12252 X86ISD::LCMPXCHG8_DAG;
12253 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12255 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12256 Regs64bit ? X86::RAX : X86::EAX,
12257 HalfT, Result.getValue(1));
12258 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12259 Regs64bit ? X86::RDX : X86::EDX,
12260 HalfT, cpOutL.getValue(2));
12261 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12262 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12263 Results.push_back(cpOutH.getValue(1));
12266 case ISD::ATOMIC_LOAD_ADD:
12267 case ISD::ATOMIC_LOAD_AND:
12268 case ISD::ATOMIC_LOAD_NAND:
12269 case ISD::ATOMIC_LOAD_OR:
12270 case ISD::ATOMIC_LOAD_SUB:
12271 case ISD::ATOMIC_LOAD_XOR:
12272 case ISD::ATOMIC_LOAD_MAX:
12273 case ISD::ATOMIC_LOAD_MIN:
12274 case ISD::ATOMIC_LOAD_UMAX:
12275 case ISD::ATOMIC_LOAD_UMIN:
12276 case ISD::ATOMIC_SWAP: {
12278 switch (N->getOpcode()) {
12279 default: llvm_unreachable("Unexpected opcode");
12280 case ISD::ATOMIC_LOAD_ADD:
12281 Opc = X86ISD::ATOMADD64_DAG;
12283 case ISD::ATOMIC_LOAD_AND:
12284 Opc = X86ISD::ATOMAND64_DAG;
12286 case ISD::ATOMIC_LOAD_NAND:
12287 Opc = X86ISD::ATOMNAND64_DAG;
12289 case ISD::ATOMIC_LOAD_OR:
12290 Opc = X86ISD::ATOMOR64_DAG;
12292 case ISD::ATOMIC_LOAD_SUB:
12293 Opc = X86ISD::ATOMSUB64_DAG;
12295 case ISD::ATOMIC_LOAD_XOR:
12296 Opc = X86ISD::ATOMXOR64_DAG;
12298 case ISD::ATOMIC_LOAD_MAX:
12299 Opc = X86ISD::ATOMMAX64_DAG;
12301 case ISD::ATOMIC_LOAD_MIN:
12302 Opc = X86ISD::ATOMMIN64_DAG;
12304 case ISD::ATOMIC_LOAD_UMAX:
12305 Opc = X86ISD::ATOMUMAX64_DAG;
12307 case ISD::ATOMIC_LOAD_UMIN:
12308 Opc = X86ISD::ATOMUMIN64_DAG;
12310 case ISD::ATOMIC_SWAP:
12311 Opc = X86ISD::ATOMSWAP64_DAG;
12314 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12317 case ISD::ATOMIC_LOAD:
12318 ReplaceATOMIC_LOAD(N, Results, DAG);
12322 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12324 default: return NULL;
12325 case X86ISD::BSF: return "X86ISD::BSF";
12326 case X86ISD::BSR: return "X86ISD::BSR";
12327 case X86ISD::SHLD: return "X86ISD::SHLD";
12328 case X86ISD::SHRD: return "X86ISD::SHRD";
12329 case X86ISD::FAND: return "X86ISD::FAND";
12330 case X86ISD::FOR: return "X86ISD::FOR";
12331 case X86ISD::FXOR: return "X86ISD::FXOR";
12332 case X86ISD::FSRL: return "X86ISD::FSRL";
12333 case X86ISD::FILD: return "X86ISD::FILD";
12334 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
12335 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12336 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12337 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12338 case X86ISD::FLD: return "X86ISD::FLD";
12339 case X86ISD::FST: return "X86ISD::FST";
12340 case X86ISD::CALL: return "X86ISD::CALL";
12341 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
12342 case X86ISD::BT: return "X86ISD::BT";
12343 case X86ISD::CMP: return "X86ISD::CMP";
12344 case X86ISD::COMI: return "X86ISD::COMI";
12345 case X86ISD::UCOMI: return "X86ISD::UCOMI";
12346 case X86ISD::SETCC: return "X86ISD::SETCC";
12347 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
12348 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
12349 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
12350 case X86ISD::CMOV: return "X86ISD::CMOV";
12351 case X86ISD::BRCOND: return "X86ISD::BRCOND";
12352 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
12353 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
12354 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
12355 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
12356 case X86ISD::Wrapper: return "X86ISD::Wrapper";
12357 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
12358 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
12359 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
12360 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
12361 case X86ISD::PINSRB: return "X86ISD::PINSRB";
12362 case X86ISD::PINSRW: return "X86ISD::PINSRW";
12363 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
12364 case X86ISD::ANDNP: return "X86ISD::ANDNP";
12365 case X86ISD::PSIGN: return "X86ISD::PSIGN";
12366 case X86ISD::BLENDV: return "X86ISD::BLENDV";
12367 case X86ISD::BLENDI: return "X86ISD::BLENDI";
12368 case X86ISD::SUBUS: return "X86ISD::SUBUS";
12369 case X86ISD::HADD: return "X86ISD::HADD";
12370 case X86ISD::HSUB: return "X86ISD::HSUB";
12371 case X86ISD::FHADD: return "X86ISD::FHADD";
12372 case X86ISD::FHSUB: return "X86ISD::FHSUB";
12373 case X86ISD::UMAX: return "X86ISD::UMAX";
12374 case X86ISD::UMIN: return "X86ISD::UMIN";
12375 case X86ISD::SMAX: return "X86ISD::SMAX";
12376 case X86ISD::SMIN: return "X86ISD::SMIN";
12377 case X86ISD::FMAX: return "X86ISD::FMAX";
12378 case X86ISD::FMIN: return "X86ISD::FMIN";
12379 case X86ISD::FMAXC: return "X86ISD::FMAXC";
12380 case X86ISD::FMINC: return "X86ISD::FMINC";
12381 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
12382 case X86ISD::FRCP: return "X86ISD::FRCP";
12383 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
12384 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
12385 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
12386 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
12387 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
12388 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
12389 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
12390 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
12391 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
12392 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
12393 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
12394 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
12395 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
12396 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
12397 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
12398 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
12399 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
12400 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
12401 case X86ISD::VSEXT_MOVL: return "X86ISD::VSEXT_MOVL";
12402 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
12403 case X86ISD::VZEXT: return "X86ISD::VZEXT";
12404 case X86ISD::VSEXT: return "X86ISD::VSEXT";
12405 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
12406 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
12407 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
12408 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
12409 case X86ISD::VSHL: return "X86ISD::VSHL";
12410 case X86ISD::VSRL: return "X86ISD::VSRL";
12411 case X86ISD::VSRA: return "X86ISD::VSRA";
12412 case X86ISD::VSHLI: return "X86ISD::VSHLI";
12413 case X86ISD::VSRLI: return "X86ISD::VSRLI";
12414 case X86ISD::VSRAI: return "X86ISD::VSRAI";
12415 case X86ISD::CMPP: return "X86ISD::CMPP";
12416 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
12417 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
12418 case X86ISD::ADD: return "X86ISD::ADD";
12419 case X86ISD::SUB: return "X86ISD::SUB";
12420 case X86ISD::ADC: return "X86ISD::ADC";
12421 case X86ISD::SBB: return "X86ISD::SBB";
12422 case X86ISD::SMUL: return "X86ISD::SMUL";
12423 case X86ISD::UMUL: return "X86ISD::UMUL";
12424 case X86ISD::INC: return "X86ISD::INC";
12425 case X86ISD::DEC: return "X86ISD::DEC";
12426 case X86ISD::OR: return "X86ISD::OR";
12427 case X86ISD::XOR: return "X86ISD::XOR";
12428 case X86ISD::AND: return "X86ISD::AND";
12429 case X86ISD::BLSI: return "X86ISD::BLSI";
12430 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
12431 case X86ISD::BLSR: return "X86ISD::BLSR";
12432 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
12433 case X86ISD::PTEST: return "X86ISD::PTEST";
12434 case X86ISD::TESTP: return "X86ISD::TESTP";
12435 case X86ISD::PALIGN: return "X86ISD::PALIGN";
12436 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
12437 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
12438 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
12439 case X86ISD::SHUFP: return "X86ISD::SHUFP";
12440 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
12441 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
12442 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
12443 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
12444 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
12445 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
12446 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
12447 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
12448 case X86ISD::MOVSD: return "X86ISD::MOVSD";
12449 case X86ISD::MOVSS: return "X86ISD::MOVSS";
12450 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
12451 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
12452 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
12453 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
12454 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
12455 case X86ISD::VPERMV: return "X86ISD::VPERMV";
12456 case X86ISD::VPERMI: return "X86ISD::VPERMI";
12457 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
12458 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12459 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
12460 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
12461 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
12462 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
12463 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
12464 case X86ISD::SAHF: return "X86ISD::SAHF";
12465 case X86ISD::RDRAND: return "X86ISD::RDRAND";
12466 case X86ISD::FMADD: return "X86ISD::FMADD";
12467 case X86ISD::FMSUB: return "X86ISD::FMSUB";
12468 case X86ISD::FNMADD: return "X86ISD::FNMADD";
12469 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
12470 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
12471 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
12472 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
12473 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
12477 // isLegalAddressingMode - Return true if the addressing mode represented
12478 // by AM is legal for this target, for a load/store of the specified type.
12479 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12481 // X86 supports extremely general addressing modes.
12482 CodeModel::Model M = getTargetMachine().getCodeModel();
12483 Reloc::Model R = getTargetMachine().getRelocationModel();
12485 // X86 allows a sign-extended 32-bit immediate field as a displacement.
12486 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12491 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12493 // If a reference to this global requires an extra load, we can't fold it.
12494 if (isGlobalStubReference(GVFlags))
12497 // If BaseGV requires a register for the PIC base, we cannot also have a
12498 // BaseReg specified.
12499 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12502 // If lower 4G is not available, then we must use rip-relative addressing.
12503 if ((M != CodeModel::Small || R != Reloc::Static) &&
12504 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12508 switch (AM.Scale) {
12514 // These scales always work.
12519 // These scales are formed with basereg+scalereg. Only accept if there is
12524 default: // Other stuff never works.
12531 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12532 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12534 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12535 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12536 return NumBits1 > NumBits2;
12539 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12540 return isInt<32>(Imm);
12543 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12544 // Can also use sub to handle negated immediates.
12545 return isInt<32>(Imm);
12548 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12549 if (!VT1.isInteger() || !VT2.isInteger())
12551 unsigned NumBits1 = VT1.getSizeInBits();
12552 unsigned NumBits2 = VT2.getSizeInBits();
12553 return NumBits1 > NumBits2;
12556 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12557 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12558 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12561 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12562 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12563 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12566 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12567 EVT VT1 = Val.getValueType();
12568 if (isZExtFree(VT1, VT2))
12571 if (Val.getOpcode() != ISD::LOAD)
12574 if (!VT1.isSimple() || !VT1.isInteger() ||
12575 !VT2.isSimple() || !VT2.isInteger())
12578 switch (VT1.getSimpleVT().SimpleTy) {
12583 // X86 has 8, 16, and 32-bit zero-extending loads.
12590 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12591 // i16 instructions are longer (0x66 prefix) and potentially slower.
12592 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12595 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12596 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12597 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12598 /// are assumed to be legal.
12600 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12602 // Very little shuffling can be done for 64-bit vectors right now.
12603 if (VT.getSizeInBits() == 64)
12606 // FIXME: pshufb, blends, shifts.
12607 return (VT.getVectorNumElements() == 2 ||
12608 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12609 isMOVLMask(M, VT) ||
12610 isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12611 isPSHUFDMask(M, VT) ||
12612 isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12613 isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12614 isPALIGNRMask(M, VT, Subtarget) ||
12615 isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12616 isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12617 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12618 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12622 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12624 unsigned NumElts = VT.getVectorNumElements();
12625 // FIXME: This collection of masks seems suspect.
12628 if (NumElts == 4 && VT.is128BitVector()) {
12629 return (isMOVLMask(Mask, VT) ||
12630 isCommutedMOVLMask(Mask, VT, true) ||
12631 isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12632 isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12637 //===----------------------------------------------------------------------===//
12638 // X86 Scheduler Hooks
12639 //===----------------------------------------------------------------------===//
12641 /// Utility function to emit xbegin specifying the start of an RTM region.
12642 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12643 const TargetInstrInfo *TII) {
12644 DebugLoc DL = MI->getDebugLoc();
12646 const BasicBlock *BB = MBB->getBasicBlock();
12647 MachineFunction::iterator I = MBB;
12650 // For the v = xbegin(), we generate
12661 MachineBasicBlock *thisMBB = MBB;
12662 MachineFunction *MF = MBB->getParent();
12663 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12664 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12665 MF->insert(I, mainMBB);
12666 MF->insert(I, sinkMBB);
12668 // Transfer the remainder of BB and its successor edges to sinkMBB.
12669 sinkMBB->splice(sinkMBB->begin(), MBB,
12670 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12671 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12675 // # fallthrough to mainMBB
12676 // # abortion to sinkMBB
12677 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12678 thisMBB->addSuccessor(mainMBB);
12679 thisMBB->addSuccessor(sinkMBB);
12683 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12684 mainMBB->addSuccessor(sinkMBB);
12687 // EAX is live into the sinkMBB
12688 sinkMBB->addLiveIn(X86::EAX);
12689 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12690 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12693 MI->eraseFromParent();
12697 // Get CMPXCHG opcode for the specified data type.
12698 static unsigned getCmpXChgOpcode(EVT VT) {
12699 switch (VT.getSimpleVT().SimpleTy) {
12700 case MVT::i8: return X86::LCMPXCHG8;
12701 case MVT::i16: return X86::LCMPXCHG16;
12702 case MVT::i32: return X86::LCMPXCHG32;
12703 case MVT::i64: return X86::LCMPXCHG64;
12707 llvm_unreachable("Invalid operand size!");
12710 // Get LOAD opcode for the specified data type.
12711 static unsigned getLoadOpcode(EVT VT) {
12712 switch (VT.getSimpleVT().SimpleTy) {
12713 case MVT::i8: return X86::MOV8rm;
12714 case MVT::i16: return X86::MOV16rm;
12715 case MVT::i32: return X86::MOV32rm;
12716 case MVT::i64: return X86::MOV64rm;
12720 llvm_unreachable("Invalid operand size!");
12723 // Get opcode of the non-atomic one from the specified atomic instruction.
12724 static unsigned getNonAtomicOpcode(unsigned Opc) {
12726 case X86::ATOMAND8: return X86::AND8rr;
12727 case X86::ATOMAND16: return X86::AND16rr;
12728 case X86::ATOMAND32: return X86::AND32rr;
12729 case X86::ATOMAND64: return X86::AND64rr;
12730 case X86::ATOMOR8: return X86::OR8rr;
12731 case X86::ATOMOR16: return X86::OR16rr;
12732 case X86::ATOMOR32: return X86::OR32rr;
12733 case X86::ATOMOR64: return X86::OR64rr;
12734 case X86::ATOMXOR8: return X86::XOR8rr;
12735 case X86::ATOMXOR16: return X86::XOR16rr;
12736 case X86::ATOMXOR32: return X86::XOR32rr;
12737 case X86::ATOMXOR64: return X86::XOR64rr;
12739 llvm_unreachable("Unhandled atomic-load-op opcode!");
12742 // Get opcode of the non-atomic one from the specified atomic instruction with
12744 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12745 unsigned &ExtraOpc) {
12747 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
12748 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
12749 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
12750 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
12751 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
12752 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12753 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12754 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12755 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
12756 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12757 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12758 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12759 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
12760 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12761 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12762 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12763 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
12764 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12765 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12766 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12768 llvm_unreachable("Unhandled atomic-load-op opcode!");
12771 // Get opcode of the non-atomic one from the specified atomic instruction for
12772 // 64-bit data type on 32-bit target.
12773 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12775 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
12776 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
12777 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
12778 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
12779 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
12780 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12781 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
12782 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
12783 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
12784 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
12786 llvm_unreachable("Unhandled atomic-load-op opcode!");
12789 // Get opcode of the non-atomic one from the specified atomic instruction for
12790 // 64-bit data type on 32-bit target with extra opcode.
12791 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12793 unsigned &ExtraOpc) {
12795 case X86::ATOMNAND6432:
12796 ExtraOpc = X86::NOT32r;
12797 HiOpc = X86::AND32rr;
12798 return X86::AND32rr;
12800 llvm_unreachable("Unhandled atomic-load-op opcode!");
12803 // Get pseudo CMOV opcode from the specified data type.
12804 static unsigned getPseudoCMOVOpc(EVT VT) {
12805 switch (VT.getSimpleVT().SimpleTy) {
12806 case MVT::i8: return X86::CMOV_GR8;
12807 case MVT::i16: return X86::CMOV_GR16;
12808 case MVT::i32: return X86::CMOV_GR32;
12812 llvm_unreachable("Unknown CMOV opcode!");
12815 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12816 // They will be translated into a spin-loop or compare-exchange loop from
12819 // dst = atomic-fetch-op MI.addr, MI.val
12825 // EAX = LOAD MI.addr
12827 // t1 = OP MI.val, EAX
12828 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12833 MachineBasicBlock *
12834 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12835 MachineBasicBlock *MBB) const {
12836 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12837 DebugLoc DL = MI->getDebugLoc();
12839 MachineFunction *MF = MBB->getParent();
12840 MachineRegisterInfo &MRI = MF->getRegInfo();
12842 const BasicBlock *BB = MBB->getBasicBlock();
12843 MachineFunction::iterator I = MBB;
12846 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12847 "Unexpected number of operands");
12849 assert(MI->hasOneMemOperand() &&
12850 "Expected atomic-load-op to have one memoperand");
12852 // Memory Reference
12853 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12854 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12856 unsigned DstReg, SrcReg;
12857 unsigned MemOpndSlot;
12859 unsigned CurOp = 0;
12861 DstReg = MI->getOperand(CurOp++).getReg();
12862 MemOpndSlot = CurOp;
12863 CurOp += X86::AddrNumOperands;
12864 SrcReg = MI->getOperand(CurOp++).getReg();
12866 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12867 MVT::SimpleValueType VT = *RC->vt_begin();
12868 unsigned AccPhyReg = getX86SubSuperRegister(X86::EAX, VT);
12870 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12871 unsigned LOADOpc = getLoadOpcode(VT);
12873 // For the atomic load-arith operator, we generate
12876 // EAX = LOAD [MI.addr]
12878 // t1 = OP MI.val, EAX
12879 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12883 MachineBasicBlock *thisMBB = MBB;
12884 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12885 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12886 MF->insert(I, mainMBB);
12887 MF->insert(I, sinkMBB);
12889 MachineInstrBuilder MIB;
12891 // Transfer the remainder of BB and its successor edges to sinkMBB.
12892 sinkMBB->splice(sinkMBB->begin(), MBB,
12893 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12894 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12897 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), AccPhyReg);
12898 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
12899 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
12900 MIB.setMemRefs(MMOBegin, MMOEnd);
12902 thisMBB->addSuccessor(mainMBB);
12905 MachineBasicBlock *origMainMBB = mainMBB;
12906 mainMBB->addLiveIn(AccPhyReg);
12908 // Copy AccPhyReg as it is used more than once.
12909 unsigned AccReg = MRI.createVirtualRegister(RC);
12910 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccReg)
12911 .addReg(AccPhyReg);
12913 unsigned t1 = MRI.createVirtualRegister(RC);
12914 unsigned Opc = MI->getOpcode();
12917 llvm_unreachable("Unhandled atomic-load-op opcode!");
12918 case X86::ATOMAND8:
12919 case X86::ATOMAND16:
12920 case X86::ATOMAND32:
12921 case X86::ATOMAND64:
12923 case X86::ATOMOR16:
12924 case X86::ATOMOR32:
12925 case X86::ATOMOR64:
12926 case X86::ATOMXOR8:
12927 case X86::ATOMXOR16:
12928 case X86::ATOMXOR32:
12929 case X86::ATOMXOR64: {
12930 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
12931 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t1).addReg(SrcReg)
12935 case X86::ATOMNAND8:
12936 case X86::ATOMNAND16:
12937 case X86::ATOMNAND32:
12938 case X86::ATOMNAND64: {
12939 unsigned t2 = MRI.createVirtualRegister(RC);
12941 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
12942 BuildMI(mainMBB, DL, TII->get(ANDOpc), t2).addReg(SrcReg)
12944 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1).addReg(t2);
12947 case X86::ATOMMAX8:
12948 case X86::ATOMMAX16:
12949 case X86::ATOMMAX32:
12950 case X86::ATOMMAX64:
12951 case X86::ATOMMIN8:
12952 case X86::ATOMMIN16:
12953 case X86::ATOMMIN32:
12954 case X86::ATOMMIN64:
12955 case X86::ATOMUMAX8:
12956 case X86::ATOMUMAX16:
12957 case X86::ATOMUMAX32:
12958 case X86::ATOMUMAX64:
12959 case X86::ATOMUMIN8:
12960 case X86::ATOMUMIN16:
12961 case X86::ATOMUMIN32:
12962 case X86::ATOMUMIN64: {
12964 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
12966 BuildMI(mainMBB, DL, TII->get(CMPOpc))
12970 if (Subtarget->hasCMov()) {
12971 if (VT != MVT::i8) {
12973 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t1)
12977 // Promote i8 to i32 to use CMOV32
12978 const TargetRegisterClass *RC32 = getRegClassFor(MVT::i32);
12979 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
12980 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
12981 unsigned t2 = MRI.createVirtualRegister(RC32);
12983 unsigned Undef = MRI.createVirtualRegister(RC32);
12984 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
12986 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
12989 .addImm(X86::sub_8bit);
12990 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
12993 .addImm(X86::sub_8bit);
12995 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
12999 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t1)
13000 .addReg(t2, 0, X86::sub_8bit);
13003 // Use pseudo select and lower them.
13004 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13005 "Invalid atomic-load-op transformation!");
13006 unsigned SelOpc = getPseudoCMOVOpc(VT);
13007 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13008 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13009 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t1)
13010 .addReg(SrcReg).addReg(AccReg)
13012 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13018 // Copy AccPhyReg back from virtual register.
13019 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), AccPhyReg)
13022 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13023 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13024 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13026 MIB.setMemRefs(MMOBegin, MMOEnd);
13028 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13030 mainMBB->addSuccessor(origMainMBB);
13031 mainMBB->addSuccessor(sinkMBB);
13034 sinkMBB->addLiveIn(AccPhyReg);
13036 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13037 TII->get(TargetOpcode::COPY), DstReg)
13038 .addReg(AccPhyReg);
13040 MI->eraseFromParent();
13044 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13045 // instructions. They will be translated into a spin-loop or compare-exchange
13049 // dst = atomic-fetch-op MI.addr, MI.val
13055 // EAX = LOAD [MI.addr + 0]
13056 // EDX = LOAD [MI.addr + 4]
13058 // EBX = OP MI.val.lo, EAX
13059 // ECX = OP MI.val.hi, EDX
13060 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13065 MachineBasicBlock *
13066 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13067 MachineBasicBlock *MBB) const {
13068 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13069 DebugLoc DL = MI->getDebugLoc();
13071 MachineFunction *MF = MBB->getParent();
13072 MachineRegisterInfo &MRI = MF->getRegInfo();
13074 const BasicBlock *BB = MBB->getBasicBlock();
13075 MachineFunction::iterator I = MBB;
13078 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13079 "Unexpected number of operands");
13081 assert(MI->hasOneMemOperand() &&
13082 "Expected atomic-load-op32 to have one memoperand");
13084 // Memory Reference
13085 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13086 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13088 unsigned DstLoReg, DstHiReg;
13089 unsigned SrcLoReg, SrcHiReg;
13090 unsigned MemOpndSlot;
13092 unsigned CurOp = 0;
13094 DstLoReg = MI->getOperand(CurOp++).getReg();
13095 DstHiReg = MI->getOperand(CurOp++).getReg();
13096 MemOpndSlot = CurOp;
13097 CurOp += X86::AddrNumOperands;
13098 SrcLoReg = MI->getOperand(CurOp++).getReg();
13099 SrcHiReg = MI->getOperand(CurOp++).getReg();
13101 const TargetRegisterClass *RC = &X86::GR32RegClass;
13102 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13104 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13105 unsigned LOADOpc = X86::MOV32rm;
13107 // For the atomic load-arith operator, we generate
13110 // EAX = LOAD [MI.addr + 0]
13111 // EDX = LOAD [MI.addr + 4]
13113 // EBX = OP MI.vallo, EAX
13114 // ECX = OP MI.valhi, EDX
13115 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13119 MachineBasicBlock *thisMBB = MBB;
13120 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13121 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13122 MF->insert(I, mainMBB);
13123 MF->insert(I, sinkMBB);
13125 MachineInstrBuilder MIB;
13127 // Transfer the remainder of BB and its successor edges to sinkMBB.
13128 sinkMBB->splice(sinkMBB->begin(), MBB,
13129 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13130 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13134 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EAX);
13135 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13136 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13137 MIB.setMemRefs(MMOBegin, MMOEnd);
13139 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), X86::EDX);
13140 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13141 if (i == X86::AddrDisp)
13142 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13144 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13146 MIB.setMemRefs(MMOBegin, MMOEnd);
13148 thisMBB->addSuccessor(mainMBB);
13151 MachineBasicBlock *origMainMBB = mainMBB;
13152 mainMBB->addLiveIn(X86::EAX);
13153 mainMBB->addLiveIn(X86::EDX);
13155 // Copy EDX:EAX as they are used more than once.
13156 unsigned LoReg = MRI.createVirtualRegister(RC);
13157 unsigned HiReg = MRI.createVirtualRegister(RC);
13158 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), LoReg).addReg(X86::EAX);
13159 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), HiReg).addReg(X86::EDX);
13161 unsigned t1L = MRI.createVirtualRegister(RC);
13162 unsigned t1H = MRI.createVirtualRegister(RC);
13164 unsigned Opc = MI->getOpcode();
13167 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13168 case X86::ATOMAND6432:
13169 case X86::ATOMOR6432:
13170 case X86::ATOMXOR6432:
13171 case X86::ATOMADD6432:
13172 case X86::ATOMSUB6432: {
13174 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13175 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(LoReg).addReg(SrcLoReg);
13176 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(HiReg).addReg(SrcHiReg);
13179 case X86::ATOMNAND6432: {
13180 unsigned HiOpc, NOTOpc;
13181 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13182 unsigned t2L = MRI.createVirtualRegister(RC);
13183 unsigned t2H = MRI.createVirtualRegister(RC);
13184 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg).addReg(LoReg);
13185 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg).addReg(HiReg);
13186 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1L).addReg(t2L);
13187 BuildMI(mainMBB, DL, TII->get(NOTOpc), t1H).addReg(t2H);
13190 case X86::ATOMMAX6432:
13191 case X86::ATOMMIN6432:
13192 case X86::ATOMUMAX6432:
13193 case X86::ATOMUMIN6432: {
13195 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13196 unsigned cL = MRI.createVirtualRegister(RC8);
13197 unsigned cH = MRI.createVirtualRegister(RC8);
13198 unsigned cL32 = MRI.createVirtualRegister(RC);
13199 unsigned cH32 = MRI.createVirtualRegister(RC);
13200 unsigned cc = MRI.createVirtualRegister(RC);
13201 // cl := cmp src_lo, lo
13202 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13203 .addReg(SrcLoReg).addReg(LoReg);
13204 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13205 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13206 // ch := cmp src_hi, hi
13207 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13208 .addReg(SrcHiReg).addReg(HiReg);
13209 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13210 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13211 // cc := if (src_hi == hi) ? cl : ch;
13212 if (Subtarget->hasCMov()) {
13213 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13214 .addReg(cH32).addReg(cL32);
13216 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13217 .addReg(cH32).addReg(cL32)
13218 .addImm(X86::COND_E);
13219 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13221 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13222 if (Subtarget->hasCMov()) {
13223 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1L)
13224 .addReg(SrcLoReg).addReg(LoReg);
13225 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t1H)
13226 .addReg(SrcHiReg).addReg(HiReg);
13228 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1L)
13229 .addReg(SrcLoReg).addReg(LoReg)
13230 .addImm(X86::COND_NE);
13231 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13232 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t1H)
13233 .addReg(SrcHiReg).addReg(HiReg)
13234 .addImm(X86::COND_NE);
13235 mainMBB = EmitLoweredSelect(MIB, mainMBB);
13239 case X86::ATOMSWAP6432: {
13241 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13242 BuildMI(mainMBB, DL, TII->get(LoOpc), t1L).addReg(SrcLoReg);
13243 BuildMI(mainMBB, DL, TII->get(HiOpc), t1H).addReg(SrcHiReg);
13248 // Copy EDX:EAX back from HiReg:LoReg
13249 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(LoReg);
13250 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(HiReg);
13251 // Copy ECX:EBX from t1H:t1L
13252 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t1L);
13253 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t1H);
13255 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13256 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
13257 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
13258 MIB.setMemRefs(MMOBegin, MMOEnd);
13260 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13262 mainMBB->addSuccessor(origMainMBB);
13263 mainMBB->addSuccessor(sinkMBB);
13266 sinkMBB->addLiveIn(X86::EAX);
13267 sinkMBB->addLiveIn(X86::EDX);
13269 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13270 TII->get(TargetOpcode::COPY), DstLoReg)
13272 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13273 TII->get(TargetOpcode::COPY), DstHiReg)
13276 MI->eraseFromParent();
13280 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13281 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13282 // in the .td file.
13283 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13284 const TargetInstrInfo *TII) {
13286 switch (MI->getOpcode()) {
13287 default: llvm_unreachable("illegal opcode!");
13288 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
13289 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13290 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
13291 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13292 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
13293 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13294 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
13295 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13298 DebugLoc dl = MI->getDebugLoc();
13299 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13301 unsigned NumArgs = MI->getNumOperands();
13302 for (unsigned i = 1; i < NumArgs; ++i) {
13303 MachineOperand &Op = MI->getOperand(i);
13304 if (!(Op.isReg() && Op.isImplicit()))
13305 MIB.addOperand(Op);
13307 if (MI->hasOneMemOperand())
13308 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13310 BuildMI(*BB, MI, dl,
13311 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13312 .addReg(X86::XMM0);
13314 MI->eraseFromParent();
13318 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13319 // defs in an instruction pattern
13320 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13321 const TargetInstrInfo *TII) {
13323 switch (MI->getOpcode()) {
13324 default: llvm_unreachable("illegal opcode!");
13325 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
13326 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13327 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
13328 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13329 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
13330 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13331 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
13332 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13335 DebugLoc dl = MI->getDebugLoc();
13336 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13338 unsigned NumArgs = MI->getNumOperands(); // remove the results
13339 for (unsigned i = 1; i < NumArgs; ++i) {
13340 MachineOperand &Op = MI->getOperand(i);
13341 if (!(Op.isReg() && Op.isImplicit()))
13342 MIB.addOperand(Op);
13344 if (MI->hasOneMemOperand())
13345 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13347 BuildMI(*BB, MI, dl,
13348 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13351 MI->eraseFromParent();
13355 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13356 const TargetInstrInfo *TII,
13357 const X86Subtarget* Subtarget) {
13358 DebugLoc dl = MI->getDebugLoc();
13360 // Address into RAX/EAX, other two args into ECX, EDX.
13361 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13362 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13363 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13364 for (int i = 0; i < X86::AddrNumOperands; ++i)
13365 MIB.addOperand(MI->getOperand(i));
13367 unsigned ValOps = X86::AddrNumOperands;
13368 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13369 .addReg(MI->getOperand(ValOps).getReg());
13370 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13371 .addReg(MI->getOperand(ValOps+1).getReg());
13373 // The instruction doesn't actually take any operands though.
13374 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13376 MI->eraseFromParent(); // The pseudo is gone now.
13380 MachineBasicBlock *
13381 X86TargetLowering::EmitVAARG64WithCustomInserter(
13383 MachineBasicBlock *MBB) const {
13384 // Emit va_arg instruction on X86-64.
13386 // Operands to this pseudo-instruction:
13387 // 0 ) Output : destination address (reg)
13388 // 1-5) Input : va_list address (addr, i64mem)
13389 // 6 ) ArgSize : Size (in bytes) of vararg type
13390 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13391 // 8 ) Align : Alignment of type
13392 // 9 ) EFLAGS (implicit-def)
13394 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13395 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13397 unsigned DestReg = MI->getOperand(0).getReg();
13398 MachineOperand &Base = MI->getOperand(1);
13399 MachineOperand &Scale = MI->getOperand(2);
13400 MachineOperand &Index = MI->getOperand(3);
13401 MachineOperand &Disp = MI->getOperand(4);
13402 MachineOperand &Segment = MI->getOperand(5);
13403 unsigned ArgSize = MI->getOperand(6).getImm();
13404 unsigned ArgMode = MI->getOperand(7).getImm();
13405 unsigned Align = MI->getOperand(8).getImm();
13407 // Memory Reference
13408 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13409 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13410 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13412 // Machine Information
13413 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13414 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13415 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13416 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13417 DebugLoc DL = MI->getDebugLoc();
13419 // struct va_list {
13422 // i64 overflow_area (address)
13423 // i64 reg_save_area (address)
13425 // sizeof(va_list) = 24
13426 // alignment(va_list) = 8
13428 unsigned TotalNumIntRegs = 6;
13429 unsigned TotalNumXMMRegs = 8;
13430 bool UseGPOffset = (ArgMode == 1);
13431 bool UseFPOffset = (ArgMode == 2);
13432 unsigned MaxOffset = TotalNumIntRegs * 8 +
13433 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13435 /* Align ArgSize to a multiple of 8 */
13436 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13437 bool NeedsAlign = (Align > 8);
13439 MachineBasicBlock *thisMBB = MBB;
13440 MachineBasicBlock *overflowMBB;
13441 MachineBasicBlock *offsetMBB;
13442 MachineBasicBlock *endMBB;
13444 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
13445 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
13446 unsigned OffsetReg = 0;
13448 if (!UseGPOffset && !UseFPOffset) {
13449 // If we only pull from the overflow region, we don't create a branch.
13450 // We don't need to alter control flow.
13451 OffsetDestReg = 0; // unused
13452 OverflowDestReg = DestReg;
13455 overflowMBB = thisMBB;
13458 // First emit code to check if gp_offset (or fp_offset) is below the bound.
13459 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13460 // If not, pull from overflow_area. (branch to overflowMBB)
13465 // offsetMBB overflowMBB
13470 // Registers for the PHI in endMBB
13471 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13472 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13474 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13475 MachineFunction *MF = MBB->getParent();
13476 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13477 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13478 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13480 MachineFunction::iterator MBBIter = MBB;
13483 // Insert the new basic blocks
13484 MF->insert(MBBIter, offsetMBB);
13485 MF->insert(MBBIter, overflowMBB);
13486 MF->insert(MBBIter, endMBB);
13488 // Transfer the remainder of MBB and its successor edges to endMBB.
13489 endMBB->splice(endMBB->begin(), thisMBB,
13490 llvm::next(MachineBasicBlock::iterator(MI)),
13492 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13494 // Make offsetMBB and overflowMBB successors of thisMBB
13495 thisMBB->addSuccessor(offsetMBB);
13496 thisMBB->addSuccessor(overflowMBB);
13498 // endMBB is a successor of both offsetMBB and overflowMBB
13499 offsetMBB->addSuccessor(endMBB);
13500 overflowMBB->addSuccessor(endMBB);
13502 // Load the offset value into a register
13503 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13504 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13508 .addDisp(Disp, UseFPOffset ? 4 : 0)
13509 .addOperand(Segment)
13510 .setMemRefs(MMOBegin, MMOEnd);
13512 // Check if there is enough room left to pull this argument.
13513 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13515 .addImm(MaxOffset + 8 - ArgSizeA8);
13517 // Branch to "overflowMBB" if offset >= max
13518 // Fall through to "offsetMBB" otherwise
13519 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13520 .addMBB(overflowMBB);
13523 // In offsetMBB, emit code to use the reg_save_area.
13525 assert(OffsetReg != 0);
13527 // Read the reg_save_area address.
13528 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13529 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13534 .addOperand(Segment)
13535 .setMemRefs(MMOBegin, MMOEnd);
13537 // Zero-extend the offset
13538 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13539 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13542 .addImm(X86::sub_32bit);
13544 // Add the offset to the reg_save_area to get the final address.
13545 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13546 .addReg(OffsetReg64)
13547 .addReg(RegSaveReg);
13549 // Compute the offset for the next argument
13550 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13551 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13553 .addImm(UseFPOffset ? 16 : 8);
13555 // Store it back into the va_list.
13556 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13560 .addDisp(Disp, UseFPOffset ? 4 : 0)
13561 .addOperand(Segment)
13562 .addReg(NextOffsetReg)
13563 .setMemRefs(MMOBegin, MMOEnd);
13566 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13571 // Emit code to use overflow area
13574 // Load the overflow_area address into a register.
13575 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13576 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13581 .addOperand(Segment)
13582 .setMemRefs(MMOBegin, MMOEnd);
13584 // If we need to align it, do so. Otherwise, just copy the address
13585 // to OverflowDestReg.
13587 // Align the overflow address
13588 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13589 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13591 // aligned_addr = (addr + (align-1)) & ~(align-1)
13592 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13593 .addReg(OverflowAddrReg)
13596 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13598 .addImm(~(uint64_t)(Align-1));
13600 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13601 .addReg(OverflowAddrReg);
13604 // Compute the next overflow address after this argument.
13605 // (the overflow address should be kept 8-byte aligned)
13606 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13607 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13608 .addReg(OverflowDestReg)
13609 .addImm(ArgSizeA8);
13611 // Store the new overflow address.
13612 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13617 .addOperand(Segment)
13618 .addReg(NextAddrReg)
13619 .setMemRefs(MMOBegin, MMOEnd);
13621 // If we branched, emit the PHI to the front of endMBB.
13623 BuildMI(*endMBB, endMBB->begin(), DL,
13624 TII->get(X86::PHI), DestReg)
13625 .addReg(OffsetDestReg).addMBB(offsetMBB)
13626 .addReg(OverflowDestReg).addMBB(overflowMBB);
13629 // Erase the pseudo instruction
13630 MI->eraseFromParent();
13635 MachineBasicBlock *
13636 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13638 MachineBasicBlock *MBB) const {
13639 // Emit code to save XMM registers to the stack. The ABI says that the
13640 // number of registers to save is given in %al, so it's theoretically
13641 // possible to do an indirect jump trick to avoid saving all of them,
13642 // however this code takes a simpler approach and just executes all
13643 // of the stores if %al is non-zero. It's less code, and it's probably
13644 // easier on the hardware branch predictor, and stores aren't all that
13645 // expensive anyway.
13647 // Create the new basic blocks. One block contains all the XMM stores,
13648 // and one block is the final destination regardless of whether any
13649 // stores were performed.
13650 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13651 MachineFunction *F = MBB->getParent();
13652 MachineFunction::iterator MBBIter = MBB;
13654 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13655 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13656 F->insert(MBBIter, XMMSaveMBB);
13657 F->insert(MBBIter, EndMBB);
13659 // Transfer the remainder of MBB and its successor edges to EndMBB.
13660 EndMBB->splice(EndMBB->begin(), MBB,
13661 llvm::next(MachineBasicBlock::iterator(MI)),
13663 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13665 // The original block will now fall through to the XMM save block.
13666 MBB->addSuccessor(XMMSaveMBB);
13667 // The XMMSaveMBB will fall through to the end block.
13668 XMMSaveMBB->addSuccessor(EndMBB);
13670 // Now add the instructions.
13671 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13672 DebugLoc DL = MI->getDebugLoc();
13674 unsigned CountReg = MI->getOperand(0).getReg();
13675 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13676 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13678 if (!Subtarget->isTargetWin64()) {
13679 // If %al is 0, branch around the XMM save block.
13680 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13681 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13682 MBB->addSuccessor(EndMBB);
13685 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13686 // In the XMM save block, save all the XMM argument registers.
13687 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13688 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13689 MachineMemOperand *MMO =
13690 F->getMachineMemOperand(
13691 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13692 MachineMemOperand::MOStore,
13693 /*Size=*/16, /*Align=*/16);
13694 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13695 .addFrameIndex(RegSaveFrameIndex)
13696 .addImm(/*Scale=*/1)
13697 .addReg(/*IndexReg=*/0)
13698 .addImm(/*Disp=*/Offset)
13699 .addReg(/*Segment=*/0)
13700 .addReg(MI->getOperand(i).getReg())
13701 .addMemOperand(MMO);
13704 MI->eraseFromParent(); // The pseudo instruction is gone now.
13709 // The EFLAGS operand of SelectItr might be missing a kill marker
13710 // because there were multiple uses of EFLAGS, and ISel didn't know
13711 // which to mark. Figure out whether SelectItr should have had a
13712 // kill marker, and set it if it should. Returns the correct kill
13714 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13715 MachineBasicBlock* BB,
13716 const TargetRegisterInfo* TRI) {
13717 // Scan forward through BB for a use/def of EFLAGS.
13718 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13719 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13720 const MachineInstr& mi = *miI;
13721 if (mi.readsRegister(X86::EFLAGS))
13723 if (mi.definesRegister(X86::EFLAGS))
13724 break; // Should have kill-flag - update below.
13727 // If we hit the end of the block, check whether EFLAGS is live into a
13729 if (miI == BB->end()) {
13730 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13731 sEnd = BB->succ_end();
13732 sItr != sEnd; ++sItr) {
13733 MachineBasicBlock* succ = *sItr;
13734 if (succ->isLiveIn(X86::EFLAGS))
13739 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13740 // out. SelectMI should have a kill flag on EFLAGS.
13741 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13745 MachineBasicBlock *
13746 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13747 MachineBasicBlock *BB) const {
13748 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13749 DebugLoc DL = MI->getDebugLoc();
13751 // To "insert" a SELECT_CC instruction, we actually have to insert the
13752 // diamond control-flow pattern. The incoming instruction knows the
13753 // destination vreg to set, the condition code register to branch on, the
13754 // true/false values to select between, and a branch opcode to use.
13755 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13756 MachineFunction::iterator It = BB;
13762 // cmpTY ccX, r1, r2
13764 // fallthrough --> copy0MBB
13765 MachineBasicBlock *thisMBB = BB;
13766 MachineFunction *F = BB->getParent();
13767 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13768 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13769 F->insert(It, copy0MBB);
13770 F->insert(It, sinkMBB);
13772 // If the EFLAGS register isn't dead in the terminator, then claim that it's
13773 // live into the sink and copy blocks.
13774 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13775 if (!MI->killsRegister(X86::EFLAGS) &&
13776 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13777 copy0MBB->addLiveIn(X86::EFLAGS);
13778 sinkMBB->addLiveIn(X86::EFLAGS);
13781 // Transfer the remainder of BB and its successor edges to sinkMBB.
13782 sinkMBB->splice(sinkMBB->begin(), BB,
13783 llvm::next(MachineBasicBlock::iterator(MI)),
13785 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13787 // Add the true and fallthrough blocks as its successors.
13788 BB->addSuccessor(copy0MBB);
13789 BB->addSuccessor(sinkMBB);
13791 // Create the conditional branch instruction.
13793 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13794 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13797 // %FalseValue = ...
13798 // # fallthrough to sinkMBB
13799 copy0MBB->addSuccessor(sinkMBB);
13802 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13804 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13805 TII->get(X86::PHI), MI->getOperand(0).getReg())
13806 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13807 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13809 MI->eraseFromParent(); // The pseudo instruction is gone now.
13813 MachineBasicBlock *
13814 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13815 bool Is64Bit) const {
13816 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13817 DebugLoc DL = MI->getDebugLoc();
13818 MachineFunction *MF = BB->getParent();
13819 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13821 assert(getTargetMachine().Options.EnableSegmentedStacks);
13823 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13824 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13827 // ... [Till the alloca]
13828 // If stacklet is not large enough, jump to mallocMBB
13831 // Allocate by subtracting from RSP
13832 // Jump to continueMBB
13835 // Allocate by call to runtime
13839 // [rest of original BB]
13842 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13843 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13844 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13846 MachineRegisterInfo &MRI = MF->getRegInfo();
13847 const TargetRegisterClass *AddrRegClass =
13848 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
13850 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13851 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
13852 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
13853 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
13854 sizeVReg = MI->getOperand(1).getReg(),
13855 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
13857 MachineFunction::iterator MBBIter = BB;
13860 MF->insert(MBBIter, bumpMBB);
13861 MF->insert(MBBIter, mallocMBB);
13862 MF->insert(MBBIter, continueMBB);
13864 continueMBB->splice(continueMBB->begin(), BB, llvm::next
13865 (MachineBasicBlock::iterator(MI)), BB->end());
13866 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
13868 // Add code to the main basic block to check if the stack limit has been hit,
13869 // and if so, jump to mallocMBB otherwise to bumpMBB.
13870 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
13871 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
13872 .addReg(tmpSPVReg).addReg(sizeVReg);
13873 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
13874 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
13875 .addReg(SPLimitVReg);
13876 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
13878 // bumpMBB simply decreases the stack pointer, since we know the current
13879 // stacklet has enough space.
13880 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
13881 .addReg(SPLimitVReg);
13882 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
13883 .addReg(SPLimitVReg);
13884 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13886 // Calls into a routine in libgcc to allocate more space from the heap.
13887 const uint32_t *RegMask =
13888 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
13890 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
13892 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
13893 .addExternalSymbol("__morestack_allocate_stack_space")
13894 .addRegMask(RegMask)
13895 .addReg(X86::RDI, RegState::Implicit)
13896 .addReg(X86::RAX, RegState::ImplicitDefine);
13898 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
13900 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
13901 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
13902 .addExternalSymbol("__morestack_allocate_stack_space")
13903 .addRegMask(RegMask)
13904 .addReg(X86::EAX, RegState::ImplicitDefine);
13908 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
13911 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
13912 .addReg(Is64Bit ? X86::RAX : X86::EAX);
13913 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
13915 // Set up the CFG correctly.
13916 BB->addSuccessor(bumpMBB);
13917 BB->addSuccessor(mallocMBB);
13918 mallocMBB->addSuccessor(continueMBB);
13919 bumpMBB->addSuccessor(continueMBB);
13921 // Take care of the PHI nodes.
13922 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
13923 MI->getOperand(0).getReg())
13924 .addReg(mallocPtrVReg).addMBB(mallocMBB)
13925 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
13927 // Delete the original pseudo instruction.
13928 MI->eraseFromParent();
13931 return continueMBB;
13934 MachineBasicBlock *
13935 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
13936 MachineBasicBlock *BB) const {
13937 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13938 DebugLoc DL = MI->getDebugLoc();
13940 assert(!Subtarget->isTargetEnvMacho());
13942 // The lowering is pretty easy: we're just emitting the call to _alloca. The
13943 // non-trivial part is impdef of ESP.
13945 if (Subtarget->isTargetWin64()) {
13946 if (Subtarget->isTargetCygMing()) {
13947 // ___chkstk(Mingw64):
13948 // Clobbers R10, R11, RAX and EFLAGS.
13950 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13951 .addExternalSymbol("___chkstk")
13952 .addReg(X86::RAX, RegState::Implicit)
13953 .addReg(X86::RSP, RegState::Implicit)
13954 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
13955 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
13956 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13958 // __chkstk(MSVCRT): does not update stack pointer.
13959 // Clobbers R10, R11 and EFLAGS.
13960 // FIXME: RAX(allocated size) might be reused and not killed.
13961 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
13962 .addExternalSymbol("__chkstk")
13963 .addReg(X86::RAX, RegState::Implicit)
13964 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13965 // RAX has the offset to subtracted from RSP.
13966 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
13971 const char *StackProbeSymbol =
13972 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
13974 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
13975 .addExternalSymbol(StackProbeSymbol)
13976 .addReg(X86::EAX, RegState::Implicit)
13977 .addReg(X86::ESP, RegState::Implicit)
13978 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
13979 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
13980 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
13983 MI->eraseFromParent(); // The pseudo instruction is gone now.
13987 MachineBasicBlock *
13988 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
13989 MachineBasicBlock *BB) const {
13990 // This is pretty easy. We're taking the value that we received from
13991 // our load from the relocation, sticking it in either RDI (x86-64)
13992 // or EAX and doing an indirect call. The return value will then
13993 // be in the normal return register.
13994 const X86InstrInfo *TII
13995 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
13996 DebugLoc DL = MI->getDebugLoc();
13997 MachineFunction *F = BB->getParent();
13999 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14000 assert(MI->getOperand(3).isGlobal() && "This should be a global");
14002 // Get a register mask for the lowered call.
14003 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14004 // proper register mask.
14005 const uint32_t *RegMask =
14006 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14007 if (Subtarget->is64Bit()) {
14008 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14009 TII->get(X86::MOV64rm), X86::RDI)
14011 .addImm(0).addReg(0)
14012 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14013 MI->getOperand(3).getTargetFlags())
14015 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14016 addDirectMem(MIB, X86::RDI);
14017 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14018 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14019 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14020 TII->get(X86::MOV32rm), X86::EAX)
14022 .addImm(0).addReg(0)
14023 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14024 MI->getOperand(3).getTargetFlags())
14026 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14027 addDirectMem(MIB, X86::EAX);
14028 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14030 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14031 TII->get(X86::MOV32rm), X86::EAX)
14032 .addReg(TII->getGlobalBaseReg(F))
14033 .addImm(0).addReg(0)
14034 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14035 MI->getOperand(3).getTargetFlags())
14037 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14038 addDirectMem(MIB, X86::EAX);
14039 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14042 MI->eraseFromParent(); // The pseudo instruction is gone now.
14046 MachineBasicBlock *
14047 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14048 MachineBasicBlock *MBB) const {
14049 DebugLoc DL = MI->getDebugLoc();
14050 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14052 MachineFunction *MF = MBB->getParent();
14053 MachineRegisterInfo &MRI = MF->getRegInfo();
14055 const BasicBlock *BB = MBB->getBasicBlock();
14056 MachineFunction::iterator I = MBB;
14059 // Memory Reference
14060 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14061 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14064 unsigned MemOpndSlot = 0;
14066 unsigned CurOp = 0;
14068 DstReg = MI->getOperand(CurOp++).getReg();
14069 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14070 assert(RC->hasType(MVT::i32) && "Invalid destination!");
14071 unsigned mainDstReg = MRI.createVirtualRegister(RC);
14072 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14074 MemOpndSlot = CurOp;
14076 MVT PVT = getPointerTy();
14077 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14078 "Invalid Pointer Size!");
14080 // For v = setjmp(buf), we generate
14083 // buf[LabelOffset] = restoreMBB
14084 // SjLjSetup restoreMBB
14090 // v = phi(main, restore)
14095 MachineBasicBlock *thisMBB = MBB;
14096 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14097 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14098 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14099 MF->insert(I, mainMBB);
14100 MF->insert(I, sinkMBB);
14101 MF->push_back(restoreMBB);
14103 MachineInstrBuilder MIB;
14105 // Transfer the remainder of BB and its successor edges to sinkMBB.
14106 sinkMBB->splice(sinkMBB->begin(), MBB,
14107 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14108 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14111 unsigned PtrStoreOpc = 0;
14112 unsigned LabelReg = 0;
14113 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14114 Reloc::Model RM = getTargetMachine().getRelocationModel();
14115 bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14116 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14118 // Prepare IP either in reg or imm.
14119 if (!UseImmLabel) {
14120 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14121 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14122 LabelReg = MRI.createVirtualRegister(PtrRC);
14123 if (Subtarget->is64Bit()) {
14124 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14128 .addMBB(restoreMBB)
14131 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14132 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14133 .addReg(XII->getGlobalBaseReg(MF))
14136 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14140 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14142 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14143 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14144 if (i == X86::AddrDisp)
14145 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14147 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14150 MIB.addReg(LabelReg);
14152 MIB.addMBB(restoreMBB);
14153 MIB.setMemRefs(MMOBegin, MMOEnd);
14155 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14156 .addMBB(restoreMBB);
14157 MIB.addRegMask(RegInfo->getNoPreservedMask());
14158 thisMBB->addSuccessor(mainMBB);
14159 thisMBB->addSuccessor(restoreMBB);
14163 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14164 mainMBB->addSuccessor(sinkMBB);
14167 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14168 TII->get(X86::PHI), DstReg)
14169 .addReg(mainDstReg).addMBB(mainMBB)
14170 .addReg(restoreDstReg).addMBB(restoreMBB);
14173 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14174 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14175 restoreMBB->addSuccessor(sinkMBB);
14177 MI->eraseFromParent();
14181 MachineBasicBlock *
14182 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14183 MachineBasicBlock *MBB) const {
14184 DebugLoc DL = MI->getDebugLoc();
14185 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14187 MachineFunction *MF = MBB->getParent();
14188 MachineRegisterInfo &MRI = MF->getRegInfo();
14190 // Memory Reference
14191 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14192 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14194 MVT PVT = getPointerTy();
14195 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14196 "Invalid Pointer Size!");
14198 const TargetRegisterClass *RC =
14199 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14200 unsigned Tmp = MRI.createVirtualRegister(RC);
14201 // Since FP is only updated here but NOT referenced, it's treated as GPR.
14202 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14203 unsigned SP = RegInfo->getStackRegister();
14205 MachineInstrBuilder MIB;
14207 const int64_t LabelOffset = 1 * PVT.getStoreSize();
14208 const int64_t SPOffset = 2 * PVT.getStoreSize();
14210 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14211 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14214 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14215 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14216 MIB.addOperand(MI->getOperand(i));
14217 MIB.setMemRefs(MMOBegin, MMOEnd);
14219 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14220 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14221 if (i == X86::AddrDisp)
14222 MIB.addDisp(MI->getOperand(i), LabelOffset);
14224 MIB.addOperand(MI->getOperand(i));
14226 MIB.setMemRefs(MMOBegin, MMOEnd);
14228 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14229 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14230 if (i == X86::AddrDisp)
14231 MIB.addDisp(MI->getOperand(i), SPOffset);
14233 MIB.addOperand(MI->getOperand(i));
14235 MIB.setMemRefs(MMOBegin, MMOEnd);
14237 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14239 MI->eraseFromParent();
14243 MachineBasicBlock *
14244 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14245 MachineBasicBlock *BB) const {
14246 switch (MI->getOpcode()) {
14247 default: llvm_unreachable("Unexpected instr type to insert");
14248 case X86::TAILJMPd64:
14249 case X86::TAILJMPr64:
14250 case X86::TAILJMPm64:
14251 llvm_unreachable("TAILJMP64 would not be touched here.");
14252 case X86::TCRETURNdi64:
14253 case X86::TCRETURNri64:
14254 case X86::TCRETURNmi64:
14256 case X86::WIN_ALLOCA:
14257 return EmitLoweredWinAlloca(MI, BB);
14258 case X86::SEG_ALLOCA_32:
14259 return EmitLoweredSegAlloca(MI, BB, false);
14260 case X86::SEG_ALLOCA_64:
14261 return EmitLoweredSegAlloca(MI, BB, true);
14262 case X86::TLSCall_32:
14263 case X86::TLSCall_64:
14264 return EmitLoweredTLSCall(MI, BB);
14265 case X86::CMOV_GR8:
14266 case X86::CMOV_FR32:
14267 case X86::CMOV_FR64:
14268 case X86::CMOV_V4F32:
14269 case X86::CMOV_V2F64:
14270 case X86::CMOV_V2I64:
14271 case X86::CMOV_V8F32:
14272 case X86::CMOV_V4F64:
14273 case X86::CMOV_V4I64:
14274 case X86::CMOV_GR16:
14275 case X86::CMOV_GR32:
14276 case X86::CMOV_RFP32:
14277 case X86::CMOV_RFP64:
14278 case X86::CMOV_RFP80:
14279 return EmitLoweredSelect(MI, BB);
14281 case X86::FP32_TO_INT16_IN_MEM:
14282 case X86::FP32_TO_INT32_IN_MEM:
14283 case X86::FP32_TO_INT64_IN_MEM:
14284 case X86::FP64_TO_INT16_IN_MEM:
14285 case X86::FP64_TO_INT32_IN_MEM:
14286 case X86::FP64_TO_INT64_IN_MEM:
14287 case X86::FP80_TO_INT16_IN_MEM:
14288 case X86::FP80_TO_INT32_IN_MEM:
14289 case X86::FP80_TO_INT64_IN_MEM: {
14290 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14291 DebugLoc DL = MI->getDebugLoc();
14293 // Change the floating point control register to use "round towards zero"
14294 // mode when truncating to an integer value.
14295 MachineFunction *F = BB->getParent();
14296 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14297 addFrameReference(BuildMI(*BB, MI, DL,
14298 TII->get(X86::FNSTCW16m)), CWFrameIdx);
14300 // Load the old value of the high byte of the control word...
14302 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14303 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14306 // Set the high part to be round to zero...
14307 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14310 // Reload the modified control word now...
14311 addFrameReference(BuildMI(*BB, MI, DL,
14312 TII->get(X86::FLDCW16m)), CWFrameIdx);
14314 // Restore the memory image of control word to original value
14315 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14318 // Get the X86 opcode to use.
14320 switch (MI->getOpcode()) {
14321 default: llvm_unreachable("illegal opcode!");
14322 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14323 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14324 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14325 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14326 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14327 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14328 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14329 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14330 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14334 MachineOperand &Op = MI->getOperand(0);
14336 AM.BaseType = X86AddressMode::RegBase;
14337 AM.Base.Reg = Op.getReg();
14339 AM.BaseType = X86AddressMode::FrameIndexBase;
14340 AM.Base.FrameIndex = Op.getIndex();
14342 Op = MI->getOperand(1);
14344 AM.Scale = Op.getImm();
14345 Op = MI->getOperand(2);
14347 AM.IndexReg = Op.getImm();
14348 Op = MI->getOperand(3);
14349 if (Op.isGlobal()) {
14350 AM.GV = Op.getGlobal();
14352 AM.Disp = Op.getImm();
14354 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14355 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14357 // Reload the original control word now.
14358 addFrameReference(BuildMI(*BB, MI, DL,
14359 TII->get(X86::FLDCW16m)), CWFrameIdx);
14361 MI->eraseFromParent(); // The pseudo instruction is gone now.
14364 // String/text processing lowering.
14365 case X86::PCMPISTRM128REG:
14366 case X86::VPCMPISTRM128REG:
14367 case X86::PCMPISTRM128MEM:
14368 case X86::VPCMPISTRM128MEM:
14369 case X86::PCMPESTRM128REG:
14370 case X86::VPCMPESTRM128REG:
14371 case X86::PCMPESTRM128MEM:
14372 case X86::VPCMPESTRM128MEM:
14373 assert(Subtarget->hasSSE42() &&
14374 "Target must have SSE4.2 or AVX features enabled");
14375 return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14377 // String/text processing lowering.
14378 case X86::PCMPISTRIREG:
14379 case X86::VPCMPISTRIREG:
14380 case X86::PCMPISTRIMEM:
14381 case X86::VPCMPISTRIMEM:
14382 case X86::PCMPESTRIREG:
14383 case X86::VPCMPESTRIREG:
14384 case X86::PCMPESTRIMEM:
14385 case X86::VPCMPESTRIMEM:
14386 assert(Subtarget->hasSSE42() &&
14387 "Target must have SSE4.2 or AVX features enabled");
14388 return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14390 // Thread synchronization.
14392 return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14396 return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14398 // Atomic Lowering.
14399 case X86::ATOMAND8:
14400 case X86::ATOMAND16:
14401 case X86::ATOMAND32:
14402 case X86::ATOMAND64:
14405 case X86::ATOMOR16:
14406 case X86::ATOMOR32:
14407 case X86::ATOMOR64:
14409 case X86::ATOMXOR16:
14410 case X86::ATOMXOR8:
14411 case X86::ATOMXOR32:
14412 case X86::ATOMXOR64:
14414 case X86::ATOMNAND8:
14415 case X86::ATOMNAND16:
14416 case X86::ATOMNAND32:
14417 case X86::ATOMNAND64:
14419 case X86::ATOMMAX8:
14420 case X86::ATOMMAX16:
14421 case X86::ATOMMAX32:
14422 case X86::ATOMMAX64:
14424 case X86::ATOMMIN8:
14425 case X86::ATOMMIN16:
14426 case X86::ATOMMIN32:
14427 case X86::ATOMMIN64:
14429 case X86::ATOMUMAX8:
14430 case X86::ATOMUMAX16:
14431 case X86::ATOMUMAX32:
14432 case X86::ATOMUMAX64:
14434 case X86::ATOMUMIN8:
14435 case X86::ATOMUMIN16:
14436 case X86::ATOMUMIN32:
14437 case X86::ATOMUMIN64:
14438 return EmitAtomicLoadArith(MI, BB);
14440 // This group does 64-bit operations on a 32-bit host.
14441 case X86::ATOMAND6432:
14442 case X86::ATOMOR6432:
14443 case X86::ATOMXOR6432:
14444 case X86::ATOMNAND6432:
14445 case X86::ATOMADD6432:
14446 case X86::ATOMSUB6432:
14447 case X86::ATOMMAX6432:
14448 case X86::ATOMMIN6432:
14449 case X86::ATOMUMAX6432:
14450 case X86::ATOMUMIN6432:
14451 case X86::ATOMSWAP6432:
14452 return EmitAtomicLoadArith6432(MI, BB);
14454 case X86::VASTART_SAVE_XMM_REGS:
14455 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14457 case X86::VAARG_64:
14458 return EmitVAARG64WithCustomInserter(MI, BB);
14460 case X86::EH_SjLj_SetJmp32:
14461 case X86::EH_SjLj_SetJmp64:
14462 return emitEHSjLjSetJmp(MI, BB);
14464 case X86::EH_SjLj_LongJmp32:
14465 case X86::EH_SjLj_LongJmp64:
14466 return emitEHSjLjLongJmp(MI, BB);
14470 //===----------------------------------------------------------------------===//
14471 // X86 Optimization Hooks
14472 //===----------------------------------------------------------------------===//
14474 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14477 const SelectionDAG &DAG,
14478 unsigned Depth) const {
14479 unsigned BitWidth = KnownZero.getBitWidth();
14480 unsigned Opc = Op.getOpcode();
14481 assert((Opc >= ISD::BUILTIN_OP_END ||
14482 Opc == ISD::INTRINSIC_WO_CHAIN ||
14483 Opc == ISD::INTRINSIC_W_CHAIN ||
14484 Opc == ISD::INTRINSIC_VOID) &&
14485 "Should use MaskedValueIsZero if you don't know whether Op"
14486 " is a target node!");
14488 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
14502 // These nodes' second result is a boolean.
14503 if (Op.getResNo() == 0)
14506 case X86ISD::SETCC:
14507 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14509 case ISD::INTRINSIC_WO_CHAIN: {
14510 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14511 unsigned NumLoBits = 0;
14514 case Intrinsic::x86_sse_movmsk_ps:
14515 case Intrinsic::x86_avx_movmsk_ps_256:
14516 case Intrinsic::x86_sse2_movmsk_pd:
14517 case Intrinsic::x86_avx_movmsk_pd_256:
14518 case Intrinsic::x86_mmx_pmovmskb:
14519 case Intrinsic::x86_sse2_pmovmskb_128:
14520 case Intrinsic::x86_avx2_pmovmskb: {
14521 // High bits of movmskp{s|d}, pmovmskb are known zero.
14523 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14524 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
14525 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
14526 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
14527 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
14528 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
14529 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
14530 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
14532 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14541 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14542 unsigned Depth) const {
14543 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14544 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14545 return Op.getValueType().getScalarType().getSizeInBits();
14551 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14552 /// node is a GlobalAddress + offset.
14553 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14554 const GlobalValue* &GA,
14555 int64_t &Offset) const {
14556 if (N->getOpcode() == X86ISD::Wrapper) {
14557 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14558 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14559 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14563 return TargetLowering::isGAPlusOffset(N, GA, Offset);
14566 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14567 /// same as extracting the high 128-bit part of 256-bit vector and then
14568 /// inserting the result into the low part of a new 256-bit vector
14569 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14570 EVT VT = SVOp->getValueType(0);
14571 unsigned NumElems = VT.getVectorNumElements();
14573 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14574 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14575 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14576 SVOp->getMaskElt(j) >= 0)
14582 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14583 /// same as extracting the low 128-bit part of 256-bit vector and then
14584 /// inserting the result into the high part of a new 256-bit vector
14585 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14586 EVT VT = SVOp->getValueType(0);
14587 unsigned NumElems = VT.getVectorNumElements();
14589 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14590 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14591 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14592 SVOp->getMaskElt(j) >= 0)
14598 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14599 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14600 TargetLowering::DAGCombinerInfo &DCI,
14601 const X86Subtarget* Subtarget) {
14602 DebugLoc dl = N->getDebugLoc();
14603 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14604 SDValue V1 = SVOp->getOperand(0);
14605 SDValue V2 = SVOp->getOperand(1);
14606 EVT VT = SVOp->getValueType(0);
14607 unsigned NumElems = VT.getVectorNumElements();
14609 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14610 V2.getOpcode() == ISD::CONCAT_VECTORS) {
14614 // V UNDEF BUILD_VECTOR UNDEF
14616 // CONCAT_VECTOR CONCAT_VECTOR
14619 // RESULT: V + zero extended
14621 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14622 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14623 V1.getOperand(1).getOpcode() != ISD::UNDEF)
14626 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14629 // To match the shuffle mask, the first half of the mask should
14630 // be exactly the first vector, and all the rest a splat with the
14631 // first element of the second one.
14632 for (unsigned i = 0; i != NumElems/2; ++i)
14633 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14634 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14637 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14638 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14639 if (Ld->hasNUsesOfValue(1, 0)) {
14640 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14641 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14643 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14645 Ld->getPointerInfo(),
14646 Ld->getAlignment(),
14647 false/*isVolatile*/, true/*ReadMem*/,
14648 false/*WriteMem*/);
14650 // Make sure the newly-created LOAD is in the same position as Ld in
14651 // terms of dependency. We create a TokenFactor for Ld and ResNode,
14652 // and update uses of Ld's output chain to use the TokenFactor.
14653 if (Ld->hasAnyUseOfValue(1)) {
14654 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14655 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14656 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14657 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14658 SDValue(ResNode.getNode(), 1));
14661 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14665 // Emit a zeroed vector and insert the desired subvector on its
14667 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14668 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14669 return DCI.CombineTo(N, InsV);
14672 //===--------------------------------------------------------------------===//
14673 // Combine some shuffles into subvector extracts and inserts:
14676 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14677 if (isShuffleHigh128VectorInsertLow(SVOp)) {
14678 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14679 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14680 return DCI.CombineTo(N, InsV);
14683 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14684 if (isShuffleLow128VectorInsertHigh(SVOp)) {
14685 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14686 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14687 return DCI.CombineTo(N, InsV);
14693 /// PerformShuffleCombine - Performs several different shuffle combines.
14694 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14695 TargetLowering::DAGCombinerInfo &DCI,
14696 const X86Subtarget *Subtarget) {
14697 DebugLoc dl = N->getDebugLoc();
14698 EVT VT = N->getValueType(0);
14700 // Don't create instructions with illegal types after legalize types has run.
14701 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14702 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14705 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14706 if (Subtarget->hasFp256() && VT.is256BitVector() &&
14707 N->getOpcode() == ISD::VECTOR_SHUFFLE)
14708 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14710 // Only handle 128 wide vector from here on.
14711 if (!VT.is128BitVector())
14714 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14715 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14716 // consecutive, non-overlapping, and in the right order.
14717 SmallVector<SDValue, 16> Elts;
14718 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14719 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14721 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14724 /// PerformTruncateCombine - Converts truncate operation to
14725 /// a sequence of vector shuffle operations.
14726 /// It is possible when we truncate 256-bit vector to 128-bit vector
14727 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14728 TargetLowering::DAGCombinerInfo &DCI,
14729 const X86Subtarget *Subtarget) {
14733 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14734 /// specific shuffle of a load can be folded into a single element load.
14735 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14736 /// shuffles have been customed lowered so we need to handle those here.
14737 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14738 TargetLowering::DAGCombinerInfo &DCI) {
14739 if (DCI.isBeforeLegalizeOps())
14742 SDValue InVec = N->getOperand(0);
14743 SDValue EltNo = N->getOperand(1);
14745 if (!isa<ConstantSDNode>(EltNo))
14748 EVT VT = InVec.getValueType();
14750 bool HasShuffleIntoBitcast = false;
14751 if (InVec.getOpcode() == ISD::BITCAST) {
14752 // Don't duplicate a load with other uses.
14753 if (!InVec.hasOneUse())
14755 EVT BCVT = InVec.getOperand(0).getValueType();
14756 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14758 InVec = InVec.getOperand(0);
14759 HasShuffleIntoBitcast = true;
14762 if (!isTargetShuffle(InVec.getOpcode()))
14765 // Don't duplicate a load with other uses.
14766 if (!InVec.hasOneUse())
14769 SmallVector<int, 16> ShuffleMask;
14771 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14775 // Select the input vector, guarding against out of range extract vector.
14776 unsigned NumElems = VT.getVectorNumElements();
14777 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14778 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14779 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14780 : InVec.getOperand(1);
14782 // If inputs to shuffle are the same for both ops, then allow 2 uses
14783 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14785 if (LdNode.getOpcode() == ISD::BITCAST) {
14786 // Don't duplicate a load with other uses.
14787 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14790 AllowedUses = 1; // only allow 1 load use if we have a bitcast
14791 LdNode = LdNode.getOperand(0);
14794 if (!ISD::isNormalLoad(LdNode.getNode()))
14797 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14799 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14802 if (HasShuffleIntoBitcast) {
14803 // If there's a bitcast before the shuffle, check if the load type and
14804 // alignment is valid.
14805 unsigned Align = LN0->getAlignment();
14806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14807 unsigned NewAlign = TLI.getDataLayout()->
14808 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14810 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14814 // All checks match so transform back to vector_shuffle so that DAG combiner
14815 // can finish the job
14816 DebugLoc dl = N->getDebugLoc();
14818 // Create shuffle node taking into account the case that its a unary shuffle
14819 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14820 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14821 InVec.getOperand(0), Shuffle,
14823 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14824 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14828 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
14829 /// generation and convert it from being a bunch of shuffles and extracts
14830 /// to a simple store and scalar loads to extract the elements.
14831 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
14832 TargetLowering::DAGCombinerInfo &DCI) {
14833 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
14834 if (NewOp.getNode())
14837 SDValue InputVector = N->getOperand(0);
14838 // Detect whether we are trying to convert from mmx to i32 and the bitcast
14839 // from mmx to v2i32 has a single usage.
14840 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
14841 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
14842 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
14843 return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
14844 N->getValueType(0),
14845 InputVector.getNode()->getOperand(0));
14847 // Only operate on vectors of 4 elements, where the alternative shuffling
14848 // gets to be more expensive.
14849 if (InputVector.getValueType() != MVT::v4i32)
14852 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
14853 // single use which is a sign-extend or zero-extend, and all elements are
14855 SmallVector<SDNode *, 4> Uses;
14856 unsigned ExtractedElements = 0;
14857 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
14858 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
14859 if (UI.getUse().getResNo() != InputVector.getResNo())
14862 SDNode *Extract = *UI;
14863 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
14866 if (Extract->getValueType(0) != MVT::i32)
14868 if (!Extract->hasOneUse())
14870 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
14871 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
14873 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
14876 // Record which element was extracted.
14877 ExtractedElements |=
14878 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
14880 Uses.push_back(Extract);
14883 // If not all the elements were used, this may not be worthwhile.
14884 if (ExtractedElements != 15)
14887 // Ok, we've now decided to do the transformation.
14888 DebugLoc dl = InputVector.getDebugLoc();
14890 // Store the value to a temporary stack slot.
14891 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
14892 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
14893 MachinePointerInfo(), false, false, 0);
14895 // Replace each use (extract) with a load of the appropriate element.
14896 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
14897 UE = Uses.end(); UI != UE; ++UI) {
14898 SDNode *Extract = *UI;
14900 // cOMpute the element's address.
14901 SDValue Idx = Extract->getOperand(1);
14903 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
14904 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
14905 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14906 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
14908 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
14909 StackPtr, OffsetVal);
14911 // Load the scalar.
14912 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
14913 ScalarAddr, MachinePointerInfo(),
14914 false, false, false, 0);
14916 // Replace the exact with the load.
14917 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
14920 // The replacement was made in place; don't return anything.
14924 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
14925 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
14926 SDValue RHS, SelectionDAG &DAG,
14927 const X86Subtarget *Subtarget) {
14928 if (!VT.isVector())
14931 switch (VT.getSimpleVT().SimpleTy) {
14936 if (!Subtarget->hasAVX2())
14941 if (!Subtarget->hasSSE2())
14945 // SSE2 has only a small subset of the operations.
14946 bool hasUnsigned = Subtarget->hasSSE41() ||
14947 (Subtarget->hasSSE2() && VT == MVT::v16i8);
14948 bool hasSigned = Subtarget->hasSSE41() ||
14949 (Subtarget->hasSSE2() && VT == MVT::v8i16);
14951 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
14953 // Check for x CC y ? x : y.
14954 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
14955 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
14960 return hasUnsigned ? X86ISD::UMIN : 0;
14963 return hasUnsigned ? X86ISD::UMAX : 0;
14966 return hasSigned ? X86ISD::SMIN : 0;
14969 return hasSigned ? X86ISD::SMAX : 0;
14971 // Check for x CC y ? y : x -- a min/max with reversed arms.
14972 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
14973 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
14978 return hasUnsigned ? X86ISD::UMAX : 0;
14981 return hasUnsigned ? X86ISD::UMIN : 0;
14984 return hasSigned ? X86ISD::SMAX : 0;
14987 return hasSigned ? X86ISD::SMIN : 0;
14994 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
14996 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
14997 TargetLowering::DAGCombinerInfo &DCI,
14998 const X86Subtarget *Subtarget) {
14999 DebugLoc DL = N->getDebugLoc();
15000 SDValue Cond = N->getOperand(0);
15001 // Get the LHS/RHS of the select.
15002 SDValue LHS = N->getOperand(1);
15003 SDValue RHS = N->getOperand(2);
15004 EVT VT = LHS.getValueType();
15006 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15007 // instructions match the semantics of the common C idiom x<y?x:y but not
15008 // x<=y?x:y, because of how they handle negative zero (which can be
15009 // ignored in unsafe-math mode).
15010 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15011 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15012 (Subtarget->hasSSE2() ||
15013 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15014 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15016 unsigned Opcode = 0;
15017 // Check for x CC y ? x : y.
15018 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15019 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15023 // Converting this to a min would handle NaNs incorrectly, and swapping
15024 // the operands would cause it to handle comparisons between positive
15025 // and negative zero incorrectly.
15026 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15027 if (!DAG.getTarget().Options.UnsafeFPMath &&
15028 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15030 std::swap(LHS, RHS);
15032 Opcode = X86ISD::FMIN;
15035 // Converting this to a min would handle comparisons between positive
15036 // and negative zero incorrectly.
15037 if (!DAG.getTarget().Options.UnsafeFPMath &&
15038 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15040 Opcode = X86ISD::FMIN;
15043 // Converting this to a min would handle both negative zeros and NaNs
15044 // incorrectly, but we can swap the operands to fix both.
15045 std::swap(LHS, RHS);
15049 Opcode = X86ISD::FMIN;
15053 // Converting this to a max would handle comparisons between positive
15054 // and negative zero incorrectly.
15055 if (!DAG.getTarget().Options.UnsafeFPMath &&
15056 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15058 Opcode = X86ISD::FMAX;
15061 // Converting this to a max would handle NaNs incorrectly, and swapping
15062 // the operands would cause it to handle comparisons between positive
15063 // and negative zero incorrectly.
15064 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15065 if (!DAG.getTarget().Options.UnsafeFPMath &&
15066 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15068 std::swap(LHS, RHS);
15070 Opcode = X86ISD::FMAX;
15073 // Converting this to a max would handle both negative zeros and NaNs
15074 // incorrectly, but we can swap the operands to fix both.
15075 std::swap(LHS, RHS);
15079 Opcode = X86ISD::FMAX;
15082 // Check for x CC y ? y : x -- a min/max with reversed arms.
15083 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15084 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15088 // Converting this to a min would handle comparisons between positive
15089 // and negative zero incorrectly, and swapping the operands would
15090 // cause it to handle NaNs incorrectly.
15091 if (!DAG.getTarget().Options.UnsafeFPMath &&
15092 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15093 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15095 std::swap(LHS, RHS);
15097 Opcode = X86ISD::FMIN;
15100 // Converting this to a min would handle NaNs incorrectly.
15101 if (!DAG.getTarget().Options.UnsafeFPMath &&
15102 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15104 Opcode = X86ISD::FMIN;
15107 // Converting this to a min would handle both negative zeros and NaNs
15108 // incorrectly, but we can swap the operands to fix both.
15109 std::swap(LHS, RHS);
15113 Opcode = X86ISD::FMIN;
15117 // Converting this to a max would handle NaNs incorrectly.
15118 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15120 Opcode = X86ISD::FMAX;
15123 // Converting this to a max would handle comparisons between positive
15124 // and negative zero incorrectly, and swapping the operands would
15125 // cause it to handle NaNs incorrectly.
15126 if (!DAG.getTarget().Options.UnsafeFPMath &&
15127 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15128 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15130 std::swap(LHS, RHS);
15132 Opcode = X86ISD::FMAX;
15135 // Converting this to a max would handle both negative zeros and NaNs
15136 // incorrectly, but we can swap the operands to fix both.
15137 std::swap(LHS, RHS);
15141 Opcode = X86ISD::FMAX;
15147 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15150 // If this is a select between two integer constants, try to do some
15152 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15153 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15154 // Don't do this for crazy integer types.
15155 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15156 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15157 // so that TrueC (the true value) is larger than FalseC.
15158 bool NeedsCondInvert = false;
15160 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15161 // Efficiently invertible.
15162 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
15163 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
15164 isa<ConstantSDNode>(Cond.getOperand(1))))) {
15165 NeedsCondInvert = true;
15166 std::swap(TrueC, FalseC);
15169 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
15170 if (FalseC->getAPIntValue() == 0 &&
15171 TrueC->getAPIntValue().isPowerOf2()) {
15172 if (NeedsCondInvert) // Invert the condition if needed.
15173 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15174 DAG.getConstant(1, Cond.getValueType()));
15176 // Zero extend the condition if needed.
15177 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15179 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15180 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15181 DAG.getConstant(ShAmt, MVT::i8));
15184 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15185 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15186 if (NeedsCondInvert) // Invert the condition if needed.
15187 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15188 DAG.getConstant(1, Cond.getValueType()));
15190 // Zero extend the condition if needed.
15191 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15192 FalseC->getValueType(0), Cond);
15193 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15194 SDValue(FalseC, 0));
15197 // Optimize cases that will turn into an LEA instruction. This requires
15198 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15199 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15200 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15201 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15203 bool isFastMultiplier = false;
15205 switch ((unsigned char)Diff) {
15207 case 1: // result = add base, cond
15208 case 2: // result = lea base( , cond*2)
15209 case 3: // result = lea base(cond, cond*2)
15210 case 4: // result = lea base( , cond*4)
15211 case 5: // result = lea base(cond, cond*4)
15212 case 8: // result = lea base( , cond*8)
15213 case 9: // result = lea base(cond, cond*8)
15214 isFastMultiplier = true;
15219 if (isFastMultiplier) {
15220 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15221 if (NeedsCondInvert) // Invert the condition if needed.
15222 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15223 DAG.getConstant(1, Cond.getValueType()));
15225 // Zero extend the condition if needed.
15226 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15228 // Scale the condition by the difference.
15230 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15231 DAG.getConstant(Diff, Cond.getValueType()));
15233 // Add the base if non-zero.
15234 if (FalseC->getAPIntValue() != 0)
15235 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15236 SDValue(FalseC, 0));
15243 // Canonicalize max and min:
15244 // (x > y) ? x : y -> (x >= y) ? x : y
15245 // (x < y) ? x : y -> (x <= y) ? x : y
15246 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15247 // the need for an extra compare
15248 // against zero. e.g.
15249 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15251 // testl %edi, %edi
15253 // cmovgl %edi, %eax
15257 // cmovsl %eax, %edi
15258 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15259 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15260 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15261 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15266 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15267 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15268 Cond.getOperand(0), Cond.getOperand(1), NewCC);
15269 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15274 // Match VSELECTs into subs with unsigned saturation.
15275 if (!DCI.isBeforeLegalize() &&
15276 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15277 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15278 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15279 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15280 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15282 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15283 // left side invert the predicate to simplify logic below.
15285 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15287 CC = ISD::getSetCCInverse(CC, true);
15288 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15292 if (Other.getNode() && Other->getNumOperands() == 2 &&
15293 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15294 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15295 SDValue CondRHS = Cond->getOperand(1);
15297 // Look for a general sub with unsigned saturation first.
15298 // x >= y ? x-y : 0 --> subus x, y
15299 // x > y ? x-y : 0 --> subus x, y
15300 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15301 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15302 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15304 // If the RHS is a constant we have to reverse the const canonicalization.
15305 // x > C-1 ? x+-C : 0 --> subus x, C
15306 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15307 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15308 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15309 if (CondRHS.getConstantOperandVal(0) == -A-1) {
15310 SmallVector<SDValue, 32> V(VT.getVectorNumElements(),
15311 DAG.getConstant(-A, VT.getScalarType()));
15312 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15313 DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
15314 V.data(), V.size()));
15318 // Another special case: If C was a sign bit, the sub has been
15319 // canonicalized into a xor.
15320 // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15321 // it's safe to decanonicalize the xor?
15322 // x s< 0 ? x^C : 0 --> subus x, C
15323 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15324 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15325 isSplatVector(OpRHS.getNode())) {
15326 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15328 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15333 // Try to match a min/max vector operation.
15334 if (!DCI.isBeforeLegalize() &&
15335 N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15336 if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15337 return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15339 // If we know that this node is legal then we know that it is going to be
15340 // matched by one of the SSE/AVX BLEND instructions. These instructions only
15341 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15342 // to simplify previous instructions.
15343 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15344 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15345 !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15346 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15348 // Don't optimize vector selects that map to mask-registers.
15352 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15353 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15355 APInt KnownZero, KnownOne;
15356 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15357 DCI.isBeforeLegalizeOps());
15358 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15359 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15360 DCI.CommitTargetLoweringOpt(TLO);
15366 // Check whether a boolean test is testing a boolean value generated by
15367 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15370 // Simplify the following patterns:
15371 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15372 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15373 // to (Op EFLAGS Cond)
15375 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15376 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15377 // to (Op EFLAGS !Cond)
15379 // where Op could be BRCOND or CMOV.
15381 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15382 // Quit if not CMP and SUB with its value result used.
15383 if (Cmp.getOpcode() != X86ISD::CMP &&
15384 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15387 // Quit if not used as a boolean value.
15388 if (CC != X86::COND_E && CC != X86::COND_NE)
15391 // Check CMP operands. One of them should be 0 or 1 and the other should be
15392 // an SetCC or extended from it.
15393 SDValue Op1 = Cmp.getOperand(0);
15394 SDValue Op2 = Cmp.getOperand(1);
15397 const ConstantSDNode* C = 0;
15398 bool needOppositeCond = (CC == X86::COND_E);
15400 if ((C = dyn_cast<ConstantSDNode>(Op1)))
15402 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15404 else // Quit if all operands are not constants.
15407 if (C->getZExtValue() == 1)
15408 needOppositeCond = !needOppositeCond;
15409 else if (C->getZExtValue() != 0)
15410 // Quit if the constant is neither 0 or 1.
15413 // Skip 'zext' node.
15414 if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15415 SetCC = SetCC.getOperand(0);
15417 switch (SetCC.getOpcode()) {
15418 case X86ISD::SETCC:
15419 // Set the condition code or opposite one if necessary.
15420 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15421 if (needOppositeCond)
15422 CC = X86::GetOppositeBranchCondition(CC);
15423 return SetCC.getOperand(1);
15424 case X86ISD::CMOV: {
15425 // Check whether false/true value has canonical one, i.e. 0 or 1.
15426 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15427 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15428 // Quit if true value is not a constant.
15431 // Quit if false value is not a constant.
15433 // A special case for rdrand, where 0 is set if false cond is found.
15434 SDValue Op = SetCC.getOperand(0);
15435 if (Op.getOpcode() != X86ISD::RDRAND)
15438 // Quit if false value is not the constant 0 or 1.
15439 bool FValIsFalse = true;
15440 if (FVal && FVal->getZExtValue() != 0) {
15441 if (FVal->getZExtValue() != 1)
15443 // If FVal is 1, opposite cond is needed.
15444 needOppositeCond = !needOppositeCond;
15445 FValIsFalse = false;
15447 // Quit if TVal is not the constant opposite of FVal.
15448 if (FValIsFalse && TVal->getZExtValue() != 1)
15450 if (!FValIsFalse && TVal->getZExtValue() != 0)
15452 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15453 if (needOppositeCond)
15454 CC = X86::GetOppositeBranchCondition(CC);
15455 return SetCC.getOperand(3);
15462 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15463 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15464 TargetLowering::DAGCombinerInfo &DCI,
15465 const X86Subtarget *Subtarget) {
15466 DebugLoc DL = N->getDebugLoc();
15468 // If the flag operand isn't dead, don't touch this CMOV.
15469 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15472 SDValue FalseOp = N->getOperand(0);
15473 SDValue TrueOp = N->getOperand(1);
15474 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15475 SDValue Cond = N->getOperand(3);
15477 if (CC == X86::COND_E || CC == X86::COND_NE) {
15478 switch (Cond.getOpcode()) {
15482 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15483 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15484 return (CC == X86::COND_E) ? FalseOp : TrueOp;
15490 Flags = checkBoolTestSetCCCombine(Cond, CC);
15491 if (Flags.getNode() &&
15492 // Extra check as FCMOV only supports a subset of X86 cond.
15493 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15494 SDValue Ops[] = { FalseOp, TrueOp,
15495 DAG.getConstant(CC, MVT::i8), Flags };
15496 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15497 Ops, array_lengthof(Ops));
15500 // If this is a select between two integer constants, try to do some
15501 // optimizations. Note that the operands are ordered the opposite of SELECT
15503 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15504 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15505 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15506 // larger than FalseC (the false value).
15507 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15508 CC = X86::GetOppositeBranchCondition(CC);
15509 std::swap(TrueC, FalseC);
15510 std::swap(TrueOp, FalseOp);
15513 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
15514 // This is efficient for any integer data type (including i8/i16) and
15516 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15517 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15518 DAG.getConstant(CC, MVT::i8), Cond);
15520 // Zero extend the condition if needed.
15521 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15523 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15524 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15525 DAG.getConstant(ShAmt, MVT::i8));
15526 if (N->getNumValues() == 2) // Dead flag value?
15527 return DCI.CombineTo(N, Cond, SDValue());
15531 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
15532 // for any integer data type, including i8/i16.
15533 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15534 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15535 DAG.getConstant(CC, MVT::i8), Cond);
15537 // Zero extend the condition if needed.
15538 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15539 FalseC->getValueType(0), Cond);
15540 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15541 SDValue(FalseC, 0));
15543 if (N->getNumValues() == 2) // Dead flag value?
15544 return DCI.CombineTo(N, Cond, SDValue());
15548 // Optimize cases that will turn into an LEA instruction. This requires
15549 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15550 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15551 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15552 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15554 bool isFastMultiplier = false;
15556 switch ((unsigned char)Diff) {
15558 case 1: // result = add base, cond
15559 case 2: // result = lea base( , cond*2)
15560 case 3: // result = lea base(cond, cond*2)
15561 case 4: // result = lea base( , cond*4)
15562 case 5: // result = lea base(cond, cond*4)
15563 case 8: // result = lea base( , cond*8)
15564 case 9: // result = lea base(cond, cond*8)
15565 isFastMultiplier = true;
15570 if (isFastMultiplier) {
15571 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15572 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15573 DAG.getConstant(CC, MVT::i8), Cond);
15574 // Zero extend the condition if needed.
15575 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15577 // Scale the condition by the difference.
15579 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15580 DAG.getConstant(Diff, Cond.getValueType()));
15582 // Add the base if non-zero.
15583 if (FalseC->getAPIntValue() != 0)
15584 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15585 SDValue(FalseC, 0));
15586 if (N->getNumValues() == 2) // Dead flag value?
15587 return DCI.CombineTo(N, Cond, SDValue());
15594 // Handle these cases:
15595 // (select (x != c), e, c) -> select (x != c), e, x),
15596 // (select (x == c), c, e) -> select (x == c), x, e)
15597 // where the c is an integer constant, and the "select" is the combination
15598 // of CMOV and CMP.
15600 // The rationale for this change is that the conditional-move from a constant
15601 // needs two instructions, however, conditional-move from a register needs
15602 // only one instruction.
15604 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15605 // some instruction-combining opportunities. This opt needs to be
15606 // postponed as late as possible.
15608 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15609 // the DCI.xxxx conditions are provided to postpone the optimization as
15610 // late as possible.
15612 ConstantSDNode *CmpAgainst = 0;
15613 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15614 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15615 dyn_cast<ConstantSDNode>(Cond.getOperand(0)) == 0) {
15617 if (CC == X86::COND_NE &&
15618 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15619 CC = X86::GetOppositeBranchCondition(CC);
15620 std::swap(TrueOp, FalseOp);
15623 if (CC == X86::COND_E &&
15624 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15625 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15626 DAG.getConstant(CC, MVT::i8), Cond };
15627 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15628 array_lengthof(Ops));
15636 /// PerformMulCombine - Optimize a single multiply with constant into two
15637 /// in order to implement it with two cheaper instructions, e.g.
15638 /// LEA + SHL, LEA + LEA.
15639 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15640 TargetLowering::DAGCombinerInfo &DCI) {
15641 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15644 EVT VT = N->getValueType(0);
15645 if (VT != MVT::i64)
15648 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15651 uint64_t MulAmt = C->getZExtValue();
15652 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15655 uint64_t MulAmt1 = 0;
15656 uint64_t MulAmt2 = 0;
15657 if ((MulAmt % 9) == 0) {
15659 MulAmt2 = MulAmt / 9;
15660 } else if ((MulAmt % 5) == 0) {
15662 MulAmt2 = MulAmt / 5;
15663 } else if ((MulAmt % 3) == 0) {
15665 MulAmt2 = MulAmt / 3;
15668 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15669 DebugLoc DL = N->getDebugLoc();
15671 if (isPowerOf2_64(MulAmt2) &&
15672 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15673 // If second multiplifer is pow2, issue it first. We want the multiply by
15674 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15676 std::swap(MulAmt1, MulAmt2);
15679 if (isPowerOf2_64(MulAmt1))
15680 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15681 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15683 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15684 DAG.getConstant(MulAmt1, VT));
15686 if (isPowerOf2_64(MulAmt2))
15687 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15688 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15690 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15691 DAG.getConstant(MulAmt2, VT));
15693 // Do not add new nodes to DAG combiner worklist.
15694 DCI.CombineTo(N, NewMul, false);
15699 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15700 SDValue N0 = N->getOperand(0);
15701 SDValue N1 = N->getOperand(1);
15702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15703 EVT VT = N0.getValueType();
15705 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15706 // since the result of setcc_c is all zero's or all ones.
15707 if (VT.isInteger() && !VT.isVector() &&
15708 N1C && N0.getOpcode() == ISD::AND &&
15709 N0.getOperand(1).getOpcode() == ISD::Constant) {
15710 SDValue N00 = N0.getOperand(0);
15711 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15712 ((N00.getOpcode() == ISD::ANY_EXTEND ||
15713 N00.getOpcode() == ISD::ZERO_EXTEND) &&
15714 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15715 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15716 APInt ShAmt = N1C->getAPIntValue();
15717 Mask = Mask.shl(ShAmt);
15719 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15720 N00, DAG.getConstant(Mask, VT));
15724 // Hardware support for vector shifts is sparse which makes us scalarize the
15725 // vector operations in many cases. Also, on sandybridge ADD is faster than
15727 // (shl V, 1) -> add V,V
15728 if (isSplatVector(N1.getNode())) {
15729 assert(N0.getValueType().isVector() && "Invalid vector shift type");
15730 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15731 // We shift all of the values by one. In many cases we do not have
15732 // hardware support for this operation. This is better expressed as an ADD
15734 if (N1C && (1 == N1C->getZExtValue())) {
15735 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15742 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15744 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15745 TargetLowering::DAGCombinerInfo &DCI,
15746 const X86Subtarget *Subtarget) {
15747 EVT VT = N->getValueType(0);
15748 if (N->getOpcode() == ISD::SHL) {
15749 SDValue V = PerformSHLCombine(N, DAG);
15750 if (V.getNode()) return V;
15753 // On X86 with SSE2 support, we can transform this to a vector shift if
15754 // all elements are shifted by the same amount. We can't do this in legalize
15755 // because the a constant vector is typically transformed to a constant pool
15756 // so we have no knowledge of the shift amount.
15757 if (!Subtarget->hasSSE2())
15760 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15761 (!Subtarget->hasInt256() ||
15762 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15765 SDValue ShAmtOp = N->getOperand(1);
15766 EVT EltVT = VT.getVectorElementType();
15767 DebugLoc DL = N->getDebugLoc();
15768 SDValue BaseShAmt = SDValue();
15769 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15770 unsigned NumElts = VT.getVectorNumElements();
15772 for (; i != NumElts; ++i) {
15773 SDValue Arg = ShAmtOp.getOperand(i);
15774 if (Arg.getOpcode() == ISD::UNDEF) continue;
15778 // Handle the case where the build_vector is all undef
15779 // FIXME: Should DAG allow this?
15783 for (; i != NumElts; ++i) {
15784 SDValue Arg = ShAmtOp.getOperand(i);
15785 if (Arg.getOpcode() == ISD::UNDEF) continue;
15786 if (Arg != BaseShAmt) {
15790 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15791 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15792 SDValue InVec = ShAmtOp.getOperand(0);
15793 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15794 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15796 for (; i != NumElts; ++i) {
15797 SDValue Arg = InVec.getOperand(i);
15798 if (Arg.getOpcode() == ISD::UNDEF) continue;
15802 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15804 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15805 if (C->getZExtValue() == SplatIdx)
15806 BaseShAmt = InVec.getOperand(1);
15809 if (BaseShAmt.getNode() == 0) {
15810 // Don't create instructions with illegal types after legalize
15812 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15813 !DCI.isBeforeLegalize())
15816 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15817 DAG.getIntPtrConstant(0));
15822 // The shift amount is an i32.
15823 if (EltVT.bitsGT(MVT::i32))
15824 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15825 else if (EltVT.bitsLT(MVT::i32))
15826 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15828 // The shift amount is identical so we can do a vector shift.
15829 SDValue ValOp = N->getOperand(0);
15830 switch (N->getOpcode()) {
15832 llvm_unreachable("Unknown shift opcode!");
15834 switch (VT.getSimpleVT().SimpleTy) {
15835 default: return SDValue();
15842 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
15845 switch (VT.getSimpleVT().SimpleTy) {
15846 default: return SDValue();
15851 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
15854 switch (VT.getSimpleVT().SimpleTy) {
15855 default: return SDValue();
15862 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
15867 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
15868 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
15869 // and friends. Likewise for OR -> CMPNEQSS.
15870 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
15871 TargetLowering::DAGCombinerInfo &DCI,
15872 const X86Subtarget *Subtarget) {
15875 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
15876 // we're requiring SSE2 for both.
15877 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
15878 SDValue N0 = N->getOperand(0);
15879 SDValue N1 = N->getOperand(1);
15880 SDValue CMP0 = N0->getOperand(1);
15881 SDValue CMP1 = N1->getOperand(1);
15882 DebugLoc DL = N->getDebugLoc();
15884 // The SETCCs should both refer to the same CMP.
15885 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
15888 SDValue CMP00 = CMP0->getOperand(0);
15889 SDValue CMP01 = CMP0->getOperand(1);
15890 EVT VT = CMP00.getValueType();
15892 if (VT == MVT::f32 || VT == MVT::f64) {
15893 bool ExpectingFlags = false;
15894 // Check for any users that want flags:
15895 for (SDNode::use_iterator UI = N->use_begin(),
15897 !ExpectingFlags && UI != UE; ++UI)
15898 switch (UI->getOpcode()) {
15903 ExpectingFlags = true;
15905 case ISD::CopyToReg:
15906 case ISD::SIGN_EXTEND:
15907 case ISD::ZERO_EXTEND:
15908 case ISD::ANY_EXTEND:
15912 if (!ExpectingFlags) {
15913 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
15914 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
15916 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
15917 X86::CondCode tmp = cc0;
15922 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
15923 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
15924 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
15925 X86ISD::NodeType NTOperator = is64BitFP ?
15926 X86ISD::FSETCCsd : X86ISD::FSETCCss;
15927 // FIXME: need symbolic constants for these magic numbers.
15928 // See X86ATTInstPrinter.cpp:printSSECC().
15929 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
15930 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
15931 DAG.getConstant(x86cc, MVT::i8));
15932 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
15934 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
15935 DAG.getConstant(1, MVT::i32));
15936 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
15937 return OneBitOfTruth;
15945 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
15946 /// so it can be folded inside ANDNP.
15947 static bool CanFoldXORWithAllOnes(const SDNode *N) {
15948 EVT VT = N->getValueType(0);
15950 // Match direct AllOnes for 128 and 256-bit vectors
15951 if (ISD::isBuildVectorAllOnes(N))
15954 // Look through a bit convert.
15955 if (N->getOpcode() == ISD::BITCAST)
15956 N = N->getOperand(0).getNode();
15958 // Sometimes the operand may come from a insert_subvector building a 256-bit
15960 if (VT.is256BitVector() &&
15961 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
15962 SDValue V1 = N->getOperand(0);
15963 SDValue V2 = N->getOperand(1);
15965 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
15966 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
15967 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
15968 ISD::isBuildVectorAllOnes(V2.getNode()))
15975 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
15976 // register. In most cases we actually compare or select YMM-sized registers
15977 // and mixing the two types creates horrible code. This method optimizes
15978 // some of the transition sequences.
15979 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
15980 TargetLowering::DAGCombinerInfo &DCI,
15981 const X86Subtarget *Subtarget) {
15982 EVT VT = N->getValueType(0);
15983 if (!VT.is256BitVector())
15986 assert((N->getOpcode() == ISD::ANY_EXTEND ||
15987 N->getOpcode() == ISD::ZERO_EXTEND ||
15988 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
15990 SDValue Narrow = N->getOperand(0);
15991 EVT NarrowVT = Narrow->getValueType(0);
15992 if (!NarrowVT.is128BitVector())
15995 if (Narrow->getOpcode() != ISD::XOR &&
15996 Narrow->getOpcode() != ISD::AND &&
15997 Narrow->getOpcode() != ISD::OR)
16000 SDValue N0 = Narrow->getOperand(0);
16001 SDValue N1 = Narrow->getOperand(1);
16002 DebugLoc DL = Narrow->getDebugLoc();
16004 // The Left side has to be a trunc.
16005 if (N0.getOpcode() != ISD::TRUNCATE)
16008 // The type of the truncated inputs.
16009 EVT WideVT = N0->getOperand(0)->getValueType(0);
16013 // The right side has to be a 'trunc' or a constant vector.
16014 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16015 bool RHSConst = (isSplatVector(N1.getNode()) &&
16016 isa<ConstantSDNode>(N1->getOperand(0)));
16017 if (!RHSTrunc && !RHSConst)
16020 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16022 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16025 // Set N0 and N1 to hold the inputs to the new wide operation.
16026 N0 = N0->getOperand(0);
16028 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16029 N1->getOperand(0));
16030 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16031 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16032 } else if (RHSTrunc) {
16033 N1 = N1->getOperand(0);
16036 // Generate the wide operation.
16037 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16038 unsigned Opcode = N->getOpcode();
16040 case ISD::ANY_EXTEND:
16042 case ISD::ZERO_EXTEND: {
16043 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16044 APInt Mask = APInt::getAllOnesValue(InBits);
16045 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16046 return DAG.getNode(ISD::AND, DL, VT,
16047 Op, DAG.getConstant(Mask, VT));
16049 case ISD::SIGN_EXTEND:
16050 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16051 Op, DAG.getValueType(NarrowVT));
16053 llvm_unreachable("Unexpected opcode");
16057 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16058 TargetLowering::DAGCombinerInfo &DCI,
16059 const X86Subtarget *Subtarget) {
16060 EVT VT = N->getValueType(0);
16061 if (DCI.isBeforeLegalizeOps())
16064 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16068 // Create BLSI, and BLSR instructions
16069 // BLSI is X & (-X)
16070 // BLSR is X & (X-1)
16071 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16072 SDValue N0 = N->getOperand(0);
16073 SDValue N1 = N->getOperand(1);
16074 DebugLoc DL = N->getDebugLoc();
16076 // Check LHS for neg
16077 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16078 isZero(N0.getOperand(0)))
16079 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16081 // Check RHS for neg
16082 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16083 isZero(N1.getOperand(0)))
16084 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16086 // Check LHS for X-1
16087 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16088 isAllOnes(N0.getOperand(1)))
16089 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16091 // Check RHS for X-1
16092 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16093 isAllOnes(N1.getOperand(1)))
16094 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16099 // Want to form ANDNP nodes:
16100 // 1) In the hopes of then easily combining them with OR and AND nodes
16101 // to form PBLEND/PSIGN.
16102 // 2) To match ANDN packed intrinsics
16103 if (VT != MVT::v2i64 && VT != MVT::v4i64)
16106 SDValue N0 = N->getOperand(0);
16107 SDValue N1 = N->getOperand(1);
16108 DebugLoc DL = N->getDebugLoc();
16110 // Check LHS for vnot
16111 if (N0.getOpcode() == ISD::XOR &&
16112 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16113 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16114 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16116 // Check RHS for vnot
16117 if (N1.getOpcode() == ISD::XOR &&
16118 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16119 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16120 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16125 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16126 TargetLowering::DAGCombinerInfo &DCI,
16127 const X86Subtarget *Subtarget) {
16128 EVT VT = N->getValueType(0);
16129 if (DCI.isBeforeLegalizeOps())
16132 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16136 SDValue N0 = N->getOperand(0);
16137 SDValue N1 = N->getOperand(1);
16139 // look for psign/blend
16140 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16141 if (!Subtarget->hasSSSE3() ||
16142 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16145 // Canonicalize pandn to RHS
16146 if (N0.getOpcode() == X86ISD::ANDNP)
16148 // or (and (m, y), (pandn m, x))
16149 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16150 SDValue Mask = N1.getOperand(0);
16151 SDValue X = N1.getOperand(1);
16153 if (N0.getOperand(0) == Mask)
16154 Y = N0.getOperand(1);
16155 if (N0.getOperand(1) == Mask)
16156 Y = N0.getOperand(0);
16158 // Check to see if the mask appeared in both the AND and ANDNP and
16162 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16163 // Look through mask bitcast.
16164 if (Mask.getOpcode() == ISD::BITCAST)
16165 Mask = Mask.getOperand(0);
16166 if (X.getOpcode() == ISD::BITCAST)
16167 X = X.getOperand(0);
16168 if (Y.getOpcode() == ISD::BITCAST)
16169 Y = Y.getOperand(0);
16171 EVT MaskVT = Mask.getValueType();
16173 // Validate that the Mask operand is a vector sra node.
16174 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16175 // there is no psrai.b
16176 if (Mask.getOpcode() != X86ISD::VSRAI)
16179 // Check that the SRA is all signbits.
16180 SDValue SraC = Mask.getOperand(1);
16181 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
16182 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16183 if ((SraAmt + 1) != EltBits)
16186 DebugLoc DL = N->getDebugLoc();
16188 // We are going to replace the AND, OR, NAND with either BLEND
16189 // or PSIGN, which only look at the MSB. The VSRAI instruction
16190 // does not affect the highest bit, so we can get rid of it.
16191 Mask = Mask.getOperand(0);
16193 // Now we know we at least have a plendvb with the mask val. See if
16194 // we can form a psignb/w/d.
16195 // psign = x.type == y.type == mask.type && y = sub(0, x);
16196 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16197 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16198 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16199 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16200 "Unsupported VT for PSIGN");
16201 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask);
16202 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16204 // PBLENDVB only available on SSE 4.1
16205 if (!Subtarget->hasSSE41())
16208 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16210 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16211 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16212 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16213 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16214 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16218 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16221 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16222 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16224 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16226 if (!N0.hasOneUse() || !N1.hasOneUse())
16229 SDValue ShAmt0 = N0.getOperand(1);
16230 if (ShAmt0.getValueType() != MVT::i8)
16232 SDValue ShAmt1 = N1.getOperand(1);
16233 if (ShAmt1.getValueType() != MVT::i8)
16235 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16236 ShAmt0 = ShAmt0.getOperand(0);
16237 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16238 ShAmt1 = ShAmt1.getOperand(0);
16240 DebugLoc DL = N->getDebugLoc();
16241 unsigned Opc = X86ISD::SHLD;
16242 SDValue Op0 = N0.getOperand(0);
16243 SDValue Op1 = N1.getOperand(0);
16244 if (ShAmt0.getOpcode() == ISD::SUB) {
16245 Opc = X86ISD::SHRD;
16246 std::swap(Op0, Op1);
16247 std::swap(ShAmt0, ShAmt1);
16250 unsigned Bits = VT.getSizeInBits();
16251 if (ShAmt1.getOpcode() == ISD::SUB) {
16252 SDValue Sum = ShAmt1.getOperand(0);
16253 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16254 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16255 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16256 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16257 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16258 return DAG.getNode(Opc, DL, VT,
16260 DAG.getNode(ISD::TRUNCATE, DL,
16263 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16264 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16266 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16267 return DAG.getNode(Opc, DL, VT,
16268 N0.getOperand(0), N1.getOperand(0),
16269 DAG.getNode(ISD::TRUNCATE, DL,
16276 // Generate NEG and CMOV for integer abs.
16277 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16278 EVT VT = N->getValueType(0);
16280 // Since X86 does not have CMOV for 8-bit integer, we don't convert
16281 // 8-bit integer abs to NEG and CMOV.
16282 if (VT.isInteger() && VT.getSizeInBits() == 8)
16285 SDValue N0 = N->getOperand(0);
16286 SDValue N1 = N->getOperand(1);
16287 DebugLoc DL = N->getDebugLoc();
16289 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16290 // and change it to SUB and CMOV.
16291 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16292 N0.getOpcode() == ISD::ADD &&
16293 N0.getOperand(1) == N1 &&
16294 N1.getOpcode() == ISD::SRA &&
16295 N1.getOperand(0) == N0.getOperand(0))
16296 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16297 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16298 // Generate SUB & CMOV.
16299 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16300 DAG.getConstant(0, VT), N0.getOperand(0));
16302 SDValue Ops[] = { N0.getOperand(0), Neg,
16303 DAG.getConstant(X86::COND_GE, MVT::i8),
16304 SDValue(Neg.getNode(), 1) };
16305 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16306 Ops, array_lengthof(Ops));
16311 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16312 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16313 TargetLowering::DAGCombinerInfo &DCI,
16314 const X86Subtarget *Subtarget) {
16315 EVT VT = N->getValueType(0);
16316 if (DCI.isBeforeLegalizeOps())
16319 if (Subtarget->hasCMov()) {
16320 SDValue RV = performIntegerAbsCombine(N, DAG);
16325 // Try forming BMI if it is available.
16326 if (!Subtarget->hasBMI())
16329 if (VT != MVT::i32 && VT != MVT::i64)
16332 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16334 // Create BLSMSK instructions by finding X ^ (X-1)
16335 SDValue N0 = N->getOperand(0);
16336 SDValue N1 = N->getOperand(1);
16337 DebugLoc DL = N->getDebugLoc();
16339 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16340 isAllOnes(N0.getOperand(1)))
16341 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16343 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16344 isAllOnes(N1.getOperand(1)))
16345 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16350 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16351 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16352 TargetLowering::DAGCombinerInfo &DCI,
16353 const X86Subtarget *Subtarget) {
16354 LoadSDNode *Ld = cast<LoadSDNode>(N);
16355 EVT RegVT = Ld->getValueType(0);
16356 EVT MemVT = Ld->getMemoryVT();
16357 DebugLoc dl = Ld->getDebugLoc();
16358 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16359 unsigned RegSz = RegVT.getSizeInBits();
16361 ISD::LoadExtType Ext = Ld->getExtensionType();
16362 unsigned Alignment = Ld->getAlignment();
16363 bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16365 // On Sandybridge unaligned 256bit loads are inefficient.
16366 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16367 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16368 unsigned NumElems = RegVT.getVectorNumElements();
16372 SDValue Ptr = Ld->getBasePtr();
16373 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16375 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16377 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16378 Ld->getPointerInfo(), Ld->isVolatile(),
16379 Ld->isNonTemporal(), Ld->isInvariant(),
16381 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16382 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16383 Ld->getPointerInfo(), Ld->isVolatile(),
16384 Ld->isNonTemporal(), Ld->isInvariant(),
16385 std::max(Alignment/2U, 1U));
16386 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16388 Load2.getValue(1));
16390 SDValue NewVec = DAG.getUNDEF(RegVT);
16391 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16392 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16393 return DCI.CombineTo(N, NewVec, TF, true);
16396 // If this is a vector EXT Load then attempt to optimize it using a
16397 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16398 // expansion is still better than scalar code.
16399 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16400 // emit a shuffle and a arithmetic shift.
16401 // TODO: It is possible to support ZExt by zeroing the undef values
16402 // during the shuffle phase or after the shuffle.
16403 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16404 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16405 assert(MemVT != RegVT && "Cannot extend to the same type");
16406 assert(MemVT.isVector() && "Must load a vector from memory");
16408 unsigned NumElems = RegVT.getVectorNumElements();
16409 unsigned MemSz = MemVT.getSizeInBits();
16410 assert(RegSz > MemSz && "Register size must be greater than the mem size");
16412 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16415 // All sizes must be a power of two.
16416 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16419 // Attempt to load the original value using scalar loads.
16420 // Find the largest scalar type that divides the total loaded size.
16421 MVT SclrLoadTy = MVT::i8;
16422 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16423 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16424 MVT Tp = (MVT::SimpleValueType)tp;
16425 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16430 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16431 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16433 SclrLoadTy = MVT::f64;
16435 // Calculate the number of scalar loads that we need to perform
16436 // in order to load our vector from memory.
16437 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16438 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16441 unsigned loadRegZize = RegSz;
16442 if (Ext == ISD::SEXTLOAD && RegSz == 256)
16445 // Represent our vector as a sequence of elements which are the
16446 // largest scalar that we can load.
16447 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16448 loadRegZize/SclrLoadTy.getSizeInBits());
16450 // Represent the data using the same element type that is stored in
16451 // memory. In practice, we ''widen'' MemVT.
16453 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16454 loadRegZize/MemVT.getScalarType().getSizeInBits());
16456 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16457 "Invalid vector type");
16459 // We can't shuffle using an illegal type.
16460 if (!TLI.isTypeLegal(WideVecVT))
16463 SmallVector<SDValue, 8> Chains;
16464 SDValue Ptr = Ld->getBasePtr();
16465 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16466 TLI.getPointerTy());
16467 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16469 for (unsigned i = 0; i < NumLoads; ++i) {
16470 // Perform a single load.
16471 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16472 Ptr, Ld->getPointerInfo(),
16473 Ld->isVolatile(), Ld->isNonTemporal(),
16474 Ld->isInvariant(), Ld->getAlignment());
16475 Chains.push_back(ScalarLoad.getValue(1));
16476 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16477 // another round of DAGCombining.
16479 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16481 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16482 ScalarLoad, DAG.getIntPtrConstant(i));
16484 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16487 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16490 // Bitcast the loaded value to a vector of the original element type, in
16491 // the size of the target vector type.
16492 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16493 unsigned SizeRatio = RegSz/MemSz;
16495 if (Ext == ISD::SEXTLOAD) {
16496 // If we have SSE4.1 we can directly emit a VSEXT node.
16497 if (Subtarget->hasSSE41()) {
16498 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16499 return DCI.CombineTo(N, Sext, TF, true);
16502 // Otherwise we'll shuffle the small elements in the high bits of the
16503 // larger type and perform an arithmetic shift. If the shift is not legal
16504 // it's better to scalarize.
16505 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16508 // Redistribute the loaded elements into the different locations.
16509 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16510 for (unsigned i = 0; i != NumElems; ++i)
16511 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16513 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16514 DAG.getUNDEF(WideVecVT),
16517 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16519 // Build the arithmetic shift.
16520 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16521 MemVT.getVectorElementType().getSizeInBits();
16522 SmallVector<SDValue, 8> C(NumElems,
16523 DAG.getConstant(Amt, RegVT.getScalarType()));
16524 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, RegVT, &C[0], C.size());
16525 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff, BV);
16527 return DCI.CombineTo(N, Shuff, TF, true);
16530 // Redistribute the loaded elements into the different locations.
16531 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16532 for (unsigned i = 0; i != NumElems; ++i)
16533 ShuffleVec[i*SizeRatio] = i;
16535 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16536 DAG.getUNDEF(WideVecVT),
16539 // Bitcast to the requested type.
16540 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16541 // Replace the original load with the new sequence
16542 // and return the new chain.
16543 return DCI.CombineTo(N, Shuff, TF, true);
16549 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16550 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16551 const X86Subtarget *Subtarget) {
16552 StoreSDNode *St = cast<StoreSDNode>(N);
16553 EVT VT = St->getValue().getValueType();
16554 EVT StVT = St->getMemoryVT();
16555 DebugLoc dl = St->getDebugLoc();
16556 SDValue StoredVal = St->getOperand(1);
16557 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16558 unsigned Alignment = St->getAlignment();
16559 bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16561 // If we are saving a concatenation of two XMM registers, perform two stores.
16562 // On Sandy Bridge, 256-bit memory operations are executed by two
16563 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16564 // memory operation.
16565 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16566 StVT == VT && !IsAligned) {
16567 unsigned NumElems = VT.getVectorNumElements();
16571 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16572 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16574 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16575 SDValue Ptr0 = St->getBasePtr();
16576 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16578 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16579 St->getPointerInfo(), St->isVolatile(),
16580 St->isNonTemporal(), Alignment);
16581 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16582 St->getPointerInfo(), St->isVolatile(),
16583 St->isNonTemporal(),
16584 std::max(Alignment/2U, 1U));
16585 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16588 // Optimize trunc store (of multiple scalars) to shuffle and store.
16589 // First, pack all of the elements in one place. Next, store to memory
16590 // in fewer chunks.
16591 if (St->isTruncatingStore() && VT.isVector()) {
16592 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16593 unsigned NumElems = VT.getVectorNumElements();
16594 assert(StVT != VT && "Cannot truncate to the same type");
16595 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16596 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16598 // From, To sizes and ElemCount must be pow of two
16599 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16600 // We are going to use the original vector elt for storing.
16601 // Accumulated smaller vector elements must be a multiple of the store size.
16602 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16604 unsigned SizeRatio = FromSz / ToSz;
16606 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16608 // Create a type on which we perform the shuffle
16609 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16610 StVT.getScalarType(), NumElems*SizeRatio);
16612 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16614 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16615 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16616 for (unsigned i = 0; i != NumElems; ++i)
16617 ShuffleVec[i] = i * SizeRatio;
16619 // Can't shuffle using an illegal type.
16620 if (!TLI.isTypeLegal(WideVecVT))
16623 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16624 DAG.getUNDEF(WideVecVT),
16626 // At this point all of the data is stored at the bottom of the
16627 // register. We now need to save it to mem.
16629 // Find the largest store unit
16630 MVT StoreType = MVT::i8;
16631 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16632 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16633 MVT Tp = (MVT::SimpleValueType)tp;
16634 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16638 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16639 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16640 (64 <= NumElems * ToSz))
16641 StoreType = MVT::f64;
16643 // Bitcast the original vector into a vector of store-size units
16644 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16645 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16646 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16647 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16648 SmallVector<SDValue, 8> Chains;
16649 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16650 TLI.getPointerTy());
16651 SDValue Ptr = St->getBasePtr();
16653 // Perform one or more big stores into memory.
16654 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16655 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16656 StoreType, ShuffWide,
16657 DAG.getIntPtrConstant(i));
16658 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16659 St->getPointerInfo(), St->isVolatile(),
16660 St->isNonTemporal(), St->getAlignment());
16661 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16662 Chains.push_back(Ch);
16665 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16669 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
16670 // the FP state in cases where an emms may be missing.
16671 // A preferable solution to the general problem is to figure out the right
16672 // places to insert EMMS. This qualifies as a quick hack.
16674 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16675 if (VT.getSizeInBits() != 64)
16678 const Function *F = DAG.getMachineFunction().getFunction();
16679 bool NoImplicitFloatOps = F->getAttributes().
16680 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16681 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16682 && Subtarget->hasSSE2();
16683 if ((VT.isVector() ||
16684 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16685 isa<LoadSDNode>(St->getValue()) &&
16686 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16687 St->getChain().hasOneUse() && !St->isVolatile()) {
16688 SDNode* LdVal = St->getValue().getNode();
16689 LoadSDNode *Ld = 0;
16690 int TokenFactorIndex = -1;
16691 SmallVector<SDValue, 8> Ops;
16692 SDNode* ChainVal = St->getChain().getNode();
16693 // Must be a store of a load. We currently handle two cases: the load
16694 // is a direct child, and it's under an intervening TokenFactor. It is
16695 // possible to dig deeper under nested TokenFactors.
16696 if (ChainVal == LdVal)
16697 Ld = cast<LoadSDNode>(St->getChain());
16698 else if (St->getValue().hasOneUse() &&
16699 ChainVal->getOpcode() == ISD::TokenFactor) {
16700 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16701 if (ChainVal->getOperand(i).getNode() == LdVal) {
16702 TokenFactorIndex = i;
16703 Ld = cast<LoadSDNode>(St->getValue());
16705 Ops.push_back(ChainVal->getOperand(i));
16709 if (!Ld || !ISD::isNormalLoad(Ld))
16712 // If this is not the MMX case, i.e. we are just turning i64 load/store
16713 // into f64 load/store, avoid the transformation if there are multiple
16714 // uses of the loaded value.
16715 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16718 DebugLoc LdDL = Ld->getDebugLoc();
16719 DebugLoc StDL = N->getDebugLoc();
16720 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16721 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16723 if (Subtarget->is64Bit() || F64IsLegal) {
16724 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16725 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16726 Ld->getPointerInfo(), Ld->isVolatile(),
16727 Ld->isNonTemporal(), Ld->isInvariant(),
16728 Ld->getAlignment());
16729 SDValue NewChain = NewLd.getValue(1);
16730 if (TokenFactorIndex != -1) {
16731 Ops.push_back(NewChain);
16732 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16735 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16736 St->getPointerInfo(),
16737 St->isVolatile(), St->isNonTemporal(),
16738 St->getAlignment());
16741 // Otherwise, lower to two pairs of 32-bit loads / stores.
16742 SDValue LoAddr = Ld->getBasePtr();
16743 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16744 DAG.getConstant(4, MVT::i32));
16746 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16747 Ld->getPointerInfo(),
16748 Ld->isVolatile(), Ld->isNonTemporal(),
16749 Ld->isInvariant(), Ld->getAlignment());
16750 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16751 Ld->getPointerInfo().getWithOffset(4),
16752 Ld->isVolatile(), Ld->isNonTemporal(),
16754 MinAlign(Ld->getAlignment(), 4));
16756 SDValue NewChain = LoLd.getValue(1);
16757 if (TokenFactorIndex != -1) {
16758 Ops.push_back(LoLd);
16759 Ops.push_back(HiLd);
16760 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16764 LoAddr = St->getBasePtr();
16765 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16766 DAG.getConstant(4, MVT::i32));
16768 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16769 St->getPointerInfo(),
16770 St->isVolatile(), St->isNonTemporal(),
16771 St->getAlignment());
16772 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16773 St->getPointerInfo().getWithOffset(4),
16775 St->isNonTemporal(),
16776 MinAlign(St->getAlignment(), 4));
16777 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16782 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16783 /// and return the operands for the horizontal operation in LHS and RHS. A
16784 /// horizontal operation performs the binary operation on successive elements
16785 /// of its first operand, then on successive elements of its second operand,
16786 /// returning the resulting values in a vector. For example, if
16787 /// A = < float a0, float a1, float a2, float a3 >
16789 /// B = < float b0, float b1, float b2, float b3 >
16790 /// then the result of doing a horizontal operation on A and B is
16791 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16792 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16793 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16794 /// set to A, RHS to B, and the routine returns 'true'.
16795 /// Note that the binary operation should have the property that if one of the
16796 /// operands is UNDEF then the result is UNDEF.
16797 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16798 // Look for the following pattern: if
16799 // A = < float a0, float a1, float a2, float a3 >
16800 // B = < float b0, float b1, float b2, float b3 >
16802 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16803 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16804 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16805 // which is A horizontal-op B.
16807 // At least one of the operands should be a vector shuffle.
16808 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16809 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16812 EVT VT = LHS.getValueType();
16814 assert((VT.is128BitVector() || VT.is256BitVector()) &&
16815 "Unsupported vector type for horizontal add/sub");
16817 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16818 // operate independently on 128-bit lanes.
16819 unsigned NumElts = VT.getVectorNumElements();
16820 unsigned NumLanes = VT.getSizeInBits()/128;
16821 unsigned NumLaneElts = NumElts / NumLanes;
16822 assert((NumLaneElts % 2 == 0) &&
16823 "Vector type should have an even number of elements in each lane");
16824 unsigned HalfLaneElts = NumLaneElts/2;
16826 // View LHS in the form
16827 // LHS = VECTOR_SHUFFLE A, B, LMask
16828 // If LHS is not a shuffle then pretend it is the shuffle
16829 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16830 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16833 SmallVector<int, 16> LMask(NumElts);
16834 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16835 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16836 A = LHS.getOperand(0);
16837 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16838 B = LHS.getOperand(1);
16839 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
16840 std::copy(Mask.begin(), Mask.end(), LMask.begin());
16842 if (LHS.getOpcode() != ISD::UNDEF)
16844 for (unsigned i = 0; i != NumElts; ++i)
16848 // Likewise, view RHS in the form
16849 // RHS = VECTOR_SHUFFLE C, D, RMask
16851 SmallVector<int, 16> RMask(NumElts);
16852 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16853 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
16854 C = RHS.getOperand(0);
16855 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
16856 D = RHS.getOperand(1);
16857 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
16858 std::copy(Mask.begin(), Mask.end(), RMask.begin());
16860 if (RHS.getOpcode() != ISD::UNDEF)
16862 for (unsigned i = 0; i != NumElts; ++i)
16866 // Check that the shuffles are both shuffling the same vectors.
16867 if (!(A == C && B == D) && !(A == D && B == C))
16870 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
16871 if (!A.getNode() && !B.getNode())
16874 // If A and B occur in reverse order in RHS, then "swap" them (which means
16875 // rewriting the mask).
16877 CommuteVectorShuffleMask(RMask, NumElts);
16879 // At this point LHS and RHS are equivalent to
16880 // LHS = VECTOR_SHUFFLE A, B, LMask
16881 // RHS = VECTOR_SHUFFLE A, B, RMask
16882 // Check that the masks correspond to performing a horizontal operation.
16883 for (unsigned i = 0; i != NumElts; ++i) {
16884 int LIdx = LMask[i], RIdx = RMask[i];
16886 // Ignore any UNDEF components.
16887 if (LIdx < 0 || RIdx < 0 ||
16888 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
16889 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
16892 // Check that successive elements are being operated on. If not, this is
16893 // not a horizontal operation.
16894 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
16895 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
16896 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
16897 if (!(LIdx == Index && RIdx == Index + 1) &&
16898 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
16902 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
16903 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
16907 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
16908 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
16909 const X86Subtarget *Subtarget) {
16910 EVT VT = N->getValueType(0);
16911 SDValue LHS = N->getOperand(0);
16912 SDValue RHS = N->getOperand(1);
16914 // Try to synthesize horizontal adds from adds of shuffles.
16915 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16916 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16917 isHorizontalBinOp(LHS, RHS, true))
16918 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
16922 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
16923 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
16924 const X86Subtarget *Subtarget) {
16925 EVT VT = N->getValueType(0);
16926 SDValue LHS = N->getOperand(0);
16927 SDValue RHS = N->getOperand(1);
16929 // Try to synthesize horizontal subs from subs of shuffles.
16930 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
16931 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
16932 isHorizontalBinOp(LHS, RHS, false))
16933 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
16937 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
16938 /// X86ISD::FXOR nodes.
16939 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
16940 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
16941 // F[X]OR(0.0, x) -> x
16942 // F[X]OR(x, 0.0) -> x
16943 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16944 if (C->getValueAPF().isPosZero())
16945 return N->getOperand(1);
16946 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16947 if (C->getValueAPF().isPosZero())
16948 return N->getOperand(0);
16952 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
16953 /// X86ISD::FMAX nodes.
16954 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
16955 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
16957 // Only perform optimizations if UnsafeMath is used.
16958 if (!DAG.getTarget().Options.UnsafeFPMath)
16961 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
16962 // into FMINC and FMAXC, which are Commutative operations.
16963 unsigned NewOp = 0;
16964 switch (N->getOpcode()) {
16965 default: llvm_unreachable("unknown opcode");
16966 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
16967 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
16970 return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
16971 N->getOperand(0), N->getOperand(1));
16974 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
16975 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
16976 // FAND(0.0, x) -> 0.0
16977 // FAND(x, 0.0) -> 0.0
16978 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
16979 if (C->getValueAPF().isPosZero())
16980 return N->getOperand(0);
16981 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
16982 if (C->getValueAPF().isPosZero())
16983 return N->getOperand(1);
16987 static SDValue PerformBTCombine(SDNode *N,
16989 TargetLowering::DAGCombinerInfo &DCI) {
16990 // BT ignores high bits in the bit index operand.
16991 SDValue Op1 = N->getOperand(1);
16992 if (Op1.hasOneUse()) {
16993 unsigned BitWidth = Op1.getValueSizeInBits();
16994 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
16995 APInt KnownZero, KnownOne;
16996 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
16997 !DCI.isBeforeLegalizeOps());
16998 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16999 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17000 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17001 DCI.CommitTargetLoweringOpt(TLO);
17006 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17007 SDValue Op = N->getOperand(0);
17008 if (Op.getOpcode() == ISD::BITCAST)
17009 Op = Op.getOperand(0);
17010 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17011 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17012 VT.getVectorElementType().getSizeInBits() ==
17013 OpVT.getVectorElementType().getSizeInBits()) {
17014 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17019 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17020 TargetLowering::DAGCombinerInfo &DCI,
17021 const X86Subtarget *Subtarget) {
17022 if (!DCI.isBeforeLegalizeOps())
17025 if (!Subtarget->hasFp256())
17028 EVT VT = N->getValueType(0);
17029 if (VT.isVector() && VT.getSizeInBits() == 256) {
17030 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17038 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17039 const X86Subtarget* Subtarget) {
17040 DebugLoc dl = N->getDebugLoc();
17041 EVT VT = N->getValueType(0);
17043 // Let legalize expand this if it isn't a legal type yet.
17044 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17047 EVT ScalarVT = VT.getScalarType();
17048 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17049 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17052 SDValue A = N->getOperand(0);
17053 SDValue B = N->getOperand(1);
17054 SDValue C = N->getOperand(2);
17056 bool NegA = (A.getOpcode() == ISD::FNEG);
17057 bool NegB = (B.getOpcode() == ISD::FNEG);
17058 bool NegC = (C.getOpcode() == ISD::FNEG);
17060 // Negative multiplication when NegA xor NegB
17061 bool NegMul = (NegA != NegB);
17063 A = A.getOperand(0);
17065 B = B.getOperand(0);
17067 C = C.getOperand(0);
17071 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17073 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17075 return DAG.getNode(Opcode, dl, VT, A, B, C);
17078 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17079 TargetLowering::DAGCombinerInfo &DCI,
17080 const X86Subtarget *Subtarget) {
17081 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
17082 // (and (i32 x86isd::setcc_carry), 1)
17083 // This eliminates the zext. This transformation is necessary because
17084 // ISD::SETCC is always legalized to i8.
17085 DebugLoc dl = N->getDebugLoc();
17086 SDValue N0 = N->getOperand(0);
17087 EVT VT = N->getValueType(0);
17089 if (N0.getOpcode() == ISD::AND &&
17091 N0.getOperand(0).hasOneUse()) {
17092 SDValue N00 = N0.getOperand(0);
17093 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17094 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17095 if (!C || C->getZExtValue() != 1)
17097 return DAG.getNode(ISD::AND, dl, VT,
17098 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17099 N00.getOperand(0), N00.getOperand(1)),
17100 DAG.getConstant(1, VT));
17104 if (VT.is256BitVector()) {
17105 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17113 // Optimize x == -y --> x+y == 0
17114 // x != -y --> x+y != 0
17115 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17116 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17117 SDValue LHS = N->getOperand(0);
17118 SDValue RHS = N->getOperand(1);
17120 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17121 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17122 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17123 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17124 LHS.getValueType(), RHS, LHS.getOperand(1));
17125 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17126 addV, DAG.getConstant(0, addV.getValueType()), CC);
17128 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17130 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17131 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17132 RHS.getValueType(), LHS, RHS.getOperand(1));
17133 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17134 addV, DAG.getConstant(0, addV.getValueType()), CC);
17139 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17140 // as "sbb reg,reg", since it can be extended without zext and produces
17141 // an all-ones bit which is more useful than 0/1 in some cases.
17142 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17143 return DAG.getNode(ISD::AND, DL, MVT::i8,
17144 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17145 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17146 DAG.getConstant(1, MVT::i8));
17149 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17150 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17151 TargetLowering::DAGCombinerInfo &DCI,
17152 const X86Subtarget *Subtarget) {
17153 DebugLoc DL = N->getDebugLoc();
17154 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17155 SDValue EFLAGS = N->getOperand(1);
17157 if (CC == X86::COND_A) {
17158 // Try to convert COND_A into COND_B in an attempt to facilitate
17159 // materializing "setb reg".
17161 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17162 // cannot take an immediate as its first operand.
17164 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17165 EFLAGS.getValueType().isInteger() &&
17166 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17167 SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17168 EFLAGS.getNode()->getVTList(),
17169 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17170 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17171 return MaterializeSETB(DL, NewEFLAGS, DAG);
17175 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17176 // a zext and produces an all-ones bit which is more useful than 0/1 in some
17178 if (CC == X86::COND_B)
17179 return MaterializeSETB(DL, EFLAGS, DAG);
17183 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17184 if (Flags.getNode()) {
17185 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17186 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17192 // Optimize branch condition evaluation.
17194 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17195 TargetLowering::DAGCombinerInfo &DCI,
17196 const X86Subtarget *Subtarget) {
17197 DebugLoc DL = N->getDebugLoc();
17198 SDValue Chain = N->getOperand(0);
17199 SDValue Dest = N->getOperand(1);
17200 SDValue EFLAGS = N->getOperand(3);
17201 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17205 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17206 if (Flags.getNode()) {
17207 SDValue Cond = DAG.getConstant(CC, MVT::i8);
17208 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17215 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17216 const X86TargetLowering *XTLI) {
17217 SDValue Op0 = N->getOperand(0);
17218 EVT InVT = Op0->getValueType(0);
17220 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17221 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17222 DebugLoc dl = N->getDebugLoc();
17223 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17224 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17225 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17228 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17229 // a 32-bit target where SSE doesn't support i64->FP operations.
17230 if (Op0.getOpcode() == ISD::LOAD) {
17231 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17232 EVT VT = Ld->getValueType(0);
17233 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17234 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17235 !XTLI->getSubtarget()->is64Bit() &&
17236 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17237 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17238 Ld->getChain(), Op0, DAG);
17239 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17246 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17247 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17248 X86TargetLowering::DAGCombinerInfo &DCI) {
17249 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17250 // the result is either zero or one (depending on the input carry bit).
17251 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17252 if (X86::isZeroNode(N->getOperand(0)) &&
17253 X86::isZeroNode(N->getOperand(1)) &&
17254 // We don't have a good way to replace an EFLAGS use, so only do this when
17256 SDValue(N, 1).use_empty()) {
17257 DebugLoc DL = N->getDebugLoc();
17258 EVT VT = N->getValueType(0);
17259 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17260 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17261 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17262 DAG.getConstant(X86::COND_B,MVT::i8),
17264 DAG.getConstant(1, VT));
17265 return DCI.CombineTo(N, Res1, CarryOut);
17271 // fold (add Y, (sete X, 0)) -> adc 0, Y
17272 // (add Y, (setne X, 0)) -> sbb -1, Y
17273 // (sub (sete X, 0), Y) -> sbb 0, Y
17274 // (sub (setne X, 0), Y) -> adc -1, Y
17275 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17276 DebugLoc DL = N->getDebugLoc();
17278 // Look through ZExts.
17279 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17280 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17283 SDValue SetCC = Ext.getOperand(0);
17284 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17287 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17288 if (CC != X86::COND_E && CC != X86::COND_NE)
17291 SDValue Cmp = SetCC.getOperand(1);
17292 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17293 !X86::isZeroNode(Cmp.getOperand(1)) ||
17294 !Cmp.getOperand(0).getValueType().isInteger())
17297 SDValue CmpOp0 = Cmp.getOperand(0);
17298 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17299 DAG.getConstant(1, CmpOp0.getValueType()));
17301 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17302 if (CC == X86::COND_NE)
17303 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17304 DL, OtherVal.getValueType(), OtherVal,
17305 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17306 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17307 DL, OtherVal.getValueType(), OtherVal,
17308 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17311 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17312 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17313 const X86Subtarget *Subtarget) {
17314 EVT VT = N->getValueType(0);
17315 SDValue Op0 = N->getOperand(0);
17316 SDValue Op1 = N->getOperand(1);
17318 // Try to synthesize horizontal adds from adds of shuffles.
17319 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17320 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17321 isHorizontalBinOp(Op0, Op1, true))
17322 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17324 return OptimizeConditionalInDecrement(N, DAG);
17327 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17328 const X86Subtarget *Subtarget) {
17329 SDValue Op0 = N->getOperand(0);
17330 SDValue Op1 = N->getOperand(1);
17332 // X86 can't encode an immediate LHS of a sub. See if we can push the
17333 // negation into a preceding instruction.
17334 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17335 // If the RHS of the sub is a XOR with one use and a constant, invert the
17336 // immediate. Then add one to the LHS of the sub so we can turn
17337 // X-Y -> X+~Y+1, saving one register.
17338 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17339 isa<ConstantSDNode>(Op1.getOperand(1))) {
17340 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17341 EVT VT = Op0.getValueType();
17342 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17344 DAG.getConstant(~XorC, VT));
17345 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17346 DAG.getConstant(C->getAPIntValue()+1, VT));
17350 // Try to synthesize horizontal adds from adds of shuffles.
17351 EVT VT = N->getValueType(0);
17352 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17353 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17354 isHorizontalBinOp(Op0, Op1, true))
17355 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17357 return OptimizeConditionalInDecrement(N, DAG);
17360 /// performVZEXTCombine - Performs build vector combines
17361 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17362 TargetLowering::DAGCombinerInfo &DCI,
17363 const X86Subtarget *Subtarget) {
17364 // (vzext (bitcast (vzext (x)) -> (vzext x)
17365 SDValue In = N->getOperand(0);
17366 while (In.getOpcode() == ISD::BITCAST)
17367 In = In.getOperand(0);
17369 if (In.getOpcode() != X86ISD::VZEXT)
17372 return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0), In.getOperand(0));
17375 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17376 DAGCombinerInfo &DCI) const {
17377 SelectionDAG &DAG = DCI.DAG;
17378 switch (N->getOpcode()) {
17380 case ISD::EXTRACT_VECTOR_ELT:
17381 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17383 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17384 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17385 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
17386 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
17387 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
17388 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
17391 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
17392 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
17393 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
17394 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
17395 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
17396 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
17397 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
17398 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
17399 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
17401 case X86ISD::FOR: return PerformFORCombine(N, DAG);
17403 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
17404 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
17405 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
17406 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
17407 case ISD::ANY_EXTEND:
17408 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
17409 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
17410 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17411 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
17412 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17413 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17414 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
17415 case X86ISD::SHUFP: // Handle all target specific shuffles
17416 case X86ISD::PALIGN:
17417 case X86ISD::UNPCKH:
17418 case X86ISD::UNPCKL:
17419 case X86ISD::MOVHLPS:
17420 case X86ISD::MOVLHPS:
17421 case X86ISD::PSHUFD:
17422 case X86ISD::PSHUFHW:
17423 case X86ISD::PSHUFLW:
17424 case X86ISD::MOVSS:
17425 case X86ISD::MOVSD:
17426 case X86ISD::VPERMILP:
17427 case X86ISD::VPERM2X128:
17428 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17429 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
17435 /// isTypeDesirableForOp - Return true if the target has native support for
17436 /// the specified value type and it is 'desirable' to use the type for the
17437 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17438 /// instruction encodings are longer and some i16 instructions are slow.
17439 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17440 if (!isTypeLegal(VT))
17442 if (VT != MVT::i16)
17449 case ISD::SIGN_EXTEND:
17450 case ISD::ZERO_EXTEND:
17451 case ISD::ANY_EXTEND:
17464 /// IsDesirableToPromoteOp - This method query the target whether it is
17465 /// beneficial for dag combiner to promote the specified node. If true, it
17466 /// should return the desired promotion type by reference.
17467 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17468 EVT VT = Op.getValueType();
17469 if (VT != MVT::i16)
17472 bool Promote = false;
17473 bool Commute = false;
17474 switch (Op.getOpcode()) {
17477 LoadSDNode *LD = cast<LoadSDNode>(Op);
17478 // If the non-extending load has a single use and it's not live out, then it
17479 // might be folded.
17480 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17481 Op.hasOneUse()*/) {
17482 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17483 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17484 // The only case where we'd want to promote LOAD (rather then it being
17485 // promoted as an operand is when it's only use is liveout.
17486 if (UI->getOpcode() != ISD::CopyToReg)
17493 case ISD::SIGN_EXTEND:
17494 case ISD::ZERO_EXTEND:
17495 case ISD::ANY_EXTEND:
17500 SDValue N0 = Op.getOperand(0);
17501 // Look out for (store (shl (load), x)).
17502 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17515 SDValue N0 = Op.getOperand(0);
17516 SDValue N1 = Op.getOperand(1);
17517 if (!Commute && MayFoldLoad(N1))
17519 // Avoid disabling potential load folding opportunities.
17520 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17522 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17532 //===----------------------------------------------------------------------===//
17533 // X86 Inline Assembly Support
17534 //===----------------------------------------------------------------------===//
17537 // Helper to match a string separated by whitespace.
17538 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17539 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17541 for (unsigned i = 0, e = args.size(); i != e; ++i) {
17542 StringRef piece(*args[i]);
17543 if (!s.startswith(piece)) // Check if the piece matches.
17546 s = s.substr(piece.size());
17547 StringRef::size_type pos = s.find_first_not_of(" \t");
17548 if (pos == 0) // We matched a prefix.
17556 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17559 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17560 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17562 std::string AsmStr = IA->getAsmString();
17564 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17565 if (!Ty || Ty->getBitWidth() % 16 != 0)
17568 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17569 SmallVector<StringRef, 4> AsmPieces;
17570 SplitString(AsmStr, AsmPieces, ";\n");
17572 switch (AsmPieces.size()) {
17573 default: return false;
17575 // FIXME: this should verify that we are targeting a 486 or better. If not,
17576 // we will turn this bswap into something that will be lowered to logical
17577 // ops instead of emitting the bswap asm. For now, we don't support 486 or
17578 // lower so don't worry about this.
17580 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17581 matchAsm(AsmPieces[0], "bswapl", "$0") ||
17582 matchAsm(AsmPieces[0], "bswapq", "$0") ||
17583 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17584 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17585 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17586 // No need to check constraints, nothing other than the equivalent of
17587 // "=r,0" would be valid here.
17588 return IntrinsicLowering::LowerToByteSwap(CI);
17591 // rorw $$8, ${0:w} --> llvm.bswap.i16
17592 if (CI->getType()->isIntegerTy(16) &&
17593 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17594 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17595 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17597 const std::string &ConstraintsStr = IA->getConstraintString();
17598 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17599 std::sort(AsmPieces.begin(), AsmPieces.end());
17600 if (AsmPieces.size() == 4 &&
17601 AsmPieces[0] == "~{cc}" &&
17602 AsmPieces[1] == "~{dirflag}" &&
17603 AsmPieces[2] == "~{flags}" &&
17604 AsmPieces[3] == "~{fpsr}")
17605 return IntrinsicLowering::LowerToByteSwap(CI);
17609 if (CI->getType()->isIntegerTy(32) &&
17610 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17611 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17612 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17613 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17615 const std::string &ConstraintsStr = IA->getConstraintString();
17616 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17617 std::sort(AsmPieces.begin(), AsmPieces.end());
17618 if (AsmPieces.size() == 4 &&
17619 AsmPieces[0] == "~{cc}" &&
17620 AsmPieces[1] == "~{dirflag}" &&
17621 AsmPieces[2] == "~{flags}" &&
17622 AsmPieces[3] == "~{fpsr}")
17623 return IntrinsicLowering::LowerToByteSwap(CI);
17626 if (CI->getType()->isIntegerTy(64)) {
17627 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17628 if (Constraints.size() >= 2 &&
17629 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17630 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17631 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
17632 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17633 matchAsm(AsmPieces[1], "bswap", "%edx") &&
17634 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17635 return IntrinsicLowering::LowerToByteSwap(CI);
17643 /// getConstraintType - Given a constraint letter, return the type of
17644 /// constraint it is for this target.
17645 X86TargetLowering::ConstraintType
17646 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17647 if (Constraint.size() == 1) {
17648 switch (Constraint[0]) {
17659 return C_RegisterClass;
17683 return TargetLowering::getConstraintType(Constraint);
17686 /// Examine constraint type and operand type and determine a weight value.
17687 /// This object must already have been set up with the operand type
17688 /// and the current alternative constraint selected.
17689 TargetLowering::ConstraintWeight
17690 X86TargetLowering::getSingleConstraintMatchWeight(
17691 AsmOperandInfo &info, const char *constraint) const {
17692 ConstraintWeight weight = CW_Invalid;
17693 Value *CallOperandVal = info.CallOperandVal;
17694 // If we don't have a value, we can't do a match,
17695 // but allow it at the lowest weight.
17696 if (CallOperandVal == NULL)
17698 Type *type = CallOperandVal->getType();
17699 // Look at the constraint type.
17700 switch (*constraint) {
17702 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17713 if (CallOperandVal->getType()->isIntegerTy())
17714 weight = CW_SpecificReg;
17719 if (type->isFloatingPointTy())
17720 weight = CW_SpecificReg;
17723 if (type->isX86_MMXTy() && Subtarget->hasMMX())
17724 weight = CW_SpecificReg;
17728 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17729 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17730 weight = CW_Register;
17733 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17734 if (C->getZExtValue() <= 31)
17735 weight = CW_Constant;
17739 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17740 if (C->getZExtValue() <= 63)
17741 weight = CW_Constant;
17745 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17746 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17747 weight = CW_Constant;
17751 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17752 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17753 weight = CW_Constant;
17757 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17758 if (C->getZExtValue() <= 3)
17759 weight = CW_Constant;
17763 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17764 if (C->getZExtValue() <= 0xff)
17765 weight = CW_Constant;
17770 if (dyn_cast<ConstantFP>(CallOperandVal)) {
17771 weight = CW_Constant;
17775 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17776 if ((C->getSExtValue() >= -0x80000000LL) &&
17777 (C->getSExtValue() <= 0x7fffffffLL))
17778 weight = CW_Constant;
17782 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17783 if (C->getZExtValue() <= 0xffffffff)
17784 weight = CW_Constant;
17791 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17792 /// with another that has more specific requirements based on the type of the
17793 /// corresponding operand.
17794 const char *X86TargetLowering::
17795 LowerXConstraint(EVT ConstraintVT) const {
17796 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17797 // 'f' like normal targets.
17798 if (ConstraintVT.isFloatingPoint()) {
17799 if (Subtarget->hasSSE2())
17801 if (Subtarget->hasSSE1())
17805 return TargetLowering::LowerXConstraint(ConstraintVT);
17808 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17809 /// vector. If it is invalid, don't add anything to Ops.
17810 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17811 std::string &Constraint,
17812 std::vector<SDValue>&Ops,
17813 SelectionDAG &DAG) const {
17814 SDValue Result(0, 0);
17816 // Only support length 1 constraints for now.
17817 if (Constraint.length() > 1) return;
17819 char ConstraintLetter = Constraint[0];
17820 switch (ConstraintLetter) {
17823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17824 if (C->getZExtValue() <= 31) {
17825 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17831 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17832 if (C->getZExtValue() <= 63) {
17833 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17839 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17840 if (isInt<8>(C->getSExtValue())) {
17841 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17847 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17848 if (C->getZExtValue() <= 255) {
17849 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17855 // 32-bit signed value
17856 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17857 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17858 C->getSExtValue())) {
17859 // Widen to 64 bits here to get it sign extended.
17860 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
17863 // FIXME gcc accepts some relocatable values here too, but only in certain
17864 // memory models; it's complicated.
17869 // 32-bit unsigned value
17870 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
17871 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
17872 C->getZExtValue())) {
17873 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
17877 // FIXME gcc accepts some relocatable values here too, but only in certain
17878 // memory models; it's complicated.
17882 // Literal immediates are always ok.
17883 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
17884 // Widen to 64 bits here to get it sign extended.
17885 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
17889 // In any sort of PIC mode addresses need to be computed at runtime by
17890 // adding in a register or some sort of table lookup. These can't
17891 // be used as immediates.
17892 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
17895 // If we are in non-pic codegen mode, we allow the address of a global (with
17896 // an optional displacement) to be used with 'i'.
17897 GlobalAddressSDNode *GA = 0;
17898 int64_t Offset = 0;
17900 // Match either (GA), (GA+C), (GA+C1+C2), etc.
17902 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
17903 Offset += GA->getOffset();
17905 } else if (Op.getOpcode() == ISD::ADD) {
17906 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17907 Offset += C->getZExtValue();
17908 Op = Op.getOperand(0);
17911 } else if (Op.getOpcode() == ISD::SUB) {
17912 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
17913 Offset += -C->getZExtValue();
17914 Op = Op.getOperand(0);
17919 // Otherwise, this isn't something we can handle, reject it.
17923 const GlobalValue *GV = GA->getGlobal();
17924 // If we require an extra load to get this address, as in PIC mode, we
17925 // can't accept it.
17926 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
17927 getTargetMachine())))
17930 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
17931 GA->getValueType(0), Offset);
17936 if (Result.getNode()) {
17937 Ops.push_back(Result);
17940 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17943 std::pair<unsigned, const TargetRegisterClass*>
17944 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
17946 // First, see if this is a constraint that directly corresponds to an LLVM
17948 if (Constraint.size() == 1) {
17949 // GCC Constraint Letters
17950 switch (Constraint[0]) {
17952 // TODO: Slight differences here in allocation order and leaving
17953 // RIP in the class. Do they matter any more here than they do
17954 // in the normal allocation?
17955 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
17956 if (Subtarget->is64Bit()) {
17957 if (VT == MVT::i32 || VT == MVT::f32)
17958 return std::make_pair(0U, &X86::GR32RegClass);
17959 if (VT == MVT::i16)
17960 return std::make_pair(0U, &X86::GR16RegClass);
17961 if (VT == MVT::i8 || VT == MVT::i1)
17962 return std::make_pair(0U, &X86::GR8RegClass);
17963 if (VT == MVT::i64 || VT == MVT::f64)
17964 return std::make_pair(0U, &X86::GR64RegClass);
17967 // 32-bit fallthrough
17968 case 'Q': // Q_REGS
17969 if (VT == MVT::i32 || VT == MVT::f32)
17970 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
17971 if (VT == MVT::i16)
17972 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
17973 if (VT == MVT::i8 || VT == MVT::i1)
17974 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
17975 if (VT == MVT::i64)
17976 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
17978 case 'r': // GENERAL_REGS
17979 case 'l': // INDEX_REGS
17980 if (VT == MVT::i8 || VT == MVT::i1)
17981 return std::make_pair(0U, &X86::GR8RegClass);
17982 if (VT == MVT::i16)
17983 return std::make_pair(0U, &X86::GR16RegClass);
17984 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
17985 return std::make_pair(0U, &X86::GR32RegClass);
17986 return std::make_pair(0U, &X86::GR64RegClass);
17987 case 'R': // LEGACY_REGS
17988 if (VT == MVT::i8 || VT == MVT::i1)
17989 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
17990 if (VT == MVT::i16)
17991 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
17992 if (VT == MVT::i32 || !Subtarget->is64Bit())
17993 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
17994 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
17995 case 'f': // FP Stack registers.
17996 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
17997 // value to the correct fpstack register class.
17998 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
17999 return std::make_pair(0U, &X86::RFP32RegClass);
18000 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18001 return std::make_pair(0U, &X86::RFP64RegClass);
18002 return std::make_pair(0U, &X86::RFP80RegClass);
18003 case 'y': // MMX_REGS if MMX allowed.
18004 if (!Subtarget->hasMMX()) break;
18005 return std::make_pair(0U, &X86::VR64RegClass);
18006 case 'Y': // SSE_REGS if SSE2 allowed
18007 if (!Subtarget->hasSSE2()) break;
18009 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18010 if (!Subtarget->hasSSE1()) break;
18012 switch (VT.getSimpleVT().SimpleTy) {
18014 // Scalar SSE types.
18017 return std::make_pair(0U, &X86::FR32RegClass);
18020 return std::make_pair(0U, &X86::FR64RegClass);
18028 return std::make_pair(0U, &X86::VR128RegClass);
18036 return std::make_pair(0U, &X86::VR256RegClass);
18042 // Use the default implementation in TargetLowering to convert the register
18043 // constraint into a member of a register class.
18044 std::pair<unsigned, const TargetRegisterClass*> Res;
18045 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18047 // Not found as a standard register?
18048 if (Res.second == 0) {
18049 // Map st(0) -> st(7) -> ST0
18050 if (Constraint.size() == 7 && Constraint[0] == '{' &&
18051 tolower(Constraint[1]) == 's' &&
18052 tolower(Constraint[2]) == 't' &&
18053 Constraint[3] == '(' &&
18054 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18055 Constraint[5] == ')' &&
18056 Constraint[6] == '}') {
18058 Res.first = X86::ST0+Constraint[4]-'0';
18059 Res.second = &X86::RFP80RegClass;
18063 // GCC allows "st(0)" to be called just plain "st".
18064 if (StringRef("{st}").equals_lower(Constraint)) {
18065 Res.first = X86::ST0;
18066 Res.second = &X86::RFP80RegClass;
18071 if (StringRef("{flags}").equals_lower(Constraint)) {
18072 Res.first = X86::EFLAGS;
18073 Res.second = &X86::CCRRegClass;
18077 // 'A' means EAX + EDX.
18078 if (Constraint == "A") {
18079 Res.first = X86::EAX;
18080 Res.second = &X86::GR32_ADRegClass;
18086 // Otherwise, check to see if this is a register class of the wrong value
18087 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18088 // turn into {ax},{dx}.
18089 if (Res.second->hasType(VT))
18090 return Res; // Correct type already, nothing to do.
18092 // All of the single-register GCC register classes map their values onto
18093 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
18094 // really want an 8-bit or 32-bit register, map to the appropriate register
18095 // class and return the appropriate register.
18096 if (Res.second == &X86::GR16RegClass) {
18097 if (VT == MVT::i8) {
18098 unsigned DestReg = 0;
18099 switch (Res.first) {
18101 case X86::AX: DestReg = X86::AL; break;
18102 case X86::DX: DestReg = X86::DL; break;
18103 case X86::CX: DestReg = X86::CL; break;
18104 case X86::BX: DestReg = X86::BL; break;
18107 Res.first = DestReg;
18108 Res.second = &X86::GR8RegClass;
18110 } else if (VT == MVT::i32) {
18111 unsigned DestReg = 0;
18112 switch (Res.first) {
18114 case X86::AX: DestReg = X86::EAX; break;
18115 case X86::DX: DestReg = X86::EDX; break;
18116 case X86::CX: DestReg = X86::ECX; break;
18117 case X86::BX: DestReg = X86::EBX; break;
18118 case X86::SI: DestReg = X86::ESI; break;
18119 case X86::DI: DestReg = X86::EDI; break;
18120 case X86::BP: DestReg = X86::EBP; break;
18121 case X86::SP: DestReg = X86::ESP; break;
18124 Res.first = DestReg;
18125 Res.second = &X86::GR32RegClass;
18127 } else if (VT == MVT::i64) {
18128 unsigned DestReg = 0;
18129 switch (Res.first) {
18131 case X86::AX: DestReg = X86::RAX; break;
18132 case X86::DX: DestReg = X86::RDX; break;
18133 case X86::CX: DestReg = X86::RCX; break;
18134 case X86::BX: DestReg = X86::RBX; break;
18135 case X86::SI: DestReg = X86::RSI; break;
18136 case X86::DI: DestReg = X86::RDI; break;
18137 case X86::BP: DestReg = X86::RBP; break;
18138 case X86::SP: DestReg = X86::RSP; break;
18141 Res.first = DestReg;
18142 Res.second = &X86::GR64RegClass;
18145 } else if (Res.second == &X86::FR32RegClass ||
18146 Res.second == &X86::FR64RegClass ||
18147 Res.second == &X86::VR128RegClass) {
18148 // Handle references to XMM physical registers that got mapped into the
18149 // wrong class. This can happen with constraints like {xmm0} where the
18150 // target independent register mapper will just pick the first match it can
18151 // find, ignoring the required type.
18153 if (VT == MVT::f32 || VT == MVT::i32)
18154 Res.second = &X86::FR32RegClass;
18155 else if (VT == MVT::f64 || VT == MVT::i64)
18156 Res.second = &X86::FR64RegClass;
18157 else if (X86::VR128RegClass.hasType(VT))
18158 Res.second = &X86::VR128RegClass;
18159 else if (X86::VR256RegClass.hasType(VT))
18160 Res.second = &X86::VR256RegClass;