1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
16 #include "X86ISelLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VariadicFunction.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
54 STATISTIC(NumTailCalls, "Number of tail calls");
56 // Forward declarations.
57 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
60 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
61 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
62 /// simple subregister reference. Idx is an index in the 128 bits we
63 /// want. It need not be aligned to a 128-bit bounday. That makes
64 /// lowering EXTRACT_VECTOR_ELT operations easier.
65 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
66 SelectionDAG &DAG, DebugLoc dl) {
67 EVT VT = Vec.getValueType();
68 assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
69 EVT ElVT = VT.getVectorElementType();
70 unsigned Factor = VT.getSizeInBits()/128;
71 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72 VT.getVectorNumElements()/Factor);
74 // Extract from UNDEF is UNDEF.
75 if (Vec.getOpcode() == ISD::UNDEF)
76 return DAG.getUNDEF(ResultVT);
78 // Extract the relevant 128 bits. Generate an EXTRACT_SUBVECTOR
79 // we can match to VEXTRACTF128.
80 unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
82 // This is the index of the first element of the 128-bit chunk
84 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
87 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
88 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
95 /// sets things up to match to an AVX VINSERTF128 instruction or a
96 /// simple superregister reference. Idx is an index in the 128 bits
97 /// we want. It need not be aligned to a 128-bit bounday. That makes
98 /// lowering INSERT_VECTOR_ELT operations easier.
99 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
100 unsigned IdxVal, SelectionDAG &DAG,
102 EVT VT = Vec.getValueType();
103 assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
105 EVT ElVT = VT.getVectorElementType();
106 EVT ResultVT = Result.getValueType();
108 // Insert the relevant 128 bits.
109 unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
111 // This is the index of the first element of the 128-bit chunk
113 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
116 SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
117 Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
122 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
123 /// instructions. This is used because creating CONCAT_VECTOR nodes of
124 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
125 /// large BUILD_VECTORS.
126 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
127 unsigned NumElems, SelectionDAG &DAG,
129 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
130 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
133 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
134 const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
135 bool is64Bit = Subtarget->is64Bit();
137 if (Subtarget->isTargetEnvMacho()) {
139 return new X8664_MachoTargetObjectFile();
140 return new TargetLoweringObjectFileMachO();
143 if (Subtarget->isTargetELF())
144 return new TargetLoweringObjectFileELF();
145 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
146 return new TargetLoweringObjectFileCOFF();
147 llvm_unreachable("unknown subtarget type");
150 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
151 : TargetLowering(TM, createTLOF(TM)) {
152 Subtarget = &TM.getSubtarget<X86Subtarget>();
153 X86ScalarSSEf64 = Subtarget->hasSSE2();
154 X86ScalarSSEf32 = Subtarget->hasSSE1();
155 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
157 RegInfo = TM.getRegisterInfo();
158 TD = getTargetData();
160 // Set up the TargetLowering object.
161 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
163 // X86 is weird, it always uses i8 for shift amounts and setcc results.
164 setBooleanContents(ZeroOrOneBooleanContent);
165 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
166 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
168 // For 64-bit since we have so many registers use the ILP scheduler, for
169 // 32-bit code use the register pressure specific scheduling.
170 // For Atom, always use ILP scheduling.
171 if (Subtarget->isAtom())
172 setSchedulingPreference(Sched::ILP);
173 else if (Subtarget->is64Bit())
174 setSchedulingPreference(Sched::ILP);
176 setSchedulingPreference(Sched::RegPressure);
177 setStackPointerRegisterToSaveRestore(X86StackPtr);
179 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
180 // Setup Windows compiler runtime calls.
181 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
182 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
183 setLibcallName(RTLIB::SREM_I64, "_allrem");
184 setLibcallName(RTLIB::UREM_I64, "_aullrem");
185 setLibcallName(RTLIB::MUL_I64, "_allmul");
186 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
187 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
188 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
189 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
190 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
192 // The _ftol2 runtime function has an unusual calling conv, which
193 // is modeled by a special pseudo-instruction.
194 setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
195 setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
196 setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
197 setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
200 if (Subtarget->isTargetDarwin()) {
201 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
202 setUseUnderscoreSetJmp(false);
203 setUseUnderscoreLongJmp(false);
204 } else if (Subtarget->isTargetMingw()) {
205 // MS runtime is weird: it exports _setjmp, but longjmp!
206 setUseUnderscoreSetJmp(true);
207 setUseUnderscoreLongJmp(false);
209 setUseUnderscoreSetJmp(true);
210 setUseUnderscoreLongJmp(true);
213 // Set up the register classes.
214 addRegisterClass(MVT::i8, &X86::GR8RegClass);
215 addRegisterClass(MVT::i16, &X86::GR16RegClass);
216 addRegisterClass(MVT::i32, &X86::GR32RegClass);
217 if (Subtarget->is64Bit())
218 addRegisterClass(MVT::i64, &X86::GR64RegClass);
220 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
222 // We don't accept any truncstore of integer registers.
223 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
224 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
225 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
226 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
227 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
228 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
230 // SETOEQ and SETUNE require checking two conditions.
231 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
232 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
233 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
234 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
235 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
236 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
238 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
240 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
241 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
242 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
244 if (Subtarget->is64Bit()) {
245 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
246 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
247 } else if (!TM.Options.UseSoftFloat) {
248 // We have an algorithm for SSE2->double, and we turn this into a
249 // 64-bit FILD followed by conditional FADD for other targets.
250 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
251 // We have an algorithm for SSE2, and we turn this into a 64-bit
252 // FILD for other targets.
253 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
256 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
258 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
259 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
261 if (!TM.Options.UseSoftFloat) {
262 // SSE has no i16 to fp conversion, only i32
263 if (X86ScalarSSEf32) {
264 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
265 // f32 and f64 cases are Legal, f80 case is not
266 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
268 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
269 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
272 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
273 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
276 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
277 // are Legal, f80 is custom lowered.
278 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
279 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
281 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
283 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
284 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
286 if (X86ScalarSSEf32) {
287 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
288 // f32 and f64 cases are Legal, f80 case is not
289 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
291 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
292 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
295 // Handle FP_TO_UINT by promoting the destination to a larger signed
297 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
298 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
299 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
301 if (Subtarget->is64Bit()) {
302 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
303 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
304 } else if (!TM.Options.UseSoftFloat) {
305 // Since AVX is a superset of SSE3, only check for SSE here.
306 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
307 // Expand FP_TO_UINT into a select.
308 // FIXME: We would like to use a Custom expander here eventually to do
309 // the optimal thing for SSE vs. the default expansion in the legalizer.
310 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
312 // With SSE3 we can use fisttpll to convert to a signed i64; without
313 // SSE, we're stuck with a fistpll.
314 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
317 if (isTargetFTOL()) {
318 // Use the _ftol2 runtime function, which has a pseudo-instruction
319 // to handle its weird calling convention.
320 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
323 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
324 if (!X86ScalarSSEf64) {
325 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
326 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
327 if (Subtarget->is64Bit()) {
328 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
329 // Without SSE, i64->f64 goes through memory.
330 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
334 // Scalar integer divide and remainder are lowered to use operations that
335 // produce two results, to match the available instructions. This exposes
336 // the two-result form to trivial CSE, which is able to combine x/y and x%y
337 // into a single instruction.
339 // Scalar integer multiply-high is also lowered to use two-result
340 // operations, to match the available instructions. However, plain multiply
341 // (low) operations are left as Legal, as there are single-result
342 // instructions for this in x86. Using the two-result multiply instructions
343 // when both high and low results are needed must be arranged by dagcombine.
344 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
346 setOperationAction(ISD::MULHS, VT, Expand);
347 setOperationAction(ISD::MULHU, VT, Expand);
348 setOperationAction(ISD::SDIV, VT, Expand);
349 setOperationAction(ISD::UDIV, VT, Expand);
350 setOperationAction(ISD::SREM, VT, Expand);
351 setOperationAction(ISD::UREM, VT, Expand);
353 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
354 setOperationAction(ISD::ADDC, VT, Custom);
355 setOperationAction(ISD::ADDE, VT, Custom);
356 setOperationAction(ISD::SUBC, VT, Custom);
357 setOperationAction(ISD::SUBE, VT, Custom);
360 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
361 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
362 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
363 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
364 if (Subtarget->is64Bit())
365 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
366 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
367 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
368 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
369 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
370 setOperationAction(ISD::FREM , MVT::f32 , Expand);
371 setOperationAction(ISD::FREM , MVT::f64 , Expand);
372 setOperationAction(ISD::FREM , MVT::f80 , Expand);
373 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
375 // Promote the i8 variants and force them on up to i32 which has a shorter
377 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
378 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
379 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
380 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
381 if (Subtarget->hasBMI()) {
382 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
383 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
384 if (Subtarget->is64Bit())
385 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
387 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
388 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
389 if (Subtarget->is64Bit())
390 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
393 if (Subtarget->hasLZCNT()) {
394 // When promoting the i8 variants, force them to i32 for a shorter
396 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
397 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
398 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
399 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
400 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
401 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
402 if (Subtarget->is64Bit())
403 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
405 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
406 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
407 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
410 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
411 if (Subtarget->is64Bit()) {
412 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
417 if (Subtarget->hasPOPCNT()) {
418 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
420 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
421 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
422 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
423 if (Subtarget->is64Bit())
424 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
427 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
428 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
430 // These should be promoted to a larger select which is supported.
431 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
432 // X86 wants to expand cmov itself.
433 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
434 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
435 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
436 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
437 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
438 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
439 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
440 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
441 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
442 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
443 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
444 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
445 if (Subtarget->is64Bit()) {
446 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
447 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
449 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
452 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
453 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
454 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
455 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
456 if (Subtarget->is64Bit())
457 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
458 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
459 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
460 if (Subtarget->is64Bit()) {
461 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
462 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
463 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
464 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
465 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
467 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
468 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
469 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
470 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
471 if (Subtarget->is64Bit()) {
472 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
473 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
474 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
477 if (Subtarget->hasSSE1())
478 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
480 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
481 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
483 // On X86 and X86-64, atomic operations are lowered to locked instructions.
484 // Locked instructions, in turn, have implicit fence semantics (all memory
485 // operations are flushed before issuing the locked instruction, and they
486 // are not buffered), so we can fold away the common pattern of
487 // fence-atomic-fence.
488 setShouldFoldAtomicFences(true);
490 // Expand certain atomics
491 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
493 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
494 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
495 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
498 if (!Subtarget->is64Bit()) {
499 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
500 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
501 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
502 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
503 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
504 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
505 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
506 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
509 if (Subtarget->hasCmpxchg16b()) {
510 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
513 // FIXME - use subtarget debug flags
514 if (!Subtarget->isTargetDarwin() &&
515 !Subtarget->isTargetELF() &&
516 !Subtarget->isTargetCygMing()) {
517 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
520 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
521 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
522 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
523 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
524 if (Subtarget->is64Bit()) {
525 setExceptionPointerRegister(X86::RAX);
526 setExceptionSelectorRegister(X86::RDX);
528 setExceptionPointerRegister(X86::EAX);
529 setExceptionSelectorRegister(X86::EDX);
531 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
532 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
534 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
535 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
537 setOperationAction(ISD::TRAP, MVT::Other, Legal);
539 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
540 setOperationAction(ISD::VASTART , MVT::Other, Custom);
541 setOperationAction(ISD::VAEND , MVT::Other, Expand);
542 if (Subtarget->is64Bit()) {
543 setOperationAction(ISD::VAARG , MVT::Other, Custom);
544 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
546 setOperationAction(ISD::VAARG , MVT::Other, Expand);
547 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
550 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
551 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
553 if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
554 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
555 MVT::i64 : MVT::i32, Custom);
556 else if (TM.Options.EnableSegmentedStacks)
557 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
558 MVT::i64 : MVT::i32, Custom);
560 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
561 MVT::i64 : MVT::i32, Expand);
563 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
564 // f32 and f64 use SSE.
565 // Set up the FP register classes.
566 addRegisterClass(MVT::f32, &X86::FR32RegClass);
567 addRegisterClass(MVT::f64, &X86::FR64RegClass);
569 // Use ANDPD to simulate FABS.
570 setOperationAction(ISD::FABS , MVT::f64, Custom);
571 setOperationAction(ISD::FABS , MVT::f32, Custom);
573 // Use XORP to simulate FNEG.
574 setOperationAction(ISD::FNEG , MVT::f64, Custom);
575 setOperationAction(ISD::FNEG , MVT::f32, Custom);
577 // Use ANDPD and ORPD to simulate FCOPYSIGN.
578 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
579 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
581 // Lower this to FGETSIGNx86 plus an AND.
582 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
583 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
585 // We don't support sin/cos/fmod
586 setOperationAction(ISD::FSIN , MVT::f64, Expand);
587 setOperationAction(ISD::FCOS , MVT::f64, Expand);
588 setOperationAction(ISD::FSIN , MVT::f32, Expand);
589 setOperationAction(ISD::FCOS , MVT::f32, Expand);
591 // Expand FP immediates into loads from the stack, except for the special
593 addLegalFPImmediate(APFloat(+0.0)); // xorpd
594 addLegalFPImmediate(APFloat(+0.0f)); // xorps
595 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
596 // Use SSE for f32, x87 for f64.
597 // Set up the FP register classes.
598 addRegisterClass(MVT::f32, &X86::FR32RegClass);
599 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
601 // Use ANDPS to simulate FABS.
602 setOperationAction(ISD::FABS , MVT::f32, Custom);
604 // Use XORP to simulate FNEG.
605 setOperationAction(ISD::FNEG , MVT::f32, Custom);
607 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
609 // Use ANDPS and ORPS to simulate FCOPYSIGN.
610 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
611 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
613 // We don't support sin/cos/fmod
614 setOperationAction(ISD::FSIN , MVT::f32, Expand);
615 setOperationAction(ISD::FCOS , MVT::f32, Expand);
617 // Special cases we handle for FP constants.
618 addLegalFPImmediate(APFloat(+0.0f)); // xorps
619 addLegalFPImmediate(APFloat(+0.0)); // FLD0
620 addLegalFPImmediate(APFloat(+1.0)); // FLD1
621 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
622 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
624 if (!TM.Options.UnsafeFPMath) {
625 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
626 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
628 } else if (!TM.Options.UseSoftFloat) {
629 // f32 and f64 in x87.
630 // Set up the FP register classes.
631 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
634 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
635 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
636 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
637 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
639 if (!TM.Options.UnsafeFPMath) {
640 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
641 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
643 addLegalFPImmediate(APFloat(+0.0)); // FLD0
644 addLegalFPImmediate(APFloat(+1.0)); // FLD1
645 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
646 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
647 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
648 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
649 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
650 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
653 // We don't support FMA.
654 setOperationAction(ISD::FMA, MVT::f64, Expand);
655 setOperationAction(ISD::FMA, MVT::f32, Expand);
657 // Long double always uses X87.
658 if (!TM.Options.UseSoftFloat) {
659 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
660 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
661 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
663 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
664 addLegalFPImmediate(TmpFlt); // FLD0
666 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
669 APFloat TmpFlt2(+1.0);
670 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
672 addLegalFPImmediate(TmpFlt2); // FLD1
673 TmpFlt2.changeSign();
674 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
677 if (!TM.Options.UnsafeFPMath) {
678 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
679 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
682 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
683 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
684 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
685 setOperationAction(ISD::FRINT, MVT::f80, Expand);
686 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
687 setOperationAction(ISD::FMA, MVT::f80, Expand);
690 // Always use a library call for pow.
691 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
692 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
693 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
695 setOperationAction(ISD::FLOG, MVT::f80, Expand);
696 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
697 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
698 setOperationAction(ISD::FEXP, MVT::f80, Expand);
699 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
701 // First set operation action for all vector types to either promote
702 // (for widening) or expand (for scalarization). Then we will selectively
703 // turn on ones that can be effectively codegen'd.
704 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
705 VT <= MVT::LAST_VECTOR_VALUETYPE; ++VT) {
706 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
707 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
708 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
709 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
710 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
711 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
712 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
713 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
714 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
715 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
716 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
717 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
718 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
719 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
720 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
721 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
722 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
723 setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
724 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
725 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
726 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
727 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
728 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
729 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
730 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
731 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
732 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
733 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
734 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
735 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
736 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
737 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
738 setOperationAction(ISD::CTTZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
739 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
740 setOperationAction(ISD::CTLZ_ZERO_UNDEF, (MVT::SimpleValueType)VT, Expand);
741 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
742 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
743 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
744 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
745 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
746 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
747 setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
748 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
749 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
750 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
751 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
752 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
753 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
754 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
755 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
756 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
757 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
758 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
759 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
760 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
761 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
762 setOperationAction(ISD::VSELECT, (MVT::SimpleValueType)VT, Expand);
763 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
764 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
765 setTruncStoreAction((MVT::SimpleValueType)VT,
766 (MVT::SimpleValueType)InnerVT, Expand);
767 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
768 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
769 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
772 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
773 // with -msoft-float, disable use of MMX as well.
774 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
775 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
776 // No operations on x86mmx supported, everything uses intrinsics.
779 // MMX-sized vectors (other than x86mmx) are expected to be expanded
780 // into smaller operations.
781 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
782 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
783 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
784 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
785 setOperationAction(ISD::AND, MVT::v8i8, Expand);
786 setOperationAction(ISD::AND, MVT::v4i16, Expand);
787 setOperationAction(ISD::AND, MVT::v2i32, Expand);
788 setOperationAction(ISD::AND, MVT::v1i64, Expand);
789 setOperationAction(ISD::OR, MVT::v8i8, Expand);
790 setOperationAction(ISD::OR, MVT::v4i16, Expand);
791 setOperationAction(ISD::OR, MVT::v2i32, Expand);
792 setOperationAction(ISD::OR, MVT::v1i64, Expand);
793 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
794 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
795 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
796 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
797 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
798 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
799 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
800 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
801 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
802 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
803 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
804 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
805 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
806 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
807 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
808 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
809 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
811 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
812 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
814 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
815 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
816 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
817 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
818 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
819 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
820 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
821 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
822 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
823 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
825 setOperationAction(ISD::SETCC, MVT::v4f32, Custom);
828 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
829 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
831 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
832 // registers cannot be used even for integer operations.
833 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
834 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
835 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
836 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
838 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
839 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
840 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
841 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
842 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
843 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
844 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
845 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
846 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
847 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
848 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
849 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
850 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
851 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
852 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
853 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
855 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
856 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
857 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
858 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
860 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
861 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
862 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
863 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
866 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
867 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
868 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
869 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
870 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
872 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
873 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
874 EVT VT = (MVT::SimpleValueType)i;
875 // Do not attempt to custom lower non-power-of-2 vectors
876 if (!isPowerOf2_32(VT.getVectorNumElements()))
878 // Do not attempt to custom lower non-128-bit vectors
879 if (!VT.is128BitVector())
881 setOperationAction(ISD::BUILD_VECTOR,
882 VT.getSimpleVT().SimpleTy, Custom);
883 setOperationAction(ISD::VECTOR_SHUFFLE,
884 VT.getSimpleVT().SimpleTy, Custom);
885 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
886 VT.getSimpleVT().SimpleTy, Custom);
889 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
891 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
893 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
896 if (Subtarget->is64Bit()) {
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
901 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
902 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
903 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
906 // Do not attempt to promote non-128-bit vectors
907 if (!VT.is128BitVector())
910 setOperationAction(ISD::AND, SVT, Promote);
911 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
912 setOperationAction(ISD::OR, SVT, Promote);
913 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
914 setOperationAction(ISD::XOR, SVT, Promote);
915 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
916 setOperationAction(ISD::LOAD, SVT, Promote);
917 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
918 setOperationAction(ISD::SELECT, SVT, Promote);
919 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
922 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
924 // Custom lower v2i64 and v2f64 selects.
925 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
926 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
927 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
928 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
930 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
931 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
934 if (Subtarget->hasSSE41()) {
935 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
936 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
937 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
938 setOperationAction(ISD::FRINT, MVT::f32, Legal);
939 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
940 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
941 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
942 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
943 setOperationAction(ISD::FRINT, MVT::f64, Legal);
944 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
946 // FIXME: Do we need to handle scalar-to-vector here?
947 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
949 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
950 setOperationAction(ISD::VSELECT, MVT::v2i64, Legal);
951 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
952 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
953 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
955 // i8 and i16 vectors are custom , because the source register and source
956 // source memory operand types are not the same width. f32 vectors are
957 // custom since the immediate controlling the insert encodes additional
959 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
960 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
961 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
962 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
964 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
965 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
966 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
967 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
969 // FIXME: these should be Legal but thats only for the case where
970 // the index is constant. For now custom expand to deal with that.
971 if (Subtarget->is64Bit()) {
972 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
973 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
977 if (Subtarget->hasSSE2()) {
978 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
979 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
981 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
982 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
984 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
985 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
987 if (Subtarget->hasAVX2()) {
988 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
989 setOperationAction(ISD::SRL, MVT::v4i32, Legal);
991 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
992 setOperationAction(ISD::SHL, MVT::v4i32, Legal);
994 setOperationAction(ISD::SRA, MVT::v4i32, Legal);
996 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
997 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
999 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1000 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1002 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1006 if (Subtarget->hasSSE42())
1007 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1009 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX()) {
1010 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1011 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1012 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1013 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1014 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1015 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1017 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1018 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1019 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1021 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1022 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1023 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1024 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1025 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1026 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1028 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1029 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1030 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1031 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1032 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1033 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1035 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1036 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1037 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1039 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4f64, Custom);
1040 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i64, Custom);
1041 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f32, Custom);
1042 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i32, Custom);
1043 setOperationAction(ISD::CONCAT_VECTORS, MVT::v32i8, Custom);
1044 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i16, Custom);
1046 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1047 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1049 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1050 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1052 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1053 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1055 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1056 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1057 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1058 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1060 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1061 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1062 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1064 setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
1065 setOperationAction(ISD::VSELECT, MVT::v4i64, Legal);
1066 setOperationAction(ISD::VSELECT, MVT::v8i32, Legal);
1067 setOperationAction(ISD::VSELECT, MVT::v8f32, Legal);
1069 if (Subtarget->hasAVX2()) {
1070 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1071 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1072 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1073 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1075 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1076 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1077 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1078 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1080 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1081 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1082 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1083 // Don't lower v32i8 because there is no 128-bit byte mul
1085 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1087 setOperationAction(ISD::SRL, MVT::v4i64, Legal);
1088 setOperationAction(ISD::SRL, MVT::v8i32, Legal);
1090 setOperationAction(ISD::SHL, MVT::v4i64, Legal);
1091 setOperationAction(ISD::SHL, MVT::v8i32, Legal);
1093 setOperationAction(ISD::SRA, MVT::v8i32, Legal);
1095 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1096 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1097 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1098 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1100 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1101 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1102 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1103 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1105 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1106 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1107 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1108 // Don't lower v32i8 because there is no 128-bit byte mul
1110 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1111 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1113 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1114 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1116 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1119 // Custom lower several nodes for 256-bit types.
1120 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1121 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1122 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1125 // Extract subvector is special because the value type
1126 // (result) is 128-bit but the source is 256-bit wide.
1127 if (VT.is128BitVector())
1128 setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1130 // Do not attempt to custom lower other non-256-bit vectors
1131 if (!VT.is256BitVector())
1134 setOperationAction(ISD::BUILD_VECTOR, SVT, Custom);
1135 setOperationAction(ISD::VECTOR_SHUFFLE, SVT, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, SVT, Custom);
1137 setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1138 setOperationAction(ISD::SCALAR_TO_VECTOR, SVT, Custom);
1139 setOperationAction(ISD::INSERT_SUBVECTOR, SVT, Custom);
1142 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1143 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1144 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1147 // Do not attempt to promote non-256-bit vectors
1148 if (!VT.is256BitVector())
1151 setOperationAction(ISD::AND, SVT, Promote);
1152 AddPromotedToType (ISD::AND, SVT, MVT::v4i64);
1153 setOperationAction(ISD::OR, SVT, Promote);
1154 AddPromotedToType (ISD::OR, SVT, MVT::v4i64);
1155 setOperationAction(ISD::XOR, SVT, Promote);
1156 AddPromotedToType (ISD::XOR, SVT, MVT::v4i64);
1157 setOperationAction(ISD::LOAD, SVT, Promote);
1158 AddPromotedToType (ISD::LOAD, SVT, MVT::v4i64);
1159 setOperationAction(ISD::SELECT, SVT, Promote);
1160 AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1164 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1165 // of this type with custom code.
1166 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1167 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1168 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1172 // We want to custom lower some of our intrinsics.
1173 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1176 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1177 // handle type legalization for these operations here.
1179 // FIXME: We really should do custom legalization for addition and
1180 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1181 // than generic legalization for 64-bit multiplication-with-overflow, though.
1182 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1183 // Add/Sub/Mul with overflow operations are custom lowered.
1185 setOperationAction(ISD::SADDO, VT, Custom);
1186 setOperationAction(ISD::UADDO, VT, Custom);
1187 setOperationAction(ISD::SSUBO, VT, Custom);
1188 setOperationAction(ISD::USUBO, VT, Custom);
1189 setOperationAction(ISD::SMULO, VT, Custom);
1190 setOperationAction(ISD::UMULO, VT, Custom);
1193 // There are no 8-bit 3-address imul/mul instructions
1194 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1195 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1197 if (!Subtarget->is64Bit()) {
1198 // These libcalls are not available in 32-bit.
1199 setLibcallName(RTLIB::SHL_I128, 0);
1200 setLibcallName(RTLIB::SRL_I128, 0);
1201 setLibcallName(RTLIB::SRA_I128, 0);
1204 // We have target-specific dag combine patterns for the following nodes:
1205 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1206 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1207 setTargetDAGCombine(ISD::VSELECT);
1208 setTargetDAGCombine(ISD::SELECT);
1209 setTargetDAGCombine(ISD::SHL);
1210 setTargetDAGCombine(ISD::SRA);
1211 setTargetDAGCombine(ISD::SRL);
1212 setTargetDAGCombine(ISD::OR);
1213 setTargetDAGCombine(ISD::AND);
1214 setTargetDAGCombine(ISD::ADD);
1215 setTargetDAGCombine(ISD::FADD);
1216 setTargetDAGCombine(ISD::FSUB);
1217 setTargetDAGCombine(ISD::SUB);
1218 setTargetDAGCombine(ISD::LOAD);
1219 setTargetDAGCombine(ISD::STORE);
1220 setTargetDAGCombine(ISD::ZERO_EXTEND);
1221 setTargetDAGCombine(ISD::ANY_EXTEND);
1222 setTargetDAGCombine(ISD::SIGN_EXTEND);
1223 setTargetDAGCombine(ISD::TRUNCATE);
1224 setTargetDAGCombine(ISD::UINT_TO_FP);
1225 setTargetDAGCombine(ISD::SINT_TO_FP);
1226 setTargetDAGCombine(ISD::SETCC);
1227 setTargetDAGCombine(ISD::FP_TO_SINT);
1228 if (Subtarget->is64Bit())
1229 setTargetDAGCombine(ISD::MUL);
1230 if (Subtarget->hasBMI())
1231 setTargetDAGCombine(ISD::XOR);
1233 computeRegisterProperties();
1235 // On Darwin, -Os means optimize for size without hurting performance,
1236 // do not reduce the limit.
1237 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1238 maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1239 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1240 maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1241 maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1242 maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1243 setPrefLoopAlignment(4); // 2^4 bytes.
1244 benefitFromCodePlacementOpt = true;
1246 // Predictable cmov don't hurt on atom because it's in-order.
1247 predictableSelectIsExpensive = !Subtarget->isAtom();
1249 setPrefFunctionAlignment(4); // 2^4 bytes.
1253 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1254 if (!VT.isVector()) return MVT::i8;
1255 return VT.changeVectorElementTypeToInteger();
1259 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1260 /// the desired ByVal argument alignment.
1261 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1264 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1265 if (VTy->getBitWidth() == 128)
1267 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1268 unsigned EltAlign = 0;
1269 getMaxByValAlign(ATy->getElementType(), EltAlign);
1270 if (EltAlign > MaxAlign)
1271 MaxAlign = EltAlign;
1272 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1273 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1274 unsigned EltAlign = 0;
1275 getMaxByValAlign(STy->getElementType(i), EltAlign);
1276 if (EltAlign > MaxAlign)
1277 MaxAlign = EltAlign;
1284 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1285 /// function arguments in the caller parameter area. For X86, aggregates
1286 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1287 /// are at 4-byte boundaries.
1288 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1289 if (Subtarget->is64Bit()) {
1290 // Max of 8 and alignment of type.
1291 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1298 if (Subtarget->hasSSE1())
1299 getMaxByValAlign(Ty, Align);
1303 /// getOptimalMemOpType - Returns the target specific optimal type for load
1304 /// and store operations as a result of memset, memcpy, and memmove
1305 /// lowering. If DstAlign is zero that means it's safe to destination
1306 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1307 /// means there isn't a need to check it against alignment requirement,
1308 /// probably because the source does not need to be loaded. If
1309 /// 'IsZeroVal' is true, that means it's safe to return a
1310 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1311 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1312 /// constant so it does not need to be loaded.
1313 /// It returns EVT::Other if the type should be determined using generic
1314 /// target-independent logic.
1316 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1317 unsigned DstAlign, unsigned SrcAlign,
1320 MachineFunction &MF) const {
1321 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1322 // linux. This is because the stack realignment code can't handle certain
1323 // cases like PR2962. This should be removed when PR2962 is fixed.
1324 const Function *F = MF.getFunction();
1326 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1328 (Subtarget->isUnalignedMemAccessFast() ||
1329 ((DstAlign == 0 || DstAlign >= 16) &&
1330 (SrcAlign == 0 || SrcAlign >= 16))) &&
1331 Subtarget->getStackAlignment() >= 16) {
1332 if (Subtarget->getStackAlignment() >= 32) {
1333 if (Subtarget->hasAVX2())
1335 if (Subtarget->hasAVX())
1338 if (Subtarget->hasSSE2())
1340 if (Subtarget->hasSSE1())
1342 } else if (!MemcpyStrSrc && Size >= 8 &&
1343 !Subtarget->is64Bit() &&
1344 Subtarget->getStackAlignment() >= 8 &&
1345 Subtarget->hasSSE2()) {
1346 // Do not use f64 to lower memcpy if source is string constant. It's
1347 // better to use i32 to avoid the loads.
1351 if (Subtarget->is64Bit() && Size >= 8)
1356 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1357 /// current function. The returned value is a member of the
1358 /// MachineJumpTableInfo::JTEntryKind enum.
1359 unsigned X86TargetLowering::getJumpTableEncoding() const {
1360 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1362 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1363 Subtarget->isPICStyleGOT())
1364 return MachineJumpTableInfo::EK_Custom32;
1366 // Otherwise, use the normal jump table encoding heuristics.
1367 return TargetLowering::getJumpTableEncoding();
1371 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1372 const MachineBasicBlock *MBB,
1373 unsigned uid,MCContext &Ctx) const{
1374 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1375 Subtarget->isPICStyleGOT());
1376 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1378 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1379 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1382 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1384 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1385 SelectionDAG &DAG) const {
1386 if (!Subtarget->is64Bit())
1387 // This doesn't have DebugLoc associated with it, but is not really the
1388 // same as a Register.
1389 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1393 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1394 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1396 const MCExpr *X86TargetLowering::
1397 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1398 MCContext &Ctx) const {
1399 // X86-64 uses RIP relative addressing based on the jump table label.
1400 if (Subtarget->isPICStyleRIPRel())
1401 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1403 // Otherwise, the reference is relative to the PIC base.
1404 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1407 // FIXME: Why this routine is here? Move to RegInfo!
1408 std::pair<const TargetRegisterClass*, uint8_t>
1409 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1410 const TargetRegisterClass *RRC = 0;
1412 switch (VT.getSimpleVT().SimpleTy) {
1414 return TargetLowering::findRepresentativeClass(VT);
1415 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1416 RRC = Subtarget->is64Bit() ?
1417 (const TargetRegisterClass*)&X86::GR64RegClass :
1418 (const TargetRegisterClass*)&X86::GR32RegClass;
1421 RRC = &X86::VR64RegClass;
1423 case MVT::f32: case MVT::f64:
1424 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1425 case MVT::v4f32: case MVT::v2f64:
1426 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1428 RRC = &X86::VR128RegClass;
1431 return std::make_pair(RRC, Cost);
1434 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1435 unsigned &Offset) const {
1436 if (!Subtarget->isTargetLinux())
1439 if (Subtarget->is64Bit()) {
1440 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1442 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1455 //===----------------------------------------------------------------------===//
1456 // Return Value Calling Convention Implementation
1457 //===----------------------------------------------------------------------===//
1459 #include "X86GenCallingConv.inc"
1462 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1463 MachineFunction &MF, bool isVarArg,
1464 const SmallVectorImpl<ISD::OutputArg> &Outs,
1465 LLVMContext &Context) const {
1466 SmallVector<CCValAssign, 16> RVLocs;
1467 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1469 return CCInfo.CheckReturn(Outs, RetCC_X86);
1473 X86TargetLowering::LowerReturn(SDValue Chain,
1474 CallingConv::ID CallConv, bool isVarArg,
1475 const SmallVectorImpl<ISD::OutputArg> &Outs,
1476 const SmallVectorImpl<SDValue> &OutVals,
1477 DebugLoc dl, SelectionDAG &DAG) const {
1478 MachineFunction &MF = DAG.getMachineFunction();
1479 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1481 SmallVector<CCValAssign, 16> RVLocs;
1482 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1483 RVLocs, *DAG.getContext());
1484 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1486 // Add the regs to the liveout set for the function.
1487 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1488 for (unsigned i = 0; i != RVLocs.size(); ++i)
1489 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1490 MRI.addLiveOut(RVLocs[i].getLocReg());
1494 SmallVector<SDValue, 6> RetOps;
1495 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1496 // Operand #1 = Bytes To Pop
1497 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1500 // Copy the result values into the output registers.
1501 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1502 CCValAssign &VA = RVLocs[i];
1503 assert(VA.isRegLoc() && "Can only return in registers!");
1504 SDValue ValToCopy = OutVals[i];
1505 EVT ValVT = ValToCopy.getValueType();
1507 // If this is x86-64, and we disabled SSE, we can't return FP values,
1508 // or SSE or MMX vectors.
1509 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1510 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1511 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1512 report_fatal_error("SSE register return with SSE disabled");
1514 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1515 // llvm-gcc has never done it right and no one has noticed, so this
1516 // should be OK for now.
1517 if (ValVT == MVT::f64 &&
1518 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1519 report_fatal_error("SSE2 register return with SSE2 disabled");
1521 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1522 // the RET instruction and handled by the FP Stackifier.
1523 if (VA.getLocReg() == X86::ST0 ||
1524 VA.getLocReg() == X86::ST1) {
1525 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1526 // change the value to the FP stack register class.
1527 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1528 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1529 RetOps.push_back(ValToCopy);
1530 // Don't emit a copytoreg.
1534 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1535 // which is returned in RAX / RDX.
1536 if (Subtarget->is64Bit()) {
1537 if (ValVT == MVT::x86mmx) {
1538 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1539 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1540 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1542 // If we don't have SSE2 available, convert to v4f32 so the generated
1543 // register is legal.
1544 if (!Subtarget->hasSSE2())
1545 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1550 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1551 Flag = Chain.getValue(1);
1554 // The x86-64 ABI for returning structs by value requires that we copy
1555 // the sret argument into %rax for the return. We saved the argument into
1556 // a virtual register in the entry block, so now we copy the value out
1558 if (Subtarget->is64Bit() &&
1559 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1560 MachineFunction &MF = DAG.getMachineFunction();
1561 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1562 unsigned Reg = FuncInfo->getSRetReturnReg();
1564 "SRetReturnReg should have been set in LowerFormalArguments().");
1565 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1567 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1568 Flag = Chain.getValue(1);
1570 // RAX now acts like a return value.
1571 MRI.addLiveOut(X86::RAX);
1574 RetOps[0] = Chain; // Update chain.
1576 // Add the flag if we have it.
1578 RetOps.push_back(Flag);
1580 return DAG.getNode(X86ISD::RET_FLAG, dl,
1581 MVT::Other, &RetOps[0], RetOps.size());
1584 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1585 if (N->getNumValues() != 1)
1587 if (!N->hasNUsesOfValue(1, 0))
1590 SDValue TCChain = Chain;
1591 SDNode *Copy = *N->use_begin();
1592 if (Copy->getOpcode() == ISD::CopyToReg) {
1593 // If the copy has a glue operand, we conservatively assume it isn't safe to
1594 // perform a tail call.
1595 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1597 TCChain = Copy->getOperand(0);
1598 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1601 bool HasRet = false;
1602 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1604 if (UI->getOpcode() != X86ISD::RET_FLAG)
1617 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1618 ISD::NodeType ExtendKind) const {
1620 // TODO: Is this also valid on 32-bit?
1621 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1622 ReturnMVT = MVT::i8;
1624 ReturnMVT = MVT::i32;
1626 EVT MinVT = getRegisterType(Context, ReturnMVT);
1627 return VT.bitsLT(MinVT) ? MinVT : VT;
1630 /// LowerCallResult - Lower the result values of a call into the
1631 /// appropriate copies out of appropriate physical registers.
1634 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1635 CallingConv::ID CallConv, bool isVarArg,
1636 const SmallVectorImpl<ISD::InputArg> &Ins,
1637 DebugLoc dl, SelectionDAG &DAG,
1638 SmallVectorImpl<SDValue> &InVals) const {
1640 // Assign locations to each value returned by this call.
1641 SmallVector<CCValAssign, 16> RVLocs;
1642 bool Is64Bit = Subtarget->is64Bit();
1643 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1644 getTargetMachine(), RVLocs, *DAG.getContext());
1645 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1647 // Copy all of the result registers out of their specified physreg.
1648 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1649 CCValAssign &VA = RVLocs[i];
1650 EVT CopyVT = VA.getValVT();
1652 // If this is x86-64, and we disabled SSE, we can't return FP values
1653 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1654 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1655 report_fatal_error("SSE register return with SSE disabled");
1660 // If this is a call to a function that returns an fp value on the floating
1661 // point stack, we must guarantee the the value is popped from the stack, so
1662 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1663 // if the return value is not used. We use the FpPOP_RETVAL instruction
1665 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1666 // If we prefer to use the value in xmm registers, copy it out as f80 and
1667 // use a truncate to move it from fp stack reg to xmm reg.
1668 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1669 SDValue Ops[] = { Chain, InFlag };
1670 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1671 MVT::Other, MVT::Glue, Ops, 2), 1);
1672 Val = Chain.getValue(0);
1674 // Round the f80 to the right size, which also moves it to the appropriate
1676 if (CopyVT != VA.getValVT())
1677 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1678 // This truncation won't change the value.
1679 DAG.getIntPtrConstant(1));
1681 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1682 CopyVT, InFlag).getValue(1);
1683 Val = Chain.getValue(0);
1685 InFlag = Chain.getValue(2);
1686 InVals.push_back(Val);
1693 //===----------------------------------------------------------------------===//
1694 // C & StdCall & Fast Calling Convention implementation
1695 //===----------------------------------------------------------------------===//
1696 // StdCall calling convention seems to be standard for many Windows' API
1697 // routines and around. It differs from C calling convention just a little:
1698 // callee should clean up the stack, not caller. Symbols should be also
1699 // decorated in some fancy way :) It doesn't support any vector arguments.
1700 // For info on fast calling convention see Fast Calling Convention (tail call)
1701 // implementation LowerX86_32FastCCCallTo.
1703 /// CallIsStructReturn - Determines whether a call uses struct return
1705 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1709 return Outs[0].Flags.isSRet();
1712 /// ArgsAreStructReturn - Determines whether a function uses struct
1713 /// return semantics.
1715 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1719 return Ins[0].Flags.isSRet();
1722 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1723 /// by "Src" to address "Dst" with size and alignment information specified by
1724 /// the specific parameter attribute. The copy will be passed as a byval
1725 /// function parameter.
1727 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1728 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1730 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1732 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1733 /*isVolatile*/false, /*AlwaysInline=*/true,
1734 MachinePointerInfo(), MachinePointerInfo());
1737 /// IsTailCallConvention - Return true if the calling convention is one that
1738 /// supports tail call optimization.
1739 static bool IsTailCallConvention(CallingConv::ID CC) {
1740 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1743 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1744 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1748 CallingConv::ID CalleeCC = CS.getCallingConv();
1749 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1755 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1756 /// a tailcall target by changing its ABI.
1757 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1758 bool GuaranteedTailCallOpt) {
1759 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1763 X86TargetLowering::LowerMemArgument(SDValue Chain,
1764 CallingConv::ID CallConv,
1765 const SmallVectorImpl<ISD::InputArg> &Ins,
1766 DebugLoc dl, SelectionDAG &DAG,
1767 const CCValAssign &VA,
1768 MachineFrameInfo *MFI,
1770 // Create the nodes corresponding to a load from this parameter slot.
1771 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1772 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1773 getTargetMachine().Options.GuaranteedTailCallOpt);
1774 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1777 // If value is passed by pointer we have address passed instead of the value
1779 if (VA.getLocInfo() == CCValAssign::Indirect)
1780 ValVT = VA.getLocVT();
1782 ValVT = VA.getValVT();
1784 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1785 // changed with more analysis.
1786 // In case of tail call optimization mark all arguments mutable. Since they
1787 // could be overwritten by lowering of arguments in case of a tail call.
1788 if (Flags.isByVal()) {
1789 unsigned Bytes = Flags.getByValSize();
1790 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1791 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1792 return DAG.getFrameIndex(FI, getPointerTy());
1794 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1795 VA.getLocMemOffset(), isImmutable);
1796 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1797 return DAG.getLoad(ValVT, dl, Chain, FIN,
1798 MachinePointerInfo::getFixedStack(FI),
1799 false, false, false, 0);
1804 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1805 CallingConv::ID CallConv,
1807 const SmallVectorImpl<ISD::InputArg> &Ins,
1810 SmallVectorImpl<SDValue> &InVals)
1812 MachineFunction &MF = DAG.getMachineFunction();
1813 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1815 const Function* Fn = MF.getFunction();
1816 if (Fn->hasExternalLinkage() &&
1817 Subtarget->isTargetCygMing() &&
1818 Fn->getName() == "main")
1819 FuncInfo->setForceFramePointer(true);
1821 MachineFrameInfo *MFI = MF.getFrameInfo();
1822 bool Is64Bit = Subtarget->is64Bit();
1823 bool IsWindows = Subtarget->isTargetWindows();
1824 bool IsWin64 = Subtarget->isTargetWin64();
1826 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1827 "Var args not supported with calling convention fastcc or ghc");
1829 // Assign locations to all of the incoming arguments.
1830 SmallVector<CCValAssign, 16> ArgLocs;
1831 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1832 ArgLocs, *DAG.getContext());
1834 // Allocate shadow area for Win64
1836 CCInfo.AllocateStack(32, 8);
1839 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1841 unsigned LastVal = ~0U;
1843 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1844 CCValAssign &VA = ArgLocs[i];
1845 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1847 assert(VA.getValNo() != LastVal &&
1848 "Don't support value assigned to multiple locs yet");
1850 LastVal = VA.getValNo();
1852 if (VA.isRegLoc()) {
1853 EVT RegVT = VA.getLocVT();
1854 const TargetRegisterClass *RC;
1855 if (RegVT == MVT::i32)
1856 RC = &X86::GR32RegClass;
1857 else if (Is64Bit && RegVT == MVT::i64)
1858 RC = &X86::GR64RegClass;
1859 else if (RegVT == MVT::f32)
1860 RC = &X86::FR32RegClass;
1861 else if (RegVT == MVT::f64)
1862 RC = &X86::FR64RegClass;
1863 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1864 RC = &X86::VR256RegClass;
1865 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1866 RC = &X86::VR128RegClass;
1867 else if (RegVT == MVT::x86mmx)
1868 RC = &X86::VR64RegClass;
1870 llvm_unreachable("Unknown argument type!");
1872 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1873 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1875 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1876 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1878 if (VA.getLocInfo() == CCValAssign::SExt)
1879 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1880 DAG.getValueType(VA.getValVT()));
1881 else if (VA.getLocInfo() == CCValAssign::ZExt)
1882 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1883 DAG.getValueType(VA.getValVT()));
1884 else if (VA.getLocInfo() == CCValAssign::BCvt)
1885 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1887 if (VA.isExtInLoc()) {
1888 // Handle MMX values passed in XMM regs.
1889 if (RegVT.isVector()) {
1890 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1893 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1896 assert(VA.isMemLoc());
1897 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1900 // If value is passed via pointer - do a load.
1901 if (VA.getLocInfo() == CCValAssign::Indirect)
1902 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1903 MachinePointerInfo(), false, false, false, 0);
1905 InVals.push_back(ArgValue);
1908 // The x86-64 ABI for returning structs by value requires that we copy
1909 // the sret argument into %rax for the return. Save the argument into
1910 // a virtual register so that we can access it from the return points.
1911 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1912 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1913 unsigned Reg = FuncInfo->getSRetReturnReg();
1915 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1916 FuncInfo->setSRetReturnReg(Reg);
1918 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1919 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1922 unsigned StackSize = CCInfo.getNextStackOffset();
1923 // Align stack specially for tail calls.
1924 if (FuncIsMadeTailCallSafe(CallConv,
1925 MF.getTarget().Options.GuaranteedTailCallOpt))
1926 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1928 // If the function takes variable number of arguments, make a frame index for
1929 // the start of the first vararg value... for expansion of llvm.va_start.
1931 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1932 CallConv != CallingConv::X86_ThisCall)) {
1933 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1936 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1938 // FIXME: We should really autogenerate these arrays
1939 static const uint16_t GPR64ArgRegsWin64[] = {
1940 X86::RCX, X86::RDX, X86::R8, X86::R9
1942 static const uint16_t GPR64ArgRegs64Bit[] = {
1943 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1945 static const uint16_t XMMArgRegs64Bit[] = {
1946 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1947 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1949 const uint16_t *GPR64ArgRegs;
1950 unsigned NumXMMRegs = 0;
1953 // The XMM registers which might contain var arg parameters are shadowed
1954 // in their paired GPR. So we only need to save the GPR to their home
1956 TotalNumIntRegs = 4;
1957 GPR64ArgRegs = GPR64ArgRegsWin64;
1959 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1960 GPR64ArgRegs = GPR64ArgRegs64Bit;
1962 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
1965 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1968 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1969 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1970 "SSE register cannot be used when SSE is disabled!");
1971 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
1972 NoImplicitFloatOps) &&
1973 "SSE register cannot be used when SSE is disabled!");
1974 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
1975 !Subtarget->hasSSE1())
1976 // Kernel mode asks for SSE to be disabled, so don't push them
1978 TotalNumXMMRegs = 0;
1981 const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1982 // Get to the caller-allocated home save location. Add 8 to account
1983 // for the return address.
1984 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1985 FuncInfo->setRegSaveFrameIndex(
1986 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1987 // Fixup to set vararg frame on shadow area (4 x i64).
1989 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1991 // For X86-64, if there are vararg parameters that are passed via
1992 // registers, then we must store them to their spots on the stack so
1993 // they may be loaded by deferencing the result of va_next.
1994 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1995 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1996 FuncInfo->setRegSaveFrameIndex(
1997 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2001 // Store the integer parameter registers.
2002 SmallVector<SDValue, 8> MemOps;
2003 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2005 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2006 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2007 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2008 DAG.getIntPtrConstant(Offset));
2009 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2010 &X86::GR64RegClass);
2011 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2013 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2014 MachinePointerInfo::getFixedStack(
2015 FuncInfo->getRegSaveFrameIndex(), Offset),
2017 MemOps.push_back(Store);
2021 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2022 // Now store the XMM (fp + vector) parameter registers.
2023 SmallVector<SDValue, 11> SaveXMMOps;
2024 SaveXMMOps.push_back(Chain);
2026 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2027 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2028 SaveXMMOps.push_back(ALVal);
2030 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2031 FuncInfo->getRegSaveFrameIndex()));
2032 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2033 FuncInfo->getVarArgsFPOffset()));
2035 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2036 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2037 &X86::VR128RegClass);
2038 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2039 SaveXMMOps.push_back(Val);
2041 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2043 &SaveXMMOps[0], SaveXMMOps.size()));
2046 if (!MemOps.empty())
2047 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2048 &MemOps[0], MemOps.size());
2052 // Some CCs need callee pop.
2053 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2054 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2055 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2057 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2058 // If this is an sret function, the return should pop the hidden pointer.
2059 if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2060 ArgsAreStructReturn(Ins))
2061 FuncInfo->setBytesToPopOnReturn(4);
2065 // RegSaveFrameIndex is X86-64 only.
2066 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2067 if (CallConv == CallingConv::X86_FastCall ||
2068 CallConv == CallingConv::X86_ThisCall)
2069 // fastcc functions can't have varargs.
2070 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2073 FuncInfo->setArgumentStackSize(StackSize);
2079 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2080 SDValue StackPtr, SDValue Arg,
2081 DebugLoc dl, SelectionDAG &DAG,
2082 const CCValAssign &VA,
2083 ISD::ArgFlagsTy Flags) const {
2084 unsigned LocMemOffset = VA.getLocMemOffset();
2085 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2086 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2087 if (Flags.isByVal())
2088 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2090 return DAG.getStore(Chain, dl, Arg, PtrOff,
2091 MachinePointerInfo::getStack(LocMemOffset),
2095 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2096 /// optimization is performed and it is required.
2098 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2099 SDValue &OutRetAddr, SDValue Chain,
2100 bool IsTailCall, bool Is64Bit,
2101 int FPDiff, DebugLoc dl) const {
2102 // Adjust the Return address stack slot.
2103 EVT VT = getPointerTy();
2104 OutRetAddr = getReturnAddressFrameIndex(DAG);
2106 // Load the "old" Return address.
2107 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2108 false, false, false, 0);
2109 return SDValue(OutRetAddr.getNode(), 1);
2112 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2113 /// optimization is performed and it is required (FPDiff!=0).
2115 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2116 SDValue Chain, SDValue RetAddrFrIdx,
2117 bool Is64Bit, int FPDiff, DebugLoc dl) {
2118 // Store the return address to the appropriate stack slot.
2119 if (!FPDiff) return Chain;
2120 // Calculate the new stack slot for the return address.
2121 int SlotSize = Is64Bit ? 8 : 4;
2122 int NewReturnAddrFI =
2123 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2124 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2125 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2126 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2127 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2133 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2134 SmallVectorImpl<SDValue> &InVals) const {
2135 SelectionDAG &DAG = CLI.DAG;
2136 DebugLoc &dl = CLI.DL;
2137 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2138 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2139 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2140 SDValue Chain = CLI.Chain;
2141 SDValue Callee = CLI.Callee;
2142 CallingConv::ID CallConv = CLI.CallConv;
2143 bool &isTailCall = CLI.IsTailCall;
2144 bool isVarArg = CLI.IsVarArg;
2146 MachineFunction &MF = DAG.getMachineFunction();
2147 bool Is64Bit = Subtarget->is64Bit();
2148 bool IsWin64 = Subtarget->isTargetWin64();
2149 bool IsWindows = Subtarget->isTargetWindows();
2150 bool IsStructRet = CallIsStructReturn(Outs);
2151 bool IsSibcall = false;
2153 if (MF.getTarget().Options.DisableTailCalls)
2157 // Check if it's really possible to do a tail call.
2158 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2159 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2160 Outs, OutVals, Ins, DAG);
2162 // Sibcalls are automatically detected tailcalls which do not require
2164 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2171 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2172 "Var args not supported with calling convention fastcc or ghc");
2174 // Analyze operands of the call, assigning locations to each operand.
2175 SmallVector<CCValAssign, 16> ArgLocs;
2176 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2177 ArgLocs, *DAG.getContext());
2179 // Allocate shadow area for Win64
2181 CCInfo.AllocateStack(32, 8);
2184 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2186 // Get a count of how many bytes are to be pushed on the stack.
2187 unsigned NumBytes = CCInfo.getNextStackOffset();
2189 // This is a sibcall. The memory operands are available in caller's
2190 // own caller's stack.
2192 else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2193 IsTailCallConvention(CallConv))
2194 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2197 if (isTailCall && !IsSibcall) {
2198 // Lower arguments at fp - stackoffset + fpdiff.
2199 unsigned NumBytesCallerPushed =
2200 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2201 FPDiff = NumBytesCallerPushed - NumBytes;
2203 // Set the delta of movement of the returnaddr stackslot.
2204 // But only set if delta is greater than previous delta.
2205 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2206 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2210 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2212 SDValue RetAddrFrIdx;
2213 // Load return address for tail calls.
2214 if (isTailCall && FPDiff)
2215 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2216 Is64Bit, FPDiff, dl);
2218 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2219 SmallVector<SDValue, 8> MemOpChains;
2222 // Walk the register/memloc assignments, inserting copies/loads. In the case
2223 // of tail call optimization arguments are handle later.
2224 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2225 CCValAssign &VA = ArgLocs[i];
2226 EVT RegVT = VA.getLocVT();
2227 SDValue Arg = OutVals[i];
2228 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2229 bool isByVal = Flags.isByVal();
2231 // Promote the value if needed.
2232 switch (VA.getLocInfo()) {
2233 default: llvm_unreachable("Unknown loc info!");
2234 case CCValAssign::Full: break;
2235 case CCValAssign::SExt:
2236 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2238 case CCValAssign::ZExt:
2239 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2241 case CCValAssign::AExt:
2242 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2243 // Special case: passing MMX values in XMM registers.
2244 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2245 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2246 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2248 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2250 case CCValAssign::BCvt:
2251 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2253 case CCValAssign::Indirect: {
2254 // Store the argument.
2255 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2256 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2257 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2258 MachinePointerInfo::getFixedStack(FI),
2265 if (VA.isRegLoc()) {
2266 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2267 if (isVarArg && IsWin64) {
2268 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2269 // shadow reg if callee is a varargs function.
2270 unsigned ShadowReg = 0;
2271 switch (VA.getLocReg()) {
2272 case X86::XMM0: ShadowReg = X86::RCX; break;
2273 case X86::XMM1: ShadowReg = X86::RDX; break;
2274 case X86::XMM2: ShadowReg = X86::R8; break;
2275 case X86::XMM3: ShadowReg = X86::R9; break;
2278 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2280 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2281 assert(VA.isMemLoc());
2282 if (StackPtr.getNode() == 0)
2283 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2284 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2285 dl, DAG, VA, Flags));
2289 if (!MemOpChains.empty())
2290 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2291 &MemOpChains[0], MemOpChains.size());
2293 // Build a sequence of copy-to-reg nodes chained together with token chain
2294 // and flag operands which copy the outgoing args into registers.
2296 // Tail call byval lowering might overwrite argument registers so in case of
2297 // tail call optimization the copies to registers are lowered later.
2299 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2300 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2301 RegsToPass[i].second, InFlag);
2302 InFlag = Chain.getValue(1);
2305 if (Subtarget->isPICStyleGOT()) {
2306 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2309 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2310 DAG.getNode(X86ISD::GlobalBaseReg,
2311 DebugLoc(), getPointerTy()),
2313 InFlag = Chain.getValue(1);
2315 // If we are tail calling and generating PIC/GOT style code load the
2316 // address of the callee into ECX. The value in ecx is used as target of
2317 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2318 // for tail calls on PIC/GOT architectures. Normally we would just put the
2319 // address of GOT into ebx and then call target@PLT. But for tail calls
2320 // ebx would be restored (since ebx is callee saved) before jumping to the
2323 // Note: The actual moving to ECX is done further down.
2324 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2325 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2326 !G->getGlobal()->hasProtectedVisibility())
2327 Callee = LowerGlobalAddress(Callee, DAG);
2328 else if (isa<ExternalSymbolSDNode>(Callee))
2329 Callee = LowerExternalSymbol(Callee, DAG);
2333 if (Is64Bit && isVarArg && !IsWin64) {
2334 // From AMD64 ABI document:
2335 // For calls that may call functions that use varargs or stdargs
2336 // (prototype-less calls or calls to functions containing ellipsis (...) in
2337 // the declaration) %al is used as hidden argument to specify the number
2338 // of SSE registers used. The contents of %al do not need to match exactly
2339 // the number of registers, but must be an ubound on the number of SSE
2340 // registers used and is in the range 0 - 8 inclusive.
2342 // Count the number of XMM registers allocated.
2343 static const uint16_t XMMArgRegs[] = {
2344 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2345 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2347 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2348 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2349 && "SSE registers cannot be used when SSE is disabled");
2351 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2352 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2353 InFlag = Chain.getValue(1);
2357 // For tail calls lower the arguments to the 'real' stack slot.
2359 // Force all the incoming stack arguments to be loaded from the stack
2360 // before any new outgoing arguments are stored to the stack, because the
2361 // outgoing stack slots may alias the incoming argument stack slots, and
2362 // the alias isn't otherwise explicit. This is slightly more conservative
2363 // than necessary, because it means that each store effectively depends
2364 // on every argument instead of just those arguments it would clobber.
2365 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2367 SmallVector<SDValue, 8> MemOpChains2;
2370 // Do not flag preceding copytoreg stuff together with the following stuff.
2372 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2373 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2374 CCValAssign &VA = ArgLocs[i];
2377 assert(VA.isMemLoc());
2378 SDValue Arg = OutVals[i];
2379 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2380 // Create frame index.
2381 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2382 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2383 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2384 FIN = DAG.getFrameIndex(FI, getPointerTy());
2386 if (Flags.isByVal()) {
2387 // Copy relative to framepointer.
2388 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2389 if (StackPtr.getNode() == 0)
2390 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2392 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2394 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2398 // Store relative to framepointer.
2399 MemOpChains2.push_back(
2400 DAG.getStore(ArgChain, dl, Arg, FIN,
2401 MachinePointerInfo::getFixedStack(FI),
2407 if (!MemOpChains2.empty())
2408 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2409 &MemOpChains2[0], MemOpChains2.size());
2411 // Copy arguments to their registers.
2412 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2413 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2414 RegsToPass[i].second, InFlag);
2415 InFlag = Chain.getValue(1);
2419 // Store the return address to the appropriate stack slot.
2420 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2424 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2425 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2426 // In the 64-bit large code model, we have to make all calls
2427 // through a register, since the call instruction's 32-bit
2428 // pc-relative offset may not be large enough to hold the whole
2430 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2431 // If the callee is a GlobalAddress node (quite common, every direct call
2432 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2435 // We should use extra load for direct calls to dllimported functions in
2437 const GlobalValue *GV = G->getGlobal();
2438 if (!GV->hasDLLImportLinkage()) {
2439 unsigned char OpFlags = 0;
2440 bool ExtraLoad = false;
2441 unsigned WrapperKind = ISD::DELETED_NODE;
2443 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2444 // external symbols most go through the PLT in PIC mode. If the symbol
2445 // has hidden or protected visibility, or if it is static or local, then
2446 // we don't need to use the PLT - we can directly call it.
2447 if (Subtarget->isTargetELF() &&
2448 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2449 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2450 OpFlags = X86II::MO_PLT;
2451 } else if (Subtarget->isPICStyleStubAny() &&
2452 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2453 (!Subtarget->getTargetTriple().isMacOSX() ||
2454 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2455 // PC-relative references to external symbols should go through $stub,
2456 // unless we're building with the leopard linker or later, which
2457 // automatically synthesizes these stubs.
2458 OpFlags = X86II::MO_DARWIN_STUB;
2459 } else if (Subtarget->isPICStyleRIPRel() &&
2460 isa<Function>(GV) &&
2461 cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2462 // If the function is marked as non-lazy, generate an indirect call
2463 // which loads from the GOT directly. This avoids runtime overhead
2464 // at the cost of eager binding (and one extra byte of encoding).
2465 OpFlags = X86II::MO_GOTPCREL;
2466 WrapperKind = X86ISD::WrapperRIP;
2470 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2471 G->getOffset(), OpFlags);
2473 // Add a wrapper if needed.
2474 if (WrapperKind != ISD::DELETED_NODE)
2475 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2476 // Add extra indirection if needed.
2478 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2479 MachinePointerInfo::getGOT(),
2480 false, false, false, 0);
2482 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2483 unsigned char OpFlags = 0;
2485 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2486 // external symbols should go through the PLT.
2487 if (Subtarget->isTargetELF() &&
2488 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2489 OpFlags = X86II::MO_PLT;
2490 } else if (Subtarget->isPICStyleStubAny() &&
2491 (!Subtarget->getTargetTriple().isMacOSX() ||
2492 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2493 // PC-relative references to external symbols should go through $stub,
2494 // unless we're building with the leopard linker or later, which
2495 // automatically synthesizes these stubs.
2496 OpFlags = X86II::MO_DARWIN_STUB;
2499 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2503 // Returns a chain & a flag for retval copy to use.
2504 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2505 SmallVector<SDValue, 8> Ops;
2507 if (!IsSibcall && isTailCall) {
2508 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2509 DAG.getIntPtrConstant(0, true), InFlag);
2510 InFlag = Chain.getValue(1);
2513 Ops.push_back(Chain);
2514 Ops.push_back(Callee);
2517 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2519 // Add argument registers to the end of the list so that they are known live
2521 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2522 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2523 RegsToPass[i].second.getValueType()));
2525 // Add an implicit use GOT pointer in EBX.
2526 if (!isTailCall && Subtarget->isPICStyleGOT())
2527 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2529 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2530 if (Is64Bit && isVarArg && !IsWin64)
2531 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2533 // Add a register mask operand representing the call-preserved registers.
2534 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2535 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2536 assert(Mask && "Missing call preserved mask for calling convention");
2537 Ops.push_back(DAG.getRegisterMask(Mask));
2539 if (InFlag.getNode())
2540 Ops.push_back(InFlag);
2544 //// If this is the first return lowered for this function, add the regs
2545 //// to the liveout set for the function.
2546 // This isn't right, although it's probably harmless on x86; liveouts
2547 // should be computed from returns not tail calls. Consider a void
2548 // function making a tail call to a function returning int.
2549 return DAG.getNode(X86ISD::TC_RETURN, dl,
2550 NodeTys, &Ops[0], Ops.size());
2553 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2554 InFlag = Chain.getValue(1);
2556 // Create the CALLSEQ_END node.
2557 unsigned NumBytesForCalleeToPush;
2558 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2559 getTargetMachine().Options.GuaranteedTailCallOpt))
2560 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2561 else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2563 // If this is a call to a struct-return function, the callee
2564 // pops the hidden struct pointer, so we have to push it back.
2565 // This is common for Darwin/X86, Linux & Mingw32 targets.
2566 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2567 NumBytesForCalleeToPush = 4;
2569 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2571 // Returns a flag for retval copy to use.
2573 Chain = DAG.getCALLSEQ_END(Chain,
2574 DAG.getIntPtrConstant(NumBytes, true),
2575 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2578 InFlag = Chain.getValue(1);
2581 // Handle result values, copying them out of physregs into vregs that we
2583 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2584 Ins, dl, DAG, InVals);
2588 //===----------------------------------------------------------------------===//
2589 // Fast Calling Convention (tail call) implementation
2590 //===----------------------------------------------------------------------===//
2592 // Like std call, callee cleans arguments, convention except that ECX is
2593 // reserved for storing the tail called function address. Only 2 registers are
2594 // free for argument passing (inreg). Tail call optimization is performed
2596 // * tailcallopt is enabled
2597 // * caller/callee are fastcc
2598 // On X86_64 architecture with GOT-style position independent code only local
2599 // (within module) calls are supported at the moment.
2600 // To keep the stack aligned according to platform abi the function
2601 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2602 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2603 // If a tail called function callee has more arguments than the caller the
2604 // caller needs to make sure that there is room to move the RETADDR to. This is
2605 // achieved by reserving an area the size of the argument delta right after the
2606 // original REtADDR, but before the saved framepointer or the spilled registers
2607 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2619 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2620 /// for a 16 byte align requirement.
2622 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2623 SelectionDAG& DAG) const {
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 const TargetMachine &TM = MF.getTarget();
2626 const TargetFrameLowering &TFI = *TM.getFrameLowering();
2627 unsigned StackAlignment = TFI.getStackAlignment();
2628 uint64_t AlignMask = StackAlignment - 1;
2629 int64_t Offset = StackSize;
2630 uint64_t SlotSize = TD->getPointerSize();
2631 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2632 // Number smaller than 12 so just add the difference.
2633 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2635 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2636 Offset = ((~AlignMask) & Offset) + StackAlignment +
2637 (StackAlignment-SlotSize);
2642 /// MatchingStackOffset - Return true if the given stack call argument is
2643 /// already available in the same position (relatively) of the caller's
2644 /// incoming argument stack.
2646 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2647 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2648 const X86InstrInfo *TII) {
2649 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2651 if (Arg.getOpcode() == ISD::CopyFromReg) {
2652 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2653 if (!TargetRegisterInfo::isVirtualRegister(VR))
2655 MachineInstr *Def = MRI->getVRegDef(VR);
2658 if (!Flags.isByVal()) {
2659 if (!TII->isLoadFromStackSlot(Def, FI))
2662 unsigned Opcode = Def->getOpcode();
2663 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2664 Def->getOperand(1).isFI()) {
2665 FI = Def->getOperand(1).getIndex();
2666 Bytes = Flags.getByValSize();
2670 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2671 if (Flags.isByVal())
2672 // ByVal argument is passed in as a pointer but it's now being
2673 // dereferenced. e.g.
2674 // define @foo(%struct.X* %A) {
2675 // tail call @bar(%struct.X* byval %A)
2678 SDValue Ptr = Ld->getBasePtr();
2679 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2682 FI = FINode->getIndex();
2683 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2684 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2685 FI = FINode->getIndex();
2686 Bytes = Flags.getByValSize();
2690 assert(FI != INT_MAX);
2691 if (!MFI->isFixedObjectIndex(FI))
2693 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2696 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2697 /// for tail call optimization. Targets which want to do tail call
2698 /// optimization should implement this function.
2700 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2701 CallingConv::ID CalleeCC,
2703 bool isCalleeStructRet,
2704 bool isCallerStructRet,
2705 const SmallVectorImpl<ISD::OutputArg> &Outs,
2706 const SmallVectorImpl<SDValue> &OutVals,
2707 const SmallVectorImpl<ISD::InputArg> &Ins,
2708 SelectionDAG& DAG) const {
2709 if (!IsTailCallConvention(CalleeCC) &&
2710 CalleeCC != CallingConv::C)
2713 // If -tailcallopt is specified, make fastcc functions tail-callable.
2714 const MachineFunction &MF = DAG.getMachineFunction();
2715 const Function *CallerF = DAG.getMachineFunction().getFunction();
2716 CallingConv::ID CallerCC = CallerF->getCallingConv();
2717 bool CCMatch = CallerCC == CalleeCC;
2719 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2720 if (IsTailCallConvention(CalleeCC) && CCMatch)
2725 // Look for obvious safe cases to perform tail call optimization that do not
2726 // require ABI changes. This is what gcc calls sibcall.
2728 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2729 // emit a special epilogue.
2730 if (RegInfo->needsStackRealignment(MF))
2733 // Also avoid sibcall optimization if either caller or callee uses struct
2734 // return semantics.
2735 if (isCalleeStructRet || isCallerStructRet)
2738 // An stdcall caller is expected to clean up its arguments; the callee
2739 // isn't going to do that.
2740 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2743 // Do not sibcall optimize vararg calls unless all arguments are passed via
2745 if (isVarArg && !Outs.empty()) {
2747 // Optimizing for varargs on Win64 is unlikely to be safe without
2748 // additional testing.
2749 if (Subtarget->isTargetWin64())
2752 SmallVector<CCValAssign, 16> ArgLocs;
2753 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2754 getTargetMachine(), ArgLocs, *DAG.getContext());
2756 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2757 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2758 if (!ArgLocs[i].isRegLoc())
2762 // If the call result is in ST0 / ST1, it needs to be popped off the x87
2763 // stack. Therefore, if it's not used by the call it is not safe to optimize
2764 // this into a sibcall.
2765 bool Unused = false;
2766 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2773 SmallVector<CCValAssign, 16> RVLocs;
2774 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2775 getTargetMachine(), RVLocs, *DAG.getContext());
2776 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2777 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2778 CCValAssign &VA = RVLocs[i];
2779 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2784 // If the calling conventions do not match, then we'd better make sure the
2785 // results are returned in the same way as what the caller expects.
2787 SmallVector<CCValAssign, 16> RVLocs1;
2788 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2789 getTargetMachine(), RVLocs1, *DAG.getContext());
2790 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2792 SmallVector<CCValAssign, 16> RVLocs2;
2793 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2794 getTargetMachine(), RVLocs2, *DAG.getContext());
2795 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2797 if (RVLocs1.size() != RVLocs2.size())
2799 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2800 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2802 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2804 if (RVLocs1[i].isRegLoc()) {
2805 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2808 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2814 // If the callee takes no arguments then go on to check the results of the
2816 if (!Outs.empty()) {
2817 // Check if stack adjustment is needed. For now, do not do this if any
2818 // argument is passed on the stack.
2819 SmallVector<CCValAssign, 16> ArgLocs;
2820 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2821 getTargetMachine(), ArgLocs, *DAG.getContext());
2823 // Allocate shadow area for Win64
2824 if (Subtarget->isTargetWin64()) {
2825 CCInfo.AllocateStack(32, 8);
2828 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2829 if (CCInfo.getNextStackOffset()) {
2830 MachineFunction &MF = DAG.getMachineFunction();
2831 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2834 // Check if the arguments are already laid out in the right way as
2835 // the caller's fixed stack objects.
2836 MachineFrameInfo *MFI = MF.getFrameInfo();
2837 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2838 const X86InstrInfo *TII =
2839 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2840 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2841 CCValAssign &VA = ArgLocs[i];
2842 SDValue Arg = OutVals[i];
2843 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2844 if (VA.getLocInfo() == CCValAssign::Indirect)
2846 if (!VA.isRegLoc()) {
2847 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2854 // If the tailcall address may be in a register, then make sure it's
2855 // possible to register allocate for it. In 32-bit, the call address can
2856 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2857 // callee-saved registers are restored. These happen to be the same
2858 // registers used to pass 'inreg' arguments so watch out for those.
2859 if (!Subtarget->is64Bit() &&
2860 !isa<GlobalAddressSDNode>(Callee) &&
2861 !isa<ExternalSymbolSDNode>(Callee)) {
2862 unsigned NumInRegs = 0;
2863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2864 CCValAssign &VA = ArgLocs[i];
2867 unsigned Reg = VA.getLocReg();
2870 case X86::EAX: case X86::EDX: case X86::ECX:
2871 if (++NumInRegs == 3)
2883 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2884 return X86::createFastISel(funcInfo);
2888 //===----------------------------------------------------------------------===//
2889 // Other Lowering Hooks
2890 //===----------------------------------------------------------------------===//
2892 static bool MayFoldLoad(SDValue Op) {
2893 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2896 static bool MayFoldIntoStore(SDValue Op) {
2897 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2900 static bool isTargetShuffle(unsigned Opcode) {
2902 default: return false;
2903 case X86ISD::PSHUFD:
2904 case X86ISD::PSHUFHW:
2905 case X86ISD::PSHUFLW:
2907 case X86ISD::PALIGN:
2908 case X86ISD::MOVLHPS:
2909 case X86ISD::MOVLHPD:
2910 case X86ISD::MOVHLPS:
2911 case X86ISD::MOVLPS:
2912 case X86ISD::MOVLPD:
2913 case X86ISD::MOVSHDUP:
2914 case X86ISD::MOVSLDUP:
2915 case X86ISD::MOVDDUP:
2918 case X86ISD::UNPCKL:
2919 case X86ISD::UNPCKH:
2920 case X86ISD::VPERMILP:
2921 case X86ISD::VPERM2X128:
2922 case X86ISD::VPERMI:
2927 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2928 SDValue V1, SelectionDAG &DAG) {
2930 default: llvm_unreachable("Unknown x86 shuffle node");
2931 case X86ISD::MOVSHDUP:
2932 case X86ISD::MOVSLDUP:
2933 case X86ISD::MOVDDUP:
2934 return DAG.getNode(Opc, dl, VT, V1);
2938 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2939 SDValue V1, unsigned TargetMask,
2940 SelectionDAG &DAG) {
2942 default: llvm_unreachable("Unknown x86 shuffle node");
2943 case X86ISD::PSHUFD:
2944 case X86ISD::PSHUFHW:
2945 case X86ISD::PSHUFLW:
2946 case X86ISD::VPERMILP:
2947 case X86ISD::VPERMI:
2948 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2952 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2953 SDValue V1, SDValue V2, unsigned TargetMask,
2954 SelectionDAG &DAG) {
2956 default: llvm_unreachable("Unknown x86 shuffle node");
2957 case X86ISD::PALIGN:
2959 case X86ISD::VPERM2X128:
2960 return DAG.getNode(Opc, dl, VT, V1, V2,
2961 DAG.getConstant(TargetMask, MVT::i8));
2965 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2966 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2968 default: llvm_unreachable("Unknown x86 shuffle node");
2969 case X86ISD::MOVLHPS:
2970 case X86ISD::MOVLHPD:
2971 case X86ISD::MOVHLPS:
2972 case X86ISD::MOVLPS:
2973 case X86ISD::MOVLPD:
2976 case X86ISD::UNPCKL:
2977 case X86ISD::UNPCKH:
2978 return DAG.getNode(Opc, dl, VT, V1, V2);
2982 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2983 MachineFunction &MF = DAG.getMachineFunction();
2984 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2985 int ReturnAddrIndex = FuncInfo->getRAIndex();
2987 if (ReturnAddrIndex == 0) {
2988 // Set up a frame object for the return address.
2989 uint64_t SlotSize = TD->getPointerSize();
2990 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2992 FuncInfo->setRAIndex(ReturnAddrIndex);
2995 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2999 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3000 bool hasSymbolicDisplacement) {
3001 // Offset should fit into 32 bit immediate field.
3002 if (!isInt<32>(Offset))
3005 // If we don't have a symbolic displacement - we don't have any extra
3007 if (!hasSymbolicDisplacement)
3010 // FIXME: Some tweaks might be needed for medium code model.
3011 if (M != CodeModel::Small && M != CodeModel::Kernel)
3014 // For small code model we assume that latest object is 16MB before end of 31
3015 // bits boundary. We may also accept pretty large negative constants knowing
3016 // that all objects are in the positive half of address space.
3017 if (M == CodeModel::Small && Offset < 16*1024*1024)
3020 // For kernel code model we know that all object resist in the negative half
3021 // of 32bits address space. We may not accept negative offsets, since they may
3022 // be just off and we may accept pretty large positive ones.
3023 if (M == CodeModel::Kernel && Offset > 0)
3029 /// isCalleePop - Determines whether the callee is required to pop its
3030 /// own arguments. Callee pop is necessary to support tail calls.
3031 bool X86::isCalleePop(CallingConv::ID CallingConv,
3032 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3036 switch (CallingConv) {
3039 case CallingConv::X86_StdCall:
3041 case CallingConv::X86_FastCall:
3043 case CallingConv::X86_ThisCall:
3045 case CallingConv::Fast:
3047 case CallingConv::GHC:
3052 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3053 /// specific condition code, returning the condition code and the LHS/RHS of the
3054 /// comparison to make.
3055 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3056 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3058 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3059 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3060 // X > -1 -> X == 0, jump !sign.
3061 RHS = DAG.getConstant(0, RHS.getValueType());
3062 return X86::COND_NS;
3064 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3065 // X < 0 -> X == 0, jump on sign.
3068 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3070 RHS = DAG.getConstant(0, RHS.getValueType());
3071 return X86::COND_LE;
3075 switch (SetCCOpcode) {
3076 default: llvm_unreachable("Invalid integer condition!");
3077 case ISD::SETEQ: return X86::COND_E;
3078 case ISD::SETGT: return X86::COND_G;
3079 case ISD::SETGE: return X86::COND_GE;
3080 case ISD::SETLT: return X86::COND_L;
3081 case ISD::SETLE: return X86::COND_LE;
3082 case ISD::SETNE: return X86::COND_NE;
3083 case ISD::SETULT: return X86::COND_B;
3084 case ISD::SETUGT: return X86::COND_A;
3085 case ISD::SETULE: return X86::COND_BE;
3086 case ISD::SETUGE: return X86::COND_AE;
3090 // First determine if it is required or is profitable to flip the operands.
3092 // If LHS is a foldable load, but RHS is not, flip the condition.
3093 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3094 !ISD::isNON_EXTLoad(RHS.getNode())) {
3095 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3096 std::swap(LHS, RHS);
3099 switch (SetCCOpcode) {
3105 std::swap(LHS, RHS);
3109 // On a floating point condition, the flags are set as follows:
3111 // 0 | 0 | 0 | X > Y
3112 // 0 | 0 | 1 | X < Y
3113 // 1 | 0 | 0 | X == Y
3114 // 1 | 1 | 1 | unordered
3115 switch (SetCCOpcode) {
3116 default: llvm_unreachable("Condcode should be pre-legalized away");
3118 case ISD::SETEQ: return X86::COND_E;
3119 case ISD::SETOLT: // flipped
3121 case ISD::SETGT: return X86::COND_A;
3122 case ISD::SETOLE: // flipped
3124 case ISD::SETGE: return X86::COND_AE;
3125 case ISD::SETUGT: // flipped
3127 case ISD::SETLT: return X86::COND_B;
3128 case ISD::SETUGE: // flipped
3130 case ISD::SETLE: return X86::COND_BE;
3132 case ISD::SETNE: return X86::COND_NE;
3133 case ISD::SETUO: return X86::COND_P;
3134 case ISD::SETO: return X86::COND_NP;
3136 case ISD::SETUNE: return X86::COND_INVALID;
3140 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3141 /// code. Current x86 isa includes the following FP cmov instructions:
3142 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3143 static bool hasFPCMov(unsigned X86CC) {
3159 /// isFPImmLegal - Returns true if the target can instruction select the
3160 /// specified FP immediate natively. If false, the legalizer will
3161 /// materialize the FP immediate as a load from a constant pool.
3162 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3163 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3164 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3170 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3171 /// the specified range (L, H].
3172 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3173 return (Val < 0) || (Val >= Low && Val < Hi);
3176 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3177 /// specified value.
3178 static bool isUndefOrEqual(int Val, int CmpVal) {
3179 if (Val < 0 || Val == CmpVal)
3184 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3185 /// from position Pos and ending in Pos+Size, falls within the specified
3186 /// sequential range (L, L+Pos]. or is undef.
3187 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3188 unsigned Pos, unsigned Size, int Low) {
3189 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3190 if (!isUndefOrEqual(Mask[i], Low))
3195 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3196 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3197 /// the second operand.
3198 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3199 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3200 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3201 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3202 return (Mask[0] < 2 && Mask[1] < 2);
3206 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3207 /// is suitable for input to PSHUFHW.
3208 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3209 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3212 // Lower quadword copied in order or undef.
3213 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3216 // Upper quadword shuffled.
3217 for (unsigned i = 4; i != 8; ++i)
3218 if (!isUndefOrInRange(Mask[i], 4, 8))
3221 if (VT == MVT::v16i16) {
3222 // Lower quadword copied in order or undef.
3223 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3226 // Upper quadword shuffled.
3227 for (unsigned i = 12; i != 16; ++i)
3228 if (!isUndefOrInRange(Mask[i], 12, 16))
3235 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3236 /// is suitable for input to PSHUFLW.
3237 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3238 if (VT != MVT::v8i16 && (!HasAVX2 || VT != MVT::v16i16))
3241 // Upper quadword copied in order.
3242 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3245 // Lower quadword shuffled.
3246 for (unsigned i = 0; i != 4; ++i)
3247 if (!isUndefOrInRange(Mask[i], 0, 4))
3250 if (VT == MVT::v16i16) {
3251 // Upper quadword copied in order.
3252 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3255 // Lower quadword shuffled.
3256 for (unsigned i = 8; i != 12; ++i)
3257 if (!isUndefOrInRange(Mask[i], 8, 12))
3264 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3265 /// is suitable for input to PALIGNR.
3266 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3267 const X86Subtarget *Subtarget) {
3268 if ((VT.getSizeInBits() == 128 && !Subtarget->hasSSSE3()) ||
3269 (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2()))
3272 unsigned NumElts = VT.getVectorNumElements();
3273 unsigned NumLanes = VT.getSizeInBits()/128;
3274 unsigned NumLaneElts = NumElts/NumLanes;
3276 // Do not handle 64-bit element shuffles with palignr.
3277 if (NumLaneElts == 2)
3280 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3282 for (i = 0; i != NumLaneElts; ++i) {
3287 // Lane is all undef, go to next lane
3288 if (i == NumLaneElts)
3291 int Start = Mask[i+l];
3293 // Make sure its in this lane in one of the sources
3294 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3295 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3298 // If not lane 0, then we must match lane 0
3299 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3302 // Correct second source to be contiguous with first source
3303 if (Start >= (int)NumElts)
3304 Start -= NumElts - NumLaneElts;
3306 // Make sure we're shifting in the right direction.
3307 if (Start <= (int)(i+l))
3312 // Check the rest of the elements to see if they are consecutive.
3313 for (++i; i != NumLaneElts; ++i) {
3314 int Idx = Mask[i+l];
3316 // Make sure its in this lane
3317 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3318 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3321 // If not lane 0, then we must match lane 0
3322 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3325 if (Idx >= (int)NumElts)
3326 Idx -= NumElts - NumLaneElts;
3328 if (!isUndefOrEqual(Idx, Start+i))
3337 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3338 /// the two vector operands have swapped position.
3339 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3340 unsigned NumElems) {
3341 for (unsigned i = 0; i != NumElems; ++i) {
3345 else if (idx < (int)NumElems)
3346 Mask[i] = idx + NumElems;
3348 Mask[i] = idx - NumElems;
3352 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3353 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3354 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3355 /// reverse of what x86 shuffles want.
3356 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX,
3357 bool Commuted = false) {
3358 if (!HasAVX && VT.getSizeInBits() == 256)
3361 unsigned NumElems = VT.getVectorNumElements();
3362 unsigned NumLanes = VT.getSizeInBits()/128;
3363 unsigned NumLaneElems = NumElems/NumLanes;
3365 if (NumLaneElems != 2 && NumLaneElems != 4)
3368 // VSHUFPSY divides the resulting vector into 4 chunks.
3369 // The sources are also splitted into 4 chunks, and each destination
3370 // chunk must come from a different source chunk.
3372 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3373 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3375 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3376 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3378 // VSHUFPDY divides the resulting vector into 4 chunks.
3379 // The sources are also splitted into 4 chunks, and each destination
3380 // chunk must come from a different source chunk.
3382 // SRC1 => X3 X2 X1 X0
3383 // SRC2 => Y3 Y2 Y1 Y0
3385 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3387 unsigned HalfLaneElems = NumLaneElems/2;
3388 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3389 for (unsigned i = 0; i != NumLaneElems; ++i) {
3390 int Idx = Mask[i+l];
3391 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3392 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3394 // For VSHUFPSY, the mask of the second half must be the same as the
3395 // first but with the appropriate offsets. This works in the same way as
3396 // VPERMILPS works with masks.
3397 if (NumElems != 8 || l == 0 || Mask[i] < 0)
3399 if (!isUndefOrEqual(Idx, Mask[i]+l))
3407 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3408 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3409 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3410 unsigned NumElems = VT.getVectorNumElements();
3412 if (VT.getSizeInBits() != 128)
3418 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3419 return isUndefOrEqual(Mask[0], 6) &&
3420 isUndefOrEqual(Mask[1], 7) &&
3421 isUndefOrEqual(Mask[2], 2) &&
3422 isUndefOrEqual(Mask[3], 3);
3425 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3426 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3428 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3429 unsigned NumElems = VT.getVectorNumElements();
3431 if (VT.getSizeInBits() != 128)
3437 return isUndefOrEqual(Mask[0], 2) &&
3438 isUndefOrEqual(Mask[1], 3) &&
3439 isUndefOrEqual(Mask[2], 2) &&
3440 isUndefOrEqual(Mask[3], 3);
3443 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3444 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3445 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3446 if (VT.getSizeInBits() != 128)
3449 unsigned NumElems = VT.getVectorNumElements();
3451 if (NumElems != 2 && NumElems != 4)
3454 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3455 if (!isUndefOrEqual(Mask[i], i + NumElems))
3458 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3459 if (!isUndefOrEqual(Mask[i], i))
3465 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3466 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3467 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3468 unsigned NumElems = VT.getVectorNumElements();
3470 if ((NumElems != 2 && NumElems != 4)
3471 || VT.getSizeInBits() > 128)
3474 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3475 if (!isUndefOrEqual(Mask[i], i))
3478 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3479 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3485 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3486 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3487 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3488 bool HasAVX2, bool V2IsSplat = false) {
3489 unsigned NumElts = VT.getVectorNumElements();
3491 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3492 "Unsupported vector type for unpckh");
3494 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3495 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3498 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3499 // independently on 128-bit lanes.
3500 unsigned NumLanes = VT.getSizeInBits()/128;
3501 unsigned NumLaneElts = NumElts/NumLanes;
3503 for (unsigned l = 0; l != NumLanes; ++l) {
3504 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3505 i != (l+1)*NumLaneElts;
3508 int BitI1 = Mask[i+1];
3509 if (!isUndefOrEqual(BitI, j))
3512 if (!isUndefOrEqual(BitI1, NumElts))
3515 if (!isUndefOrEqual(BitI1, j + NumElts))
3524 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3525 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3526 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3527 bool HasAVX2, bool V2IsSplat = false) {
3528 unsigned NumElts = VT.getVectorNumElements();
3530 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3531 "Unsupported vector type for unpckh");
3533 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3534 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3537 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3538 // independently on 128-bit lanes.
3539 unsigned NumLanes = VT.getSizeInBits()/128;
3540 unsigned NumLaneElts = NumElts/NumLanes;
3542 for (unsigned l = 0; l != NumLanes; ++l) {
3543 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3544 i != (l+1)*NumLaneElts; i += 2, ++j) {
3546 int BitI1 = Mask[i+1];
3547 if (!isUndefOrEqual(BitI, j))
3550 if (isUndefOrEqual(BitI1, NumElts))
3553 if (!isUndefOrEqual(BitI1, j+NumElts))
3561 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3562 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3564 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT,
3566 unsigned NumElts = VT.getVectorNumElements();
3568 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3569 "Unsupported vector type for unpckh");
3571 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3572 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3575 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3576 // FIXME: Need a better way to get rid of this, there's no latency difference
3577 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3578 // the former later. We should also remove the "_undef" special mask.
3579 if (NumElts == 4 && VT.getSizeInBits() == 256)
3582 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3583 // independently on 128-bit lanes.
3584 unsigned NumLanes = VT.getSizeInBits()/128;
3585 unsigned NumLaneElts = NumElts/NumLanes;
3587 for (unsigned l = 0; l != NumLanes; ++l) {
3588 for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3589 i != (l+1)*NumLaneElts;
3592 int BitI1 = Mask[i+1];
3594 if (!isUndefOrEqual(BitI, j))
3596 if (!isUndefOrEqual(BitI1, j))
3604 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3605 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3607 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX2) {
3608 unsigned NumElts = VT.getVectorNumElements();
3610 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3611 "Unsupported vector type for unpckh");
3613 if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3614 (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3617 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3618 // independently on 128-bit lanes.
3619 unsigned NumLanes = VT.getSizeInBits()/128;
3620 unsigned NumLaneElts = NumElts/NumLanes;
3622 for (unsigned l = 0; l != NumLanes; ++l) {
3623 for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3624 i != (l+1)*NumLaneElts; i += 2, ++j) {
3626 int BitI1 = Mask[i+1];
3627 if (!isUndefOrEqual(BitI, j))
3629 if (!isUndefOrEqual(BitI1, j))
3636 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3637 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3638 /// MOVSD, and MOVD, i.e. setting the lowest element.
3639 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3640 if (VT.getVectorElementType().getSizeInBits() < 32)
3642 if (VT.getSizeInBits() == 256)
3645 unsigned NumElts = VT.getVectorNumElements();
3647 if (!isUndefOrEqual(Mask[0], NumElts))
3650 for (unsigned i = 1; i != NumElts; ++i)
3651 if (!isUndefOrEqual(Mask[i], i))
3657 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3658 /// as permutations between 128-bit chunks or halves. As an example: this
3660 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3661 /// The first half comes from the second half of V1 and the second half from the
3662 /// the second half of V2.
3663 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3664 if (!HasAVX || VT.getSizeInBits() != 256)
3667 // The shuffle result is divided into half A and half B. In total the two
3668 // sources have 4 halves, namely: C, D, E, F. The final values of A and
3669 // B must come from C, D, E or F.
3670 unsigned HalfSize = VT.getVectorNumElements()/2;
3671 bool MatchA = false, MatchB = false;
3673 // Check if A comes from one of C, D, E, F.
3674 for (unsigned Half = 0; Half != 4; ++Half) {
3675 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3681 // Check if B comes from one of C, D, E, F.
3682 for (unsigned Half = 0; Half != 4; ++Half) {
3683 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3689 return MatchA && MatchB;
3692 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3693 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3694 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3695 EVT VT = SVOp->getValueType(0);
3697 unsigned HalfSize = VT.getVectorNumElements()/2;
3699 unsigned FstHalf = 0, SndHalf = 0;
3700 for (unsigned i = 0; i < HalfSize; ++i) {
3701 if (SVOp->getMaskElt(i) > 0) {
3702 FstHalf = SVOp->getMaskElt(i)/HalfSize;
3706 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3707 if (SVOp->getMaskElt(i) > 0) {
3708 SndHalf = SVOp->getMaskElt(i)/HalfSize;
3713 return (FstHalf | (SndHalf << 4));
3716 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3717 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3718 /// Note that VPERMIL mask matching is different depending whether theunderlying
3719 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3720 /// to the same elements of the low, but to the higher half of the source.
3721 /// In VPERMILPD the two lanes could be shuffled independently of each other
3722 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3723 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3727 unsigned NumElts = VT.getVectorNumElements();
3728 // Only match 256-bit with 32/64-bit types
3729 if (VT.getSizeInBits() != 256 || (NumElts != 4 && NumElts != 8))
3732 unsigned NumLanes = VT.getSizeInBits()/128;
3733 unsigned LaneSize = NumElts/NumLanes;
3734 for (unsigned l = 0; l != NumElts; l += LaneSize) {
3735 for (unsigned i = 0; i != LaneSize; ++i) {
3736 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3738 if (NumElts != 8 || l == 0)
3740 // VPERMILPS handling
3743 if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3751 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3752 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3753 /// element of vector 2 and the other elements to come from vector 1 in order.
3754 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3755 bool V2IsSplat = false, bool V2IsUndef = false) {
3756 unsigned NumOps = VT.getVectorNumElements();
3757 if (VT.getSizeInBits() == 256)
3759 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3762 if (!isUndefOrEqual(Mask[0], 0))
3765 for (unsigned i = 1; i != NumOps; ++i)
3766 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3767 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3768 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3774 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3775 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3776 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3777 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3778 const X86Subtarget *Subtarget) {
3779 if (!Subtarget->hasSSE3())
3782 unsigned NumElems = VT.getVectorNumElements();
3784 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3785 (VT.getSizeInBits() == 256 && NumElems != 8))
3788 // "i+1" is the value the indexed mask element must have
3789 for (unsigned i = 0; i != NumElems; i += 2)
3790 if (!isUndefOrEqual(Mask[i], i+1) ||
3791 !isUndefOrEqual(Mask[i+1], i+1))
3797 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3798 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3799 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3800 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3801 const X86Subtarget *Subtarget) {
3802 if (!Subtarget->hasSSE3())
3805 unsigned NumElems = VT.getVectorNumElements();
3807 if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3808 (VT.getSizeInBits() == 256 && NumElems != 8))
3811 // "i" is the value the indexed mask element must have
3812 for (unsigned i = 0; i != NumElems; i += 2)
3813 if (!isUndefOrEqual(Mask[i], i) ||
3814 !isUndefOrEqual(Mask[i+1], i))
3820 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3821 /// specifies a shuffle of elements that is suitable for input to 256-bit
3822 /// version of MOVDDUP.
3823 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasAVX) {
3824 unsigned NumElts = VT.getVectorNumElements();
3826 if (!HasAVX || VT.getSizeInBits() != 256 || NumElts != 4)
3829 for (unsigned i = 0; i != NumElts/2; ++i)
3830 if (!isUndefOrEqual(Mask[i], 0))
3832 for (unsigned i = NumElts/2; i != NumElts; ++i)
3833 if (!isUndefOrEqual(Mask[i], NumElts/2))
3838 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3839 /// specifies a shuffle of elements that is suitable for input to 128-bit
3840 /// version of MOVDDUP.
3841 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
3842 if (VT.getSizeInBits() != 128)
3845 unsigned e = VT.getVectorNumElements() / 2;
3846 for (unsigned i = 0; i != e; ++i)
3847 if (!isUndefOrEqual(Mask[i], i))
3849 for (unsigned i = 0; i != e; ++i)
3850 if (!isUndefOrEqual(Mask[e+i], i))
3855 /// isVEXTRACTF128Index - Return true if the specified
3856 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3857 /// suitable for input to VEXTRACTF128.
3858 bool X86::isVEXTRACTF128Index(SDNode *N) {
3859 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3862 // The index should be aligned on a 128-bit boundary.
3864 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3866 unsigned VL = N->getValueType(0).getVectorNumElements();
3867 unsigned VBits = N->getValueType(0).getSizeInBits();
3868 unsigned ElSize = VBits / VL;
3869 bool Result = (Index * ElSize) % 128 == 0;
3874 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
3875 /// operand specifies a subvector insert that is suitable for input to
3877 bool X86::isVINSERTF128Index(SDNode *N) {
3878 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3881 // The index should be aligned on a 128-bit boundary.
3883 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3885 unsigned VL = N->getValueType(0).getVectorNumElements();
3886 unsigned VBits = N->getValueType(0).getSizeInBits();
3887 unsigned ElSize = VBits / VL;
3888 bool Result = (Index * ElSize) % 128 == 0;
3893 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3894 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3895 /// Handles 128-bit and 256-bit.
3896 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
3897 EVT VT = N->getValueType(0);
3899 assert((VT.is128BitVector() || VT.is256BitVector()) &&
3900 "Unsupported vector type for PSHUF/SHUFP");
3902 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
3903 // independently on 128-bit lanes.
3904 unsigned NumElts = VT.getVectorNumElements();
3905 unsigned NumLanes = VT.getSizeInBits()/128;
3906 unsigned NumLaneElts = NumElts/NumLanes;
3908 assert((NumLaneElts == 2 || NumLaneElts == 4) &&
3909 "Only supports 2 or 4 elements per lane");
3911 unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
3913 for (unsigned i = 0; i != NumElts; ++i) {
3914 int Elt = N->getMaskElt(i);
3915 if (Elt < 0) continue;
3916 Elt &= NumLaneElts - 1;
3917 unsigned ShAmt = (i << Shift) % 8;
3918 Mask |= Elt << ShAmt;
3924 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3925 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3926 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
3927 EVT VT = N->getValueType(0);
3929 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3930 "Unsupported vector type for PSHUFHW");
3932 unsigned NumElts = VT.getVectorNumElements();
3935 for (unsigned l = 0; l != NumElts; l += 8) {
3936 // 8 nodes per lane, but we only care about the last 4.
3937 for (unsigned i = 0; i < 4; ++i) {
3938 int Elt = N->getMaskElt(l+i+4);
3939 if (Elt < 0) continue;
3940 Elt &= 0x3; // only 2-bits.
3941 Mask |= Elt << (i * 2);
3948 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3949 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3950 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
3951 EVT VT = N->getValueType(0);
3953 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
3954 "Unsupported vector type for PSHUFHW");
3956 unsigned NumElts = VT.getVectorNumElements();
3959 for (unsigned l = 0; l != NumElts; l += 8) {
3960 // 8 nodes per lane, but we only care about the first 4.
3961 for (unsigned i = 0; i < 4; ++i) {
3962 int Elt = N->getMaskElt(l+i);
3963 if (Elt < 0) continue;
3964 Elt &= 0x3; // only 2-bits
3965 Mask |= Elt << (i * 2);
3972 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3973 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3974 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
3975 EVT VT = SVOp->getValueType(0);
3976 unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
3978 unsigned NumElts = VT.getVectorNumElements();
3979 unsigned NumLanes = VT.getSizeInBits()/128;
3980 unsigned NumLaneElts = NumElts/NumLanes;
3984 for (i = 0; i != NumElts; ++i) {
3985 Val = SVOp->getMaskElt(i);
3989 if (Val >= (int)NumElts)
3990 Val -= NumElts - NumLaneElts;
3992 assert(Val - i > 0 && "PALIGNR imm should be positive");
3993 return (Val - i) * EltSize;
3996 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
3997 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
3999 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4000 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4001 llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4004 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4006 EVT VecVT = N->getOperand(0).getValueType();
4007 EVT ElVT = VecVT.getVectorElementType();
4009 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4010 return Index / NumElemsPerChunk;
4013 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4014 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4016 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4017 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4018 llvm_unreachable("Illegal insert subvector for VINSERTF128");
4021 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4023 EVT VecVT = N->getValueType(0);
4024 EVT ElVT = VecVT.getVectorElementType();
4026 unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4027 return Index / NumElemsPerChunk;
4030 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4031 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4032 /// Handles 256-bit.
4033 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4034 EVT VT = N->getValueType(0);
4036 unsigned NumElts = VT.getVectorNumElements();
4038 assert((VT.is256BitVector() && NumElts == 4) &&
4039 "Unsupported vector type for VPERMQ/VPERMPD");
4042 for (unsigned i = 0; i != NumElts; ++i) {
4043 int Elt = N->getMaskElt(i);
4046 Mask |= Elt << (i*2);
4051 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4053 bool X86::isZeroNode(SDValue Elt) {
4054 return ((isa<ConstantSDNode>(Elt) &&
4055 cast<ConstantSDNode>(Elt)->isNullValue()) ||
4056 (isa<ConstantFPSDNode>(Elt) &&
4057 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4060 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4061 /// their permute mask.
4062 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4063 SelectionDAG &DAG) {
4064 EVT VT = SVOp->getValueType(0);
4065 unsigned NumElems = VT.getVectorNumElements();
4066 SmallVector<int, 8> MaskVec;
4068 for (unsigned i = 0; i != NumElems; ++i) {
4069 int Idx = SVOp->getMaskElt(i);
4071 if (Idx < (int)NumElems)
4076 MaskVec.push_back(Idx);
4078 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4079 SVOp->getOperand(0), &MaskVec[0]);
4082 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4083 /// match movhlps. The lower half elements should come from upper half of
4084 /// V1 (and in order), and the upper half elements should come from the upper
4085 /// half of V2 (and in order).
4086 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4087 if (VT.getSizeInBits() != 128)
4089 if (VT.getVectorNumElements() != 4)
4091 for (unsigned i = 0, e = 2; i != e; ++i)
4092 if (!isUndefOrEqual(Mask[i], i+2))
4094 for (unsigned i = 2; i != 4; ++i)
4095 if (!isUndefOrEqual(Mask[i], i+4))
4100 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4101 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4103 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4104 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4106 N = N->getOperand(0).getNode();
4107 if (!ISD::isNON_EXTLoad(N))
4110 *LD = cast<LoadSDNode>(N);
4114 // Test whether the given value is a vector value which will be legalized
4116 static bool WillBeConstantPoolLoad(SDNode *N) {
4117 if (N->getOpcode() != ISD::BUILD_VECTOR)
4120 // Check for any non-constant elements.
4121 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4122 switch (N->getOperand(i).getNode()->getOpcode()) {
4124 case ISD::ConstantFP:
4131 // Vectors of all-zeros and all-ones are materialized with special
4132 // instructions rather than being loaded.
4133 return !ISD::isBuildVectorAllZeros(N) &&
4134 !ISD::isBuildVectorAllOnes(N);
4137 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4138 /// match movlp{s|d}. The lower half elements should come from lower half of
4139 /// V1 (and in order), and the upper half elements should come from the upper
4140 /// half of V2 (and in order). And since V1 will become the source of the
4141 /// MOVLP, it must be either a vector load or a scalar load to vector.
4142 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4143 ArrayRef<int> Mask, EVT VT) {
4144 if (VT.getSizeInBits() != 128)
4147 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4149 // Is V2 is a vector load, don't do this transformation. We will try to use
4150 // load folding shufps op.
4151 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4154 unsigned NumElems = VT.getVectorNumElements();
4156 if (NumElems != 2 && NumElems != 4)
4158 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4159 if (!isUndefOrEqual(Mask[i], i))
4161 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4162 if (!isUndefOrEqual(Mask[i], i+NumElems))
4167 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4169 static bool isSplatVector(SDNode *N) {
4170 if (N->getOpcode() != ISD::BUILD_VECTOR)
4173 SDValue SplatValue = N->getOperand(0);
4174 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4175 if (N->getOperand(i) != SplatValue)
4180 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4181 /// to an zero vector.
4182 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4183 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4184 SDValue V1 = N->getOperand(0);
4185 SDValue V2 = N->getOperand(1);
4186 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4187 for (unsigned i = 0; i != NumElems; ++i) {
4188 int Idx = N->getMaskElt(i);
4189 if (Idx >= (int)NumElems) {
4190 unsigned Opc = V2.getOpcode();
4191 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4193 if (Opc != ISD::BUILD_VECTOR ||
4194 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4196 } else if (Idx >= 0) {
4197 unsigned Opc = V1.getOpcode();
4198 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4200 if (Opc != ISD::BUILD_VECTOR ||
4201 !X86::isZeroNode(V1.getOperand(Idx)))
4208 /// getZeroVector - Returns a vector of specified type with all zero elements.
4210 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4211 SelectionDAG &DAG, DebugLoc dl) {
4212 assert(VT.isVector() && "Expected a vector type");
4213 unsigned Size = VT.getSizeInBits();
4215 // Always build SSE zero vectors as <4 x i32> bitcasted
4216 // to their dest type. This ensures they get CSE'd.
4218 if (Size == 128) { // SSE
4219 if (Subtarget->hasSSE2()) { // SSE2
4220 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4221 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4223 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4224 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4226 } else if (Size == 256) { // AVX
4227 if (Subtarget->hasAVX2()) { // AVX2
4228 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4229 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4230 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4232 // 256-bit logic and arithmetic instructions in AVX are all
4233 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4234 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4235 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4236 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4239 llvm_unreachable("Unexpected vector type");
4241 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4244 /// getOnesVector - Returns a vector of specified type with all bits set.
4245 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4246 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4247 /// Then bitcast to their original type, ensuring they get CSE'd.
4248 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4250 assert(VT.isVector() && "Expected a vector type");
4251 unsigned Size = VT.getSizeInBits();
4253 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4256 if (HasAVX2) { // AVX2
4257 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4258 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4260 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4261 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4263 } else if (Size == 128) {
4264 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4266 llvm_unreachable("Unexpected vector type");
4268 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4271 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4272 /// that point to V2 points to its first element.
4273 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4274 for (unsigned i = 0; i != NumElems; ++i) {
4275 if (Mask[i] > (int)NumElems) {
4281 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4282 /// operation of specified width.
4283 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4285 unsigned NumElems = VT.getVectorNumElements();
4286 SmallVector<int, 8> Mask;
4287 Mask.push_back(NumElems);
4288 for (unsigned i = 1; i != NumElems; ++i)
4290 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4293 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4294 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4296 unsigned NumElems = VT.getVectorNumElements();
4297 SmallVector<int, 8> Mask;
4298 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4300 Mask.push_back(i + NumElems);
4302 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4305 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4306 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4308 unsigned NumElems = VT.getVectorNumElements();
4309 SmallVector<int, 8> Mask;
4310 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4311 Mask.push_back(i + Half);
4312 Mask.push_back(i + NumElems + Half);
4314 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4317 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4318 // a generic shuffle instruction because the target has no such instructions.
4319 // Generate shuffles which repeat i16 and i8 several times until they can be
4320 // represented by v4f32 and then be manipulated by target suported shuffles.
4321 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4322 EVT VT = V.getValueType();
4323 int NumElems = VT.getVectorNumElements();
4324 DebugLoc dl = V.getDebugLoc();
4326 while (NumElems > 4) {
4327 if (EltNo < NumElems/2) {
4328 V = getUnpackl(DAG, dl, VT, V, V);
4330 V = getUnpackh(DAG, dl, VT, V, V);
4331 EltNo -= NumElems/2;
4338 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4339 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4340 EVT VT = V.getValueType();
4341 DebugLoc dl = V.getDebugLoc();
4342 unsigned Size = VT.getSizeInBits();
4345 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4346 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4347 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4349 } else if (Size == 256) {
4350 // To use VPERMILPS to splat scalars, the second half of indicies must
4351 // refer to the higher part, which is a duplication of the lower one,
4352 // because VPERMILPS can only handle in-lane permutations.
4353 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4354 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4356 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4357 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4360 llvm_unreachable("Vector size not supported");
4362 return DAG.getNode(ISD::BITCAST, dl, VT, V);
4365 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4366 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4367 EVT SrcVT = SV->getValueType(0);
4368 SDValue V1 = SV->getOperand(0);
4369 DebugLoc dl = SV->getDebugLoc();
4371 int EltNo = SV->getSplatIndex();
4372 int NumElems = SrcVT.getVectorNumElements();
4373 unsigned Size = SrcVT.getSizeInBits();
4375 assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4376 "Unknown how to promote splat for type");
4378 // Extract the 128-bit part containing the splat element and update
4379 // the splat element index when it refers to the higher register.
4381 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4382 if (EltNo >= NumElems/2)
4383 EltNo -= NumElems/2;
4386 // All i16 and i8 vector types can't be used directly by a generic shuffle
4387 // instruction because the target has no such instruction. Generate shuffles
4388 // which repeat i16 and i8 several times until they fit in i32, and then can
4389 // be manipulated by target suported shuffles.
4390 EVT EltVT = SrcVT.getVectorElementType();
4391 if (EltVT == MVT::i8 || EltVT == MVT::i16)
4392 V1 = PromoteSplati8i16(V1, DAG, EltNo);
4394 // Recreate the 256-bit vector and place the same 128-bit vector
4395 // into the low and high part. This is necessary because we want
4396 // to use VPERM* to shuffle the vectors
4398 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4401 return getLegalSplat(DAG, V1, EltNo);
4404 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4405 /// vector of zero or undef vector. This produces a shuffle where the low
4406 /// element of V2 is swizzled into the zero/undef vector, landing at element
4407 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
4408 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4410 const X86Subtarget *Subtarget,
4411 SelectionDAG &DAG) {
4412 EVT VT = V2.getValueType();
4414 ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4415 unsigned NumElems = VT.getVectorNumElements();
4416 SmallVector<int, 16> MaskVec;
4417 for (unsigned i = 0; i != NumElems; ++i)
4418 // If this is the insertion idx, put the low elt of V2 here.
4419 MaskVec.push_back(i == Idx ? NumElems : i);
4420 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4423 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4424 /// target specific opcode. Returns true if the Mask could be calculated.
4425 /// Sets IsUnary to true if only uses one source.
4426 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4427 SmallVectorImpl<int> &Mask, bool &IsUnary) {
4428 unsigned NumElems = VT.getVectorNumElements();
4432 switch(N->getOpcode()) {
4434 ImmN = N->getOperand(N->getNumOperands()-1);
4435 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4437 case X86ISD::UNPCKH:
4438 DecodeUNPCKHMask(VT, Mask);
4440 case X86ISD::UNPCKL:
4441 DecodeUNPCKLMask(VT, Mask);
4443 case X86ISD::MOVHLPS:
4444 DecodeMOVHLPSMask(NumElems, Mask);
4446 case X86ISD::MOVLHPS:
4447 DecodeMOVLHPSMask(NumElems, Mask);
4449 case X86ISD::PSHUFD:
4450 case X86ISD::VPERMILP:
4451 ImmN = N->getOperand(N->getNumOperands()-1);
4452 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4455 case X86ISD::PSHUFHW:
4456 ImmN = N->getOperand(N->getNumOperands()-1);
4457 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460 case X86ISD::PSHUFLW:
4461 ImmN = N->getOperand(N->getNumOperands()-1);
4462 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4465 case X86ISD::VPERMI:
4466 ImmN = N->getOperand(N->getNumOperands()-1);
4467 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4471 case X86ISD::MOVSD: {
4472 // The index 0 always comes from the first element of the second source,
4473 // this is why MOVSS and MOVSD are used in the first place. The other
4474 // elements come from the other positions of the first source vector
4475 Mask.push_back(NumElems);
4476 for (unsigned i = 1; i != NumElems; ++i) {
4481 case X86ISD::VPERM2X128:
4482 ImmN = N->getOperand(N->getNumOperands()-1);
4483 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4484 if (Mask.empty()) return false;
4486 case X86ISD::MOVDDUP:
4487 case X86ISD::MOVLHPD:
4488 case X86ISD::MOVLPD:
4489 case X86ISD::MOVLPS:
4490 case X86ISD::MOVSHDUP:
4491 case X86ISD::MOVSLDUP:
4492 case X86ISD::PALIGN:
4493 // Not yet implemented
4495 default: llvm_unreachable("unknown target shuffle node");
4501 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4502 /// element of the result of the vector shuffle.
4503 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4506 return SDValue(); // Limit search depth.
4508 SDValue V = SDValue(N, 0);
4509 EVT VT = V.getValueType();
4510 unsigned Opcode = V.getOpcode();
4512 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4513 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4514 int Elt = SV->getMaskElt(Index);
4517 return DAG.getUNDEF(VT.getVectorElementType());
4519 unsigned NumElems = VT.getVectorNumElements();
4520 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4521 : SV->getOperand(1);
4522 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4525 // Recurse into target specific vector shuffles to find scalars.
4526 if (isTargetShuffle(Opcode)) {
4527 MVT ShufVT = V.getValueType().getSimpleVT();
4528 unsigned NumElems = ShufVT.getVectorNumElements();
4529 SmallVector<int, 16> ShuffleMask;
4533 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4536 int Elt = ShuffleMask[Index];
4538 return DAG.getUNDEF(ShufVT.getVectorElementType());
4540 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4542 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4546 // Actual nodes that may contain scalar elements
4547 if (Opcode == ISD::BITCAST) {
4548 V = V.getOperand(0);
4549 EVT SrcVT = V.getValueType();
4550 unsigned NumElems = VT.getVectorNumElements();
4552 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4556 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4557 return (Index == 0) ? V.getOperand(0)
4558 : DAG.getUNDEF(VT.getVectorElementType());
4560 if (V.getOpcode() == ISD::BUILD_VECTOR)
4561 return V.getOperand(Index);
4566 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4567 /// shuffle operation which come from a consecutively from a zero. The
4568 /// search can start in two different directions, from left or right.
4570 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4571 bool ZerosFromLeft, SelectionDAG &DAG) {
4573 for (i = 0; i != NumElems; ++i) {
4574 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4575 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4576 if (!(Elt.getNode() &&
4577 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4584 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4585 /// correspond consecutively to elements from one of the vector operands,
4586 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4588 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4589 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4590 unsigned NumElems, unsigned &OpNum) {
4591 bool SeenV1 = false;
4592 bool SeenV2 = false;
4594 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4595 int Idx = SVOp->getMaskElt(i);
4596 // Ignore undef indicies
4600 if (Idx < (int)NumElems)
4605 // Only accept consecutive elements from the same vector
4606 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4610 OpNum = SeenV1 ? 0 : 1;
4614 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4615 /// logical left shift of a vector.
4616 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4617 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4618 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4619 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4620 false /* check zeros from right */, DAG);
4626 // Considering the elements in the mask that are not consecutive zeros,
4627 // check if they consecutively come from only one of the source vectors.
4629 // V1 = {X, A, B, C} 0
4631 // vector_shuffle V1, V2 <1, 2, 3, X>
4633 if (!isShuffleMaskConsecutive(SVOp,
4634 0, // Mask Start Index
4635 NumElems-NumZeros, // Mask End Index(exclusive)
4636 NumZeros, // Where to start looking in the src vector
4637 NumElems, // Number of elements in vector
4638 OpSrc)) // Which source operand ?
4643 ShVal = SVOp->getOperand(OpSrc);
4647 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4648 /// logical left shift of a vector.
4649 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4650 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4651 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4652 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4653 true /* check zeros from left */, DAG);
4659 // Considering the elements in the mask that are not consecutive zeros,
4660 // check if they consecutively come from only one of the source vectors.
4662 // 0 { A, B, X, X } = V2
4664 // vector_shuffle V1, V2 <X, X, 4, 5>
4666 if (!isShuffleMaskConsecutive(SVOp,
4667 NumZeros, // Mask Start Index
4668 NumElems, // Mask End Index(exclusive)
4669 0, // Where to start looking in the src vector
4670 NumElems, // Number of elements in vector
4671 OpSrc)) // Which source operand ?
4676 ShVal = SVOp->getOperand(OpSrc);
4680 /// isVectorShift - Returns true if the shuffle can be implemented as a
4681 /// logical left or right shift of a vector.
4682 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4683 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4684 // Although the logic below support any bitwidth size, there are no
4685 // shift instructions which handle more than 128-bit vectors.
4686 if (SVOp->getValueType(0).getSizeInBits() > 128)
4689 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4690 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4696 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4698 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4699 unsigned NumNonZero, unsigned NumZero,
4701 const X86Subtarget* Subtarget,
4702 const TargetLowering &TLI) {
4706 DebugLoc dl = Op.getDebugLoc();
4709 for (unsigned i = 0; i < 16; ++i) {
4710 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4711 if (ThisIsNonZero && First) {
4713 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4715 V = DAG.getUNDEF(MVT::v8i16);
4720 SDValue ThisElt(0, 0), LastElt(0, 0);
4721 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4722 if (LastIsNonZero) {
4723 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4724 MVT::i16, Op.getOperand(i-1));
4726 if (ThisIsNonZero) {
4727 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4728 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4729 ThisElt, DAG.getConstant(8, MVT::i8));
4731 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4735 if (ThisElt.getNode())
4736 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4737 DAG.getIntPtrConstant(i/2));
4741 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4744 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4746 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4747 unsigned NumNonZero, unsigned NumZero,
4749 const X86Subtarget* Subtarget,
4750 const TargetLowering &TLI) {
4754 DebugLoc dl = Op.getDebugLoc();
4757 for (unsigned i = 0; i < 8; ++i) {
4758 bool isNonZero = (NonZeros & (1 << i)) != 0;
4762 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4764 V = DAG.getUNDEF(MVT::v8i16);
4767 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4768 MVT::v8i16, V, Op.getOperand(i),
4769 DAG.getIntPtrConstant(i));
4776 /// getVShift - Return a vector logical shift node.
4778 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4779 unsigned NumBits, SelectionDAG &DAG,
4780 const TargetLowering &TLI, DebugLoc dl) {
4781 assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4782 EVT ShVT = MVT::v2i64;
4783 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4784 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4785 return DAG.getNode(ISD::BITCAST, dl, VT,
4786 DAG.getNode(Opc, dl, ShVT, SrcOp,
4787 DAG.getConstant(NumBits,
4788 TLI.getShiftAmountTy(SrcOp.getValueType()))));
4792 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4793 SelectionDAG &DAG) const {
4795 // Check if the scalar load can be widened into a vector load. And if
4796 // the address is "base + cst" see if the cst can be "absorbed" into
4797 // the shuffle mask.
4798 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4799 SDValue Ptr = LD->getBasePtr();
4800 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4802 EVT PVT = LD->getValueType(0);
4803 if (PVT != MVT::i32 && PVT != MVT::f32)
4808 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4809 FI = FINode->getIndex();
4811 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4812 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4813 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4814 Offset = Ptr.getConstantOperandVal(1);
4815 Ptr = Ptr.getOperand(0);
4820 // FIXME: 256-bit vector instructions don't require a strict alignment,
4821 // improve this code to support it better.
4822 unsigned RequiredAlign = VT.getSizeInBits()/8;
4823 SDValue Chain = LD->getChain();
4824 // Make sure the stack object alignment is at least 16 or 32.
4825 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4826 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4827 if (MFI->isFixedObjectIndex(FI)) {
4828 // Can't change the alignment. FIXME: It's possible to compute
4829 // the exact stack offset and reference FI + adjust offset instead.
4830 // If someone *really* cares about this. That's the way to implement it.
4833 MFI->setObjectAlignment(FI, RequiredAlign);
4837 // (Offset % 16 or 32) must be multiple of 4. Then address is then
4838 // Ptr + (Offset & ~15).
4841 if ((Offset % RequiredAlign) & 3)
4843 int64_t StartOffset = Offset & ~(RequiredAlign-1);
4845 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4846 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4848 int EltNo = (Offset - StartOffset) >> 2;
4849 unsigned NumElems = VT.getVectorNumElements();
4851 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4852 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4853 LD->getPointerInfo().getWithOffset(StartOffset),
4854 false, false, false, 0);
4856 SmallVector<int, 8> Mask;
4857 for (unsigned i = 0; i != NumElems; ++i)
4858 Mask.push_back(EltNo);
4860 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4866 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4867 /// vector of type 'VT', see if the elements can be replaced by a single large
4868 /// load which has the same value as a build_vector whose operands are 'elts'.
4870 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4872 /// FIXME: we'd also like to handle the case where the last elements are zero
4873 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4874 /// There's even a handy isZeroNode for that purpose.
4875 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4876 DebugLoc &DL, SelectionDAG &DAG) {
4877 EVT EltVT = VT.getVectorElementType();
4878 unsigned NumElems = Elts.size();
4880 LoadSDNode *LDBase = NULL;
4881 unsigned LastLoadedElt = -1U;
4883 // For each element in the initializer, see if we've found a load or an undef.
4884 // If we don't find an initial load element, or later load elements are
4885 // non-consecutive, bail out.
4886 for (unsigned i = 0; i < NumElems; ++i) {
4887 SDValue Elt = Elts[i];
4889 if (!Elt.getNode() ||
4890 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4893 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4895 LDBase = cast<LoadSDNode>(Elt.getNode());
4899 if (Elt.getOpcode() == ISD::UNDEF)
4902 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4903 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4908 // If we have found an entire vector of loads and undefs, then return a large
4909 // load of the entire vector width starting at the base pointer. If we found
4910 // consecutive loads for the low half, generate a vzext_load node.
4911 if (LastLoadedElt == NumElems - 1) {
4912 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4913 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4914 LDBase->getPointerInfo(),
4915 LDBase->isVolatile(), LDBase->isNonTemporal(),
4916 LDBase->isInvariant(), 0);
4917 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4918 LDBase->getPointerInfo(),
4919 LDBase->isVolatile(), LDBase->isNonTemporal(),
4920 LDBase->isInvariant(), LDBase->getAlignment());
4922 if (NumElems == 4 && LastLoadedElt == 1 &&
4923 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4924 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4925 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4927 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
4928 LDBase->getPointerInfo(),
4929 LDBase->getAlignment(),
4930 false/*isVolatile*/, true/*ReadMem*/,
4932 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4937 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
4938 /// to generate a splat value for the following cases:
4939 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
4940 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
4941 /// a scalar load, or a constant.
4942 /// The VBROADCAST node is returned when a pattern is found,
4943 /// or SDValue() otherwise.
4945 X86TargetLowering::LowerVectorBroadcast(SDValue &Op, SelectionDAG &DAG) const {
4946 if (!Subtarget->hasAVX())
4949 EVT VT = Op.getValueType();
4950 DebugLoc dl = Op.getDebugLoc();
4952 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4953 "Unsupported vector type for broadcast.");
4958 switch (Op.getOpcode()) {
4960 // Unknown pattern found.
4963 case ISD::BUILD_VECTOR: {
4964 // The BUILD_VECTOR node must be a splat.
4965 if (!isSplatVector(Op.getNode()))
4968 Ld = Op.getOperand(0);
4969 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4970 Ld.getOpcode() == ISD::ConstantFP);
4972 // The suspected load node has several users. Make sure that all
4973 // of its users are from the BUILD_VECTOR node.
4974 // Constants may have multiple users.
4975 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
4980 case ISD::VECTOR_SHUFFLE: {
4981 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4983 // Shuffles must have a splat mask where the first element is
4985 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
4988 SDValue Sc = Op.getOperand(0);
4989 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
4990 Sc.getOpcode() != ISD::BUILD_VECTOR)
4993 Ld = Sc.getOperand(0);
4994 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
4995 Ld.getOpcode() == ISD::ConstantFP);
4997 // The scalar_to_vector node and the suspected
4998 // load node must have exactly one user.
4999 // Constants may have multiple users.
5000 if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5006 bool Is256 = VT.getSizeInBits() == 256;
5008 // Handle the broadcasting a single constant scalar from the constant pool
5009 // into a vector. On Sandybridge it is still better to load a constant vector
5010 // from the constant pool and not to broadcast it from a scalar.
5011 if (ConstSplatVal && Subtarget->hasAVX2()) {
5012 EVT CVT = Ld.getValueType();
5013 assert(!CVT.isVector() && "Must not broadcast a vector type");
5014 unsigned ScalarSize = CVT.getSizeInBits();
5016 if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5017 const Constant *C = 0;
5018 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5019 C = CI->getConstantIntValue();
5020 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5021 C = CF->getConstantFPValue();
5023 assert(C && "Invalid constant type");
5025 SDValue CP = DAG.getConstantPool(C, getPointerTy());
5026 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5027 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5028 MachinePointerInfo::getConstantPool(),
5029 false, false, false, Alignment);
5031 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5035 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5036 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5038 // Handle AVX2 in-register broadcasts.
5039 if (!IsLoad && Subtarget->hasAVX2() &&
5040 (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5041 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5043 // The scalar source must be a normal load.
5047 if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5048 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5050 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5051 // double since there is no vbroadcastsd xmm
5052 if (Subtarget->hasAVX2() && Ld.getValueType().isInteger()) {
5053 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5054 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5057 // Unsupported broadcast.
5062 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5063 DebugLoc dl = Op.getDebugLoc();
5065 EVT VT = Op.getValueType();
5066 EVT ExtVT = VT.getVectorElementType();
5067 unsigned NumElems = Op.getNumOperands();
5069 // Vectors containing all zeros can be matched by pxor and xorps later
5070 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5071 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5072 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5073 if (VT == MVT::v4i32 || VT == MVT::v8i32)
5076 return getZeroVector(VT, Subtarget, DAG, dl);
5079 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5080 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5081 // vpcmpeqd on 256-bit vectors.
5082 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5083 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasAVX2()))
5086 return getOnesVector(VT, Subtarget->hasAVX2(), DAG, dl);
5089 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5090 if (Broadcast.getNode())
5093 unsigned EVTBits = ExtVT.getSizeInBits();
5095 unsigned NumZero = 0;
5096 unsigned NumNonZero = 0;
5097 unsigned NonZeros = 0;
5098 bool IsAllConstants = true;
5099 SmallSet<SDValue, 8> Values;
5100 for (unsigned i = 0; i < NumElems; ++i) {
5101 SDValue Elt = Op.getOperand(i);
5102 if (Elt.getOpcode() == ISD::UNDEF)
5105 if (Elt.getOpcode() != ISD::Constant &&
5106 Elt.getOpcode() != ISD::ConstantFP)
5107 IsAllConstants = false;
5108 if (X86::isZeroNode(Elt))
5111 NonZeros |= (1 << i);
5116 // All undef vector. Return an UNDEF. All zero vectors were handled above.
5117 if (NumNonZero == 0)
5118 return DAG.getUNDEF(VT);
5120 // Special case for single non-zero, non-undef, element.
5121 if (NumNonZero == 1) {
5122 unsigned Idx = CountTrailingZeros_32(NonZeros);
5123 SDValue Item = Op.getOperand(Idx);
5125 // If this is an insertion of an i64 value on x86-32, and if the top bits of
5126 // the value are obviously zero, truncate the value to i32 and do the
5127 // insertion that way. Only do this if the value is non-constant or if the
5128 // value is a constant being inserted into element 0. It is cheaper to do
5129 // a constant pool load than it is to do a movd + shuffle.
5130 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5131 (!IsAllConstants || Idx == 0)) {
5132 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5134 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5135 EVT VecVT = MVT::v4i32;
5136 unsigned VecElts = 4;
5138 // Truncate the value (which may itself be a constant) to i32, and
5139 // convert it to a vector with movd (S2V+shuffle to zero extend).
5140 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5141 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5142 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5144 // Now we have our 32-bit value zero extended in the low element of
5145 // a vector. If Idx != 0, swizzle it into place.
5147 SmallVector<int, 4> Mask;
5148 Mask.push_back(Idx);
5149 for (unsigned i = 1; i != VecElts; ++i)
5151 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5154 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5158 // If we have a constant or non-constant insertion into the low element of
5159 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5160 // the rest of the elements. This will be matched as movd/movq/movss/movsd
5161 // depending on what the source datatype is.
5164 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5166 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5167 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5168 if (VT.getSizeInBits() == 256) {
5169 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5170 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5171 Item, DAG.getIntPtrConstant(0));
5173 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5174 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5175 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5176 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5179 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5180 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5181 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5182 if (VT.getSizeInBits() == 256) {
5183 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5184 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5186 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5187 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5189 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5193 // Is it a vector logical left shift?
5194 if (NumElems == 2 && Idx == 1 &&
5195 X86::isZeroNode(Op.getOperand(0)) &&
5196 !X86::isZeroNode(Op.getOperand(1))) {
5197 unsigned NumBits = VT.getSizeInBits();
5198 return getVShift(true, VT,
5199 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5200 VT, Op.getOperand(1)),
5201 NumBits/2, DAG, *this, dl);
5204 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5207 // Otherwise, if this is a vector with i32 or f32 elements, and the element
5208 // is a non-constant being inserted into an element other than the low one,
5209 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
5210 // movd/movss) to move this into the low element, then shuffle it into
5212 if (EVTBits == 32) {
5213 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5215 // Turn it into a shuffle of zero and zero-extended scalar to vector.
5216 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5217 SmallVector<int, 8> MaskVec;
5218 for (unsigned i = 0; i != NumElems; ++i)
5219 MaskVec.push_back(i == Idx ? 0 : 1);
5220 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5224 // Splat is obviously ok. Let legalizer expand it to a shuffle.
5225 if (Values.size() == 1) {
5226 if (EVTBits == 32) {
5227 // Instead of a shuffle like this:
5228 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5229 // Check if it's possible to issue this instead.
5230 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5231 unsigned Idx = CountTrailingZeros_32(NonZeros);
5232 SDValue Item = Op.getOperand(Idx);
5233 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5234 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5239 // A vector full of immediates; various special cases are already
5240 // handled, so this is best done with a single constant-pool load.
5244 // For AVX-length vectors, build the individual 128-bit pieces and use
5245 // shuffles to put them in place.
5246 if (VT.getSizeInBits() == 256) {
5247 SmallVector<SDValue, 32> V;
5248 for (unsigned i = 0; i != NumElems; ++i)
5249 V.push_back(Op.getOperand(i));
5251 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5253 // Build both the lower and upper subvector.
5254 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5255 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5258 // Recreate the wider vector with the lower and upper part.
5259 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5262 // Let legalizer expand 2-wide build_vectors.
5263 if (EVTBits == 64) {
5264 if (NumNonZero == 1) {
5265 // One half is zero or undef.
5266 unsigned Idx = CountTrailingZeros_32(NonZeros);
5267 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5268 Op.getOperand(Idx));
5269 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5274 // If element VT is < 32 bits, convert it to inserts into a zero vector.
5275 if (EVTBits == 8 && NumElems == 16) {
5276 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5278 if (V.getNode()) return V;
5281 if (EVTBits == 16 && NumElems == 8) {
5282 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5284 if (V.getNode()) return V;
5287 // If element VT is == 32 bits, turn it into a number of shuffles.
5288 SmallVector<SDValue, 8> V(NumElems);
5289 if (NumElems == 4 && NumZero > 0) {
5290 for (unsigned i = 0; i < 4; ++i) {
5291 bool isZero = !(NonZeros & (1 << i));
5293 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5295 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5298 for (unsigned i = 0; i < 2; ++i) {
5299 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5302 V[i] = V[i*2]; // Must be a zero vector.
5305 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5308 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5311 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5316 bool Reverse1 = (NonZeros & 0x3) == 2;
5317 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5321 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5322 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
5324 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5327 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5328 // Check for a build vector of consecutive loads.
5329 for (unsigned i = 0; i < NumElems; ++i)
5330 V[i] = Op.getOperand(i);
5332 // Check for elements which are consecutive loads.
5333 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5337 // For SSE 4.1, use insertps to put the high elements into the low element.
5338 if (getSubtarget()->hasSSE41()) {
5340 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5341 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5343 Result = DAG.getUNDEF(VT);
5345 for (unsigned i = 1; i < NumElems; ++i) {
5346 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5347 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5348 Op.getOperand(i), DAG.getIntPtrConstant(i));
5353 // Otherwise, expand into a number of unpckl*, start by extending each of
5354 // our (non-undef) elements to the full vector width with the element in the
5355 // bottom slot of the vector (which generates no code for SSE).
5356 for (unsigned i = 0; i < NumElems; ++i) {
5357 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5358 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5360 V[i] = DAG.getUNDEF(VT);
5363 // Next, we iteratively mix elements, e.g. for v4f32:
5364 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5365 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5366 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
5367 unsigned EltStride = NumElems >> 1;
5368 while (EltStride != 0) {
5369 for (unsigned i = 0; i < EltStride; ++i) {
5370 // If V[i+EltStride] is undef and this is the first round of mixing,
5371 // then it is safe to just drop this shuffle: V[i] is already in the
5372 // right place, the one element (since it's the first round) being
5373 // inserted as undef can be dropped. This isn't safe for successive
5374 // rounds because they will permute elements within both vectors.
5375 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5376 EltStride == NumElems/2)
5379 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5388 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5389 // them in a MMX register. This is better than doing a stack convert.
5390 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5391 DebugLoc dl = Op.getDebugLoc();
5392 EVT ResVT = Op.getValueType();
5394 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5395 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5397 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5398 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5399 InVec = Op.getOperand(1);
5400 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5401 unsigned NumElts = ResVT.getVectorNumElements();
5402 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5403 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5404 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5406 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5407 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5408 Mask[0] = 0; Mask[1] = 2;
5409 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5411 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5414 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5415 // to create 256-bit vectors from two other 128-bit ones.
5416 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5417 DebugLoc dl = Op.getDebugLoc();
5418 EVT ResVT = Op.getValueType();
5420 assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5422 SDValue V1 = Op.getOperand(0);
5423 SDValue V2 = Op.getOperand(1);
5424 unsigned NumElems = ResVT.getVectorNumElements();
5426 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5430 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5431 EVT ResVT = Op.getValueType();
5433 assert(Op.getNumOperands() == 2);
5434 assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5435 "Unsupported CONCAT_VECTORS for value type");
5437 // We support concatenate two MMX registers and place them in a MMX register.
5438 // This is better than doing a stack convert.
5439 if (ResVT.is128BitVector())
5440 return LowerMMXCONCAT_VECTORS(Op, DAG);
5442 // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5443 // from two other 128-bit ones.
5444 return LowerAVXCONCAT_VECTORS(Op, DAG);
5447 // Try to lower a shuffle node into a simple blend instruction.
5448 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5449 const X86Subtarget *Subtarget,
5450 SelectionDAG &DAG) {
5451 SDValue V1 = SVOp->getOperand(0);
5452 SDValue V2 = SVOp->getOperand(1);
5453 DebugLoc dl = SVOp->getDebugLoc();
5454 MVT VT = SVOp->getValueType(0).getSimpleVT();
5455 unsigned NumElems = VT.getVectorNumElements();
5457 if (!Subtarget->hasSSE41())
5463 switch (VT.SimpleTy) {
5464 default: return SDValue();
5466 ISDNo = X86ISD::BLENDPW;
5471 ISDNo = X86ISD::BLENDPS;
5476 ISDNo = X86ISD::BLENDPD;
5481 if (!Subtarget->hasAVX())
5483 ISDNo = X86ISD::BLENDPS;
5488 if (!Subtarget->hasAVX())
5490 ISDNo = X86ISD::BLENDPD;
5494 assert(ISDNo && "Invalid Op Number");
5496 unsigned MaskVals = 0;
5498 for (unsigned i = 0; i != NumElems; ++i) {
5499 int EltIdx = SVOp->getMaskElt(i);
5500 if (EltIdx == (int)i || EltIdx < 0)
5502 else if (EltIdx == (int)(i + NumElems))
5503 continue; // Bit is set to zero;
5508 V1 = DAG.getNode(ISD::BITCAST, dl, OpTy, V1);
5509 V2 = DAG.getNode(ISD::BITCAST, dl, OpTy, V2);
5510 SDValue Ret = DAG.getNode(ISDNo, dl, OpTy, V1, V2,
5511 DAG.getConstant(MaskVals, MVT::i32));
5512 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5515 // v8i16 shuffles - Prefer shuffles in the following order:
5516 // 1. [all] pshuflw, pshufhw, optional move
5517 // 2. [ssse3] 1 x pshufb
5518 // 3. [ssse3] 2 x pshufb + 1 x por
5519 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5521 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5522 SelectionDAG &DAG) const {
5523 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5524 SDValue V1 = SVOp->getOperand(0);
5525 SDValue V2 = SVOp->getOperand(1);
5526 DebugLoc dl = SVOp->getDebugLoc();
5527 SmallVector<int, 8> MaskVals;
5529 // Determine if more than 1 of the words in each of the low and high quadwords
5530 // of the result come from the same quadword of one of the two inputs. Undef
5531 // mask values count as coming from any quadword, for better codegen.
5532 unsigned LoQuad[] = { 0, 0, 0, 0 };
5533 unsigned HiQuad[] = { 0, 0, 0, 0 };
5534 std::bitset<4> InputQuads;
5535 for (unsigned i = 0; i < 8; ++i) {
5536 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5537 int EltIdx = SVOp->getMaskElt(i);
5538 MaskVals.push_back(EltIdx);
5547 InputQuads.set(EltIdx / 4);
5550 int BestLoQuad = -1;
5551 unsigned MaxQuad = 1;
5552 for (unsigned i = 0; i < 4; ++i) {
5553 if (LoQuad[i] > MaxQuad) {
5555 MaxQuad = LoQuad[i];
5559 int BestHiQuad = -1;
5561 for (unsigned i = 0; i < 4; ++i) {
5562 if (HiQuad[i] > MaxQuad) {
5564 MaxQuad = HiQuad[i];
5568 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5569 // of the two input vectors, shuffle them into one input vector so only a
5570 // single pshufb instruction is necessary. If There are more than 2 input
5571 // quads, disable the next transformation since it does not help SSSE3.
5572 bool V1Used = InputQuads[0] || InputQuads[1];
5573 bool V2Used = InputQuads[2] || InputQuads[3];
5574 if (Subtarget->hasSSSE3()) {
5575 if (InputQuads.count() == 2 && V1Used && V2Used) {
5576 BestLoQuad = InputQuads[0] ? 0 : 1;
5577 BestHiQuad = InputQuads[2] ? 2 : 3;
5579 if (InputQuads.count() > 2) {
5585 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5586 // the shuffle mask. If a quad is scored as -1, that means that it contains
5587 // words from all 4 input quadwords.
5589 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5591 BestLoQuad < 0 ? 0 : BestLoQuad,
5592 BestHiQuad < 0 ? 1 : BestHiQuad
5594 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5595 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5596 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5597 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5599 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5600 // source words for the shuffle, to aid later transformations.
5601 bool AllWordsInNewV = true;
5602 bool InOrder[2] = { true, true };
5603 for (unsigned i = 0; i != 8; ++i) {
5604 int idx = MaskVals[i];
5606 InOrder[i/4] = false;
5607 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5609 AllWordsInNewV = false;
5613 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5614 if (AllWordsInNewV) {
5615 for (int i = 0; i != 8; ++i) {
5616 int idx = MaskVals[i];
5619 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5620 if ((idx != i) && idx < 4)
5622 if ((idx != i) && idx > 3)
5631 // If we've eliminated the use of V2, and the new mask is a pshuflw or
5632 // pshufhw, that's as cheap as it gets. Return the new shuffle.
5633 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5634 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5635 unsigned TargetMask = 0;
5636 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5637 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5638 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5639 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5640 getShufflePSHUFLWImmediate(SVOp);
5641 V1 = NewV.getOperand(0);
5642 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5646 // If we have SSSE3, and all words of the result are from 1 input vector,
5647 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
5648 // is present, fall back to case 4.
5649 if (Subtarget->hasSSSE3()) {
5650 SmallVector<SDValue,16> pshufbMask;
5652 // If we have elements from both input vectors, set the high bit of the
5653 // shuffle mask element to zero out elements that come from V2 in the V1
5654 // mask, and elements that come from V1 in the V2 mask, so that the two
5655 // results can be OR'd together.
5656 bool TwoInputs = V1Used && V2Used;
5657 for (unsigned i = 0; i != 8; ++i) {
5658 int EltIdx = MaskVals[i] * 2;
5659 int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5660 int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5661 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5662 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5664 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5665 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5666 DAG.getNode(ISD::BUILD_VECTOR, dl,
5667 MVT::v16i8, &pshufbMask[0], 16));
5669 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5671 // Calculate the shuffle mask for the second input, shuffle it, and
5672 // OR it with the first shuffled input.
5674 for (unsigned i = 0; i != 8; ++i) {
5675 int EltIdx = MaskVals[i] * 2;
5676 int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5677 int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5678 pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5679 pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5681 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5682 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5683 DAG.getNode(ISD::BUILD_VECTOR, dl,
5684 MVT::v16i8, &pshufbMask[0], 16));
5685 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5686 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5689 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5690 // and update MaskVals with new element order.
5691 std::bitset<8> InOrder;
5692 if (BestLoQuad >= 0) {
5693 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5694 for (int i = 0; i != 4; ++i) {
5695 int idx = MaskVals[i];
5698 } else if ((idx / 4) == BestLoQuad) {
5703 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5706 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5707 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5708 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5710 getShufflePSHUFLWImmediate(SVOp), DAG);
5714 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5715 // and update MaskVals with the new element order.
5716 if (BestHiQuad >= 0) {
5717 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5718 for (unsigned i = 4; i != 8; ++i) {
5719 int idx = MaskVals[i];
5722 } else if ((idx / 4) == BestHiQuad) {
5723 MaskV[i] = (idx & 3) + 4;
5727 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5730 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5731 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5732 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5734 getShufflePSHUFHWImmediate(SVOp), DAG);
5738 // In case BestHi & BestLo were both -1, which means each quadword has a word
5739 // from each of the four input quadwords, calculate the InOrder bitvector now
5740 // before falling through to the insert/extract cleanup.
5741 if (BestLoQuad == -1 && BestHiQuad == -1) {
5743 for (int i = 0; i != 8; ++i)
5744 if (MaskVals[i] < 0 || MaskVals[i] == i)
5748 // The other elements are put in the right place using pextrw and pinsrw.
5749 for (unsigned i = 0; i != 8; ++i) {
5752 int EltIdx = MaskVals[i];
5755 SDValue ExtOp = (EltIdx < 8) ?
5756 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5757 DAG.getIntPtrConstant(EltIdx)) :
5758 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5759 DAG.getIntPtrConstant(EltIdx - 8));
5760 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5761 DAG.getIntPtrConstant(i));
5766 // v16i8 shuffles - Prefer shuffles in the following order:
5767 // 1. [ssse3] 1 x pshufb
5768 // 2. [ssse3] 2 x pshufb + 1 x por
5769 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
5771 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5773 const X86TargetLowering &TLI) {
5774 SDValue V1 = SVOp->getOperand(0);
5775 SDValue V2 = SVOp->getOperand(1);
5776 DebugLoc dl = SVOp->getDebugLoc();
5777 ArrayRef<int> MaskVals = SVOp->getMask();
5779 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5781 // If we have SSSE3, case 1 is generated when all result bytes come from
5782 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
5783 // present, fall back to case 3.
5785 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5786 if (TLI.getSubtarget()->hasSSSE3()) {
5787 SmallVector<SDValue,16> pshufbMask;
5789 // If all result elements are from one input vector, then only translate
5790 // undef mask values to 0x80 (zero out result) in the pshufb mask.
5792 // Otherwise, we have elements from both input vectors, and must zero out
5793 // elements that come from V2 in the first mask, and V1 in the second mask
5794 // so that we can OR them together.
5795 for (unsigned i = 0; i != 16; ++i) {
5796 int EltIdx = MaskVals[i];
5797 if (EltIdx < 0 || EltIdx >= 16)
5799 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5801 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5802 DAG.getNode(ISD::BUILD_VECTOR, dl,
5803 MVT::v16i8, &pshufbMask[0], 16));
5807 // Calculate the shuffle mask for the second input, shuffle it, and
5808 // OR it with the first shuffled input.
5810 for (unsigned i = 0; i != 16; ++i) {
5811 int EltIdx = MaskVals[i];
5812 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5813 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5815 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5816 DAG.getNode(ISD::BUILD_VECTOR, dl,
5817 MVT::v16i8, &pshufbMask[0], 16));
5818 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5821 // No SSSE3 - Calculate in place words and then fix all out of place words
5822 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
5823 // the 16 different words that comprise the two doublequadword input vectors.
5824 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5825 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5827 for (int i = 0; i != 8; ++i) {
5828 int Elt0 = MaskVals[i*2];
5829 int Elt1 = MaskVals[i*2+1];
5831 // This word of the result is all undef, skip it.
5832 if (Elt0 < 0 && Elt1 < 0)
5835 // This word of the result is already in the correct place, skip it.
5836 if ((Elt0 == i*2) && (Elt1 == i*2+1))
5839 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5840 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5843 // If Elt0 and Elt1 are defined, are consecutive, and can be load
5844 // using a single extract together, load it and store it.
5845 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5846 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5847 DAG.getIntPtrConstant(Elt1 / 2));
5848 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5849 DAG.getIntPtrConstant(i));
5853 // If Elt1 is defined, extract it from the appropriate source. If the
5854 // source byte is not also odd, shift the extracted word left 8 bits
5855 // otherwise clear the bottom 8 bits if we need to do an or.
5857 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5858 DAG.getIntPtrConstant(Elt1 / 2));
5859 if ((Elt1 & 1) == 0)
5860 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
5862 TLI.getShiftAmountTy(InsElt.getValueType())));
5864 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
5865 DAG.getConstant(0xFF00, MVT::i16));
5867 // If Elt0 is defined, extract it from the appropriate source. If the
5868 // source byte is not also even, shift the extracted word right 8 bits. If
5869 // Elt1 was also defined, OR the extracted values together before
5870 // inserting them in the result.
5872 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
5873 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
5874 if ((Elt0 & 1) != 0)
5875 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
5877 TLI.getShiftAmountTy(InsElt0.getValueType())));
5879 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
5880 DAG.getConstant(0x00FF, MVT::i16));
5881 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
5884 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5885 DAG.getIntPtrConstant(i));
5887 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
5890 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
5891 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
5892 /// done when every pair / quad of shuffle mask elements point to elements in
5893 /// the right sequence. e.g.
5894 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
5896 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
5897 SelectionDAG &DAG, DebugLoc dl) {
5898 MVT VT = SVOp->getValueType(0).getSimpleVT();
5899 unsigned NumElems = VT.getVectorNumElements();
5902 switch (VT.SimpleTy) {
5903 default: llvm_unreachable("Unexpected!");
5904 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
5905 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
5906 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
5907 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
5908 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
5909 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
5912 SmallVector<int, 8> MaskVec;
5913 for (unsigned i = 0; i != NumElems; i += Scale) {
5915 for (unsigned j = 0; j != Scale; ++j) {
5916 int EltIdx = SVOp->getMaskElt(i+j);
5920 StartIdx = (EltIdx / Scale);
5921 if (EltIdx != (int)(StartIdx*Scale + j))
5924 MaskVec.push_back(StartIdx);
5927 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
5928 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
5929 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
5932 /// getVZextMovL - Return a zero-extending vector move low node.
5934 static SDValue getVZextMovL(EVT VT, EVT OpVT,
5935 SDValue SrcOp, SelectionDAG &DAG,
5936 const X86Subtarget *Subtarget, DebugLoc dl) {
5937 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
5938 LoadSDNode *LD = NULL;
5939 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
5940 LD = dyn_cast<LoadSDNode>(SrcOp);
5942 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
5944 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
5945 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
5946 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5947 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
5948 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
5950 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
5951 return DAG.getNode(ISD::BITCAST, dl, VT,
5952 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5953 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5961 return DAG.getNode(ISD::BITCAST, dl, VT,
5962 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
5963 DAG.getNode(ISD::BITCAST, dl,
5967 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
5968 /// which could not be matched by any known target speficic shuffle
5970 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
5971 EVT VT = SVOp->getValueType(0);
5973 unsigned NumElems = VT.getVectorNumElements();
5974 unsigned NumLaneElems = NumElems / 2;
5976 DebugLoc dl = SVOp->getDebugLoc();
5977 MVT EltVT = VT.getVectorElementType().getSimpleVT();
5978 EVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
5981 SmallVector<int, 16> Mask;
5982 for (unsigned l = 0; l < 2; ++l) {
5983 // Build a shuffle mask for the output, discovering on the fly which
5984 // input vectors to use as shuffle operands (recorded in InputUsed).
5985 // If building a suitable shuffle vector proves too hard, then bail
5986 // out with UseBuildVector set.
5987 bool UseBuildVector = false;
5988 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
5989 unsigned LaneStart = l * NumLaneElems;
5990 for (unsigned i = 0; i != NumLaneElems; ++i) {
5991 // The mask element. This indexes into the input.
5992 int Idx = SVOp->getMaskElt(i+LaneStart);
5994 // the mask element does not index into any input vector.
5999 // The input vector this mask element indexes into.
6000 int Input = Idx / NumLaneElems;
6002 // Turn the index into an offset from the start of the input vector.
6003 Idx -= Input * NumLaneElems;
6005 // Find or create a shuffle vector operand to hold this input.
6007 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6008 if (InputUsed[OpNo] == Input)
6009 // This input vector is already an operand.
6011 if (InputUsed[OpNo] < 0) {
6012 // Create a new operand for this input vector.
6013 InputUsed[OpNo] = Input;
6018 if (OpNo >= array_lengthof(InputUsed)) {
6019 // More than two input vectors used! Give up on trying to create a
6020 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
6021 UseBuildVector = true;
6025 // Add the mask index for the new shuffle vector.
6026 Mask.push_back(Idx + OpNo * NumLaneElems);
6029 if (UseBuildVector) {
6030 SmallVector<SDValue, 16> SVOps;
6031 for (unsigned i = 0; i != NumLaneElems; ++i) {
6032 // The mask element. This indexes into the input.
6033 int Idx = SVOp->getMaskElt(i+LaneStart);
6035 SVOps.push_back(DAG.getUNDEF(EltVT));
6039 // The input vector this mask element indexes into.
6040 int Input = Idx / NumElems;
6042 // Turn the index into an offset from the start of the input vector.
6043 Idx -= Input * NumElems;
6045 // Extract the vector element by hand.
6046 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6047 SVOp->getOperand(Input),
6048 DAG.getIntPtrConstant(Idx)));
6051 // Construct the output using a BUILD_VECTOR.
6052 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6054 } else if (InputUsed[0] < 0) {
6055 // No input vectors were used! The result is undefined.
6056 Output[l] = DAG.getUNDEF(NVT);
6058 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6059 (InputUsed[0] % 2) * NumLaneElems,
6061 // If only one input was used, use an undefined vector for the other.
6062 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6063 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6064 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6065 // At least one input vector was used. Create a new shuffle vector.
6066 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6072 // Concatenate the result back
6073 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6076 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6077 /// 4 elements, and match them with several different shuffle types.
6079 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6080 SDValue V1 = SVOp->getOperand(0);
6081 SDValue V2 = SVOp->getOperand(1);
6082 DebugLoc dl = SVOp->getDebugLoc();
6083 EVT VT = SVOp->getValueType(0);
6085 assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6087 std::pair<int, int> Locs[4];
6088 int Mask1[] = { -1, -1, -1, -1 };
6089 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6093 for (unsigned i = 0; i != 4; ++i) {
6094 int Idx = PermMask[i];
6096 Locs[i] = std::make_pair(-1, -1);
6098 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6100 Locs[i] = std::make_pair(0, NumLo);
6104 Locs[i] = std::make_pair(1, NumHi);
6106 Mask1[2+NumHi] = Idx;
6112 if (NumLo <= 2 && NumHi <= 2) {
6113 // If no more than two elements come from either vector. This can be
6114 // implemented with two shuffles. First shuffle gather the elements.
6115 // The second shuffle, which takes the first shuffle as both of its
6116 // vector operands, put the elements into the right order.
6117 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6119 int Mask2[] = { -1, -1, -1, -1 };
6121 for (unsigned i = 0; i != 4; ++i)
6122 if (Locs[i].first != -1) {
6123 unsigned Idx = (i < 2) ? 0 : 4;
6124 Idx += Locs[i].first * 2 + Locs[i].second;
6128 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6131 if (NumLo == 3 || NumHi == 3) {
6132 // Otherwise, we must have three elements from one vector, call it X, and
6133 // one element from the other, call it Y. First, use a shufps to build an
6134 // intermediate vector with the one element from Y and the element from X
6135 // that will be in the same half in the final destination (the indexes don't
6136 // matter). Then, use a shufps to build the final vector, taking the half
6137 // containing the element from Y from the intermediate, and the other half
6140 // Normalize it so the 3 elements come from V1.
6141 CommuteVectorShuffleMask(PermMask, 4);
6145 // Find the element from V2.
6147 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6148 int Val = PermMask[HiIndex];
6155 Mask1[0] = PermMask[HiIndex];
6157 Mask1[2] = PermMask[HiIndex^1];
6159 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6162 Mask1[0] = PermMask[0];
6163 Mask1[1] = PermMask[1];
6164 Mask1[2] = HiIndex & 1 ? 6 : 4;
6165 Mask1[3] = HiIndex & 1 ? 4 : 6;
6166 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6169 Mask1[0] = HiIndex & 1 ? 2 : 0;
6170 Mask1[1] = HiIndex & 1 ? 0 : 2;
6171 Mask1[2] = PermMask[2];
6172 Mask1[3] = PermMask[3];
6177 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6180 // Break it into (shuffle shuffle_hi, shuffle_lo).
6181 int LoMask[] = { -1, -1, -1, -1 };
6182 int HiMask[] = { -1, -1, -1, -1 };
6184 int *MaskPtr = LoMask;
6185 unsigned MaskIdx = 0;
6188 for (unsigned i = 0; i != 4; ++i) {
6195 int Idx = PermMask[i];
6197 Locs[i] = std::make_pair(-1, -1);
6198 } else if (Idx < 4) {
6199 Locs[i] = std::make_pair(MaskIdx, LoIdx);
6200 MaskPtr[LoIdx] = Idx;
6203 Locs[i] = std::make_pair(MaskIdx, HiIdx);
6204 MaskPtr[HiIdx] = Idx;
6209 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6210 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6211 int MaskOps[] = { -1, -1, -1, -1 };
6212 for (unsigned i = 0; i != 4; ++i)
6213 if (Locs[i].first != -1)
6214 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6215 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6218 static bool MayFoldVectorLoad(SDValue V) {
6219 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6220 V = V.getOperand(0);
6221 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6222 V = V.getOperand(0);
6223 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6224 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6225 // BUILD_VECTOR (load), undef
6226 V = V.getOperand(0);
6232 // FIXME: the version above should always be used. Since there's
6233 // a bug where several vector shuffles can't be folded because the
6234 // DAG is not updated during lowering and a node claims to have two
6235 // uses while it only has one, use this version, and let isel match
6236 // another instruction if the load really happens to have more than
6237 // one use. Remove this version after this bug get fixed.
6238 // rdar://8434668, PR8156
6239 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6240 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6241 V = V.getOperand(0);
6242 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6243 V = V.getOperand(0);
6244 if (ISD::isNormalLoad(V.getNode()))
6250 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6251 EVT VT = Op.getValueType();
6253 // Canonizalize to v2f64.
6254 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6255 return DAG.getNode(ISD::BITCAST, dl, VT,
6256 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6261 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6263 SDValue V1 = Op.getOperand(0);
6264 SDValue V2 = Op.getOperand(1);
6265 EVT VT = Op.getValueType();
6267 assert(VT != MVT::v2i64 && "unsupported shuffle type");
6269 if (HasSSE2 && VT == MVT::v2f64)
6270 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6272 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6273 return DAG.getNode(ISD::BITCAST, dl, VT,
6274 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6275 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6276 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6280 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6281 SDValue V1 = Op.getOperand(0);
6282 SDValue V2 = Op.getOperand(1);
6283 EVT VT = Op.getValueType();
6285 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6286 "unsupported shuffle type");
6288 if (V2.getOpcode() == ISD::UNDEF)
6292 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6296 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6297 SDValue V1 = Op.getOperand(0);
6298 SDValue V2 = Op.getOperand(1);
6299 EVT VT = Op.getValueType();
6300 unsigned NumElems = VT.getVectorNumElements();
6302 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6303 // operand of these instructions is only memory, so check if there's a
6304 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6306 bool CanFoldLoad = false;
6308 // Trivial case, when V2 comes from a load.
6309 if (MayFoldVectorLoad(V2))
6312 // When V1 is a load, it can be folded later into a store in isel, example:
6313 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6315 // (MOVLPSmr addr:$src1, VR128:$src2)
6316 // So, recognize this potential and also use MOVLPS or MOVLPD
6317 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6320 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6322 if (HasSSE2 && NumElems == 2)
6323 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6326 // If we don't care about the second element, procede to use movss.
6327 if (SVOp->getMaskElt(1) != -1)
6328 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6331 // movl and movlp will both match v2i64, but v2i64 is never matched by
6332 // movl earlier because we make it strict to avoid messing with the movlp load
6333 // folding logic (see the code above getMOVLP call). Match it here then,
6334 // this is horrible, but will stay like this until we move all shuffle
6335 // matching to x86 specific nodes. Note that for the 1st condition all
6336 // types are matched with movsd.
6338 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6339 // as to remove this logic from here, as much as possible
6340 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6341 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6342 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6345 assert(VT != MVT::v4i32 && "unsupported shuffle type");
6347 // Invert the operand order and use SHUFPS to match it.
6348 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6349 getShuffleSHUFImmediate(SVOp), DAG);
6353 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6354 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6355 EVT VT = Op.getValueType();
6356 DebugLoc dl = Op.getDebugLoc();
6357 SDValue V1 = Op.getOperand(0);
6358 SDValue V2 = Op.getOperand(1);
6360 if (isZeroShuffle(SVOp))
6361 return getZeroVector(VT, Subtarget, DAG, dl);
6363 // Handle splat operations
6364 if (SVOp->isSplat()) {
6365 unsigned NumElem = VT.getVectorNumElements();
6366 int Size = VT.getSizeInBits();
6368 // Use vbroadcast whenever the splat comes from a foldable load
6369 SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6370 if (Broadcast.getNode())
6373 // Handle splats by matching through known shuffle masks
6374 if ((Size == 128 && NumElem <= 4) ||
6375 (Size == 256 && NumElem < 8))
6378 // All remaning splats are promoted to target supported vector shuffles.
6379 return PromoteSplat(SVOp, DAG);
6382 // If the shuffle can be profitably rewritten as a narrower shuffle, then
6384 if (VT == MVT::v8i16 || VT == MVT::v16i8 ||
6385 VT == MVT::v16i16 || VT == MVT::v32i8) {
6386 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6387 if (NewOp.getNode())
6388 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6389 } else if ((VT == MVT::v4i32 ||
6390 (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6391 // FIXME: Figure out a cleaner way to do this.
6392 // Try to make use of movq to zero out the top part.
6393 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6394 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6395 if (NewOp.getNode()) {
6396 EVT NewVT = NewOp.getValueType();
6397 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6398 NewVT, true, false))
6399 return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6400 DAG, Subtarget, dl);
6402 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6403 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6404 if (NewOp.getNode()) {
6405 EVT NewVT = NewOp.getValueType();
6406 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6407 return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6408 DAG, Subtarget, dl);
6416 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6417 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6418 SDValue V1 = Op.getOperand(0);
6419 SDValue V2 = Op.getOperand(1);
6420 EVT VT = Op.getValueType();
6421 DebugLoc dl = Op.getDebugLoc();
6422 unsigned NumElems = VT.getVectorNumElements();
6423 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6424 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6425 bool V1IsSplat = false;
6426 bool V2IsSplat = false;
6427 bool HasSSE2 = Subtarget->hasSSE2();
6428 bool HasAVX = Subtarget->hasAVX();
6429 bool HasAVX2 = Subtarget->hasAVX2();
6430 MachineFunction &MF = DAG.getMachineFunction();
6431 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6433 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6435 if (V1IsUndef && V2IsUndef)
6436 return DAG.getUNDEF(VT);
6438 assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6440 // Vector shuffle lowering takes 3 steps:
6442 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6443 // narrowing and commutation of operands should be handled.
6444 // 2) Matching of shuffles with known shuffle masks to x86 target specific
6446 // 3) Rewriting of unmatched masks into new generic shuffle operations,
6447 // so the shuffle can be broken into other shuffles and the legalizer can
6448 // try the lowering again.
6450 // The general idea is that no vector_shuffle operation should be left to
6451 // be matched during isel, all of them must be converted to a target specific
6454 // Normalize the input vectors. Here splats, zeroed vectors, profitable
6455 // narrowing and commutation of operands should be handled. The actual code
6456 // doesn't include all of those, work in progress...
6457 SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6458 if (NewOp.getNode())
6461 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6463 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6464 // unpckh_undef). Only use pshufd if speed is more important than size.
6465 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6466 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6467 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6468 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6470 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6471 V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6472 return getMOVDDup(Op, dl, V1, DAG);
6474 if (isMOVHLPS_v_undef_Mask(M, VT))
6475 return getMOVHighToLow(Op, dl, DAG);
6477 // Use to match splats
6478 if (HasSSE2 && isUNPCKHMask(M, VT, HasAVX2) && V2IsUndef &&
6479 (VT == MVT::v2f64 || VT == MVT::v2i64))
6480 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6482 if (isPSHUFDMask(M, VT)) {
6483 // The actual implementation will match the mask in the if above and then
6484 // during isel it can match several different instructions, not only pshufd
6485 // as its name says, sad but true, emulate the behavior for now...
6486 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6487 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6489 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6491 if (HasAVX && (VT == MVT::v4f32 || VT == MVT::v2f64))
6492 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask, DAG);
6494 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6495 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6497 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6501 // Check if this can be converted into a logical shift.
6502 bool isLeft = false;
6505 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6506 if (isShift && ShVal.hasOneUse()) {
6507 // If the shifted value has multiple uses, it may be cheaper to use
6508 // v_set0 + movlhps or movhlps, etc.
6509 EVT EltVT = VT.getVectorElementType();
6510 ShAmt *= EltVT.getSizeInBits();
6511 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6514 if (isMOVLMask(M, VT)) {
6515 if (ISD::isBuildVectorAllZeros(V1.getNode()))
6516 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6517 if (!isMOVLPMask(M, VT)) {
6518 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6519 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6521 if (VT == MVT::v4i32 || VT == MVT::v4f32)
6522 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6526 // FIXME: fold these into legal mask.
6527 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasAVX2))
6528 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6530 if (isMOVHLPSMask(M, VT))
6531 return getMOVHighToLow(Op, dl, DAG);
6533 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6534 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6536 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6537 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6539 if (isMOVLPMask(M, VT))
6540 return getMOVLP(Op, dl, DAG, HasSSE2);
6542 if (ShouldXformToMOVHLPS(M, VT) ||
6543 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6544 return CommuteVectorShuffle(SVOp, DAG);
6547 // No better options. Use a vshldq / vsrldq.
6548 EVT EltVT = VT.getVectorElementType();
6549 ShAmt *= EltVT.getSizeInBits();
6550 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6553 bool Commuted = false;
6554 // FIXME: This should also accept a bitcast of a splat? Be careful, not
6555 // 1,1,1,1 -> v8i16 though.
6556 V1IsSplat = isSplatVector(V1.getNode());
6557 V2IsSplat = isSplatVector(V2.getNode());
6559 // Canonicalize the splat or undef, if present, to be on the RHS.
6560 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6561 CommuteVectorShuffleMask(M, NumElems);
6563 std::swap(V1IsSplat, V2IsSplat);
6567 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6568 // Shuffling low element of v1 into undef, just return v1.
6571 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6572 // the instruction selector will not match, so get a canonical MOVL with
6573 // swapped operands to undo the commute.
6574 return getMOVL(DAG, dl, VT, V2, V1);
6577 if (isUNPCKLMask(M, VT, HasAVX2))
6578 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6580 if (isUNPCKHMask(M, VT, HasAVX2))
6581 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6584 // Normalize mask so all entries that point to V2 points to its first
6585 // element then try to match unpck{h|l} again. If match, return a
6586 // new vector_shuffle with the corrected mask.p
6587 SmallVector<int, 8> NewMask(M.begin(), M.end());
6588 NormalizeMask(NewMask, NumElems);
6589 if (isUNPCKLMask(NewMask, VT, HasAVX2, true))
6590 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6591 if (isUNPCKHMask(NewMask, VT, HasAVX2, true))
6592 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6596 // Commute is back and try unpck* again.
6597 // FIXME: this seems wrong.
6598 CommuteVectorShuffleMask(M, NumElems);
6600 std::swap(V1IsSplat, V2IsSplat);
6603 if (isUNPCKLMask(M, VT, HasAVX2))
6604 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6606 if (isUNPCKHMask(M, VT, HasAVX2))
6607 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6610 // Normalize the node to match x86 shuffle ops if needed
6611 if (!V2IsUndef && (isSHUFPMask(M, VT, HasAVX, /* Commuted */ true)))
6612 return CommuteVectorShuffle(SVOp, DAG);
6614 // The checks below are all present in isShuffleMaskLegal, but they are
6615 // inlined here right now to enable us to directly emit target specific
6616 // nodes, and remove one by one until they don't return Op anymore.
6618 if (isPALIGNRMask(M, VT, Subtarget))
6619 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6620 getShufflePALIGNRImmediate(SVOp),
6623 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6624 SVOp->getSplatIndex() == 0 && V2IsUndef) {
6625 if (VT == MVT::v2f64 || VT == MVT::v2i64)
6626 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6629 if (isPSHUFHWMask(M, VT, HasAVX2))
6630 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6631 getShufflePSHUFHWImmediate(SVOp),
6634 if (isPSHUFLWMask(M, VT, HasAVX2))
6635 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6636 getShufflePSHUFLWImmediate(SVOp),
6639 if (isSHUFPMask(M, VT, HasAVX))
6640 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6641 getShuffleSHUFImmediate(SVOp), DAG);
6643 if (isUNPCKL_v_undef_Mask(M, VT, HasAVX2))
6644 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6645 if (isUNPCKH_v_undef_Mask(M, VT, HasAVX2))
6646 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6648 //===--------------------------------------------------------------------===//
6649 // Generate target specific nodes for 128 or 256-bit shuffles only
6650 // supported in the AVX instruction set.
6653 // Handle VMOVDDUPY permutations
6654 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasAVX))
6655 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6657 // Handle VPERMILPS/D* permutations
6658 if (isVPERMILPMask(M, VT, HasAVX)) {
6659 if (HasAVX2 && VT == MVT::v8i32)
6660 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
6661 getShuffleSHUFImmediate(SVOp), DAG);
6662 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
6663 getShuffleSHUFImmediate(SVOp), DAG);
6666 // Handle VPERM2F128/VPERM2I128 permutations
6667 if (isVPERM2X128Mask(M, VT, HasAVX))
6668 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
6669 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
6671 SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
6672 if (BlendOp.getNode())
6675 if (V2IsUndef && HasAVX2 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
6676 SmallVector<SDValue, 8> permclMask;
6677 for (unsigned i = 0; i != 8; ++i) {
6678 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
6680 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
6682 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
6683 return DAG.getNode(X86ISD::VPERMV, dl, VT,
6684 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
6687 if (V2IsUndef && HasAVX2 && (VT == MVT::v4i64 || VT == MVT::v4f64))
6688 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
6689 getShuffleCLImmediate(SVOp), DAG);
6692 //===--------------------------------------------------------------------===//
6693 // Since no target specific shuffle was selected for this generic one,
6694 // lower it into other known shuffles. FIXME: this isn't true yet, but
6695 // this is the plan.
6698 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
6699 if (VT == MVT::v8i16) {
6700 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
6701 if (NewOp.getNode())
6705 if (VT == MVT::v16i8) {
6706 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
6707 if (NewOp.getNode())
6711 // Handle all 128-bit wide vectors with 4 elements, and match them with
6712 // several different shuffle types.
6713 if (NumElems == 4 && VT.getSizeInBits() == 128)
6714 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
6716 // Handle general 256-bit shuffles
6717 if (VT.is256BitVector())
6718 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
6724 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
6725 SelectionDAG &DAG) const {
6726 EVT VT = Op.getValueType();
6727 DebugLoc dl = Op.getDebugLoc();
6729 if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
6732 if (VT.getSizeInBits() == 8) {
6733 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
6734 Op.getOperand(0), Op.getOperand(1));
6735 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6736 DAG.getValueType(VT));
6737 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6740 if (VT.getSizeInBits() == 16) {
6741 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6742 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
6744 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6745 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6746 DAG.getNode(ISD::BITCAST, dl,
6750 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
6751 Op.getOperand(0), Op.getOperand(1));
6752 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
6753 DAG.getValueType(VT));
6754 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6757 if (VT == MVT::f32) {
6758 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
6759 // the result back to FR32 register. It's only worth matching if the
6760 // result has a single use which is a store or a bitcast to i32. And in
6761 // the case of a store, it's not worth it if the index is a constant 0,
6762 // because a MOVSSmr can be used instead, which is smaller and faster.
6763 if (!Op.hasOneUse())
6765 SDNode *User = *Op.getNode()->use_begin();
6766 if ((User->getOpcode() != ISD::STORE ||
6767 (isa<ConstantSDNode>(Op.getOperand(1)) &&
6768 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
6769 (User->getOpcode() != ISD::BITCAST ||
6770 User->getValueType(0) != MVT::i32))
6772 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6773 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
6776 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
6779 if (VT == MVT::i32 || VT == MVT::i64) {
6780 // ExtractPS/pextrq works with constant index.
6781 if (isa<ConstantSDNode>(Op.getOperand(1)))
6789 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6790 SelectionDAG &DAG) const {
6791 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6794 SDValue Vec = Op.getOperand(0);
6795 EVT VecVT = Vec.getValueType();
6797 // If this is a 256-bit vector result, first extract the 128-bit vector and
6798 // then extract the element from the 128-bit vector.
6799 if (VecVT.getSizeInBits() == 256) {
6800 DebugLoc dl = Op.getNode()->getDebugLoc();
6801 unsigned NumElems = VecVT.getVectorNumElements();
6802 SDValue Idx = Op.getOperand(1);
6803 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
6805 // Get the 128-bit vector.
6806 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
6808 if (IdxVal >= NumElems/2)
6809 IdxVal -= NumElems/2;
6810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
6811 DAG.getConstant(IdxVal, MVT::i32));
6814 assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
6816 if (Subtarget->hasSSE41()) {
6817 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
6822 EVT VT = Op.getValueType();
6823 DebugLoc dl = Op.getDebugLoc();
6824 // TODO: handle v16i8.
6825 if (VT.getSizeInBits() == 16) {
6826 SDValue Vec = Op.getOperand(0);
6827 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6829 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
6830 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
6831 DAG.getNode(ISD::BITCAST, dl,
6834 // Transform it so it match pextrw which produces a 32-bit result.
6835 EVT EltVT = MVT::i32;
6836 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
6837 Op.getOperand(0), Op.getOperand(1));
6838 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
6839 DAG.getValueType(VT));
6840 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
6843 if (VT.getSizeInBits() == 32) {
6844 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6848 // SHUFPS the element to the lowest double word, then movss.
6849 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
6850 EVT VVT = Op.getOperand(0).getValueType();
6851 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6852 DAG.getUNDEF(VVT), Mask);
6853 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6854 DAG.getIntPtrConstant(0));
6857 if (VT.getSizeInBits() == 64) {
6858 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
6859 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
6860 // to match extract_elt for f64.
6861 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6865 // UNPCKHPD the element to the lowest double word, then movsd.
6866 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
6867 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
6868 int Mask[2] = { 1, -1 };
6869 EVT VVT = Op.getOperand(0).getValueType();
6870 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
6871 DAG.getUNDEF(VVT), Mask);
6872 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
6873 DAG.getIntPtrConstant(0));
6880 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
6881 SelectionDAG &DAG) const {
6882 EVT VT = Op.getValueType();
6883 EVT EltVT = VT.getVectorElementType();
6884 DebugLoc dl = Op.getDebugLoc();
6886 SDValue N0 = Op.getOperand(0);
6887 SDValue N1 = Op.getOperand(1);
6888 SDValue N2 = Op.getOperand(2);
6890 if (VT.getSizeInBits() == 256)
6893 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
6894 isa<ConstantSDNode>(N2)) {
6896 if (VT == MVT::v8i16)
6897 Opc = X86ISD::PINSRW;
6898 else if (VT == MVT::v16i8)
6899 Opc = X86ISD::PINSRB;
6901 Opc = X86ISD::PINSRB;
6903 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
6905 if (N1.getValueType() != MVT::i32)
6906 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6907 if (N2.getValueType() != MVT::i32)
6908 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6909 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
6912 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
6913 // Bits [7:6] of the constant are the source select. This will always be
6914 // zero here. The DAG Combiner may combine an extract_elt index into these
6915 // bits. For example (insert (extract, 3), 2) could be matched by putting
6916 // the '3' into bits [7:6] of X86ISD::INSERTPS.
6917 // Bits [5:4] of the constant are the destination select. This is the
6918 // value of the incoming immediate.
6919 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
6920 // combine either bitwise AND or insert of float 0.0 to set these bits.
6921 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
6922 // Create this as a scalar to vector..
6923 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
6924 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
6927 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
6928 // PINSR* works with constant index.
6935 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
6936 EVT VT = Op.getValueType();
6937 EVT EltVT = VT.getVectorElementType();
6939 DebugLoc dl = Op.getDebugLoc();
6940 SDValue N0 = Op.getOperand(0);
6941 SDValue N1 = Op.getOperand(1);
6942 SDValue N2 = Op.getOperand(2);
6944 // If this is a 256-bit vector result, first extract the 128-bit vector,
6945 // insert the element into the extracted half and then place it back.
6946 if (VT.getSizeInBits() == 256) {
6947 if (!isa<ConstantSDNode>(N2))
6950 // Get the desired 128-bit vector half.
6951 unsigned NumElems = VT.getVectorNumElements();
6952 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
6953 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
6955 // Insert the element into the desired half.
6956 bool Upper = IdxVal >= NumElems/2;
6957 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
6958 DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
6960 // Insert the changed part back to the 256-bit vector
6961 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
6964 if (Subtarget->hasSSE41())
6965 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
6967 if (EltVT == MVT::i8)
6970 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
6971 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
6972 // as its second argument.
6973 if (N1.getValueType() != MVT::i32)
6974 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
6975 if (N2.getValueType() != MVT::i32)
6976 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
6977 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
6983 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6984 LLVMContext *Context = DAG.getContext();
6985 DebugLoc dl = Op.getDebugLoc();
6986 EVT OpVT = Op.getValueType();
6988 // If this is a 256-bit vector result, first insert into a 128-bit
6989 // vector and then insert into the 256-bit vector.
6990 if (OpVT.getSizeInBits() > 128) {
6991 // Insert into a 128-bit vector.
6992 EVT VT128 = EVT::getVectorVT(*Context,
6993 OpVT.getVectorElementType(),
6994 OpVT.getVectorNumElements() / 2);
6996 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
6998 // Insert the 128-bit vector.
6999 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7002 if (OpVT == MVT::v1i64 &&
7003 Op.getOperand(0).getValueType() == MVT::i64)
7004 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7006 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7007 assert(OpVT.getSizeInBits() == 128 && "Expected an SSE type!");
7008 return DAG.getNode(ISD::BITCAST, dl, OpVT,
7009 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7012 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
7013 // a simple subregister reference or explicit instructions to grab
7014 // upper bits of a vector.
7016 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7017 if (Subtarget->hasAVX()) {
7018 DebugLoc dl = Op.getNode()->getDebugLoc();
7019 SDValue Vec = Op.getNode()->getOperand(0);
7020 SDValue Idx = Op.getNode()->getOperand(1);
7022 if (Op.getNode()->getValueType(0).getSizeInBits() == 128 &&
7023 Vec.getNode()->getValueType(0).getSizeInBits() == 256 &&
7024 isa<ConstantSDNode>(Idx)) {
7025 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7026 return Extract128BitVector(Vec, IdxVal, DAG, dl);
7032 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
7033 // simple superregister reference or explicit instructions to insert
7034 // the upper bits of a vector.
7036 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7037 if (Subtarget->hasAVX()) {
7038 DebugLoc dl = Op.getNode()->getDebugLoc();
7039 SDValue Vec = Op.getNode()->getOperand(0);
7040 SDValue SubVec = Op.getNode()->getOperand(1);
7041 SDValue Idx = Op.getNode()->getOperand(2);
7043 if (Op.getNode()->getValueType(0).getSizeInBits() == 256 &&
7044 SubVec.getNode()->getValueType(0).getSizeInBits() == 128 &&
7045 isa<ConstantSDNode>(Idx)) {
7046 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7047 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7053 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7054 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7055 // one of the above mentioned nodes. It has to be wrapped because otherwise
7056 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7057 // be used to form addressing mode. These wrapped nodes will be selected
7060 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7061 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7063 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7065 unsigned char OpFlag = 0;
7066 unsigned WrapperKind = X86ISD::Wrapper;
7067 CodeModel::Model M = getTargetMachine().getCodeModel();
7069 if (Subtarget->isPICStyleRIPRel() &&
7070 (M == CodeModel::Small || M == CodeModel::Kernel))
7071 WrapperKind = X86ISD::WrapperRIP;
7072 else if (Subtarget->isPICStyleGOT())
7073 OpFlag = X86II::MO_GOTOFF;
7074 else if (Subtarget->isPICStyleStubPIC())
7075 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7077 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7079 CP->getOffset(), OpFlag);
7080 DebugLoc DL = CP->getDebugLoc();
7081 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7082 // With PIC, the address is actually $g + Offset.
7084 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7085 DAG.getNode(X86ISD::GlobalBaseReg,
7086 DebugLoc(), getPointerTy()),
7093 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7094 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7096 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7098 unsigned char OpFlag = 0;
7099 unsigned WrapperKind = X86ISD::Wrapper;
7100 CodeModel::Model M = getTargetMachine().getCodeModel();
7102 if (Subtarget->isPICStyleRIPRel() &&
7103 (M == CodeModel::Small || M == CodeModel::Kernel))
7104 WrapperKind = X86ISD::WrapperRIP;
7105 else if (Subtarget->isPICStyleGOT())
7106 OpFlag = X86II::MO_GOTOFF;
7107 else if (Subtarget->isPICStyleStubPIC())
7108 OpFlag = X86II::MO_PIC_BASE_OFFSET;
7110 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7112 DebugLoc DL = JT->getDebugLoc();
7113 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7115 // With PIC, the address is actually $g + Offset.
7117 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7118 DAG.getNode(X86ISD::GlobalBaseReg,
7119 DebugLoc(), getPointerTy()),
7126 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7127 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7129 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7131 unsigned char OpFlag = 0;
7132 unsigned WrapperKind = X86ISD::Wrapper;
7133 CodeModel::Model M = getTargetMachine().getCodeModel();
7135 if (Subtarget->isPICStyleRIPRel() &&
7136 (M == CodeModel::Small || M == CodeModel::Kernel)) {
7137 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7138 OpFlag = X86II::MO_GOTPCREL;
7139 WrapperKind = X86ISD::WrapperRIP;
7140 } else if (Subtarget->isPICStyleGOT()) {
7141 OpFlag = X86II::MO_GOT;
7142 } else if (Subtarget->isPICStyleStubPIC()) {
7143 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7144 } else if (Subtarget->isPICStyleStubNoDynamic()) {
7145 OpFlag = X86II::MO_DARWIN_NONLAZY;
7148 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7150 DebugLoc DL = Op.getDebugLoc();
7151 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7154 // With PIC, the address is actually $g + Offset.
7155 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7156 !Subtarget->is64Bit()) {
7157 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7158 DAG.getNode(X86ISD::GlobalBaseReg,
7159 DebugLoc(), getPointerTy()),
7163 // For symbols that require a load from a stub to get the address, emit the
7165 if (isGlobalStubReference(OpFlag))
7166 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7167 MachinePointerInfo::getGOT(), false, false, false, 0);
7173 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7174 // Create the TargetBlockAddressAddress node.
7175 unsigned char OpFlags =
7176 Subtarget->ClassifyBlockAddressReference();
7177 CodeModel::Model M = getTargetMachine().getCodeModel();
7178 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7179 DebugLoc dl = Op.getDebugLoc();
7180 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7181 /*isTarget=*/true, OpFlags);
7183 if (Subtarget->isPICStyleRIPRel() &&
7184 (M == CodeModel::Small || M == CodeModel::Kernel))
7185 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7187 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7189 // With PIC, the address is actually $g + Offset.
7190 if (isGlobalRelativeToPICBase(OpFlags)) {
7191 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7192 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7200 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7202 SelectionDAG &DAG) const {
7203 // Create the TargetGlobalAddress node, folding in the constant
7204 // offset if it is legal.
7205 unsigned char OpFlags =
7206 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7207 CodeModel::Model M = getTargetMachine().getCodeModel();
7209 if (OpFlags == X86II::MO_NO_FLAG &&
7210 X86::isOffsetSuitableForCodeModel(Offset, M)) {
7211 // A direct static reference to a global.
7212 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7215 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7218 if (Subtarget->isPICStyleRIPRel() &&
7219 (M == CodeModel::Small || M == CodeModel::Kernel))
7220 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7222 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7224 // With PIC, the address is actually $g + Offset.
7225 if (isGlobalRelativeToPICBase(OpFlags)) {
7226 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7227 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7231 // For globals that require a load from a stub to get the address, emit the
7233 if (isGlobalStubReference(OpFlags))
7234 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7235 MachinePointerInfo::getGOT(), false, false, false, 0);
7237 // If there was a non-zero offset that we didn't fold, create an explicit
7240 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7241 DAG.getConstant(Offset, getPointerTy()));
7247 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7248 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7249 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7250 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7254 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7255 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7256 unsigned char OperandFlags) {
7257 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7258 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7259 DebugLoc dl = GA->getDebugLoc();
7260 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7261 GA->getValueType(0),
7265 SDValue Ops[] = { Chain, TGA, *InFlag };
7266 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7268 SDValue Ops[] = { Chain, TGA };
7269 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7272 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7273 MFI->setAdjustsStack(true);
7275 SDValue Flag = Chain.getValue(1);
7276 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7279 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7281 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7284 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
7285 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7286 DAG.getNode(X86ISD::GlobalBaseReg,
7287 DebugLoc(), PtrVT), InFlag);
7288 InFlag = Chain.getValue(1);
7290 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7293 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7295 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7297 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7298 X86::RAX, X86II::MO_TLSGD);
7301 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7302 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7303 const EVT PtrVT, TLSModel::Model model,
7304 bool is64Bit, bool isPIC) {
7305 DebugLoc dl = GA->getDebugLoc();
7307 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7308 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7309 is64Bit ? 257 : 256));
7311 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7312 DAG.getIntPtrConstant(0),
7313 MachinePointerInfo(Ptr),
7314 false, false, false, 0);
7316 unsigned char OperandFlags = 0;
7317 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
7319 unsigned WrapperKind = X86ISD::Wrapper;
7320 if (model == TLSModel::LocalExec) {
7321 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7322 } else if (model == TLSModel::InitialExec) {
7324 OperandFlags = X86II::MO_GOTTPOFF;
7325 WrapperKind = X86ISD::WrapperRIP;
7327 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7330 llvm_unreachable("Unexpected model");
7333 // emit "addl x@ntpoff,%eax" (local exec)
7334 // or "addl x@indntpoff,%eax" (initial exec)
7335 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7336 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7337 GA->getValueType(0),
7338 GA->getOffset(), OperandFlags);
7339 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7341 if (model == TLSModel::InitialExec) {
7342 if (isPIC && !is64Bit) {
7343 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7344 DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7347 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7348 MachinePointerInfo::getGOT(), false, false, false,
7353 // The address of the thread local variable is the add of the thread
7354 // pointer with the offset of the variable.
7355 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7359 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7361 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7362 const GlobalValue *GV = GA->getGlobal();
7364 if (Subtarget->isTargetELF()) {
7365 // TODO: implement the "local dynamic" model
7367 // If GV is an alias then use the aliasee for determining
7368 // thread-localness.
7369 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7370 GV = GA->resolveAliasedGlobal(false);
7372 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7375 case TLSModel::GeneralDynamic:
7376 case TLSModel::LocalDynamic: // not implemented
7377 if (Subtarget->is64Bit())
7378 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7379 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7381 case TLSModel::InitialExec:
7382 case TLSModel::LocalExec:
7383 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7384 Subtarget->is64Bit(),
7385 getTargetMachine().getRelocationModel() == Reloc::PIC_);
7387 llvm_unreachable("Unknown TLS model.");
7390 if (Subtarget->isTargetDarwin()) {
7391 // Darwin only has one model of TLS. Lower to that.
7392 unsigned char OpFlag = 0;
7393 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7394 X86ISD::WrapperRIP : X86ISD::Wrapper;
7396 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7398 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7399 !Subtarget->is64Bit();
7401 OpFlag = X86II::MO_TLVP_PIC_BASE;
7403 OpFlag = X86II::MO_TLVP;
7404 DebugLoc DL = Op.getDebugLoc();
7405 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7406 GA->getValueType(0),
7407 GA->getOffset(), OpFlag);
7408 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7410 // With PIC32, the address is actually $g + Offset.
7412 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7413 DAG.getNode(X86ISD::GlobalBaseReg,
7414 DebugLoc(), getPointerTy()),
7417 // Lowering the machine isd will make sure everything is in the right
7419 SDValue Chain = DAG.getEntryNode();
7420 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7421 SDValue Args[] = { Chain, Offset };
7422 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7424 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7425 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7426 MFI->setAdjustsStack(true);
7428 // And our return value (tls address) is in the standard call return value
7430 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7431 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7435 if (Subtarget->isTargetWindows()) {
7436 // Just use the implicit TLS architecture
7437 // Need to generate someting similar to:
7438 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7440 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
7441 // mov rcx, qword [rdx+rcx*8]
7442 // mov eax, .tls$:tlsvar
7443 // [rax+rcx] contains the address
7444 // Windows 64bit: gs:0x58
7445 // Windows 32bit: fs:__tls_array
7447 // If GV is an alias then use the aliasee for determining
7448 // thread-localness.
7449 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7450 GV = GA->resolveAliasedGlobal(false);
7451 DebugLoc dl = GA->getDebugLoc();
7452 SDValue Chain = DAG.getEntryNode();
7454 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7455 // %gs:0x58 (64-bit).
7456 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7457 ? Type::getInt8PtrTy(*DAG.getContext(),
7459 : Type::getInt32PtrTy(*DAG.getContext(),
7462 SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7463 Subtarget->is64Bit()
7464 ? DAG.getIntPtrConstant(0x58)
7465 : DAG.getExternalSymbol("_tls_array",
7467 MachinePointerInfo(Ptr),
7468 false, false, false, 0);
7470 // Load the _tls_index variable
7471 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7472 if (Subtarget->is64Bit())
7473 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7474 IDX, MachinePointerInfo(), MVT::i32,
7477 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7478 false, false, false, 0);
7480 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7482 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7484 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7485 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7486 false, false, false, 0);
7488 // Get the offset of start of .tls section
7489 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7490 GA->getValueType(0),
7491 GA->getOffset(), X86II::MO_SECREL);
7492 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7494 // The address of the thread local variable is the add of the thread
7495 // pointer with the offset of the variable.
7496 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7499 llvm_unreachable("TLS not implemented for this target.");
7503 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7504 /// and take a 2 x i32 value to shift plus a shift amount.
7505 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7506 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7507 EVT VT = Op.getValueType();
7508 unsigned VTBits = VT.getSizeInBits();
7509 DebugLoc dl = Op.getDebugLoc();
7510 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7511 SDValue ShOpLo = Op.getOperand(0);
7512 SDValue ShOpHi = Op.getOperand(1);
7513 SDValue ShAmt = Op.getOperand(2);
7514 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7515 DAG.getConstant(VTBits - 1, MVT::i8))
7516 : DAG.getConstant(0, VT);
7519 if (Op.getOpcode() == ISD::SHL_PARTS) {
7520 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7521 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7523 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7524 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7527 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7528 DAG.getConstant(VTBits, MVT::i8));
7529 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7530 AndNode, DAG.getConstant(0, MVT::i8));
7533 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7534 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7535 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7537 if (Op.getOpcode() == ISD::SHL_PARTS) {
7538 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7539 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7541 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7542 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7545 SDValue Ops[2] = { Lo, Hi };
7546 return DAG.getMergeValues(Ops, 2, dl);
7549 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7550 SelectionDAG &DAG) const {
7551 EVT SrcVT = Op.getOperand(0).getValueType();
7553 if (SrcVT.isVector())
7556 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7557 "Unknown SINT_TO_FP to lower!");
7559 // These are really Legal; return the operand so the caller accepts it as
7561 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7563 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7564 Subtarget->is64Bit()) {
7568 DebugLoc dl = Op.getDebugLoc();
7569 unsigned Size = SrcVT.getSizeInBits()/8;
7570 MachineFunction &MF = DAG.getMachineFunction();
7571 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7572 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7573 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7575 MachinePointerInfo::getFixedStack(SSFI),
7577 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7580 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7582 SelectionDAG &DAG) const {
7584 DebugLoc DL = Op.getDebugLoc();
7586 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7588 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7590 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7592 unsigned ByteSize = SrcVT.getSizeInBits()/8;
7594 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7595 MachineMemOperand *MMO;
7597 int SSFI = FI->getIndex();
7599 DAG.getMachineFunction()
7600 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7601 MachineMemOperand::MOLoad, ByteSize, ByteSize);
7603 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7604 StackSlot = StackSlot.getOperand(1);
7606 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7607 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7609 Tys, Ops, array_lengthof(Ops),
7613 Chain = Result.getValue(1);
7614 SDValue InFlag = Result.getValue(2);
7616 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7617 // shouldn't be necessary except that RFP cannot be live across
7618 // multiple blocks. When stackifier is fixed, they can be uncoupled.
7619 MachineFunction &MF = DAG.getMachineFunction();
7620 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7621 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7622 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7623 Tys = DAG.getVTList(MVT::Other);
7625 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7627 MachineMemOperand *MMO =
7628 DAG.getMachineFunction()
7629 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7630 MachineMemOperand::MOStore, SSFISize, SSFISize);
7632 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7633 Ops, array_lengthof(Ops),
7634 Op.getValueType(), MMO);
7635 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7636 MachinePointerInfo::getFixedStack(SSFI),
7637 false, false, false, 0);
7643 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7644 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7645 SelectionDAG &DAG) const {
7646 // This algorithm is not obvious. Here it is what we're trying to output:
7649 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
7650 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
7654 pshufd $0x4e, %xmm0, %xmm1
7659 DebugLoc dl = Op.getDebugLoc();
7660 LLVMContext *Context = DAG.getContext();
7662 // Build some magic constants.
7663 const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
7664 Constant *C0 = ConstantDataVector::get(*Context, CV0);
7665 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7667 SmallVector<Constant*,2> CV1;
7669 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7671 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7672 Constant *C1 = ConstantVector::get(CV1);
7673 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7675 // Load the 64-bit value into an XMM register.
7676 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
7678 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7679 MachinePointerInfo::getConstantPool(),
7680 false, false, false, 16);
7681 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
7682 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
7685 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7686 MachinePointerInfo::getConstantPool(),
7687 false, false, false, 16);
7688 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
7689 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7692 if (Subtarget->hasSSE3()) {
7693 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
7694 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
7696 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
7697 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
7699 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
7700 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
7704 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
7705 DAG.getIntPtrConstant(0));
7708 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7709 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7710 SelectionDAG &DAG) const {
7711 DebugLoc dl = Op.getDebugLoc();
7712 // FP constant to bias correct the final result.
7713 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7716 // Load the 32-bit value into an XMM register.
7717 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7720 // Zero out the upper parts of the register.
7721 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
7723 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7724 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7725 DAG.getIntPtrConstant(0));
7727 // Or the load with the bias.
7728 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7729 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7730 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7732 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7733 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7734 MVT::v2f64, Bias)));
7735 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7736 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7737 DAG.getIntPtrConstant(0));
7739 // Subtract the bias.
7740 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7742 // Handle final rounding.
7743 EVT DestVT = Op.getValueType();
7745 if (DestVT.bitsLT(MVT::f64))
7746 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7747 DAG.getIntPtrConstant(0));
7748 if (DestVT.bitsGT(MVT::f64))
7749 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7751 // Handle final rounding.
7755 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7756 SelectionDAG &DAG) const {
7757 SDValue N0 = Op.getOperand(0);
7758 DebugLoc dl = Op.getDebugLoc();
7760 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
7761 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
7762 // the optimization here.
7763 if (DAG.SignBitIsZero(N0))
7764 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
7766 EVT SrcVT = N0.getValueType();
7767 EVT DstVT = Op.getValueType();
7768 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
7769 return LowerUINT_TO_FP_i64(Op, DAG);
7770 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
7771 return LowerUINT_TO_FP_i32(Op, DAG);
7772 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
7775 // Make a 64-bit buffer, and use it to build an FILD.
7776 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
7777 if (SrcVT == MVT::i32) {
7778 SDValue WordOff = DAG.getConstant(4, getPointerTy());
7779 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
7780 getPointerTy(), StackSlot, WordOff);
7781 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7782 StackSlot, MachinePointerInfo(),
7784 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
7785 OffsetSlot, MachinePointerInfo(),
7787 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
7791 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
7792 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7793 StackSlot, MachinePointerInfo(),
7795 // For i64 source, we need to add the appropriate power of 2 if the input
7796 // was negative. This is the same as the optimization in
7797 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
7798 // we must be careful to do the computation in x87 extended precision, not
7799 // in SSE. (The generic code can't know it's OK to do this, or how to.)
7800 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
7801 MachineMemOperand *MMO =
7802 DAG.getMachineFunction()
7803 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7804 MachineMemOperand::MOLoad, 8, 8);
7806 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
7807 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
7808 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
7811 APInt FF(32, 0x5F800000ULL);
7813 // Check whether the sign bit is set.
7814 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
7815 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
7818 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
7819 SDValue FudgePtr = DAG.getConstantPool(
7820 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
7823 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
7824 SDValue Zero = DAG.getIntPtrConstant(0);
7825 SDValue Four = DAG.getIntPtrConstant(4);
7826 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
7828 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
7830 // Load the value out, extending it from f32 to f80.
7831 // FIXME: Avoid the extend by constructing the right constant pool?
7832 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
7833 FudgePtr, MachinePointerInfo::getConstantPool(),
7834 MVT::f32, false, false, 4);
7835 // Extend everything to 80 bits to force it to be done on x87.
7836 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
7837 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
7840 std::pair<SDValue,SDValue> X86TargetLowering::
7841 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned, bool IsReplace) const {
7842 DebugLoc DL = Op.getDebugLoc();
7844 EVT DstTy = Op.getValueType();
7846 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
7847 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
7851 assert(DstTy.getSimpleVT() <= MVT::i64 &&
7852 DstTy.getSimpleVT() >= MVT::i16 &&
7853 "Unknown FP_TO_INT to lower!");
7855 // These are really Legal.
7856 if (DstTy == MVT::i32 &&
7857 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7858 return std::make_pair(SDValue(), SDValue());
7859 if (Subtarget->is64Bit() &&
7860 DstTy == MVT::i64 &&
7861 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
7862 return std::make_pair(SDValue(), SDValue());
7864 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
7865 // stack slot, or into the FTOL runtime function.
7866 MachineFunction &MF = DAG.getMachineFunction();
7867 unsigned MemSize = DstTy.getSizeInBits()/8;
7868 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7869 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7872 if (!IsSigned && isIntegerTypeFTOL(DstTy))
7873 Opc = X86ISD::WIN_FTOL;
7875 switch (DstTy.getSimpleVT().SimpleTy) {
7876 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
7877 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
7878 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
7879 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
7882 SDValue Chain = DAG.getEntryNode();
7883 SDValue Value = Op.getOperand(0);
7884 EVT TheVT = Op.getOperand(0).getValueType();
7885 // FIXME This causes a redundant load/store if the SSE-class value is already
7886 // in memory, such as if it is on the callstack.
7887 if (isScalarFPTypeInSSEReg(TheVT)) {
7888 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
7889 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
7890 MachinePointerInfo::getFixedStack(SSFI),
7892 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
7894 Chain, StackSlot, DAG.getValueType(TheVT)
7897 MachineMemOperand *MMO =
7898 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7899 MachineMemOperand::MOLoad, MemSize, MemSize);
7900 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
7902 Chain = Value.getValue(1);
7903 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
7904 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7907 MachineMemOperand *MMO =
7908 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7909 MachineMemOperand::MOStore, MemSize, MemSize);
7911 if (Opc != X86ISD::WIN_FTOL) {
7912 // Build the FP_TO_INT*_IN_MEM
7913 SDValue Ops[] = { Chain, Value, StackSlot };
7914 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
7915 Ops, 3, DstTy, MMO);
7916 return std::make_pair(FIST, StackSlot);
7918 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
7919 DAG.getVTList(MVT::Other, MVT::Glue),
7921 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
7922 MVT::i32, ftol.getValue(1));
7923 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
7924 MVT::i32, eax.getValue(2));
7925 SDValue Ops[] = { eax, edx };
7926 SDValue pair = IsReplace
7927 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
7928 : DAG.getMergeValues(Ops, 2, DL);
7929 return std::make_pair(pair, SDValue());
7933 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
7934 SelectionDAG &DAG) const {
7935 if (Op.getValueType().isVector())
7938 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7939 /*IsSigned=*/ true, /*IsReplace=*/ false);
7940 SDValue FIST = Vals.first, StackSlot = Vals.second;
7941 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
7942 if (FIST.getNode() == 0) return Op;
7944 if (StackSlot.getNode())
7946 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7947 FIST, StackSlot, MachinePointerInfo(),
7948 false, false, false, 0);
7950 // The node is the result.
7954 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
7955 SelectionDAG &DAG) const {
7956 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
7957 /*IsSigned=*/ false, /*IsReplace=*/ false);
7958 SDValue FIST = Vals.first, StackSlot = Vals.second;
7959 assert(FIST.getNode() && "Unexpected failure");
7961 if (StackSlot.getNode())
7963 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
7964 FIST, StackSlot, MachinePointerInfo(),
7965 false, false, false, 0);
7967 // The node is the result.
7971 SDValue X86TargetLowering::LowerFABS(SDValue Op,
7972 SelectionDAG &DAG) const {
7973 LLVMContext *Context = DAG.getContext();
7974 DebugLoc dl = Op.getDebugLoc();
7975 EVT VT = Op.getValueType();
7978 EltVT = VT.getVectorElementType();
7980 if (EltVT == MVT::f64) {
7981 C = ConstantVector::getSplat(2,
7982 ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
7984 C = ConstantVector::getSplat(4,
7985 ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
7987 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7988 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7989 MachinePointerInfo::getConstantPool(),
7990 false, false, false, 16);
7991 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
7994 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
7995 LLVMContext *Context = DAG.getContext();
7996 DebugLoc dl = Op.getDebugLoc();
7997 EVT VT = Op.getValueType();
7999 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8000 if (VT.isVector()) {
8001 EltVT = VT.getVectorElementType();
8002 NumElts = VT.getVectorNumElements();
8005 if (EltVT == MVT::f64)
8006 C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8008 C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8009 C = ConstantVector::getSplat(NumElts, C);
8010 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8011 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8012 MachinePointerInfo::getConstantPool(),
8013 false, false, false, 16);
8014 if (VT.isVector()) {
8015 MVT XORVT = VT.getSizeInBits() == 128 ? MVT::v2i64 : MVT::v4i64;
8016 return DAG.getNode(ISD::BITCAST, dl, VT,
8017 DAG.getNode(ISD::XOR, dl, XORVT,
8018 DAG.getNode(ISD::BITCAST, dl, XORVT,
8020 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8023 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8026 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8027 LLVMContext *Context = DAG.getContext();
8028 SDValue Op0 = Op.getOperand(0);
8029 SDValue Op1 = Op.getOperand(1);
8030 DebugLoc dl = Op.getDebugLoc();
8031 EVT VT = Op.getValueType();
8032 EVT SrcVT = Op1.getValueType();
8034 // If second operand is smaller, extend it first.
8035 if (SrcVT.bitsLT(VT)) {
8036 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8039 // And if it is bigger, shrink it first.
8040 if (SrcVT.bitsGT(VT)) {
8041 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8045 // At this point the operands and the result should have the same
8046 // type, and that won't be f80 since that is not custom lowered.
8048 // First get the sign bit of second operand.
8049 SmallVector<Constant*,4> CV;
8050 if (SrcVT == MVT::f64) {
8051 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8052 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8054 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8055 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8056 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8057 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8059 Constant *C = ConstantVector::get(CV);
8060 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8061 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8062 MachinePointerInfo::getConstantPool(),
8063 false, false, false, 16);
8064 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8066 // Shift sign bit right or left if the two operands have different types.
8067 if (SrcVT.bitsGT(VT)) {
8068 // Op0 is MVT::f32, Op1 is MVT::f64.
8069 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8070 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8071 DAG.getConstant(32, MVT::i32));
8072 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8073 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8074 DAG.getIntPtrConstant(0));
8077 // Clear first operand sign bit.
8079 if (VT == MVT::f64) {
8080 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8081 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8083 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8084 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8085 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8086 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8088 C = ConstantVector::get(CV);
8089 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8090 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8091 MachinePointerInfo::getConstantPool(),
8092 false, false, false, 16);
8093 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8095 // Or the value with the sign bit.
8096 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8099 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8100 SDValue N0 = Op.getOperand(0);
8101 DebugLoc dl = Op.getDebugLoc();
8102 EVT VT = Op.getValueType();
8104 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8105 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8106 DAG.getConstant(1, VT));
8107 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8110 /// Emit nodes that will be selected as "test Op0,Op0", or something
8112 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8113 SelectionDAG &DAG) const {
8114 DebugLoc dl = Op.getDebugLoc();
8116 // CF and OF aren't always set the way we want. Determine which
8117 // of these we need.
8118 bool NeedCF = false;
8119 bool NeedOF = false;
8122 case X86::COND_A: case X86::COND_AE:
8123 case X86::COND_B: case X86::COND_BE:
8126 case X86::COND_G: case X86::COND_GE:
8127 case X86::COND_L: case X86::COND_LE:
8128 case X86::COND_O: case X86::COND_NO:
8133 // See if we can use the EFLAGS value from the operand instead of
8134 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8135 // we prove that the arithmetic won't overflow, we can't use OF or CF.
8136 if (Op.getResNo() != 0 || NeedOF || NeedCF)
8137 // Emit a CMP with 0, which is the TEST pattern.
8138 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8139 DAG.getConstant(0, Op.getValueType()));
8141 unsigned Opcode = 0;
8142 unsigned NumOperands = 0;
8143 switch (Op.getNode()->getOpcode()) {
8145 // Due to an isel shortcoming, be conservative if this add is likely to be
8146 // selected as part of a load-modify-store instruction. When the root node
8147 // in a match is a store, isel doesn't know how to remap non-chain non-flag
8148 // uses of other nodes in the match, such as the ADD in this case. This
8149 // leads to the ADD being left around and reselected, with the result being
8150 // two adds in the output. Alas, even if none our users are stores, that
8151 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
8152 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
8153 // climbing the DAG back to the root, and it doesn't seem to be worth the
8155 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8156 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8157 if (UI->getOpcode() != ISD::CopyToReg &&
8158 UI->getOpcode() != ISD::SETCC &&
8159 UI->getOpcode() != ISD::STORE)
8162 if (ConstantSDNode *C =
8163 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8164 // An add of one will be selected as an INC.
8165 if (C->getAPIntValue() == 1) {
8166 Opcode = X86ISD::INC;
8171 // An add of negative one (subtract of one) will be selected as a DEC.
8172 if (C->getAPIntValue().isAllOnesValue()) {
8173 Opcode = X86ISD::DEC;
8179 // Otherwise use a regular EFLAGS-setting add.
8180 Opcode = X86ISD::ADD;
8184 // If the primary and result isn't used, don't bother using X86ISD::AND,
8185 // because a TEST instruction will be better.
8186 bool NonFlagUse = false;
8187 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8188 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8190 unsigned UOpNo = UI.getOperandNo();
8191 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8192 // Look pass truncate.
8193 UOpNo = User->use_begin().getOperandNo();
8194 User = *User->use_begin();
8197 if (User->getOpcode() != ISD::BRCOND &&
8198 User->getOpcode() != ISD::SETCC &&
8199 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8212 // Due to the ISEL shortcoming noted above, be conservative if this op is
8213 // likely to be selected as part of a load-modify-store instruction.
8214 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8215 UE = Op.getNode()->use_end(); UI != UE; ++UI)
8216 if (UI->getOpcode() == ISD::STORE)
8219 // Otherwise use a regular EFLAGS-setting instruction.
8220 switch (Op.getNode()->getOpcode()) {
8221 default: llvm_unreachable("unexpected operator!");
8222 case ISD::SUB: Opcode = X86ISD::SUB; break;
8223 case ISD::OR: Opcode = X86ISD::OR; break;
8224 case ISD::XOR: Opcode = X86ISD::XOR; break;
8225 case ISD::AND: Opcode = X86ISD::AND; break;
8237 return SDValue(Op.getNode(), 1);
8244 // Emit a CMP with 0, which is the TEST pattern.
8245 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8246 DAG.getConstant(0, Op.getValueType()));
8248 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8249 SmallVector<SDValue, 4> Ops;
8250 for (unsigned i = 0; i != NumOperands; ++i)
8251 Ops.push_back(Op.getOperand(i));
8253 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8254 DAG.ReplaceAllUsesWith(Op, New);
8255 return SDValue(New.getNode(), 1);
8258 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8260 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8261 SelectionDAG &DAG) const {
8262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8263 if (C->getAPIntValue() == 0)
8264 return EmitTest(Op0, X86CC, DAG);
8266 DebugLoc dl = Op0.getDebugLoc();
8267 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8270 /// Convert a comparison if required by the subtarget.
8271 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
8272 SelectionDAG &DAG) const {
8273 // If the subtarget does not support the FUCOMI instruction, floating-point
8274 // comparisons have to be converted.
8275 if (Subtarget->hasCMov() ||
8276 Cmp.getOpcode() != X86ISD::CMP ||
8277 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
8278 !Cmp.getOperand(1).getValueType().isFloatingPoint())
8281 // The instruction selector will select an FUCOM instruction instead of
8282 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
8283 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
8284 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
8285 DebugLoc dl = Cmp.getDebugLoc();
8286 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
8287 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
8288 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
8289 DAG.getConstant(8, MVT::i8));
8290 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
8291 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
8294 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8295 /// if it's possible.
8296 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8297 DebugLoc dl, SelectionDAG &DAG) const {
8298 SDValue Op0 = And.getOperand(0);
8299 SDValue Op1 = And.getOperand(1);
8300 if (Op0.getOpcode() == ISD::TRUNCATE)
8301 Op0 = Op0.getOperand(0);
8302 if (Op1.getOpcode() == ISD::TRUNCATE)
8303 Op1 = Op1.getOperand(0);
8306 if (Op1.getOpcode() == ISD::SHL)
8307 std::swap(Op0, Op1);
8308 if (Op0.getOpcode() == ISD::SHL) {
8309 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8310 if (And00C->getZExtValue() == 1) {
8311 // If we looked past a truncate, check that it's only truncating away
8313 unsigned BitWidth = Op0.getValueSizeInBits();
8314 unsigned AndBitWidth = And.getValueSizeInBits();
8315 if (BitWidth > AndBitWidth) {
8317 DAG.ComputeMaskedBits(Op0, Zeros, Ones);
8318 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8322 RHS = Op0.getOperand(1);
8324 } else if (Op1.getOpcode() == ISD::Constant) {
8325 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8326 uint64_t AndRHSVal = AndRHS->getZExtValue();
8327 SDValue AndLHS = Op0;
8329 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
8330 LHS = AndLHS.getOperand(0);
8331 RHS = AndLHS.getOperand(1);
8334 // Use BT if the immediate can't be encoded in a TEST instruction.
8335 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
8337 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
8341 if (LHS.getNode()) {
8342 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
8343 // instruction. Since the shift amount is in-range-or-undefined, we know
8344 // that doing a bittest on the i32 value is ok. We extend to i32 because
8345 // the encoding for the i16 version is larger than the i32 version.
8346 // Also promote i16 to i32 for performance / code size reason.
8347 if (LHS.getValueType() == MVT::i8 ||
8348 LHS.getValueType() == MVT::i16)
8349 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8351 // If the operand types disagree, extend the shift amount to match. Since
8352 // BT ignores high bits (like shifts) we can use anyextend.
8353 if (LHS.getValueType() != RHS.getValueType())
8354 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8356 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8357 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8358 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8359 DAG.getConstant(Cond, MVT::i8), BT);
8365 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8367 if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8369 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8370 SDValue Op0 = Op.getOperand(0);
8371 SDValue Op1 = Op.getOperand(1);
8372 DebugLoc dl = Op.getDebugLoc();
8373 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8375 // Optimize to BT if possible.
8376 // Lower (X & (1 << N)) == 0 to BT(X, N).
8377 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8378 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8379 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8380 Op1.getOpcode() == ISD::Constant &&
8381 cast<ConstantSDNode>(Op1)->isNullValue() &&
8382 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8383 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8384 if (NewSetCC.getNode())
8388 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
8390 if (Op1.getOpcode() == ISD::Constant &&
8391 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8392 cast<ConstantSDNode>(Op1)->isNullValue()) &&
8393 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8395 // If the input is a setcc, then reuse the input setcc or use a new one with
8396 // the inverted condition.
8397 if (Op0.getOpcode() == X86ISD::SETCC) {
8398 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8399 bool Invert = (CC == ISD::SETNE) ^
8400 cast<ConstantSDNode>(Op1)->isNullValue();
8401 if (!Invert) return Op0;
8403 CCode = X86::GetOppositeBranchCondition(CCode);
8404 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8405 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8409 bool isFP = Op1.getValueType().isFloatingPoint();
8410 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8411 if (X86CC == X86::COND_INVALID)
8414 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8415 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
8416 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8417 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8420 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8421 // ones, and then concatenate the result back.
8422 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8423 EVT VT = Op.getValueType();
8425 assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8426 "Unsupported value type for operation");
8428 unsigned NumElems = VT.getVectorNumElements();
8429 DebugLoc dl = Op.getDebugLoc();
8430 SDValue CC = Op.getOperand(2);
8432 // Extract the LHS vectors
8433 SDValue LHS = Op.getOperand(0);
8434 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
8435 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
8437 // Extract the RHS vectors
8438 SDValue RHS = Op.getOperand(1);
8439 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
8440 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
8442 // Issue the operation on the smaller types and concatenate the result back
8443 MVT EltVT = VT.getVectorElementType().getSimpleVT();
8444 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8445 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8446 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8447 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8451 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8453 SDValue Op0 = Op.getOperand(0);
8454 SDValue Op1 = Op.getOperand(1);
8455 SDValue CC = Op.getOperand(2);
8456 EVT VT = Op.getValueType();
8457 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8458 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8459 DebugLoc dl = Op.getDebugLoc();
8463 EVT EltVT = Op0.getValueType().getVectorElementType();
8464 assert(EltVT == MVT::f32 || EltVT == MVT::f64); (void)EltVT;
8468 // SSE Condition code mapping:
8477 switch (SetCCOpcode) {
8480 case ISD::SETEQ: SSECC = 0; break;
8482 case ISD::SETGT: Swap = true; // Fallthrough
8484 case ISD::SETOLT: SSECC = 1; break;
8486 case ISD::SETGE: Swap = true; // Fallthrough
8488 case ISD::SETOLE: SSECC = 2; break;
8489 case ISD::SETUO: SSECC = 3; break;
8491 case ISD::SETNE: SSECC = 4; break;
8492 case ISD::SETULE: Swap = true;
8493 case ISD::SETUGE: SSECC = 5; break;
8494 case ISD::SETULT: Swap = true;
8495 case ISD::SETUGT: SSECC = 6; break;
8496 case ISD::SETO: SSECC = 7; break;
8499 std::swap(Op0, Op1);
8501 // In the two special cases we can't handle, emit two comparisons.
8503 if (SetCCOpcode == ISD::SETUEQ) {
8505 UNORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8506 DAG.getConstant(3, MVT::i8));
8507 EQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8508 DAG.getConstant(0, MVT::i8));
8509 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8511 if (SetCCOpcode == ISD::SETONE) {
8513 ORD = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8514 DAG.getConstant(7, MVT::i8));
8515 NEQ = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8516 DAG.getConstant(4, MVT::i8));
8517 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8519 llvm_unreachable("Illegal FP comparison");
8521 // Handle all other FP comparisons here.
8522 return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
8523 DAG.getConstant(SSECC, MVT::i8));
8526 // Break 256-bit integer vector compare into smaller ones.
8527 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8528 return Lower256IntVSETCC(Op, DAG);
8530 // We are handling one of the integer comparisons here. Since SSE only has
8531 // GT and EQ comparisons for integer, swapping operands and multiple
8532 // operations may be required for some comparisons.
8534 bool Swap = false, Invert = false, FlipSigns = false;
8536 switch (SetCCOpcode) {
8538 case ISD::SETNE: Invert = true;
8539 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
8540 case ISD::SETLT: Swap = true;
8541 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
8542 case ISD::SETGE: Swap = true;
8543 case ISD::SETLE: Opc = X86ISD::PCMPGT; Invert = true; break;
8544 case ISD::SETULT: Swap = true;
8545 case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
8546 case ISD::SETUGE: Swap = true;
8547 case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
8550 std::swap(Op0, Op1);
8552 // Check that the operation in question is available (most are plain SSE2,
8553 // but PCMPGTQ and PCMPEQQ have different requirements).
8554 if (Opc == X86ISD::PCMPGT && VT == MVT::v2i64 && !Subtarget->hasSSE42())
8556 if (Opc == X86ISD::PCMPEQ && VT == MVT::v2i64 && !Subtarget->hasSSE41())
8559 // Since SSE has no unsigned integer comparisons, we need to flip the sign
8560 // bits of the inputs before performing those operations.
8562 EVT EltVT = VT.getVectorElementType();
8563 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8565 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8566 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8568 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8569 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8572 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8574 // If the logical-not of the result is required, perform that now.
8576 Result = DAG.getNOT(dl, Result, VT);
8581 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8582 static bool isX86LogicalCmp(SDValue Op) {
8583 unsigned Opc = Op.getNode()->getOpcode();
8584 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
8585 Opc == X86ISD::SAHF)
8587 if (Op.getResNo() == 1 &&
8588 (Opc == X86ISD::ADD ||
8589 Opc == X86ISD::SUB ||
8590 Opc == X86ISD::ADC ||
8591 Opc == X86ISD::SBB ||
8592 Opc == X86ISD::SMUL ||
8593 Opc == X86ISD::UMUL ||
8594 Opc == X86ISD::INC ||
8595 Opc == X86ISD::DEC ||
8596 Opc == X86ISD::OR ||
8597 Opc == X86ISD::XOR ||
8598 Opc == X86ISD::AND))
8601 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8607 static bool isZero(SDValue V) {
8608 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8609 return C && C->isNullValue();
8612 static bool isAllOnes(SDValue V) {
8613 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8614 return C && C->isAllOnesValue();
8617 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8618 bool addTest = true;
8619 SDValue Cond = Op.getOperand(0);
8620 SDValue Op1 = Op.getOperand(1);
8621 SDValue Op2 = Op.getOperand(2);
8622 DebugLoc DL = Op.getDebugLoc();
8625 if (Cond.getOpcode() == ISD::SETCC) {
8626 SDValue NewCond = LowerSETCC(Cond, DAG);
8627 if (NewCond.getNode())
8631 // Handle the following cases related to max and min:
8632 // (a > b) ? (a-b) : 0
8633 // (a >= b) ? (a-b) : 0
8634 // (b < a) ? (a-b) : 0
8635 // (b <= a) ? (a-b) : 0
8636 // Comparison is removed to use EFLAGS from SUB.
8637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2))
8638 if (Cond.getOpcode() == X86ISD::SETCC &&
8639 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8640 (Op1.getOpcode() == ISD::SUB || Op1.getOpcode() == X86ISD::SUB) &&
8641 C->getAPIntValue() == 0) {
8642 SDValue Cmp = Cond.getOperand(1);
8643 unsigned CC = cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8644 if ((DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(0)) &&
8645 DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(1)) &&
8646 (CC == X86::COND_G || CC == X86::COND_GE ||
8647 CC == X86::COND_A || CC == X86::COND_AE)) ||
8648 (DAG.isEqualTo(Op1.getOperand(0), Cmp.getOperand(1)) &&
8649 DAG.isEqualTo(Op1.getOperand(1), Cmp.getOperand(0)) &&
8650 (CC == X86::COND_L || CC == X86::COND_LE ||
8651 CC == X86::COND_B || CC == X86::COND_BE))) {
8653 if (Op1.getOpcode() == ISD::SUB) {
8654 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i32);
8655 SDValue New = DAG.getNode(X86ISD::SUB, DL, VTs,
8656 Op1.getOperand(0), Op1.getOperand(1));
8657 DAG.ReplaceAllUsesWith(Op1, New);
8661 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8662 unsigned NewCC = (CC == X86::COND_G || CC == X86::COND_GE ||
8663 CC == X86::COND_L ||
8664 CC == X86::COND_LE) ? X86::COND_GE : X86::COND_AE;
8665 SDValue Ops[] = { Op2, Op1, DAG.getConstant(NewCC, MVT::i8),
8666 SDValue(Op1.getNode(), 1) };
8667 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8671 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8672 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8673 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8674 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8675 if (Cond.getOpcode() == X86ISD::SETCC &&
8676 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8677 isZero(Cond.getOperand(1).getOperand(1))) {
8678 SDValue Cmp = Cond.getOperand(1);
8680 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8682 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8683 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8684 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8686 SDValue CmpOp0 = Cmp.getOperand(0);
8687 // Apply further optimizations for special cases
8688 // (select (x != 0), -1, 0) -> neg & sbb
8689 // (select (x == 0), 0, -1) -> neg & sbb
8690 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
8691 if (YC->isNullValue() &&
8692 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
8693 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
8694 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
8695 DAG.getConstant(0, CmpOp0.getValueType()),
8697 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8698 DAG.getConstant(X86::COND_B, MVT::i8),
8699 SDValue(Neg.getNode(), 1));
8703 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8704 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8705 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
8707 SDValue Res = // Res = 0 or -1.
8708 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8709 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8711 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8712 Res = DAG.getNOT(DL, Res, Res.getValueType());
8714 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8715 if (N2C == 0 || !N2C->isNullValue())
8716 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8721 // Look past (and (setcc_carry (cmp ...)), 1).
8722 if (Cond.getOpcode() == ISD::AND &&
8723 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8724 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8725 if (C && C->getAPIntValue() == 1)
8726 Cond = Cond.getOperand(0);
8729 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8730 // setting operand in place of the X86ISD::SETCC.
8731 unsigned CondOpcode = Cond.getOpcode();
8732 if (CondOpcode == X86ISD::SETCC ||
8733 CondOpcode == X86ISD::SETCC_CARRY) {
8734 CC = Cond.getOperand(0);
8736 SDValue Cmp = Cond.getOperand(1);
8737 unsigned Opc = Cmp.getOpcode();
8738 EVT VT = Op.getValueType();
8740 bool IllegalFPCMov = false;
8741 if (VT.isFloatingPoint() && !VT.isVector() &&
8742 !isScalarFPTypeInSSEReg(VT)) // FPStack?
8743 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8745 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8746 Opc == X86ISD::BT) { // FIXME
8750 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8751 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8752 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8753 Cond.getOperand(0).getValueType() != MVT::i8)) {
8754 SDValue LHS = Cond.getOperand(0);
8755 SDValue RHS = Cond.getOperand(1);
8759 switch (CondOpcode) {
8760 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8761 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8762 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8763 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8764 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8765 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8766 default: llvm_unreachable("unexpected overflowing operator");
8768 if (CondOpcode == ISD::UMULO)
8769 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8772 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8774 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8776 if (CondOpcode == ISD::UMULO)
8777 Cond = X86Op.getValue(2);
8779 Cond = X86Op.getValue(1);
8781 CC = DAG.getConstant(X86Cond, MVT::i8);
8786 // Look pass the truncate.
8787 if (Cond.getOpcode() == ISD::TRUNCATE)
8788 Cond = Cond.getOperand(0);
8790 // We know the result of AND is compared against zero. Try to match
8792 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8793 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8794 if (NewSetCC.getNode()) {
8795 CC = NewSetCC.getOperand(0);
8796 Cond = NewSetCC.getOperand(1);
8803 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8804 Cond = EmitTest(Cond, X86::COND_NE, DAG);
8807 // a < b ? -1 : 0 -> RES = ~setcc_carry
8808 // a < b ? 0 : -1 -> RES = setcc_carry
8809 // a >= b ? -1 : 0 -> RES = setcc_carry
8810 // a >= b ? 0 : -1 -> RES = ~setcc_carry
8811 if (Cond.getOpcode() == X86ISD::CMP) {
8812 Cond = ConvertCmpIfNecessary(Cond, DAG);
8813 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8815 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8816 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8817 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8818 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8819 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8820 return DAG.getNOT(DL, Res, Res.getValueType());
8825 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8826 // condition is true.
8827 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8828 SDValue Ops[] = { Op2, Op1, CC, Cond };
8829 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8832 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8833 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8834 // from the AND / OR.
8835 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8836 Opc = Op.getOpcode();
8837 if (Opc != ISD::OR && Opc != ISD::AND)
8839 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8840 Op.getOperand(0).hasOneUse() &&
8841 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8842 Op.getOperand(1).hasOneUse());
8845 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8846 // 1 and that the SETCC node has a single use.
8847 static bool isXor1OfSetCC(SDValue Op) {
8848 if (Op.getOpcode() != ISD::XOR)
8850 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8851 if (N1C && N1C->getAPIntValue() == 1) {
8852 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8853 Op.getOperand(0).hasOneUse();
8858 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8859 bool addTest = true;
8860 SDValue Chain = Op.getOperand(0);
8861 SDValue Cond = Op.getOperand(1);
8862 SDValue Dest = Op.getOperand(2);
8863 DebugLoc dl = Op.getDebugLoc();
8865 bool Inverted = false;
8867 if (Cond.getOpcode() == ISD::SETCC) {
8868 // Check for setcc([su]{add,sub,mul}o == 0).
8869 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
8870 isa<ConstantSDNode>(Cond.getOperand(1)) &&
8871 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
8872 Cond.getOperand(0).getResNo() == 1 &&
8873 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
8874 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
8875 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
8876 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
8877 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
8878 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
8880 Cond = Cond.getOperand(0);
8882 SDValue NewCond = LowerSETCC(Cond, DAG);
8883 if (NewCond.getNode())
8888 // FIXME: LowerXALUO doesn't handle these!!
8889 else if (Cond.getOpcode() == X86ISD::ADD ||
8890 Cond.getOpcode() == X86ISD::SUB ||
8891 Cond.getOpcode() == X86ISD::SMUL ||
8892 Cond.getOpcode() == X86ISD::UMUL)
8893 Cond = LowerXALUO(Cond, DAG);
8896 // Look pass (and (setcc_carry (cmp ...)), 1).
8897 if (Cond.getOpcode() == ISD::AND &&
8898 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8899 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8900 if (C && C->getAPIntValue() == 1)
8901 Cond = Cond.getOperand(0);
8904 // If condition flag is set by a X86ISD::CMP, then use it as the condition
8905 // setting operand in place of the X86ISD::SETCC.
8906 unsigned CondOpcode = Cond.getOpcode();
8907 if (CondOpcode == X86ISD::SETCC ||
8908 CondOpcode == X86ISD::SETCC_CARRY) {
8909 CC = Cond.getOperand(0);
8911 SDValue Cmp = Cond.getOperand(1);
8912 unsigned Opc = Cmp.getOpcode();
8913 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
8914 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
8918 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
8922 // These can only come from an arithmetic instruction with overflow,
8923 // e.g. SADDO, UADDO.
8924 Cond = Cond.getNode()->getOperand(1);
8930 CondOpcode = Cond.getOpcode();
8931 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8932 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8933 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8934 Cond.getOperand(0).getValueType() != MVT::i8)) {
8935 SDValue LHS = Cond.getOperand(0);
8936 SDValue RHS = Cond.getOperand(1);
8940 switch (CondOpcode) {
8941 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8942 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8943 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8944 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8945 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8946 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8947 default: llvm_unreachable("unexpected overflowing operator");
8950 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
8951 if (CondOpcode == ISD::UMULO)
8952 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8955 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8957 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
8959 if (CondOpcode == ISD::UMULO)
8960 Cond = X86Op.getValue(2);
8962 Cond = X86Op.getValue(1);
8964 CC = DAG.getConstant(X86Cond, MVT::i8);
8968 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
8969 SDValue Cmp = Cond.getOperand(0).getOperand(1);
8970 if (CondOpc == ISD::OR) {
8971 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
8972 // two branches instead of an explicit OR instruction with a
8974 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8975 isX86LogicalCmp(Cmp)) {
8976 CC = Cond.getOperand(0).getOperand(0);
8977 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
8978 Chain, Dest, CC, Cmp);
8979 CC = Cond.getOperand(1).getOperand(0);
8983 } else { // ISD::AND
8984 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
8985 // two branches instead of an explicit AND instruction with a
8986 // separate test. However, we only do this if this block doesn't
8987 // have a fall-through edge, because this requires an explicit
8988 // jmp when the condition is false.
8989 if (Cmp == Cond.getOperand(1).getOperand(1) &&
8990 isX86LogicalCmp(Cmp) &&
8991 Op.getNode()->hasOneUse()) {
8992 X86::CondCode CCode =
8993 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
8994 CCode = X86::GetOppositeBranchCondition(CCode);
8995 CC = DAG.getConstant(CCode, MVT::i8);
8996 SDNode *User = *Op.getNode()->use_begin();
8997 // Look for an unconditional branch following this conditional branch.
8998 // We need this because we need to reverse the successors in order
8999 // to implement FCMP_OEQ.
9000 if (User->getOpcode() == ISD::BR) {
9001 SDValue FalseBB = User->getOperand(1);
9003 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9004 assert(NewBR == User);
9008 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9009 Chain, Dest, CC, Cmp);
9010 X86::CondCode CCode =
9011 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9012 CCode = X86::GetOppositeBranchCondition(CCode);
9013 CC = DAG.getConstant(CCode, MVT::i8);
9019 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9020 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9021 // It should be transformed during dag combiner except when the condition
9022 // is set by a arithmetics with overflow node.
9023 X86::CondCode CCode =
9024 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9025 CCode = X86::GetOppositeBranchCondition(CCode);
9026 CC = DAG.getConstant(CCode, MVT::i8);
9027 Cond = Cond.getOperand(0).getOperand(1);
9029 } else if (Cond.getOpcode() == ISD::SETCC &&
9030 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9031 // For FCMP_OEQ, we can emit
9032 // two branches instead of an explicit AND instruction with a
9033 // separate test. However, we only do this if this block doesn't
9034 // have a fall-through edge, because this requires an explicit
9035 // jmp when the condition is false.
9036 if (Op.getNode()->hasOneUse()) {
9037 SDNode *User = *Op.getNode()->use_begin();
9038 // Look for an unconditional branch following this conditional branch.
9039 // We need this because we need to reverse the successors in order
9040 // to implement FCMP_OEQ.
9041 if (User->getOpcode() == ISD::BR) {
9042 SDValue FalseBB = User->getOperand(1);
9044 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9045 assert(NewBR == User);
9049 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9050 Cond.getOperand(0), Cond.getOperand(1));
9051 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9052 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9053 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9054 Chain, Dest, CC, Cmp);
9055 CC = DAG.getConstant(X86::COND_P, MVT::i8);
9060 } else if (Cond.getOpcode() == ISD::SETCC &&
9061 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9062 // For FCMP_UNE, we can emit
9063 // two branches instead of an explicit AND instruction with a
9064 // separate test. However, we only do this if this block doesn't
9065 // have a fall-through edge, because this requires an explicit
9066 // jmp when the condition is false.
9067 if (Op.getNode()->hasOneUse()) {
9068 SDNode *User = *Op.getNode()->use_begin();
9069 // Look for an unconditional branch following this conditional branch.
9070 // We need this because we need to reverse the successors in order
9071 // to implement FCMP_UNE.
9072 if (User->getOpcode() == ISD::BR) {
9073 SDValue FalseBB = User->getOperand(1);
9075 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9076 assert(NewBR == User);
9079 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9080 Cond.getOperand(0), Cond.getOperand(1));
9081 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9082 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9083 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9084 Chain, Dest, CC, Cmp);
9085 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9095 // Look pass the truncate.
9096 if (Cond.getOpcode() == ISD::TRUNCATE)
9097 Cond = Cond.getOperand(0);
9099 // We know the result of AND is compared against zero. Try to match
9101 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9102 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9103 if (NewSetCC.getNode()) {
9104 CC = NewSetCC.getOperand(0);
9105 Cond = NewSetCC.getOperand(1);
9112 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9113 Cond = EmitTest(Cond, X86::COND_NE, DAG);
9115 Cond = ConvertCmpIfNecessary(Cond, DAG);
9116 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9117 Chain, Dest, CC, Cond);
9121 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9122 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9123 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9124 // that the guard pages used by the OS virtual memory manager are allocated in
9125 // correct sequence.
9127 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9128 SelectionDAG &DAG) const {
9129 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9130 getTargetMachine().Options.EnableSegmentedStacks) &&
9131 "This should be used only on Windows targets or when segmented stacks "
9133 assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9134 DebugLoc dl = Op.getDebugLoc();
9137 SDValue Chain = Op.getOperand(0);
9138 SDValue Size = Op.getOperand(1);
9139 // FIXME: Ensure alignment here
9141 bool Is64Bit = Subtarget->is64Bit();
9142 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9144 if (getTargetMachine().Options.EnableSegmentedStacks) {
9145 MachineFunction &MF = DAG.getMachineFunction();
9146 MachineRegisterInfo &MRI = MF.getRegInfo();
9149 // The 64 bit implementation of segmented stacks needs to clobber both r10
9150 // r11. This makes it impossible to use it along with nested parameters.
9151 const Function *F = MF.getFunction();
9153 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9155 if (I->hasNestAttr())
9156 report_fatal_error("Cannot use segmented stacks with functions that "
9157 "have nested arguments.");
9160 const TargetRegisterClass *AddrRegClass =
9161 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9162 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9163 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9164 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9165 DAG.getRegister(Vreg, SPTy));
9166 SDValue Ops1[2] = { Value, Chain };
9167 return DAG.getMergeValues(Ops1, 2, dl);
9170 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9172 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9173 Flag = Chain.getValue(1);
9174 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9176 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9177 Flag = Chain.getValue(1);
9179 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9181 SDValue Ops1[2] = { Chain.getValue(0), Chain };
9182 return DAG.getMergeValues(Ops1, 2, dl);
9186 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9187 MachineFunction &MF = DAG.getMachineFunction();
9188 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9190 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9191 DebugLoc DL = Op.getDebugLoc();
9193 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9194 // vastart just stores the address of the VarArgsFrameIndex slot into the
9195 // memory location argument.
9196 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9198 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9199 MachinePointerInfo(SV), false, false, 0);
9203 // gp_offset (0 - 6 * 8)
9204 // fp_offset (48 - 48 + 8 * 16)
9205 // overflow_arg_area (point to parameters coming in memory).
9207 SmallVector<SDValue, 8> MemOps;
9208 SDValue FIN = Op.getOperand(1);
9210 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9211 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9213 FIN, MachinePointerInfo(SV), false, false, 0);
9214 MemOps.push_back(Store);
9217 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9218 FIN, DAG.getIntPtrConstant(4));
9219 Store = DAG.getStore(Op.getOperand(0), DL,
9220 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9222 FIN, MachinePointerInfo(SV, 4), false, false, 0);
9223 MemOps.push_back(Store);
9225 // Store ptr to overflow_arg_area
9226 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9227 FIN, DAG.getIntPtrConstant(4));
9228 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9230 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9231 MachinePointerInfo(SV, 8),
9233 MemOps.push_back(Store);
9235 // Store ptr to reg_save_area.
9236 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9237 FIN, DAG.getIntPtrConstant(8));
9238 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9240 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9241 MachinePointerInfo(SV, 16), false, false, 0);
9242 MemOps.push_back(Store);
9243 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9244 &MemOps[0], MemOps.size());
9247 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9248 assert(Subtarget->is64Bit() &&
9249 "LowerVAARG only handles 64-bit va_arg!");
9250 assert((Subtarget->isTargetLinux() ||
9251 Subtarget->isTargetDarwin()) &&
9252 "Unhandled target in LowerVAARG");
9253 assert(Op.getNode()->getNumOperands() == 4);
9254 SDValue Chain = Op.getOperand(0);
9255 SDValue SrcPtr = Op.getOperand(1);
9256 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9257 unsigned Align = Op.getConstantOperandVal(3);
9258 DebugLoc dl = Op.getDebugLoc();
9260 EVT ArgVT = Op.getNode()->getValueType(0);
9261 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9262 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9265 // Decide which area this value should be read from.
9266 // TODO: Implement the AMD64 ABI in its entirety. This simple
9267 // selection mechanism works only for the basic types.
9268 if (ArgVT == MVT::f80) {
9269 llvm_unreachable("va_arg for f80 not yet implemented");
9270 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9271 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
9272 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9273 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
9275 llvm_unreachable("Unhandled argument type in LowerVAARG");
9279 // Sanity Check: Make sure using fp_offset makes sense.
9280 assert(!getTargetMachine().Options.UseSoftFloat &&
9281 !(DAG.getMachineFunction()
9282 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9283 Subtarget->hasSSE1());
9286 // Insert VAARG_64 node into the DAG
9287 // VAARG_64 returns two values: Variable Argument Address, Chain
9288 SmallVector<SDValue, 11> InstOps;
9289 InstOps.push_back(Chain);
9290 InstOps.push_back(SrcPtr);
9291 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9292 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9293 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9294 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9295 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9296 VTs, &InstOps[0], InstOps.size(),
9298 MachinePointerInfo(SV),
9303 Chain = VAARG.getValue(1);
9305 // Load the next argument and return it
9306 return DAG.getLoad(ArgVT, dl,
9309 MachinePointerInfo(),
9310 false, false, false, 0);
9313 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9314 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9315 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9316 SDValue Chain = Op.getOperand(0);
9317 SDValue DstPtr = Op.getOperand(1);
9318 SDValue SrcPtr = Op.getOperand(2);
9319 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9320 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9321 DebugLoc DL = Op.getDebugLoc();
9323 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9324 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9326 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9329 // getTargetVShiftNOde - Handle vector element shifts where the shift amount
9330 // may or may not be a constant. Takes immediate version of shift as input.
9331 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
9332 SDValue SrcOp, SDValue ShAmt,
9333 SelectionDAG &DAG) {
9334 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
9336 if (isa<ConstantSDNode>(ShAmt)) {
9338 default: llvm_unreachable("Unknown target vector shift node");
9342 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9346 // Change opcode to non-immediate version
9348 default: llvm_unreachable("Unknown target vector shift node");
9349 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
9350 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
9351 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
9354 // Need to build a vector containing shift amount
9355 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
9358 ShOps[1] = DAG.getConstant(0, MVT::i32);
9359 ShOps[2] = DAG.getUNDEF(MVT::i32);
9360 ShOps[3] = DAG.getUNDEF(MVT::i32);
9361 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
9362 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9363 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
9367 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9368 DebugLoc dl = Op.getDebugLoc();
9369 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9371 default: return SDValue(); // Don't custom lower most intrinsics.
9372 // Comparison intrinsics.
9373 case Intrinsic::x86_sse_comieq_ss:
9374 case Intrinsic::x86_sse_comilt_ss:
9375 case Intrinsic::x86_sse_comile_ss:
9376 case Intrinsic::x86_sse_comigt_ss:
9377 case Intrinsic::x86_sse_comige_ss:
9378 case Intrinsic::x86_sse_comineq_ss:
9379 case Intrinsic::x86_sse_ucomieq_ss:
9380 case Intrinsic::x86_sse_ucomilt_ss:
9381 case Intrinsic::x86_sse_ucomile_ss:
9382 case Intrinsic::x86_sse_ucomigt_ss:
9383 case Intrinsic::x86_sse_ucomige_ss:
9384 case Intrinsic::x86_sse_ucomineq_ss:
9385 case Intrinsic::x86_sse2_comieq_sd:
9386 case Intrinsic::x86_sse2_comilt_sd:
9387 case Intrinsic::x86_sse2_comile_sd:
9388 case Intrinsic::x86_sse2_comigt_sd:
9389 case Intrinsic::x86_sse2_comige_sd:
9390 case Intrinsic::x86_sse2_comineq_sd:
9391 case Intrinsic::x86_sse2_ucomieq_sd:
9392 case Intrinsic::x86_sse2_ucomilt_sd:
9393 case Intrinsic::x86_sse2_ucomile_sd:
9394 case Intrinsic::x86_sse2_ucomigt_sd:
9395 case Intrinsic::x86_sse2_ucomige_sd:
9396 case Intrinsic::x86_sse2_ucomineq_sd: {
9398 ISD::CondCode CC = ISD::SETCC_INVALID;
9400 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9401 case Intrinsic::x86_sse_comieq_ss:
9402 case Intrinsic::x86_sse2_comieq_sd:
9406 case Intrinsic::x86_sse_comilt_ss:
9407 case Intrinsic::x86_sse2_comilt_sd:
9411 case Intrinsic::x86_sse_comile_ss:
9412 case Intrinsic::x86_sse2_comile_sd:
9416 case Intrinsic::x86_sse_comigt_ss:
9417 case Intrinsic::x86_sse2_comigt_sd:
9421 case Intrinsic::x86_sse_comige_ss:
9422 case Intrinsic::x86_sse2_comige_sd:
9426 case Intrinsic::x86_sse_comineq_ss:
9427 case Intrinsic::x86_sse2_comineq_sd:
9431 case Intrinsic::x86_sse_ucomieq_ss:
9432 case Intrinsic::x86_sse2_ucomieq_sd:
9433 Opc = X86ISD::UCOMI;
9436 case Intrinsic::x86_sse_ucomilt_ss:
9437 case Intrinsic::x86_sse2_ucomilt_sd:
9438 Opc = X86ISD::UCOMI;
9441 case Intrinsic::x86_sse_ucomile_ss:
9442 case Intrinsic::x86_sse2_ucomile_sd:
9443 Opc = X86ISD::UCOMI;
9446 case Intrinsic::x86_sse_ucomigt_ss:
9447 case Intrinsic::x86_sse2_ucomigt_sd:
9448 Opc = X86ISD::UCOMI;
9451 case Intrinsic::x86_sse_ucomige_ss:
9452 case Intrinsic::x86_sse2_ucomige_sd:
9453 Opc = X86ISD::UCOMI;
9456 case Intrinsic::x86_sse_ucomineq_ss:
9457 case Intrinsic::x86_sse2_ucomineq_sd:
9458 Opc = X86ISD::UCOMI;
9463 SDValue LHS = Op.getOperand(1);
9464 SDValue RHS = Op.getOperand(2);
9465 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9466 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9467 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9468 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9469 DAG.getConstant(X86CC, MVT::i8), Cond);
9470 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9472 // XOP comparison intrinsics
9473 case Intrinsic::x86_xop_vpcomltb:
9474 case Intrinsic::x86_xop_vpcomltw:
9475 case Intrinsic::x86_xop_vpcomltd:
9476 case Intrinsic::x86_xop_vpcomltq:
9477 case Intrinsic::x86_xop_vpcomltub:
9478 case Intrinsic::x86_xop_vpcomltuw:
9479 case Intrinsic::x86_xop_vpcomltud:
9480 case Intrinsic::x86_xop_vpcomltuq:
9481 case Intrinsic::x86_xop_vpcomleb:
9482 case Intrinsic::x86_xop_vpcomlew:
9483 case Intrinsic::x86_xop_vpcomled:
9484 case Intrinsic::x86_xop_vpcomleq:
9485 case Intrinsic::x86_xop_vpcomleub:
9486 case Intrinsic::x86_xop_vpcomleuw:
9487 case Intrinsic::x86_xop_vpcomleud:
9488 case Intrinsic::x86_xop_vpcomleuq:
9489 case Intrinsic::x86_xop_vpcomgtb:
9490 case Intrinsic::x86_xop_vpcomgtw:
9491 case Intrinsic::x86_xop_vpcomgtd:
9492 case Intrinsic::x86_xop_vpcomgtq:
9493 case Intrinsic::x86_xop_vpcomgtub:
9494 case Intrinsic::x86_xop_vpcomgtuw:
9495 case Intrinsic::x86_xop_vpcomgtud:
9496 case Intrinsic::x86_xop_vpcomgtuq:
9497 case Intrinsic::x86_xop_vpcomgeb:
9498 case Intrinsic::x86_xop_vpcomgew:
9499 case Intrinsic::x86_xop_vpcomged:
9500 case Intrinsic::x86_xop_vpcomgeq:
9501 case Intrinsic::x86_xop_vpcomgeub:
9502 case Intrinsic::x86_xop_vpcomgeuw:
9503 case Intrinsic::x86_xop_vpcomgeud:
9504 case Intrinsic::x86_xop_vpcomgeuq:
9505 case Intrinsic::x86_xop_vpcomeqb:
9506 case Intrinsic::x86_xop_vpcomeqw:
9507 case Intrinsic::x86_xop_vpcomeqd:
9508 case Intrinsic::x86_xop_vpcomeqq:
9509 case Intrinsic::x86_xop_vpcomequb:
9510 case Intrinsic::x86_xop_vpcomequw:
9511 case Intrinsic::x86_xop_vpcomequd:
9512 case Intrinsic::x86_xop_vpcomequq:
9513 case Intrinsic::x86_xop_vpcomneb:
9514 case Intrinsic::x86_xop_vpcomnew:
9515 case Intrinsic::x86_xop_vpcomned:
9516 case Intrinsic::x86_xop_vpcomneq:
9517 case Intrinsic::x86_xop_vpcomneub:
9518 case Intrinsic::x86_xop_vpcomneuw:
9519 case Intrinsic::x86_xop_vpcomneud:
9520 case Intrinsic::x86_xop_vpcomneuq:
9521 case Intrinsic::x86_xop_vpcomfalseb:
9522 case Intrinsic::x86_xop_vpcomfalsew:
9523 case Intrinsic::x86_xop_vpcomfalsed:
9524 case Intrinsic::x86_xop_vpcomfalseq:
9525 case Intrinsic::x86_xop_vpcomfalseub:
9526 case Intrinsic::x86_xop_vpcomfalseuw:
9527 case Intrinsic::x86_xop_vpcomfalseud:
9528 case Intrinsic::x86_xop_vpcomfalseuq:
9529 case Intrinsic::x86_xop_vpcomtrueb:
9530 case Intrinsic::x86_xop_vpcomtruew:
9531 case Intrinsic::x86_xop_vpcomtrued:
9532 case Intrinsic::x86_xop_vpcomtrueq:
9533 case Intrinsic::x86_xop_vpcomtrueub:
9534 case Intrinsic::x86_xop_vpcomtrueuw:
9535 case Intrinsic::x86_xop_vpcomtrueud:
9536 case Intrinsic::x86_xop_vpcomtrueuq: {
9541 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9542 case Intrinsic::x86_xop_vpcomltb:
9543 case Intrinsic::x86_xop_vpcomltw:
9544 case Intrinsic::x86_xop_vpcomltd:
9545 case Intrinsic::x86_xop_vpcomltq:
9547 Opc = X86ISD::VPCOM;
9549 case Intrinsic::x86_xop_vpcomltub:
9550 case Intrinsic::x86_xop_vpcomltuw:
9551 case Intrinsic::x86_xop_vpcomltud:
9552 case Intrinsic::x86_xop_vpcomltuq:
9554 Opc = X86ISD::VPCOMU;
9556 case Intrinsic::x86_xop_vpcomleb:
9557 case Intrinsic::x86_xop_vpcomlew:
9558 case Intrinsic::x86_xop_vpcomled:
9559 case Intrinsic::x86_xop_vpcomleq:
9561 Opc = X86ISD::VPCOM;
9563 case Intrinsic::x86_xop_vpcomleub:
9564 case Intrinsic::x86_xop_vpcomleuw:
9565 case Intrinsic::x86_xop_vpcomleud:
9566 case Intrinsic::x86_xop_vpcomleuq:
9568 Opc = X86ISD::VPCOMU;
9570 case Intrinsic::x86_xop_vpcomgtb:
9571 case Intrinsic::x86_xop_vpcomgtw:
9572 case Intrinsic::x86_xop_vpcomgtd:
9573 case Intrinsic::x86_xop_vpcomgtq:
9575 Opc = X86ISD::VPCOM;
9577 case Intrinsic::x86_xop_vpcomgtub:
9578 case Intrinsic::x86_xop_vpcomgtuw:
9579 case Intrinsic::x86_xop_vpcomgtud:
9580 case Intrinsic::x86_xop_vpcomgtuq:
9582 Opc = X86ISD::VPCOMU;
9584 case Intrinsic::x86_xop_vpcomgeb:
9585 case Intrinsic::x86_xop_vpcomgew:
9586 case Intrinsic::x86_xop_vpcomged:
9587 case Intrinsic::x86_xop_vpcomgeq:
9589 Opc = X86ISD::VPCOM;
9591 case Intrinsic::x86_xop_vpcomgeub:
9592 case Intrinsic::x86_xop_vpcomgeuw:
9593 case Intrinsic::x86_xop_vpcomgeud:
9594 case Intrinsic::x86_xop_vpcomgeuq:
9596 Opc = X86ISD::VPCOMU;
9598 case Intrinsic::x86_xop_vpcomeqb:
9599 case Intrinsic::x86_xop_vpcomeqw:
9600 case Intrinsic::x86_xop_vpcomeqd:
9601 case Intrinsic::x86_xop_vpcomeqq:
9603 Opc = X86ISD::VPCOM;
9605 case Intrinsic::x86_xop_vpcomequb:
9606 case Intrinsic::x86_xop_vpcomequw:
9607 case Intrinsic::x86_xop_vpcomequd:
9608 case Intrinsic::x86_xop_vpcomequq:
9610 Opc = X86ISD::VPCOMU;
9612 case Intrinsic::x86_xop_vpcomneb:
9613 case Intrinsic::x86_xop_vpcomnew:
9614 case Intrinsic::x86_xop_vpcomned:
9615 case Intrinsic::x86_xop_vpcomneq:
9617 Opc = X86ISD::VPCOM;
9619 case Intrinsic::x86_xop_vpcomneub:
9620 case Intrinsic::x86_xop_vpcomneuw:
9621 case Intrinsic::x86_xop_vpcomneud:
9622 case Intrinsic::x86_xop_vpcomneuq:
9624 Opc = X86ISD::VPCOMU;
9626 case Intrinsic::x86_xop_vpcomfalseb:
9627 case Intrinsic::x86_xop_vpcomfalsew:
9628 case Intrinsic::x86_xop_vpcomfalsed:
9629 case Intrinsic::x86_xop_vpcomfalseq:
9631 Opc = X86ISD::VPCOM;
9633 case Intrinsic::x86_xop_vpcomfalseub:
9634 case Intrinsic::x86_xop_vpcomfalseuw:
9635 case Intrinsic::x86_xop_vpcomfalseud:
9636 case Intrinsic::x86_xop_vpcomfalseuq:
9638 Opc = X86ISD::VPCOMU;
9640 case Intrinsic::x86_xop_vpcomtrueb:
9641 case Intrinsic::x86_xop_vpcomtruew:
9642 case Intrinsic::x86_xop_vpcomtrued:
9643 case Intrinsic::x86_xop_vpcomtrueq:
9645 Opc = X86ISD::VPCOM;
9647 case Intrinsic::x86_xop_vpcomtrueub:
9648 case Intrinsic::x86_xop_vpcomtrueuw:
9649 case Intrinsic::x86_xop_vpcomtrueud:
9650 case Intrinsic::x86_xop_vpcomtrueuq:
9652 Opc = X86ISD::VPCOMU;
9656 SDValue LHS = Op.getOperand(1);
9657 SDValue RHS = Op.getOperand(2);
9658 return DAG.getNode(Opc, dl, Op.getValueType(), LHS, RHS,
9659 DAG.getConstant(CC, MVT::i8));
9662 // Arithmetic intrinsics.
9663 case Intrinsic::x86_sse2_pmulu_dq:
9664 case Intrinsic::x86_avx2_pmulu_dq:
9665 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
9666 Op.getOperand(1), Op.getOperand(2));
9667 case Intrinsic::x86_sse3_hadd_ps:
9668 case Intrinsic::x86_sse3_hadd_pd:
9669 case Intrinsic::x86_avx_hadd_ps_256:
9670 case Intrinsic::x86_avx_hadd_pd_256:
9671 return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9672 Op.getOperand(1), Op.getOperand(2));
9673 case Intrinsic::x86_sse3_hsub_ps:
9674 case Intrinsic::x86_sse3_hsub_pd:
9675 case Intrinsic::x86_avx_hsub_ps_256:
9676 case Intrinsic::x86_avx_hsub_pd_256:
9677 return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9678 Op.getOperand(1), Op.getOperand(2));
9679 case Intrinsic::x86_ssse3_phadd_w_128:
9680 case Intrinsic::x86_ssse3_phadd_d_128:
9681 case Intrinsic::x86_avx2_phadd_w:
9682 case Intrinsic::x86_avx2_phadd_d:
9683 return DAG.getNode(X86ISD::HADD, dl, Op.getValueType(),
9684 Op.getOperand(1), Op.getOperand(2));
9685 case Intrinsic::x86_ssse3_phsub_w_128:
9686 case Intrinsic::x86_ssse3_phsub_d_128:
9687 case Intrinsic::x86_avx2_phsub_w:
9688 case Intrinsic::x86_avx2_phsub_d:
9689 return DAG.getNode(X86ISD::HSUB, dl, Op.getValueType(),
9690 Op.getOperand(1), Op.getOperand(2));
9691 case Intrinsic::x86_avx2_psllv_d:
9692 case Intrinsic::x86_avx2_psllv_q:
9693 case Intrinsic::x86_avx2_psllv_d_256:
9694 case Intrinsic::x86_avx2_psllv_q_256:
9695 return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9696 Op.getOperand(1), Op.getOperand(2));
9697 case Intrinsic::x86_avx2_psrlv_d:
9698 case Intrinsic::x86_avx2_psrlv_q:
9699 case Intrinsic::x86_avx2_psrlv_d_256:
9700 case Intrinsic::x86_avx2_psrlv_q_256:
9701 return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9702 Op.getOperand(1), Op.getOperand(2));
9703 case Intrinsic::x86_avx2_psrav_d:
9704 case Intrinsic::x86_avx2_psrav_d_256:
9705 return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9706 Op.getOperand(1), Op.getOperand(2));
9707 case Intrinsic::x86_ssse3_pshuf_b_128:
9708 case Intrinsic::x86_avx2_pshuf_b:
9709 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
9710 Op.getOperand(1), Op.getOperand(2));
9711 case Intrinsic::x86_ssse3_psign_b_128:
9712 case Intrinsic::x86_ssse3_psign_w_128:
9713 case Intrinsic::x86_ssse3_psign_d_128:
9714 case Intrinsic::x86_avx2_psign_b:
9715 case Intrinsic::x86_avx2_psign_w:
9716 case Intrinsic::x86_avx2_psign_d:
9717 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
9718 Op.getOperand(1), Op.getOperand(2));
9719 case Intrinsic::x86_sse41_insertps:
9720 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
9721 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9722 case Intrinsic::x86_avx_vperm2f128_ps_256:
9723 case Intrinsic::x86_avx_vperm2f128_pd_256:
9724 case Intrinsic::x86_avx_vperm2f128_si_256:
9725 case Intrinsic::x86_avx2_vperm2i128:
9726 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
9727 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
9728 case Intrinsic::x86_avx2_permd:
9729 case Intrinsic::x86_avx2_permps:
9730 // Operands intentionally swapped. Mask is last operand to intrinsic,
9731 // but second operand for node/intruction.
9732 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
9733 Op.getOperand(2), Op.getOperand(1));
9735 // ptest and testp intrinsics. The intrinsic these come from are designed to
9736 // return an integer value, not just an instruction so lower it to the ptest
9737 // or testp pattern and a setcc for the result.
9738 case Intrinsic::x86_sse41_ptestz:
9739 case Intrinsic::x86_sse41_ptestc:
9740 case Intrinsic::x86_sse41_ptestnzc:
9741 case Intrinsic::x86_avx_ptestz_256:
9742 case Intrinsic::x86_avx_ptestc_256:
9743 case Intrinsic::x86_avx_ptestnzc_256:
9744 case Intrinsic::x86_avx_vtestz_ps:
9745 case Intrinsic::x86_avx_vtestc_ps:
9746 case Intrinsic::x86_avx_vtestnzc_ps:
9747 case Intrinsic::x86_avx_vtestz_pd:
9748 case Intrinsic::x86_avx_vtestc_pd:
9749 case Intrinsic::x86_avx_vtestnzc_pd:
9750 case Intrinsic::x86_avx_vtestz_ps_256:
9751 case Intrinsic::x86_avx_vtestc_ps_256:
9752 case Intrinsic::x86_avx_vtestnzc_ps_256:
9753 case Intrinsic::x86_avx_vtestz_pd_256:
9754 case Intrinsic::x86_avx_vtestc_pd_256:
9755 case Intrinsic::x86_avx_vtestnzc_pd_256: {
9756 bool IsTestPacked = false;
9759 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9760 case Intrinsic::x86_avx_vtestz_ps:
9761 case Intrinsic::x86_avx_vtestz_pd:
9762 case Intrinsic::x86_avx_vtestz_ps_256:
9763 case Intrinsic::x86_avx_vtestz_pd_256:
9764 IsTestPacked = true; // Fallthrough
9765 case Intrinsic::x86_sse41_ptestz:
9766 case Intrinsic::x86_avx_ptestz_256:
9768 X86CC = X86::COND_E;
9770 case Intrinsic::x86_avx_vtestc_ps:
9771 case Intrinsic::x86_avx_vtestc_pd:
9772 case Intrinsic::x86_avx_vtestc_ps_256:
9773 case Intrinsic::x86_avx_vtestc_pd_256:
9774 IsTestPacked = true; // Fallthrough
9775 case Intrinsic::x86_sse41_ptestc:
9776 case Intrinsic::x86_avx_ptestc_256:
9778 X86CC = X86::COND_B;
9780 case Intrinsic::x86_avx_vtestnzc_ps:
9781 case Intrinsic::x86_avx_vtestnzc_pd:
9782 case Intrinsic::x86_avx_vtestnzc_ps_256:
9783 case Intrinsic::x86_avx_vtestnzc_pd_256:
9784 IsTestPacked = true; // Fallthrough
9785 case Intrinsic::x86_sse41_ptestnzc:
9786 case Intrinsic::x86_avx_ptestnzc_256:
9788 X86CC = X86::COND_A;
9792 SDValue LHS = Op.getOperand(1);
9793 SDValue RHS = Op.getOperand(2);
9794 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9795 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9796 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9797 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9798 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9801 // SSE/AVX shift intrinsics
9802 case Intrinsic::x86_sse2_psll_w:
9803 case Intrinsic::x86_sse2_psll_d:
9804 case Intrinsic::x86_sse2_psll_q:
9805 case Intrinsic::x86_avx2_psll_w:
9806 case Intrinsic::x86_avx2_psll_d:
9807 case Intrinsic::x86_avx2_psll_q:
9808 return DAG.getNode(X86ISD::VSHL, dl, Op.getValueType(),
9809 Op.getOperand(1), Op.getOperand(2));
9810 case Intrinsic::x86_sse2_psrl_w:
9811 case Intrinsic::x86_sse2_psrl_d:
9812 case Intrinsic::x86_sse2_psrl_q:
9813 case Intrinsic::x86_avx2_psrl_w:
9814 case Intrinsic::x86_avx2_psrl_d:
9815 case Intrinsic::x86_avx2_psrl_q:
9816 return DAG.getNode(X86ISD::VSRL, dl, Op.getValueType(),
9817 Op.getOperand(1), Op.getOperand(2));
9818 case Intrinsic::x86_sse2_psra_w:
9819 case Intrinsic::x86_sse2_psra_d:
9820 case Intrinsic::x86_avx2_psra_w:
9821 case Intrinsic::x86_avx2_psra_d:
9822 return DAG.getNode(X86ISD::VSRA, dl, Op.getValueType(),
9823 Op.getOperand(1), Op.getOperand(2));
9824 case Intrinsic::x86_sse2_pslli_w:
9825 case Intrinsic::x86_sse2_pslli_d:
9826 case Intrinsic::x86_sse2_pslli_q:
9827 case Intrinsic::x86_avx2_pslli_w:
9828 case Intrinsic::x86_avx2_pslli_d:
9829 case Intrinsic::x86_avx2_pslli_q:
9830 return getTargetVShiftNode(X86ISD::VSHLI, dl, Op.getValueType(),
9831 Op.getOperand(1), Op.getOperand(2), DAG);
9832 case Intrinsic::x86_sse2_psrli_w:
9833 case Intrinsic::x86_sse2_psrli_d:
9834 case Intrinsic::x86_sse2_psrli_q:
9835 case Intrinsic::x86_avx2_psrli_w:
9836 case Intrinsic::x86_avx2_psrli_d:
9837 case Intrinsic::x86_avx2_psrli_q:
9838 return getTargetVShiftNode(X86ISD::VSRLI, dl, Op.getValueType(),
9839 Op.getOperand(1), Op.getOperand(2), DAG);
9840 case Intrinsic::x86_sse2_psrai_w:
9841 case Intrinsic::x86_sse2_psrai_d:
9842 case Intrinsic::x86_avx2_psrai_w:
9843 case Intrinsic::x86_avx2_psrai_d:
9844 return getTargetVShiftNode(X86ISD::VSRAI, dl, Op.getValueType(),
9845 Op.getOperand(1), Op.getOperand(2), DAG);
9846 // Fix vector shift instructions where the last operand is a non-immediate
9848 case Intrinsic::x86_mmx_pslli_w:
9849 case Intrinsic::x86_mmx_pslli_d:
9850 case Intrinsic::x86_mmx_pslli_q:
9851 case Intrinsic::x86_mmx_psrli_w:
9852 case Intrinsic::x86_mmx_psrli_d:
9853 case Intrinsic::x86_mmx_psrli_q:
9854 case Intrinsic::x86_mmx_psrai_w:
9855 case Intrinsic::x86_mmx_psrai_d: {
9856 SDValue ShAmt = Op.getOperand(2);
9857 if (isa<ConstantSDNode>(ShAmt))
9860 unsigned NewIntNo = 0;
9862 case Intrinsic::x86_mmx_pslli_w:
9863 NewIntNo = Intrinsic::x86_mmx_psll_w;
9865 case Intrinsic::x86_mmx_pslli_d:
9866 NewIntNo = Intrinsic::x86_mmx_psll_d;
9868 case Intrinsic::x86_mmx_pslli_q:
9869 NewIntNo = Intrinsic::x86_mmx_psll_q;
9871 case Intrinsic::x86_mmx_psrli_w:
9872 NewIntNo = Intrinsic::x86_mmx_psrl_w;
9874 case Intrinsic::x86_mmx_psrli_d:
9875 NewIntNo = Intrinsic::x86_mmx_psrl_d;
9877 case Intrinsic::x86_mmx_psrli_q:
9878 NewIntNo = Intrinsic::x86_mmx_psrl_q;
9880 case Intrinsic::x86_mmx_psrai_w:
9881 NewIntNo = Intrinsic::x86_mmx_psra_w;
9883 case Intrinsic::x86_mmx_psrai_d:
9884 NewIntNo = Intrinsic::x86_mmx_psra_d;
9886 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
9889 // The vector shift intrinsics with scalars uses 32b shift amounts but
9890 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9892 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, ShAmt,
9893 DAG.getConstant(0, MVT::i32));
9894 // FIXME this must be lowered to get rid of the invalid type.
9896 EVT VT = Op.getValueType();
9897 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9898 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9899 DAG.getConstant(NewIntNo, MVT::i32),
9900 Op.getOperand(1), ShAmt);
9905 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9906 SelectionDAG &DAG) const {
9907 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9908 MFI->setReturnAddressIsTaken(true);
9910 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9911 DebugLoc dl = Op.getDebugLoc();
9914 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9916 DAG.getConstant(TD->getPointerSize(),
9917 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9918 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9919 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9921 MachinePointerInfo(), false, false, false, 0);
9924 // Just load the return address.
9925 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9926 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9927 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9930 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9931 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9932 MFI->setFrameAddressIsTaken(true);
9934 EVT VT = Op.getValueType();
9935 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
9936 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9937 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9938 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9940 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9941 MachinePointerInfo(),
9942 false, false, false, 0);
9946 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9947 SelectionDAG &DAG) const {
9948 return DAG.getIntPtrConstant(2*TD->getPointerSize());
9951 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9952 MachineFunction &MF = DAG.getMachineFunction();
9953 SDValue Chain = Op.getOperand(0);
9954 SDValue Offset = Op.getOperand(1);
9955 SDValue Handler = Op.getOperand(2);
9956 DebugLoc dl = Op.getDebugLoc();
9958 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9959 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9961 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9963 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9964 DAG.getIntPtrConstant(TD->getPointerSize()));
9965 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9966 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9968 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9969 MF.getRegInfo().addLiveOut(StoreAddrReg);
9971 return DAG.getNode(X86ISD::EH_RETURN, dl,
9973 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9976 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9977 SelectionDAG &DAG) const {
9978 return Op.getOperand(0);
9981 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9982 SelectionDAG &DAG) const {
9983 SDValue Root = Op.getOperand(0);
9984 SDValue Trmp = Op.getOperand(1); // trampoline
9985 SDValue FPtr = Op.getOperand(2); // nested function
9986 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9987 DebugLoc dl = Op.getDebugLoc();
9989 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9991 if (Subtarget->is64Bit()) {
9992 SDValue OutChains[6];
9994 // Large code-model.
9995 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
9996 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9998 const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9999 const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
10001 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
10003 // Load the pointer to the nested function into R11.
10004 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
10005 SDValue Addr = Trmp;
10006 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10007 Addr, MachinePointerInfo(TrmpAddr),
10010 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10011 DAG.getConstant(2, MVT::i64));
10012 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
10013 MachinePointerInfo(TrmpAddr, 2),
10016 // Load the 'nest' parameter value into R10.
10017 // R10 is specified in X86CallingConv.td
10018 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
10019 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10020 DAG.getConstant(10, MVT::i64));
10021 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10022 Addr, MachinePointerInfo(TrmpAddr, 10),
10025 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10026 DAG.getConstant(12, MVT::i64));
10027 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
10028 MachinePointerInfo(TrmpAddr, 12),
10031 // Jump to the nested function.
10032 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
10033 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10034 DAG.getConstant(20, MVT::i64));
10035 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
10036 Addr, MachinePointerInfo(TrmpAddr, 20),
10039 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
10040 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
10041 DAG.getConstant(22, MVT::i64));
10042 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
10043 MachinePointerInfo(TrmpAddr, 22),
10046 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
10048 const Function *Func =
10049 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
10050 CallingConv::ID CC = Func->getCallingConv();
10055 llvm_unreachable("Unsupported calling convention");
10056 case CallingConv::C:
10057 case CallingConv::X86_StdCall: {
10058 // Pass 'nest' parameter in ECX.
10059 // Must be kept in sync with X86CallingConv.td
10060 NestReg = X86::ECX;
10062 // Check that ECX wasn't needed by an 'inreg' parameter.
10063 FunctionType *FTy = Func->getFunctionType();
10064 const AttrListPtr &Attrs = Func->getAttributes();
10066 if (!Attrs.isEmpty() && !Func->isVarArg()) {
10067 unsigned InRegCount = 0;
10070 for (FunctionType::param_iterator I = FTy->param_begin(),
10071 E = FTy->param_end(); I != E; ++I, ++Idx)
10072 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
10073 // FIXME: should only count parameters that are lowered to integers.
10074 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
10076 if (InRegCount > 2) {
10077 report_fatal_error("Nest register in use - reduce number of inreg"
10083 case CallingConv::X86_FastCall:
10084 case CallingConv::X86_ThisCall:
10085 case CallingConv::Fast:
10086 // Pass 'nest' parameter in EAX.
10087 // Must be kept in sync with X86CallingConv.td
10088 NestReg = X86::EAX;
10092 SDValue OutChains[4];
10093 SDValue Addr, Disp;
10095 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10096 DAG.getConstant(10, MVT::i32));
10097 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
10099 // This is storing the opcode for MOV32ri.
10100 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
10101 const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
10102 OutChains[0] = DAG.getStore(Root, dl,
10103 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
10104 Trmp, MachinePointerInfo(TrmpAddr),
10107 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10108 DAG.getConstant(1, MVT::i32));
10109 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10110 MachinePointerInfo(TrmpAddr, 1),
10113 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10114 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10115 DAG.getConstant(5, MVT::i32));
10116 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10117 MachinePointerInfo(TrmpAddr, 5),
10120 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10121 DAG.getConstant(6, MVT::i32));
10122 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10123 MachinePointerInfo(TrmpAddr, 6),
10126 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10130 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10131 SelectionDAG &DAG) const {
10133 The rounding mode is in bits 11:10 of FPSR, and has the following
10135 00 Round to nearest
10140 FLT_ROUNDS, on the other hand, expects the following:
10147 To perform the conversion, we do:
10148 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10151 MachineFunction &MF = DAG.getMachineFunction();
10152 const TargetMachine &TM = MF.getTarget();
10153 const TargetFrameLowering &TFI = *TM.getFrameLowering();
10154 unsigned StackAlignment = TFI.getStackAlignment();
10155 EVT VT = Op.getValueType();
10156 DebugLoc DL = Op.getDebugLoc();
10158 // Save FP Control Word to stack slot
10159 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10160 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10163 MachineMemOperand *MMO =
10164 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10165 MachineMemOperand::MOStore, 2, 2);
10167 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10168 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10169 DAG.getVTList(MVT::Other),
10170 Ops, 2, MVT::i16, MMO);
10172 // Load FP Control Word from stack slot
10173 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10174 MachinePointerInfo(), false, false, false, 0);
10176 // Transform as necessary
10178 DAG.getNode(ISD::SRL, DL, MVT::i16,
10179 DAG.getNode(ISD::AND, DL, MVT::i16,
10180 CWD, DAG.getConstant(0x800, MVT::i16)),
10181 DAG.getConstant(11, MVT::i8));
10183 DAG.getNode(ISD::SRL, DL, MVT::i16,
10184 DAG.getNode(ISD::AND, DL, MVT::i16,
10185 CWD, DAG.getConstant(0x400, MVT::i16)),
10186 DAG.getConstant(9, MVT::i8));
10189 DAG.getNode(ISD::AND, DL, MVT::i16,
10190 DAG.getNode(ISD::ADD, DL, MVT::i16,
10191 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10192 DAG.getConstant(1, MVT::i16)),
10193 DAG.getConstant(3, MVT::i16));
10196 return DAG.getNode((VT.getSizeInBits() < 16 ?
10197 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10200 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10201 EVT VT = Op.getValueType();
10203 unsigned NumBits = VT.getSizeInBits();
10204 DebugLoc dl = Op.getDebugLoc();
10206 Op = Op.getOperand(0);
10207 if (VT == MVT::i8) {
10208 // Zero extend to i32 since there is not an i8 bsr.
10210 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10213 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10214 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10215 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10217 // If src is zero (i.e. bsr sets ZF), returns NumBits.
10220 DAG.getConstant(NumBits+NumBits-1, OpVT),
10221 DAG.getConstant(X86::COND_E, MVT::i8),
10224 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10226 // Finally xor with NumBits-1.
10227 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10230 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10234 SDValue X86TargetLowering::LowerCTLZ_ZERO_UNDEF(SDValue Op,
10235 SelectionDAG &DAG) const {
10236 EVT VT = Op.getValueType();
10238 unsigned NumBits = VT.getSizeInBits();
10239 DebugLoc dl = Op.getDebugLoc();
10241 Op = Op.getOperand(0);
10242 if (VT == MVT::i8) {
10243 // Zero extend to i32 since there is not an i8 bsr.
10245 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10248 // Issue a bsr (scan bits in reverse).
10249 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10250 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10252 // And xor with NumBits-1.
10253 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10256 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10260 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10261 EVT VT = Op.getValueType();
10262 unsigned NumBits = VT.getSizeInBits();
10263 DebugLoc dl = Op.getDebugLoc();
10264 Op = Op.getOperand(0);
10266 // Issue a bsf (scan bits forward) which also sets EFLAGS.
10267 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10268 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10270 // If src is zero (i.e. bsf sets ZF), returns NumBits.
10273 DAG.getConstant(NumBits, VT),
10274 DAG.getConstant(X86::COND_E, MVT::i8),
10277 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
10280 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10281 // ones, and then concatenate the result back.
10282 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10283 EVT VT = Op.getValueType();
10285 assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10286 "Unsupported value type for operation");
10288 unsigned NumElems = VT.getVectorNumElements();
10289 DebugLoc dl = Op.getDebugLoc();
10291 // Extract the LHS vectors
10292 SDValue LHS = Op.getOperand(0);
10293 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10294 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10296 // Extract the RHS vectors
10297 SDValue RHS = Op.getOperand(1);
10298 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10299 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10301 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10302 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10304 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10305 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10306 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10309 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10310 assert(Op.getValueType().getSizeInBits() == 256 &&
10311 Op.getValueType().isInteger() &&
10312 "Only handle AVX 256-bit vector integer operation");
10313 return Lower256IntArith(Op, DAG);
10316 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10317 assert(Op.getValueType().getSizeInBits() == 256 &&
10318 Op.getValueType().isInteger() &&
10319 "Only handle AVX 256-bit vector integer operation");
10320 return Lower256IntArith(Op, DAG);
10323 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10324 EVT VT = Op.getValueType();
10326 // Decompose 256-bit ops into smaller 128-bit ops.
10327 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10328 return Lower256IntArith(Op, DAG);
10330 assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
10331 "Only know how to lower V2I64/V4I64 multiply");
10333 DebugLoc dl = Op.getDebugLoc();
10335 // Ahi = psrlqi(a, 32);
10336 // Bhi = psrlqi(b, 32);
10338 // AloBlo = pmuludq(a, b);
10339 // AloBhi = pmuludq(a, Bhi);
10340 // AhiBlo = pmuludq(Ahi, b);
10342 // AloBhi = psllqi(AloBhi, 32);
10343 // AhiBlo = psllqi(AhiBlo, 32);
10344 // return AloBlo + AloBhi + AhiBlo;
10346 SDValue A = Op.getOperand(0);
10347 SDValue B = Op.getOperand(1);
10349 SDValue ShAmt = DAG.getConstant(32, MVT::i32);
10351 SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
10352 SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
10354 // Bit cast to 32-bit vectors for MULUDQ
10355 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
10356 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
10357 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
10358 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
10359 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
10361 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
10362 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
10363 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
10365 AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
10366 AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
10368 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10369 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10372 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10374 EVT VT = Op.getValueType();
10375 DebugLoc dl = Op.getDebugLoc();
10376 SDValue R = Op.getOperand(0);
10377 SDValue Amt = Op.getOperand(1);
10378 LLVMContext *Context = DAG.getContext();
10380 if (!Subtarget->hasSSE2())
10383 // Optimize shl/srl/sra with constant shift amount.
10384 if (isSplatVector(Amt.getNode())) {
10385 SDValue SclrAmt = Amt->getOperand(0);
10386 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10387 uint64_t ShiftAmt = C->getZExtValue();
10389 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10390 (Subtarget->hasAVX2() &&
10391 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
10392 if (Op.getOpcode() == ISD::SHL)
10393 return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
10394 DAG.getConstant(ShiftAmt, MVT::i32));
10395 if (Op.getOpcode() == ISD::SRL)
10396 return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
10397 DAG.getConstant(ShiftAmt, MVT::i32));
10398 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
10399 return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
10400 DAG.getConstant(ShiftAmt, MVT::i32));
10403 if (VT == MVT::v16i8) {
10404 if (Op.getOpcode() == ISD::SHL) {
10405 // Make a large shift.
10406 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
10407 DAG.getConstant(ShiftAmt, MVT::i32));
10408 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10409 // Zero out the rightmost bits.
10410 SmallVector<SDValue, 16> V(16,
10411 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10413 return DAG.getNode(ISD::AND, dl, VT, SHL,
10414 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10416 if (Op.getOpcode() == ISD::SRL) {
10417 // Make a large shift.
10418 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
10419 DAG.getConstant(ShiftAmt, MVT::i32));
10420 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10421 // Zero out the leftmost bits.
10422 SmallVector<SDValue, 16> V(16,
10423 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10425 return DAG.getNode(ISD::AND, dl, VT, SRL,
10426 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10428 if (Op.getOpcode() == ISD::SRA) {
10429 if (ShiftAmt == 7) {
10430 // R s>> 7 === R s< 0
10431 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10432 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10435 // R s>> a === ((R u>> a) ^ m) - m
10436 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10437 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10439 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10440 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10441 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10444 llvm_unreachable("Unknown shift opcode.");
10447 if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10448 if (Op.getOpcode() == ISD::SHL) {
10449 // Make a large shift.
10450 SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
10451 DAG.getConstant(ShiftAmt, MVT::i32));
10452 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
10453 // Zero out the rightmost bits.
10454 SmallVector<SDValue, 32> V(32,
10455 DAG.getConstant(uint8_t(-1U << ShiftAmt),
10457 return DAG.getNode(ISD::AND, dl, VT, SHL,
10458 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10460 if (Op.getOpcode() == ISD::SRL) {
10461 // Make a large shift.
10462 SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
10463 DAG.getConstant(ShiftAmt, MVT::i32));
10464 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
10465 // Zero out the leftmost bits.
10466 SmallVector<SDValue, 32> V(32,
10467 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10469 return DAG.getNode(ISD::AND, dl, VT, SRL,
10470 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10472 if (Op.getOpcode() == ISD::SRA) {
10473 if (ShiftAmt == 7) {
10474 // R s>> 7 === R s< 0
10475 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
10476 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
10479 // R s>> a === ((R u>> a) ^ m) - m
10480 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10481 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10483 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10484 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10485 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10488 llvm_unreachable("Unknown shift opcode.");
10493 // Lower SHL with variable shift amount.
10494 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10495 Op = DAG.getNode(X86ISD::VSHLI, dl, VT, Op.getOperand(1),
10496 DAG.getConstant(23, MVT::i32));
10498 const uint32_t CV[] = { 0x3f800000U, 0x3f800000U, 0x3f800000U, 0x3f800000U};
10499 Constant *C = ConstantDataVector::get(*Context, CV);
10500 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10501 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10502 MachinePointerInfo::getConstantPool(),
10503 false, false, false, 16);
10505 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10506 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10507 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10508 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10510 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10511 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
10514 Op = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, Op.getOperand(1),
10515 DAG.getConstant(5, MVT::i32));
10516 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
10518 // Turn 'a' into a mask suitable for VSELECT
10519 SDValue VSelM = DAG.getConstant(0x80, VT);
10520 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10521 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10523 SDValue CM1 = DAG.getConstant(0x0f, VT);
10524 SDValue CM2 = DAG.getConstant(0x3f, VT);
10526 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
10527 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
10528 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10529 DAG.getConstant(4, MVT::i32), DAG);
10530 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10531 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10534 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10535 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10536 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10538 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
10539 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
10540 M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
10541 DAG.getConstant(2, MVT::i32), DAG);
10542 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
10543 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
10546 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10547 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
10548 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
10550 // return VSELECT(r, r+r, a);
10551 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
10552 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
10556 // Decompose 256-bit shifts into smaller 128-bit shifts.
10557 if (VT.getSizeInBits() == 256) {
10558 unsigned NumElems = VT.getVectorNumElements();
10559 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10560 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10562 // Extract the two vectors
10563 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
10564 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
10566 // Recreate the shift amount vectors
10567 SDValue Amt1, Amt2;
10568 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10569 // Constant shift amount
10570 SmallVector<SDValue, 4> Amt1Csts;
10571 SmallVector<SDValue, 4> Amt2Csts;
10572 for (unsigned i = 0; i != NumElems/2; ++i)
10573 Amt1Csts.push_back(Amt->getOperand(i));
10574 for (unsigned i = NumElems/2; i != NumElems; ++i)
10575 Amt2Csts.push_back(Amt->getOperand(i));
10577 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10578 &Amt1Csts[0], NumElems/2);
10579 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10580 &Amt2Csts[0], NumElems/2);
10582 // Variable shift amount
10583 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
10584 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
10587 // Issue new vector shifts for the smaller types
10588 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10589 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10591 // Concatenate the result back
10592 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10598 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10599 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10600 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10601 // looks for this combo and may remove the "setcc" instruction if the "setcc"
10602 // has only one use.
10603 SDNode *N = Op.getNode();
10604 SDValue LHS = N->getOperand(0);
10605 SDValue RHS = N->getOperand(1);
10606 unsigned BaseOp = 0;
10608 DebugLoc DL = Op.getDebugLoc();
10609 switch (Op.getOpcode()) {
10610 default: llvm_unreachable("Unknown ovf instruction!");
10612 // A subtract of one will be selected as a INC. Note that INC doesn't
10613 // set CF, so we can't do this for UADDO.
10614 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10616 BaseOp = X86ISD::INC;
10617 Cond = X86::COND_O;
10620 BaseOp = X86ISD::ADD;
10621 Cond = X86::COND_O;
10624 BaseOp = X86ISD::ADD;
10625 Cond = X86::COND_B;
10628 // A subtract of one will be selected as a DEC. Note that DEC doesn't
10629 // set CF, so we can't do this for USUBO.
10630 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10632 BaseOp = X86ISD::DEC;
10633 Cond = X86::COND_O;
10636 BaseOp = X86ISD::SUB;
10637 Cond = X86::COND_O;
10640 BaseOp = X86ISD::SUB;
10641 Cond = X86::COND_B;
10644 BaseOp = X86ISD::SMUL;
10645 Cond = X86::COND_O;
10647 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10648 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10650 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10653 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10654 DAG.getConstant(X86::COND_O, MVT::i32),
10655 SDValue(Sum.getNode(), 2));
10657 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10661 // Also sets EFLAGS.
10662 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10663 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10666 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10667 DAG.getConstant(Cond, MVT::i32),
10668 SDValue(Sum.getNode(), 1));
10670 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10673 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
10674 SelectionDAG &DAG) const {
10675 DebugLoc dl = Op.getDebugLoc();
10676 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10677 EVT VT = Op.getValueType();
10679 if (!Subtarget->hasSSE2() || !VT.isVector())
10682 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10683 ExtraVT.getScalarType().getSizeInBits();
10684 SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10686 switch (VT.getSimpleVT().SimpleTy) {
10687 default: return SDValue();
10690 if (!Subtarget->hasAVX())
10692 if (!Subtarget->hasAVX2()) {
10693 // needs to be split
10694 unsigned NumElems = VT.getVectorNumElements();
10696 // Extract the LHS vectors
10697 SDValue LHS = Op.getOperand(0);
10698 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10699 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10701 MVT EltVT = VT.getVectorElementType().getSimpleVT();
10702 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10704 EVT ExtraEltVT = ExtraVT.getVectorElementType();
10705 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
10706 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10708 SDValue Extra = DAG.getValueType(ExtraVT);
10710 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10711 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10713 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10718 SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
10719 Op.getOperand(0), ShAmt, DAG);
10720 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
10726 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10727 DebugLoc dl = Op.getDebugLoc();
10729 // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10730 // There isn't any reason to disable it if the target processor supports it.
10731 if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
10732 SDValue Chain = Op.getOperand(0);
10733 SDValue Zero = DAG.getConstant(0, MVT::i32);
10735 DAG.getRegister(X86::ESP, MVT::i32), // Base
10736 DAG.getTargetConstant(1, MVT::i8), // Scale
10737 DAG.getRegister(0, MVT::i32), // Index
10738 DAG.getTargetConstant(0, MVT::i32), // Disp
10739 DAG.getRegister(0, MVT::i32), // Segment.
10744 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10745 array_lengthof(Ops));
10746 return SDValue(Res, 0);
10749 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10751 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10753 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10754 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10755 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10756 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10758 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10759 if (!Op1 && !Op2 && !Op3 && Op4)
10760 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10762 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10763 if (Op1 && !Op2 && !Op3 && !Op4)
10764 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10766 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10768 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10771 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10772 SelectionDAG &DAG) const {
10773 DebugLoc dl = Op.getDebugLoc();
10774 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10775 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10776 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10777 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10779 // The only fence that needs an instruction is a sequentially-consistent
10780 // cross-thread fence.
10781 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10782 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10783 // no-sse2). There isn't any reason to disable it if the target processor
10785 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
10786 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10788 SDValue Chain = Op.getOperand(0);
10789 SDValue Zero = DAG.getConstant(0, MVT::i32);
10791 DAG.getRegister(X86::ESP, MVT::i32), // Base
10792 DAG.getTargetConstant(1, MVT::i8), // Scale
10793 DAG.getRegister(0, MVT::i32), // Index
10794 DAG.getTargetConstant(0, MVT::i32), // Disp
10795 DAG.getRegister(0, MVT::i32), // Segment.
10800 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10801 array_lengthof(Ops));
10802 return SDValue(Res, 0);
10805 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10806 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10810 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10811 EVT T = Op.getValueType();
10812 DebugLoc DL = Op.getDebugLoc();
10815 switch(T.getSimpleVT().SimpleTy) {
10816 default: llvm_unreachable("Invalid value type!");
10817 case MVT::i8: Reg = X86::AL; size = 1; break;
10818 case MVT::i16: Reg = X86::AX; size = 2; break;
10819 case MVT::i32: Reg = X86::EAX; size = 4; break;
10821 assert(Subtarget->is64Bit() && "Node not type legal!");
10822 Reg = X86::RAX; size = 8;
10825 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10826 Op.getOperand(2), SDValue());
10827 SDValue Ops[] = { cpIn.getValue(0),
10830 DAG.getTargetConstant(size, MVT::i8),
10831 cpIn.getValue(1) };
10832 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10833 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10834 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10837 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10841 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10842 SelectionDAG &DAG) const {
10843 assert(Subtarget->is64Bit() && "Result not type legalized?");
10844 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10845 SDValue TheChain = Op.getOperand(0);
10846 DebugLoc dl = Op.getDebugLoc();
10847 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10848 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10849 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10851 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10852 DAG.getConstant(32, MVT::i8));
10854 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10857 return DAG.getMergeValues(Ops, 2, dl);
10860 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10861 SelectionDAG &DAG) const {
10862 EVT SrcVT = Op.getOperand(0).getValueType();
10863 EVT DstVT = Op.getValueType();
10864 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
10865 Subtarget->hasMMX() && "Unexpected custom BITCAST");
10866 assert((DstVT == MVT::i64 ||
10867 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10868 "Unexpected custom BITCAST");
10869 // i64 <=> MMX conversions are Legal.
10870 if (SrcVT==MVT::i64 && DstVT.isVector())
10872 if (DstVT==MVT::i64 && SrcVT.isVector())
10874 // MMX <=> MMX conversions are Legal.
10875 if (SrcVT.isVector() && DstVT.isVector())
10877 // All other conversions need to be expanded.
10881 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10882 SDNode *Node = Op.getNode();
10883 DebugLoc dl = Node->getDebugLoc();
10884 EVT T = Node->getValueType(0);
10885 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10886 DAG.getConstant(0, T), Node->getOperand(2));
10887 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10888 cast<AtomicSDNode>(Node)->getMemoryVT(),
10889 Node->getOperand(0),
10890 Node->getOperand(1), negOp,
10891 cast<AtomicSDNode>(Node)->getSrcValue(),
10892 cast<AtomicSDNode>(Node)->getAlignment(),
10893 cast<AtomicSDNode>(Node)->getOrdering(),
10894 cast<AtomicSDNode>(Node)->getSynchScope());
10897 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10898 SDNode *Node = Op.getNode();
10899 DebugLoc dl = Node->getDebugLoc();
10900 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10902 // Convert seq_cst store -> xchg
10903 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10904 // FIXME: On 32-bit, store -> fist or movq would be more efficient
10905 // (The only way to get a 16-byte store is cmpxchg16b)
10906 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10907 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10908 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10909 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10910 cast<AtomicSDNode>(Node)->getMemoryVT(),
10911 Node->getOperand(0),
10912 Node->getOperand(1), Node->getOperand(2),
10913 cast<AtomicSDNode>(Node)->getMemOperand(),
10914 cast<AtomicSDNode>(Node)->getOrdering(),
10915 cast<AtomicSDNode>(Node)->getSynchScope());
10916 return Swap.getValue(1);
10918 // Other atomic stores have a simple pattern.
10922 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10923 EVT VT = Op.getNode()->getValueType(0);
10925 // Let legalize expand this if it isn't a legal type yet.
10926 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10929 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10932 bool ExtraOp = false;
10933 switch (Op.getOpcode()) {
10934 default: llvm_unreachable("Invalid code");
10935 case ISD::ADDC: Opc = X86ISD::ADD; break;
10936 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10937 case ISD::SUBC: Opc = X86ISD::SUB; break;
10938 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10942 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10944 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10945 Op.getOperand(1), Op.getOperand(2));
10948 /// LowerOperation - Provide custom lowering hooks for some operations.
10950 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10951 switch (Op.getOpcode()) {
10952 default: llvm_unreachable("Should not custom lower this!");
10953 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
10954 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
10955 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op,DAG);
10956 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
10957 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
10958 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
10959 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
10960 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
10961 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
10962 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10963 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
10964 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG);
10965 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, DAG);
10966 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
10967 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
10968 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
10969 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
10970 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
10971 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
10972 case ISD::SHL_PARTS:
10973 case ISD::SRA_PARTS:
10974 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
10975 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
10976 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
10977 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
10978 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
10979 case ISD::FABS: return LowerFABS(Op, DAG);
10980 case ISD::FNEG: return LowerFNEG(Op, DAG);
10981 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
10982 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
10983 case ISD::SETCC: return LowerSETCC(Op, DAG);
10984 case ISD::SELECT: return LowerSELECT(Op, DAG);
10985 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
10986 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
10987 case ISD::VASTART: return LowerVASTART(Op, DAG);
10988 case ISD::VAARG: return LowerVAARG(Op, DAG);
10989 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
10990 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10991 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
10992 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
10993 case ISD::FRAME_TO_ARGS_OFFSET:
10994 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10995 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10996 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
10997 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
10998 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
10999 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
11000 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
11001 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
11002 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
11003 case ISD::MUL: return LowerMUL(Op, DAG);
11006 case ISD::SHL: return LowerShift(Op, DAG);
11012 case ISD::UMULO: return LowerXALUO(Op, DAG);
11013 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
11014 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
11018 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
11019 case ISD::ADD: return LowerADD(Op, DAG);
11020 case ISD::SUB: return LowerSUB(Op, DAG);
11024 static void ReplaceATOMIC_LOAD(SDNode *Node,
11025 SmallVectorImpl<SDValue> &Results,
11026 SelectionDAG &DAG) {
11027 DebugLoc dl = Node->getDebugLoc();
11028 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
11030 // Convert wide load -> cmpxchg8b/cmpxchg16b
11031 // FIXME: On 32-bit, load -> fild or movq would be more efficient
11032 // (The only way to get a 16-byte load is cmpxchg16b)
11033 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11034 SDValue Zero = DAG.getConstant(0, VT);
11035 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11036 Node->getOperand(0),
11037 Node->getOperand(1), Zero, Zero,
11038 cast<AtomicSDNode>(Node)->getMemOperand(),
11039 cast<AtomicSDNode>(Node)->getOrdering(),
11040 cast<AtomicSDNode>(Node)->getSynchScope());
11041 Results.push_back(Swap.getValue(0));
11042 Results.push_back(Swap.getValue(1));
11045 void X86TargetLowering::
11046 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11047 SelectionDAG &DAG, unsigned NewOp) const {
11048 DebugLoc dl = Node->getDebugLoc();
11049 assert (Node->getValueType(0) == MVT::i64 &&
11050 "Only know how to expand i64 atomics");
11052 SDValue Chain = Node->getOperand(0);
11053 SDValue In1 = Node->getOperand(1);
11054 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11055 Node->getOperand(2), DAG.getIntPtrConstant(0));
11056 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11057 Node->getOperand(2), DAG.getIntPtrConstant(1));
11058 SDValue Ops[] = { Chain, In1, In2L, In2H };
11059 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11061 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11062 cast<MemSDNode>(Node)->getMemOperand());
11063 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11064 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11065 Results.push_back(Result.getValue(2));
11068 /// ReplaceNodeResults - Replace a node with an illegal result type
11069 /// with a new node built out of custom code.
11070 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11071 SmallVectorImpl<SDValue>&Results,
11072 SelectionDAG &DAG) const {
11073 DebugLoc dl = N->getDebugLoc();
11074 switch (N->getOpcode()) {
11076 llvm_unreachable("Do not know how to custom type legalize this operation!");
11077 case ISD::SIGN_EXTEND_INREG:
11082 // We don't want to expand or promote these.
11084 case ISD::FP_TO_SINT:
11085 case ISD::FP_TO_UINT: {
11086 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
11088 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
11091 std::pair<SDValue,SDValue> Vals =
11092 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
11093 SDValue FIST = Vals.first, StackSlot = Vals.second;
11094 if (FIST.getNode() != 0) {
11095 EVT VT = N->getValueType(0);
11096 // Return a load from the stack slot.
11097 if (StackSlot.getNode() != 0)
11098 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11099 MachinePointerInfo(),
11100 false, false, false, 0));
11102 Results.push_back(FIST);
11106 case ISD::READCYCLECOUNTER: {
11107 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11108 SDValue TheChain = N->getOperand(0);
11109 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11110 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11112 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11114 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11115 SDValue Ops[] = { eax, edx };
11116 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11117 Results.push_back(edx.getValue(1));
11120 case ISD::ATOMIC_CMP_SWAP: {
11121 EVT T = N->getValueType(0);
11122 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11123 bool Regs64bit = T == MVT::i128;
11124 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11125 SDValue cpInL, cpInH;
11126 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11127 DAG.getConstant(0, HalfT));
11128 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11129 DAG.getConstant(1, HalfT));
11130 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11131 Regs64bit ? X86::RAX : X86::EAX,
11133 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11134 Regs64bit ? X86::RDX : X86::EDX,
11135 cpInH, cpInL.getValue(1));
11136 SDValue swapInL, swapInH;
11137 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11138 DAG.getConstant(0, HalfT));
11139 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11140 DAG.getConstant(1, HalfT));
11141 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11142 Regs64bit ? X86::RBX : X86::EBX,
11143 swapInL, cpInH.getValue(1));
11144 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11145 Regs64bit ? X86::RCX : X86::ECX,
11146 swapInH, swapInL.getValue(1));
11147 SDValue Ops[] = { swapInH.getValue(0),
11149 swapInH.getValue(1) };
11150 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11151 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11152 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11153 X86ISD::LCMPXCHG8_DAG;
11154 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11156 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11157 Regs64bit ? X86::RAX : X86::EAX,
11158 HalfT, Result.getValue(1));
11159 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11160 Regs64bit ? X86::RDX : X86::EDX,
11161 HalfT, cpOutL.getValue(2));
11162 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11163 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11164 Results.push_back(cpOutH.getValue(1));
11167 case ISD::ATOMIC_LOAD_ADD:
11168 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11170 case ISD::ATOMIC_LOAD_AND:
11171 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11173 case ISD::ATOMIC_LOAD_NAND:
11174 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11176 case ISD::ATOMIC_LOAD_OR:
11177 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11179 case ISD::ATOMIC_LOAD_SUB:
11180 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11182 case ISD::ATOMIC_LOAD_XOR:
11183 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11185 case ISD::ATOMIC_SWAP:
11186 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11188 case ISD::ATOMIC_LOAD:
11189 ReplaceATOMIC_LOAD(N, Results, DAG);
11193 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11195 default: return NULL;
11196 case X86ISD::BSF: return "X86ISD::BSF";
11197 case X86ISD::BSR: return "X86ISD::BSR";
11198 case X86ISD::SHLD: return "X86ISD::SHLD";
11199 case X86ISD::SHRD: return "X86ISD::SHRD";
11200 case X86ISD::FAND: return "X86ISD::FAND";
11201 case X86ISD::FOR: return "X86ISD::FOR";
11202 case X86ISD::FXOR: return "X86ISD::FXOR";
11203 case X86ISD::FSRL: return "X86ISD::FSRL";
11204 case X86ISD::FILD: return "X86ISD::FILD";
11205 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
11206 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11207 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11208 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11209 case X86ISD::FLD: return "X86ISD::FLD";
11210 case X86ISD::FST: return "X86ISD::FST";
11211 case X86ISD::CALL: return "X86ISD::CALL";
11212 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
11213 case X86ISD::BT: return "X86ISD::BT";
11214 case X86ISD::CMP: return "X86ISD::CMP";
11215 case X86ISD::COMI: return "X86ISD::COMI";
11216 case X86ISD::UCOMI: return "X86ISD::UCOMI";
11217 case X86ISD::SETCC: return "X86ISD::SETCC";
11218 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
11219 case X86ISD::FSETCCsd: return "X86ISD::FSETCCsd";
11220 case X86ISD::FSETCCss: return "X86ISD::FSETCCss";
11221 case X86ISD::CMOV: return "X86ISD::CMOV";
11222 case X86ISD::BRCOND: return "X86ISD::BRCOND";
11223 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
11224 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
11225 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
11226 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
11227 case X86ISD::Wrapper: return "X86ISD::Wrapper";
11228 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
11229 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
11230 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
11231 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
11232 case X86ISD::PINSRB: return "X86ISD::PINSRB";
11233 case X86ISD::PINSRW: return "X86ISD::PINSRW";
11234 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
11235 case X86ISD::ANDNP: return "X86ISD::ANDNP";
11236 case X86ISD::PSIGN: return "X86ISD::PSIGN";
11237 case X86ISD::BLENDV: return "X86ISD::BLENDV";
11238 case X86ISD::BLENDPW: return "X86ISD::BLENDPW";
11239 case X86ISD::BLENDPS: return "X86ISD::BLENDPS";
11240 case X86ISD::BLENDPD: return "X86ISD::BLENDPD";
11241 case X86ISD::HADD: return "X86ISD::HADD";
11242 case X86ISD::HSUB: return "X86ISD::HSUB";
11243 case X86ISD::FHADD: return "X86ISD::FHADD";
11244 case X86ISD::FHSUB: return "X86ISD::FHSUB";
11245 case X86ISD::FMAX: return "X86ISD::FMAX";
11246 case X86ISD::FMIN: return "X86ISD::FMIN";
11247 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
11248 case X86ISD::FRCP: return "X86ISD::FRCP";
11249 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
11250 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
11251 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
11252 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
11253 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
11254 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
11255 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
11256 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
11257 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
11258 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
11259 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
11260 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
11261 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
11262 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
11263 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
11264 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
11265 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
11266 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
11267 case X86ISD::VSHL: return "X86ISD::VSHL";
11268 case X86ISD::VSRL: return "X86ISD::VSRL";
11269 case X86ISD::VSRA: return "X86ISD::VSRA";
11270 case X86ISD::VSHLI: return "X86ISD::VSHLI";
11271 case X86ISD::VSRLI: return "X86ISD::VSRLI";
11272 case X86ISD::VSRAI: return "X86ISD::VSRAI";
11273 case X86ISD::CMPP: return "X86ISD::CMPP";
11274 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
11275 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
11276 case X86ISD::ADD: return "X86ISD::ADD";
11277 case X86ISD::SUB: return "X86ISD::SUB";
11278 case X86ISD::ADC: return "X86ISD::ADC";
11279 case X86ISD::SBB: return "X86ISD::SBB";
11280 case X86ISD::SMUL: return "X86ISD::SMUL";
11281 case X86ISD::UMUL: return "X86ISD::UMUL";
11282 case X86ISD::INC: return "X86ISD::INC";
11283 case X86ISD::DEC: return "X86ISD::DEC";
11284 case X86ISD::OR: return "X86ISD::OR";
11285 case X86ISD::XOR: return "X86ISD::XOR";
11286 case X86ISD::AND: return "X86ISD::AND";
11287 case X86ISD::ANDN: return "X86ISD::ANDN";
11288 case X86ISD::BLSI: return "X86ISD::BLSI";
11289 case X86ISD::BLSMSK: return "X86ISD::BLSMSK";
11290 case X86ISD::BLSR: return "X86ISD::BLSR";
11291 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
11292 case X86ISD::PTEST: return "X86ISD::PTEST";
11293 case X86ISD::TESTP: return "X86ISD::TESTP";
11294 case X86ISD::PALIGN: return "X86ISD::PALIGN";
11295 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
11296 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
11297 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
11298 case X86ISD::SHUFP: return "X86ISD::SHUFP";
11299 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
11300 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
11301 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
11302 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
11303 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
11304 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
11305 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
11306 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
11307 case X86ISD::MOVSD: return "X86ISD::MOVSD";
11308 case X86ISD::MOVSS: return "X86ISD::MOVSS";
11309 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
11310 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
11311 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
11312 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
11313 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
11314 case X86ISD::VPERMV: return "X86ISD::VPERMV";
11315 case X86ISD::VPERMI: return "X86ISD::VPERMI";
11316 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
11317 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11318 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
11319 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
11320 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
11321 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
11322 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
11323 case X86ISD::SAHF: return "X86ISD::SAHF";
11327 // isLegalAddressingMode - Return true if the addressing mode represented
11328 // by AM is legal for this target, for a load/store of the specified type.
11329 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11331 // X86 supports extremely general addressing modes.
11332 CodeModel::Model M = getTargetMachine().getCodeModel();
11333 Reloc::Model R = getTargetMachine().getRelocationModel();
11335 // X86 allows a sign-extended 32-bit immediate field as a displacement.
11336 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11341 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11343 // If a reference to this global requires an extra load, we can't fold it.
11344 if (isGlobalStubReference(GVFlags))
11347 // If BaseGV requires a register for the PIC base, we cannot also have a
11348 // BaseReg specified.
11349 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11352 // If lower 4G is not available, then we must use rip-relative addressing.
11353 if ((M != CodeModel::Small || R != Reloc::Static) &&
11354 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11358 switch (AM.Scale) {
11364 // These scales always work.
11369 // These scales are formed with basereg+scalereg. Only accept if there is
11374 default: // Other stuff never works.
11382 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11383 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11385 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11386 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11387 if (NumBits1 <= NumBits2)
11392 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11393 if (!VT1.isInteger() || !VT2.isInteger())
11395 unsigned NumBits1 = VT1.getSizeInBits();
11396 unsigned NumBits2 = VT2.getSizeInBits();
11397 if (NumBits1 <= NumBits2)
11402 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11403 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11404 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11407 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11408 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11409 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11412 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11413 // i16 instructions are longer (0x66 prefix) and potentially slower.
11414 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11417 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11418 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11419 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11420 /// are assumed to be legal.
11422 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11424 // Very little shuffling can be done for 64-bit vectors right now.
11425 if (VT.getSizeInBits() == 64)
11428 // FIXME: pshufb, blends, shifts.
11429 return (VT.getVectorNumElements() == 2 ||
11430 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11431 isMOVLMask(M, VT) ||
11432 isSHUFPMask(M, VT, Subtarget->hasAVX()) ||
11433 isPSHUFDMask(M, VT) ||
11434 isPSHUFHWMask(M, VT, Subtarget->hasAVX2()) ||
11435 isPSHUFLWMask(M, VT, Subtarget->hasAVX2()) ||
11436 isPALIGNRMask(M, VT, Subtarget) ||
11437 isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11438 isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11439 isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasAVX2()) ||
11440 isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasAVX2()));
11444 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11446 unsigned NumElts = VT.getVectorNumElements();
11447 // FIXME: This collection of masks seems suspect.
11450 if (NumElts == 4 && VT.getSizeInBits() == 128) {
11451 return (isMOVLMask(Mask, VT) ||
11452 isCommutedMOVLMask(Mask, VT, true) ||
11453 isSHUFPMask(Mask, VT, Subtarget->hasAVX()) ||
11454 isSHUFPMask(Mask, VT, Subtarget->hasAVX(), /* Commuted */ true));
11459 //===----------------------------------------------------------------------===//
11460 // X86 Scheduler Hooks
11461 //===----------------------------------------------------------------------===//
11463 // private utility function
11464 MachineBasicBlock *
11465 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11466 MachineBasicBlock *MBB,
11473 const TargetRegisterClass *RC,
11474 bool Invert) const {
11475 // For the atomic bitwise operator, we generate
11478 // ld t1 = [bitinstr.addr]
11479 // op t2 = t1, [bitinstr.val]
11480 // not t3 = t2 (if Invert)
11482 // lcs dest = [bitinstr.addr], t3 [EAX is implicit]
11484 // fallthrough -->nextMBB
11485 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11486 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11487 MachineFunction::iterator MBBIter = MBB;
11490 /// First build the CFG
11491 MachineFunction *F = MBB->getParent();
11492 MachineBasicBlock *thisMBB = MBB;
11493 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11494 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11495 F->insert(MBBIter, newMBB);
11496 F->insert(MBBIter, nextMBB);
11498 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11499 nextMBB->splice(nextMBB->begin(), thisMBB,
11500 llvm::next(MachineBasicBlock::iterator(bInstr)),
11502 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11504 // Update thisMBB to fall through to newMBB
11505 thisMBB->addSuccessor(newMBB);
11507 // newMBB jumps to itself and fall through to nextMBB
11508 newMBB->addSuccessor(nextMBB);
11509 newMBB->addSuccessor(newMBB);
11511 // Insert instructions into newMBB based on incoming instruction
11512 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11513 "unexpected number of operands");
11514 DebugLoc dl = bInstr->getDebugLoc();
11515 MachineOperand& destOper = bInstr->getOperand(0);
11516 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11517 int numArgs = bInstr->getNumOperands() - 1;
11518 for (int i=0; i < numArgs; ++i)
11519 argOpers[i] = &bInstr->getOperand(i+1);
11521 // x86 address has 4 operands: base, index, scale, and displacement
11522 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11523 int valArgIndx = lastAddrIndx + 1;
11525 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11526 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11527 for (int i=0; i <= lastAddrIndx; ++i)
11528 (*MIB).addOperand(*argOpers[i]);
11530 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11531 assert((argOpers[valArgIndx]->isReg() ||
11532 argOpers[valArgIndx]->isImm()) &&
11533 "invalid operand");
11534 if (argOpers[valArgIndx]->isReg())
11535 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11537 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11539 (*MIB).addOperand(*argOpers[valArgIndx]);
11541 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11543 MIB = BuildMI(newMBB, dl, TII->get(notOpc), t3).addReg(t2);
11548 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11551 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11552 for (int i=0; i <= lastAddrIndx; ++i)
11553 (*MIB).addOperand(*argOpers[i]);
11555 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11556 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11557 bInstr->memoperands_end());
11559 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11560 MIB.addReg(EAXreg);
11563 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11565 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11569 // private utility function: 64 bit atomics on 32 bit host.
11570 MachineBasicBlock *
11571 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11572 MachineBasicBlock *MBB,
11577 bool Invert) const {
11578 // For the atomic bitwise operator, we generate
11579 // thisMBB (instructions are in pairs, except cmpxchg8b)
11580 // ld t1,t2 = [bitinstr.addr]
11582 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11583 // op t5, t6 <- out1, out2, [bitinstr.val]
11584 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
11585 // neg t7, t8 < t5, t6 (if Invert)
11586 // mov ECX, EBX <- t5, t6
11587 // mov EAX, EDX <- t1, t2
11588 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
11589 // mov t3, t4 <- EAX, EDX
11591 // result in out1, out2
11592 // fallthrough -->nextMBB
11594 const TargetRegisterClass *RC = &X86::GR32RegClass;
11595 const unsigned LoadOpc = X86::MOV32rm;
11596 const unsigned NotOpc = X86::NOT32r;
11597 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11598 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11599 MachineFunction::iterator MBBIter = MBB;
11602 /// First build the CFG
11603 MachineFunction *F = MBB->getParent();
11604 MachineBasicBlock *thisMBB = MBB;
11605 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11606 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11607 F->insert(MBBIter, newMBB);
11608 F->insert(MBBIter, nextMBB);
11610 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11611 nextMBB->splice(nextMBB->begin(), thisMBB,
11612 llvm::next(MachineBasicBlock::iterator(bInstr)),
11614 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11616 // Update thisMBB to fall through to newMBB
11617 thisMBB->addSuccessor(newMBB);
11619 // newMBB jumps to itself and fall through to nextMBB
11620 newMBB->addSuccessor(nextMBB);
11621 newMBB->addSuccessor(newMBB);
11623 DebugLoc dl = bInstr->getDebugLoc();
11624 // Insert instructions into newMBB based on incoming instruction
11625 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11626 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11627 "unexpected number of operands");
11628 MachineOperand& dest1Oper = bInstr->getOperand(0);
11629 MachineOperand& dest2Oper = bInstr->getOperand(1);
11630 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11631 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11632 argOpers[i] = &bInstr->getOperand(i+2);
11634 // We use some of the operands multiple times, so conservatively just
11635 // clear any kill flags that might be present.
11636 if (argOpers[i]->isReg() && argOpers[i]->isUse())
11637 argOpers[i]->setIsKill(false);
11640 // x86 address has 5 operands: base, index, scale, displacement, and segment.
11641 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11643 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11644 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11645 for (int i=0; i <= lastAddrIndx; ++i)
11646 (*MIB).addOperand(*argOpers[i]);
11647 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11648 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11649 // add 4 to displacement.
11650 for (int i=0; i <= lastAddrIndx-2; ++i)
11651 (*MIB).addOperand(*argOpers[i]);
11652 MachineOperand newOp3 = *(argOpers[3]);
11653 if (newOp3.isImm())
11654 newOp3.setImm(newOp3.getImm()+4);
11656 newOp3.setOffset(newOp3.getOffset()+4);
11657 (*MIB).addOperand(newOp3);
11658 (*MIB).addOperand(*argOpers[lastAddrIndx]);
11660 // t3/4 are defined later, at the bottom of the loop
11661 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11662 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11663 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11664 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11665 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11666 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11668 // The subsequent operations should be using the destination registers of
11669 // the PHI instructions.
11670 t1 = dest1Oper.getReg();
11671 t2 = dest2Oper.getReg();
11673 int valArgIndx = lastAddrIndx + 1;
11674 assert((argOpers[valArgIndx]->isReg() ||
11675 argOpers[valArgIndx]->isImm()) &&
11676 "invalid operand");
11677 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11678 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11679 if (argOpers[valArgIndx]->isReg())
11680 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11682 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11683 if (regOpcL != X86::MOV32rr)
11685 (*MIB).addOperand(*argOpers[valArgIndx]);
11686 assert(argOpers[valArgIndx + 1]->isReg() ==
11687 argOpers[valArgIndx]->isReg());
11688 assert(argOpers[valArgIndx + 1]->isImm() ==
11689 argOpers[valArgIndx]->isImm());
11690 if (argOpers[valArgIndx + 1]->isReg())
11691 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11693 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11694 if (regOpcH != X86::MOV32rr)
11696 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11700 t7 = F->getRegInfo().createVirtualRegister(RC);
11701 t8 = F->getRegInfo().createVirtualRegister(RC);
11702 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t7).addReg(t5);
11703 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t8).addReg(t6);
11709 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11711 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11714 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11716 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11719 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11720 for (int i=0; i <= lastAddrIndx; ++i)
11721 (*MIB).addOperand(*argOpers[i]);
11723 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11724 (*MIB).setMemRefs(bInstr->memoperands_begin(),
11725 bInstr->memoperands_end());
11727 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11728 MIB.addReg(X86::EAX);
11729 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11730 MIB.addReg(X86::EDX);
11733 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11735 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
11739 // private utility function
11740 MachineBasicBlock *
11741 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11742 MachineBasicBlock *MBB,
11743 unsigned cmovOpc) const {
11744 // For the atomic min/max operator, we generate
11747 // ld t1 = [min/max.addr]
11748 // mov t2 = [min/max.val]
11750 // cmov[cond] t2 = t1
11752 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
11754 // fallthrough -->nextMBB
11756 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11757 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11758 MachineFunction::iterator MBBIter = MBB;
11761 /// First build the CFG
11762 MachineFunction *F = MBB->getParent();
11763 MachineBasicBlock *thisMBB = MBB;
11764 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11765 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11766 F->insert(MBBIter, newMBB);
11767 F->insert(MBBIter, nextMBB);
11769 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11770 nextMBB->splice(nextMBB->begin(), thisMBB,
11771 llvm::next(MachineBasicBlock::iterator(mInstr)),
11773 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11775 // Update thisMBB to fall through to newMBB
11776 thisMBB->addSuccessor(newMBB);
11778 // newMBB jumps to newMBB and fall through to nextMBB
11779 newMBB->addSuccessor(nextMBB);
11780 newMBB->addSuccessor(newMBB);
11782 DebugLoc dl = mInstr->getDebugLoc();
11783 // Insert instructions into newMBB based on incoming instruction
11784 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11785 "unexpected number of operands");
11786 MachineOperand& destOper = mInstr->getOperand(0);
11787 MachineOperand* argOpers[2 + X86::AddrNumOperands];
11788 int numArgs = mInstr->getNumOperands() - 1;
11789 for (int i=0; i < numArgs; ++i)
11790 argOpers[i] = &mInstr->getOperand(i+1);
11792 // x86 address has 4 operands: base, index, scale, and displacement
11793 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11794 int valArgIndx = lastAddrIndx + 1;
11796 unsigned t1 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11797 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11798 for (int i=0; i <= lastAddrIndx; ++i)
11799 (*MIB).addOperand(*argOpers[i]);
11801 // We only support register and immediate values
11802 assert((argOpers[valArgIndx]->isReg() ||
11803 argOpers[valArgIndx]->isImm()) &&
11804 "invalid operand");
11806 unsigned t2 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11807 if (argOpers[valArgIndx]->isReg())
11808 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11810 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11811 (*MIB).addOperand(*argOpers[valArgIndx]);
11813 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11816 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11821 unsigned t3 = F->getRegInfo().createVirtualRegister(&X86::GR32RegClass);
11822 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11826 // Cmp and exchange if none has modified the memory location
11827 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11828 for (int i=0; i <= lastAddrIndx; ++i)
11829 (*MIB).addOperand(*argOpers[i]);
11831 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11832 (*MIB).setMemRefs(mInstr->memoperands_begin(),
11833 mInstr->memoperands_end());
11835 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11836 MIB.addReg(X86::EAX);
11839 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11841 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
11845 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11846 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11847 // in the .td file.
11848 MachineBasicBlock *
11849 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11850 unsigned numArgs, bool memArg) const {
11851 assert(Subtarget->hasSSE42() &&
11852 "Target must have SSE4.2 or AVX features enabled");
11854 DebugLoc dl = MI->getDebugLoc();
11855 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11857 if (!Subtarget->hasAVX()) {
11859 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11861 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11864 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11866 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11869 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11870 for (unsigned i = 0; i < numArgs; ++i) {
11871 MachineOperand &Op = MI->getOperand(i+1);
11872 if (!(Op.isReg() && Op.isImplicit()))
11873 MIB.addOperand(Op);
11875 BuildMI(*BB, MI, dl,
11876 TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11877 MI->getOperand(0).getReg())
11878 .addReg(X86::XMM0);
11880 MI->eraseFromParent();
11884 MachineBasicBlock *
11885 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11886 DebugLoc dl = MI->getDebugLoc();
11887 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11889 // Address into RAX/EAX, other two args into ECX, EDX.
11890 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11891 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11892 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11893 for (int i = 0; i < X86::AddrNumOperands; ++i)
11894 MIB.addOperand(MI->getOperand(i));
11896 unsigned ValOps = X86::AddrNumOperands;
11897 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11898 .addReg(MI->getOperand(ValOps).getReg());
11899 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11900 .addReg(MI->getOperand(ValOps+1).getReg());
11902 // The instruction doesn't actually take any operands though.
11903 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11905 MI->eraseFromParent(); // The pseudo is gone now.
11909 MachineBasicBlock *
11910 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11911 DebugLoc dl = MI->getDebugLoc();
11912 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11914 // First arg in ECX, the second in EAX.
11915 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11916 .addReg(MI->getOperand(0).getReg());
11917 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11918 .addReg(MI->getOperand(1).getReg());
11920 // The instruction doesn't actually take any operands though.
11921 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11923 MI->eraseFromParent(); // The pseudo is gone now.
11927 MachineBasicBlock *
11928 X86TargetLowering::EmitVAARG64WithCustomInserter(
11930 MachineBasicBlock *MBB) const {
11931 // Emit va_arg instruction on X86-64.
11933 // Operands to this pseudo-instruction:
11934 // 0 ) Output : destination address (reg)
11935 // 1-5) Input : va_list address (addr, i64mem)
11936 // 6 ) ArgSize : Size (in bytes) of vararg type
11937 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11938 // 8 ) Align : Alignment of type
11939 // 9 ) EFLAGS (implicit-def)
11941 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11942 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11944 unsigned DestReg = MI->getOperand(0).getReg();
11945 MachineOperand &Base = MI->getOperand(1);
11946 MachineOperand &Scale = MI->getOperand(2);
11947 MachineOperand &Index = MI->getOperand(3);
11948 MachineOperand &Disp = MI->getOperand(4);
11949 MachineOperand &Segment = MI->getOperand(5);
11950 unsigned ArgSize = MI->getOperand(6).getImm();
11951 unsigned ArgMode = MI->getOperand(7).getImm();
11952 unsigned Align = MI->getOperand(8).getImm();
11954 // Memory Reference
11955 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11956 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11957 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11959 // Machine Information
11960 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11961 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11962 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11963 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11964 DebugLoc DL = MI->getDebugLoc();
11966 // struct va_list {
11969 // i64 overflow_area (address)
11970 // i64 reg_save_area (address)
11972 // sizeof(va_list) = 24
11973 // alignment(va_list) = 8
11975 unsigned TotalNumIntRegs = 6;
11976 unsigned TotalNumXMMRegs = 8;
11977 bool UseGPOffset = (ArgMode == 1);
11978 bool UseFPOffset = (ArgMode == 2);
11979 unsigned MaxOffset = TotalNumIntRegs * 8 +
11980 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11982 /* Align ArgSize to a multiple of 8 */
11983 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11984 bool NeedsAlign = (Align > 8);
11986 MachineBasicBlock *thisMBB = MBB;
11987 MachineBasicBlock *overflowMBB;
11988 MachineBasicBlock *offsetMBB;
11989 MachineBasicBlock *endMBB;
11991 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
11992 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
11993 unsigned OffsetReg = 0;
11995 if (!UseGPOffset && !UseFPOffset) {
11996 // If we only pull from the overflow region, we don't create a branch.
11997 // We don't need to alter control flow.
11998 OffsetDestReg = 0; // unused
11999 OverflowDestReg = DestReg;
12002 overflowMBB = thisMBB;
12005 // First emit code to check if gp_offset (or fp_offset) is below the bound.
12006 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
12007 // If not, pull from overflow_area. (branch to overflowMBB)
12012 // offsetMBB overflowMBB
12017 // Registers for the PHI in endMBB
12018 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
12019 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
12021 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12022 MachineFunction *MF = MBB->getParent();
12023 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12024 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12025 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12027 MachineFunction::iterator MBBIter = MBB;
12030 // Insert the new basic blocks
12031 MF->insert(MBBIter, offsetMBB);
12032 MF->insert(MBBIter, overflowMBB);
12033 MF->insert(MBBIter, endMBB);
12035 // Transfer the remainder of MBB and its successor edges to endMBB.
12036 endMBB->splice(endMBB->begin(), thisMBB,
12037 llvm::next(MachineBasicBlock::iterator(MI)),
12039 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12041 // Make offsetMBB and overflowMBB successors of thisMBB
12042 thisMBB->addSuccessor(offsetMBB);
12043 thisMBB->addSuccessor(overflowMBB);
12045 // endMBB is a successor of both offsetMBB and overflowMBB
12046 offsetMBB->addSuccessor(endMBB);
12047 overflowMBB->addSuccessor(endMBB);
12049 // Load the offset value into a register
12050 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12051 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12055 .addDisp(Disp, UseFPOffset ? 4 : 0)
12056 .addOperand(Segment)
12057 .setMemRefs(MMOBegin, MMOEnd);
12059 // Check if there is enough room left to pull this argument.
12060 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12062 .addImm(MaxOffset + 8 - ArgSizeA8);
12064 // Branch to "overflowMBB" if offset >= max
12065 // Fall through to "offsetMBB" otherwise
12066 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12067 .addMBB(overflowMBB);
12070 // In offsetMBB, emit code to use the reg_save_area.
12072 assert(OffsetReg != 0);
12074 // Read the reg_save_area address.
12075 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12076 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12081 .addOperand(Segment)
12082 .setMemRefs(MMOBegin, MMOEnd);
12084 // Zero-extend the offset
12085 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12086 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12089 .addImm(X86::sub_32bit);
12091 // Add the offset to the reg_save_area to get the final address.
12092 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12093 .addReg(OffsetReg64)
12094 .addReg(RegSaveReg);
12096 // Compute the offset for the next argument
12097 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12098 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12100 .addImm(UseFPOffset ? 16 : 8);
12102 // Store it back into the va_list.
12103 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12107 .addDisp(Disp, UseFPOffset ? 4 : 0)
12108 .addOperand(Segment)
12109 .addReg(NextOffsetReg)
12110 .setMemRefs(MMOBegin, MMOEnd);
12113 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12118 // Emit code to use overflow area
12121 // Load the overflow_area address into a register.
12122 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12123 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12128 .addOperand(Segment)
12129 .setMemRefs(MMOBegin, MMOEnd);
12131 // If we need to align it, do so. Otherwise, just copy the address
12132 // to OverflowDestReg.
12134 // Align the overflow address
12135 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12136 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12138 // aligned_addr = (addr + (align-1)) & ~(align-1)
12139 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12140 .addReg(OverflowAddrReg)
12143 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12145 .addImm(~(uint64_t)(Align-1));
12147 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12148 .addReg(OverflowAddrReg);
12151 // Compute the next overflow address after this argument.
12152 // (the overflow address should be kept 8-byte aligned)
12153 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12154 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12155 .addReg(OverflowDestReg)
12156 .addImm(ArgSizeA8);
12158 // Store the new overflow address.
12159 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12164 .addOperand(Segment)
12165 .addReg(NextAddrReg)
12166 .setMemRefs(MMOBegin, MMOEnd);
12168 // If we branched, emit the PHI to the front of endMBB.
12170 BuildMI(*endMBB, endMBB->begin(), DL,
12171 TII->get(X86::PHI), DestReg)
12172 .addReg(OffsetDestReg).addMBB(offsetMBB)
12173 .addReg(OverflowDestReg).addMBB(overflowMBB);
12176 // Erase the pseudo instruction
12177 MI->eraseFromParent();
12182 MachineBasicBlock *
12183 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12185 MachineBasicBlock *MBB) const {
12186 // Emit code to save XMM registers to the stack. The ABI says that the
12187 // number of registers to save is given in %al, so it's theoretically
12188 // possible to do an indirect jump trick to avoid saving all of them,
12189 // however this code takes a simpler approach and just executes all
12190 // of the stores if %al is non-zero. It's less code, and it's probably
12191 // easier on the hardware branch predictor, and stores aren't all that
12192 // expensive anyway.
12194 // Create the new basic blocks. One block contains all the XMM stores,
12195 // and one block is the final destination regardless of whether any
12196 // stores were performed.
12197 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12198 MachineFunction *F = MBB->getParent();
12199 MachineFunction::iterator MBBIter = MBB;
12201 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12202 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12203 F->insert(MBBIter, XMMSaveMBB);
12204 F->insert(MBBIter, EndMBB);
12206 // Transfer the remainder of MBB and its successor edges to EndMBB.
12207 EndMBB->splice(EndMBB->begin(), MBB,
12208 llvm::next(MachineBasicBlock::iterator(MI)),
12210 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12212 // The original block will now fall through to the XMM save block.
12213 MBB->addSuccessor(XMMSaveMBB);
12214 // The XMMSaveMBB will fall through to the end block.
12215 XMMSaveMBB->addSuccessor(EndMBB);
12217 // Now add the instructions.
12218 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12219 DebugLoc DL = MI->getDebugLoc();
12221 unsigned CountReg = MI->getOperand(0).getReg();
12222 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12223 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12225 if (!Subtarget->isTargetWin64()) {
12226 // If %al is 0, branch around the XMM save block.
12227 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12228 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12229 MBB->addSuccessor(EndMBB);
12232 unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12233 // In the XMM save block, save all the XMM argument registers.
12234 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12235 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12236 MachineMemOperand *MMO =
12237 F->getMachineMemOperand(
12238 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12239 MachineMemOperand::MOStore,
12240 /*Size=*/16, /*Align=*/16);
12241 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12242 .addFrameIndex(RegSaveFrameIndex)
12243 .addImm(/*Scale=*/1)
12244 .addReg(/*IndexReg=*/0)
12245 .addImm(/*Disp=*/Offset)
12246 .addReg(/*Segment=*/0)
12247 .addReg(MI->getOperand(i).getReg())
12248 .addMemOperand(MMO);
12251 MI->eraseFromParent(); // The pseudo instruction is gone now.
12256 // The EFLAGS operand of SelectItr might be missing a kill marker
12257 // because there were multiple uses of EFLAGS, and ISel didn't know
12258 // which to mark. Figure out whether SelectItr should have had a
12259 // kill marker, and set it if it should. Returns the correct kill
12261 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
12262 MachineBasicBlock* BB,
12263 const TargetRegisterInfo* TRI) {
12264 // Scan forward through BB for a use/def of EFLAGS.
12265 MachineBasicBlock::iterator miI(llvm::next(SelectItr));
12266 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
12267 const MachineInstr& mi = *miI;
12268 if (mi.readsRegister(X86::EFLAGS))
12270 if (mi.definesRegister(X86::EFLAGS))
12271 break; // Should have kill-flag - update below.
12274 // If we hit the end of the block, check whether EFLAGS is live into a
12276 if (miI == BB->end()) {
12277 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
12278 sEnd = BB->succ_end();
12279 sItr != sEnd; ++sItr) {
12280 MachineBasicBlock* succ = *sItr;
12281 if (succ->isLiveIn(X86::EFLAGS))
12286 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
12287 // out. SelectMI should have a kill flag on EFLAGS.
12288 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
12292 MachineBasicBlock *
12293 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12294 MachineBasicBlock *BB) const {
12295 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12296 DebugLoc DL = MI->getDebugLoc();
12298 // To "insert" a SELECT_CC instruction, we actually have to insert the
12299 // diamond control-flow pattern. The incoming instruction knows the
12300 // destination vreg to set, the condition code register to branch on, the
12301 // true/false values to select between, and a branch opcode to use.
12302 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12303 MachineFunction::iterator It = BB;
12309 // cmpTY ccX, r1, r2
12311 // fallthrough --> copy0MBB
12312 MachineBasicBlock *thisMBB = BB;
12313 MachineFunction *F = BB->getParent();
12314 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12315 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12316 F->insert(It, copy0MBB);
12317 F->insert(It, sinkMBB);
12319 // If the EFLAGS register isn't dead in the terminator, then claim that it's
12320 // live into the sink and copy blocks.
12321 const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
12322 if (!MI->killsRegister(X86::EFLAGS) &&
12323 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
12324 copy0MBB->addLiveIn(X86::EFLAGS);
12325 sinkMBB->addLiveIn(X86::EFLAGS);
12328 // Transfer the remainder of BB and its successor edges to sinkMBB.
12329 sinkMBB->splice(sinkMBB->begin(), BB,
12330 llvm::next(MachineBasicBlock::iterator(MI)),
12332 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12334 // Add the true and fallthrough blocks as its successors.
12335 BB->addSuccessor(copy0MBB);
12336 BB->addSuccessor(sinkMBB);
12338 // Create the conditional branch instruction.
12340 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12341 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12344 // %FalseValue = ...
12345 // # fallthrough to sinkMBB
12346 copy0MBB->addSuccessor(sinkMBB);
12349 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12351 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12352 TII->get(X86::PHI), MI->getOperand(0).getReg())
12353 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12354 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12356 MI->eraseFromParent(); // The pseudo instruction is gone now.
12360 MachineBasicBlock *
12361 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12362 bool Is64Bit) const {
12363 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12364 DebugLoc DL = MI->getDebugLoc();
12365 MachineFunction *MF = BB->getParent();
12366 const BasicBlock *LLVM_BB = BB->getBasicBlock();
12368 assert(getTargetMachine().Options.EnableSegmentedStacks);
12370 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12371 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12374 // ... [Till the alloca]
12375 // If stacklet is not large enough, jump to mallocMBB
12378 // Allocate by subtracting from RSP
12379 // Jump to continueMBB
12382 // Allocate by call to runtime
12386 // [rest of original BB]
12389 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12390 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12391 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12393 MachineRegisterInfo &MRI = MF->getRegInfo();
12394 const TargetRegisterClass *AddrRegClass =
12395 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12397 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12398 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12399 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12400 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12401 sizeVReg = MI->getOperand(1).getReg(),
12402 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12404 MachineFunction::iterator MBBIter = BB;
12407 MF->insert(MBBIter, bumpMBB);
12408 MF->insert(MBBIter, mallocMBB);
12409 MF->insert(MBBIter, continueMBB);
12411 continueMBB->splice(continueMBB->begin(), BB, llvm::next
12412 (MachineBasicBlock::iterator(MI)), BB->end());
12413 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12415 // Add code to the main basic block to check if the stack limit has been hit,
12416 // and if so, jump to mallocMBB otherwise to bumpMBB.
12417 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12418 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12419 .addReg(tmpSPVReg).addReg(sizeVReg);
12420 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12421 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12422 .addReg(SPLimitVReg);
12423 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12425 // bumpMBB simply decreases the stack pointer, since we know the current
12426 // stacklet has enough space.
12427 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12428 .addReg(SPLimitVReg);
12429 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12430 .addReg(SPLimitVReg);
12431 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12433 // Calls into a routine in libgcc to allocate more space from the heap.
12434 const uint32_t *RegMask =
12435 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12437 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12439 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12440 .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI)
12441 .addRegMask(RegMask)
12442 .addReg(X86::RAX, RegState::ImplicitDefine);
12444 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12446 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12447 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12448 .addExternalSymbol("__morestack_allocate_stack_space")
12449 .addRegMask(RegMask)
12450 .addReg(X86::EAX, RegState::ImplicitDefine);
12454 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12457 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12458 .addReg(Is64Bit ? X86::RAX : X86::EAX);
12459 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12461 // Set up the CFG correctly.
12462 BB->addSuccessor(bumpMBB);
12463 BB->addSuccessor(mallocMBB);
12464 mallocMBB->addSuccessor(continueMBB);
12465 bumpMBB->addSuccessor(continueMBB);
12467 // Take care of the PHI nodes.
12468 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12469 MI->getOperand(0).getReg())
12470 .addReg(mallocPtrVReg).addMBB(mallocMBB)
12471 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12473 // Delete the original pseudo instruction.
12474 MI->eraseFromParent();
12477 return continueMBB;
12480 MachineBasicBlock *
12481 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12482 MachineBasicBlock *BB) const {
12483 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12484 DebugLoc DL = MI->getDebugLoc();
12486 assert(!Subtarget->isTargetEnvMacho());
12488 // The lowering is pretty easy: we're just emitting the call to _alloca. The
12489 // non-trivial part is impdef of ESP.
12491 if (Subtarget->isTargetWin64()) {
12492 if (Subtarget->isTargetCygMing()) {
12493 // ___chkstk(Mingw64):
12494 // Clobbers R10, R11, RAX and EFLAGS.
12496 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12497 .addExternalSymbol("___chkstk")
12498 .addReg(X86::RAX, RegState::Implicit)
12499 .addReg(X86::RSP, RegState::Implicit)
12500 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12501 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12502 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12504 // __chkstk(MSVCRT): does not update stack pointer.
12505 // Clobbers R10, R11 and EFLAGS.
12506 // FIXME: RAX(allocated size) might be reused and not killed.
12507 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12508 .addExternalSymbol("__chkstk")
12509 .addReg(X86::RAX, RegState::Implicit)
12510 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12511 // RAX has the offset to subtracted from RSP.
12512 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12517 const char *StackProbeSymbol =
12518 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12520 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12521 .addExternalSymbol(StackProbeSymbol)
12522 .addReg(X86::EAX, RegState::Implicit)
12523 .addReg(X86::ESP, RegState::Implicit)
12524 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12525 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12526 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12529 MI->eraseFromParent(); // The pseudo instruction is gone now.
12533 MachineBasicBlock *
12534 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12535 MachineBasicBlock *BB) const {
12536 // This is pretty easy. We're taking the value that we received from
12537 // our load from the relocation, sticking it in either RDI (x86-64)
12538 // or EAX and doing an indirect call. The return value will then
12539 // be in the normal return register.
12540 const X86InstrInfo *TII
12541 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12542 DebugLoc DL = MI->getDebugLoc();
12543 MachineFunction *F = BB->getParent();
12545 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12546 assert(MI->getOperand(3).isGlobal() && "This should be a global");
12548 // Get a register mask for the lowered call.
12549 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
12550 // proper register mask.
12551 const uint32_t *RegMask =
12552 getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
12553 if (Subtarget->is64Bit()) {
12554 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12555 TII->get(X86::MOV64rm), X86::RDI)
12557 .addImm(0).addReg(0)
12558 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12559 MI->getOperand(3).getTargetFlags())
12561 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12562 addDirectMem(MIB, X86::RDI);
12563 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
12564 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12565 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12566 TII->get(X86::MOV32rm), X86::EAX)
12568 .addImm(0).addReg(0)
12569 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12570 MI->getOperand(3).getTargetFlags())
12572 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12573 addDirectMem(MIB, X86::EAX);
12574 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12576 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12577 TII->get(X86::MOV32rm), X86::EAX)
12578 .addReg(TII->getGlobalBaseReg(F))
12579 .addImm(0).addReg(0)
12580 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12581 MI->getOperand(3).getTargetFlags())
12583 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12584 addDirectMem(MIB, X86::EAX);
12585 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
12588 MI->eraseFromParent(); // The pseudo instruction is gone now.
12592 MachineBasicBlock *
12593 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12594 MachineBasicBlock *BB) const {
12595 switch (MI->getOpcode()) {
12596 default: llvm_unreachable("Unexpected instr type to insert");
12597 case X86::TAILJMPd64:
12598 case X86::TAILJMPr64:
12599 case X86::TAILJMPm64:
12600 llvm_unreachable("TAILJMP64 would not be touched here.");
12601 case X86::TCRETURNdi64:
12602 case X86::TCRETURNri64:
12603 case X86::TCRETURNmi64:
12605 case X86::WIN_ALLOCA:
12606 return EmitLoweredWinAlloca(MI, BB);
12607 case X86::SEG_ALLOCA_32:
12608 return EmitLoweredSegAlloca(MI, BB, false);
12609 case X86::SEG_ALLOCA_64:
12610 return EmitLoweredSegAlloca(MI, BB, true);
12611 case X86::TLSCall_32:
12612 case X86::TLSCall_64:
12613 return EmitLoweredTLSCall(MI, BB);
12614 case X86::CMOV_GR8:
12615 case X86::CMOV_FR32:
12616 case X86::CMOV_FR64:
12617 case X86::CMOV_V4F32:
12618 case X86::CMOV_V2F64:
12619 case X86::CMOV_V2I64:
12620 case X86::CMOV_V8F32:
12621 case X86::CMOV_V4F64:
12622 case X86::CMOV_V4I64:
12623 case X86::CMOV_GR16:
12624 case X86::CMOV_GR32:
12625 case X86::CMOV_RFP32:
12626 case X86::CMOV_RFP64:
12627 case X86::CMOV_RFP80:
12628 return EmitLoweredSelect(MI, BB);
12630 case X86::FP32_TO_INT16_IN_MEM:
12631 case X86::FP32_TO_INT32_IN_MEM:
12632 case X86::FP32_TO_INT64_IN_MEM:
12633 case X86::FP64_TO_INT16_IN_MEM:
12634 case X86::FP64_TO_INT32_IN_MEM:
12635 case X86::FP64_TO_INT64_IN_MEM:
12636 case X86::FP80_TO_INT16_IN_MEM:
12637 case X86::FP80_TO_INT32_IN_MEM:
12638 case X86::FP80_TO_INT64_IN_MEM: {
12639 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12640 DebugLoc DL = MI->getDebugLoc();
12642 // Change the floating point control register to use "round towards zero"
12643 // mode when truncating to an integer value.
12644 MachineFunction *F = BB->getParent();
12645 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12646 addFrameReference(BuildMI(*BB, MI, DL,
12647 TII->get(X86::FNSTCW16m)), CWFrameIdx);
12649 // Load the old value of the high byte of the control word...
12651 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
12652 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12655 // Set the high part to be round to zero...
12656 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12659 // Reload the modified control word now...
12660 addFrameReference(BuildMI(*BB, MI, DL,
12661 TII->get(X86::FLDCW16m)), CWFrameIdx);
12663 // Restore the memory image of control word to original value
12664 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12667 // Get the X86 opcode to use.
12669 switch (MI->getOpcode()) {
12670 default: llvm_unreachable("illegal opcode!");
12671 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12672 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12673 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12674 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12675 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12676 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12677 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12678 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12679 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12683 MachineOperand &Op = MI->getOperand(0);
12685 AM.BaseType = X86AddressMode::RegBase;
12686 AM.Base.Reg = Op.getReg();
12688 AM.BaseType = X86AddressMode::FrameIndexBase;
12689 AM.Base.FrameIndex = Op.getIndex();
12691 Op = MI->getOperand(1);
12693 AM.Scale = Op.getImm();
12694 Op = MI->getOperand(2);
12696 AM.IndexReg = Op.getImm();
12697 Op = MI->getOperand(3);
12698 if (Op.isGlobal()) {
12699 AM.GV = Op.getGlobal();
12701 AM.Disp = Op.getImm();
12703 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12704 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12706 // Reload the original control word now.
12707 addFrameReference(BuildMI(*BB, MI, DL,
12708 TII->get(X86::FLDCW16m)), CWFrameIdx);
12710 MI->eraseFromParent(); // The pseudo instruction is gone now.
12713 // String/text processing lowering.
12714 case X86::PCMPISTRM128REG:
12715 case X86::VPCMPISTRM128REG:
12716 return EmitPCMP(MI, BB, 3, false /* in-mem */);
12717 case X86::PCMPISTRM128MEM:
12718 case X86::VPCMPISTRM128MEM:
12719 return EmitPCMP(MI, BB, 3, true /* in-mem */);
12720 case X86::PCMPESTRM128REG:
12721 case X86::VPCMPESTRM128REG:
12722 return EmitPCMP(MI, BB, 5, false /* in mem */);
12723 case X86::PCMPESTRM128MEM:
12724 case X86::VPCMPESTRM128MEM:
12725 return EmitPCMP(MI, BB, 5, true /* in mem */);
12727 // Thread synchronization.
12729 return EmitMonitor(MI, BB);
12731 return EmitMwait(MI, BB);
12733 // Atomic Lowering.
12734 case X86::ATOMAND32:
12735 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12736 X86::AND32ri, X86::MOV32rm,
12738 X86::NOT32r, X86::EAX,
12739 &X86::GR32RegClass);
12740 case X86::ATOMOR32:
12741 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12742 X86::OR32ri, X86::MOV32rm,
12744 X86::NOT32r, X86::EAX,
12745 &X86::GR32RegClass);
12746 case X86::ATOMXOR32:
12747 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12748 X86::XOR32ri, X86::MOV32rm,
12750 X86::NOT32r, X86::EAX,
12751 &X86::GR32RegClass);
12752 case X86::ATOMNAND32:
12753 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12754 X86::AND32ri, X86::MOV32rm,
12756 X86::NOT32r, X86::EAX,
12757 &X86::GR32RegClass, true);
12758 case X86::ATOMMIN32:
12759 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12760 case X86::ATOMMAX32:
12761 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12762 case X86::ATOMUMIN32:
12763 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12764 case X86::ATOMUMAX32:
12765 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12767 case X86::ATOMAND16:
12768 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12769 X86::AND16ri, X86::MOV16rm,
12771 X86::NOT16r, X86::AX,
12772 &X86::GR16RegClass);
12773 case X86::ATOMOR16:
12774 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12775 X86::OR16ri, X86::MOV16rm,
12777 X86::NOT16r, X86::AX,
12778 &X86::GR16RegClass);
12779 case X86::ATOMXOR16:
12780 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12781 X86::XOR16ri, X86::MOV16rm,
12783 X86::NOT16r, X86::AX,
12784 &X86::GR16RegClass);
12785 case X86::ATOMNAND16:
12786 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12787 X86::AND16ri, X86::MOV16rm,
12789 X86::NOT16r, X86::AX,
12790 &X86::GR16RegClass, true);
12791 case X86::ATOMMIN16:
12792 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12793 case X86::ATOMMAX16:
12794 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12795 case X86::ATOMUMIN16:
12796 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12797 case X86::ATOMUMAX16:
12798 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12800 case X86::ATOMAND8:
12801 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12802 X86::AND8ri, X86::MOV8rm,
12804 X86::NOT8r, X86::AL,
12805 &X86::GR8RegClass);
12807 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12808 X86::OR8ri, X86::MOV8rm,
12810 X86::NOT8r, X86::AL,
12811 &X86::GR8RegClass);
12812 case X86::ATOMXOR8:
12813 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12814 X86::XOR8ri, X86::MOV8rm,
12816 X86::NOT8r, X86::AL,
12817 &X86::GR8RegClass);
12818 case X86::ATOMNAND8:
12819 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12820 X86::AND8ri, X86::MOV8rm,
12822 X86::NOT8r, X86::AL,
12823 &X86::GR8RegClass, true);
12824 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12825 // This group is for 64-bit host.
12826 case X86::ATOMAND64:
12827 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12828 X86::AND64ri32, X86::MOV64rm,
12830 X86::NOT64r, X86::RAX,
12831 &X86::GR64RegClass);
12832 case X86::ATOMOR64:
12833 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12834 X86::OR64ri32, X86::MOV64rm,
12836 X86::NOT64r, X86::RAX,
12837 &X86::GR64RegClass);
12838 case X86::ATOMXOR64:
12839 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12840 X86::XOR64ri32, X86::MOV64rm,
12842 X86::NOT64r, X86::RAX,
12843 &X86::GR64RegClass);
12844 case X86::ATOMNAND64:
12845 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12846 X86::AND64ri32, X86::MOV64rm,
12848 X86::NOT64r, X86::RAX,
12849 &X86::GR64RegClass, true);
12850 case X86::ATOMMIN64:
12851 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12852 case X86::ATOMMAX64:
12853 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12854 case X86::ATOMUMIN64:
12855 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12856 case X86::ATOMUMAX64:
12857 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12859 // This group does 64-bit operations on a 32-bit host.
12860 case X86::ATOMAND6432:
12861 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12862 X86::AND32rr, X86::AND32rr,
12863 X86::AND32ri, X86::AND32ri,
12865 case X86::ATOMOR6432:
12866 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12867 X86::OR32rr, X86::OR32rr,
12868 X86::OR32ri, X86::OR32ri,
12870 case X86::ATOMXOR6432:
12871 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12872 X86::XOR32rr, X86::XOR32rr,
12873 X86::XOR32ri, X86::XOR32ri,
12875 case X86::ATOMNAND6432:
12876 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12877 X86::AND32rr, X86::AND32rr,
12878 X86::AND32ri, X86::AND32ri,
12880 case X86::ATOMADD6432:
12881 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12882 X86::ADD32rr, X86::ADC32rr,
12883 X86::ADD32ri, X86::ADC32ri,
12885 case X86::ATOMSUB6432:
12886 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12887 X86::SUB32rr, X86::SBB32rr,
12888 X86::SUB32ri, X86::SBB32ri,
12890 case X86::ATOMSWAP6432:
12891 return EmitAtomicBit6432WithCustomInserter(MI, BB,
12892 X86::MOV32rr, X86::MOV32rr,
12893 X86::MOV32ri, X86::MOV32ri,
12895 case X86::VASTART_SAVE_XMM_REGS:
12896 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12898 case X86::VAARG_64:
12899 return EmitVAARG64WithCustomInserter(MI, BB);
12903 //===----------------------------------------------------------------------===//
12904 // X86 Optimization Hooks
12905 //===----------------------------------------------------------------------===//
12907 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12910 const SelectionDAG &DAG,
12911 unsigned Depth) const {
12912 unsigned BitWidth = KnownZero.getBitWidth();
12913 unsigned Opc = Op.getOpcode();
12914 assert((Opc >= ISD::BUILTIN_OP_END ||
12915 Opc == ISD::INTRINSIC_WO_CHAIN ||
12916 Opc == ISD::INTRINSIC_W_CHAIN ||
12917 Opc == ISD::INTRINSIC_VOID) &&
12918 "Should use MaskedValueIsZero if you don't know whether Op"
12919 " is a target node!");
12921 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
12935 // These nodes' second result is a boolean.
12936 if (Op.getResNo() == 0)
12939 case X86ISD::SETCC:
12940 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12942 case ISD::INTRINSIC_WO_CHAIN: {
12943 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12944 unsigned NumLoBits = 0;
12947 case Intrinsic::x86_sse_movmsk_ps:
12948 case Intrinsic::x86_avx_movmsk_ps_256:
12949 case Intrinsic::x86_sse2_movmsk_pd:
12950 case Intrinsic::x86_avx_movmsk_pd_256:
12951 case Intrinsic::x86_mmx_pmovmskb:
12952 case Intrinsic::x86_sse2_pmovmskb_128:
12953 case Intrinsic::x86_avx2_pmovmskb: {
12954 // High bits of movmskp{s|d}, pmovmskb are known zero.
12956 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
12957 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
12958 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
12959 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
12960 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
12961 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
12962 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
12963 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
12965 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
12974 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12975 unsigned Depth) const {
12976 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12977 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12978 return Op.getValueType().getScalarType().getSizeInBits();
12984 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12985 /// node is a GlobalAddress + offset.
12986 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12987 const GlobalValue* &GA,
12988 int64_t &Offset) const {
12989 if (N->getOpcode() == X86ISD::Wrapper) {
12990 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12991 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12992 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12996 return TargetLowering::isGAPlusOffset(N, GA, Offset);
12999 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
13000 /// same as extracting the high 128-bit part of 256-bit vector and then
13001 /// inserting the result into the low part of a new 256-bit vector
13002 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
13003 EVT VT = SVOp->getValueType(0);
13004 unsigned NumElems = VT.getVectorNumElements();
13006 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13007 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
13008 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13009 SVOp->getMaskElt(j) >= 0)
13015 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
13016 /// same as extracting the low 128-bit part of 256-bit vector and then
13017 /// inserting the result into the high part of a new 256-bit vector
13018 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
13019 EVT VT = SVOp->getValueType(0);
13020 unsigned NumElems = VT.getVectorNumElements();
13022 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13023 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
13024 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
13025 SVOp->getMaskElt(j) >= 0)
13031 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
13032 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
13033 TargetLowering::DAGCombinerInfo &DCI,
13034 const X86Subtarget* Subtarget) {
13035 DebugLoc dl = N->getDebugLoc();
13036 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
13037 SDValue V1 = SVOp->getOperand(0);
13038 SDValue V2 = SVOp->getOperand(1);
13039 EVT VT = SVOp->getValueType(0);
13040 unsigned NumElems = VT.getVectorNumElements();
13042 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
13043 V2.getOpcode() == ISD::CONCAT_VECTORS) {
13047 // V UNDEF BUILD_VECTOR UNDEF
13049 // CONCAT_VECTOR CONCAT_VECTOR
13052 // RESULT: V + zero extended
13054 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
13055 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
13056 V1.getOperand(1).getOpcode() != ISD::UNDEF)
13059 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
13062 // To match the shuffle mask, the first half of the mask should
13063 // be exactly the first vector, and all the rest a splat with the
13064 // first element of the second one.
13065 for (unsigned i = 0; i != NumElems/2; ++i)
13066 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13067 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13070 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
13071 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
13072 if (Ld->hasNUsesOfValue(1, 0)) {
13073 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
13074 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
13076 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
13078 Ld->getPointerInfo(),
13079 Ld->getAlignment(),
13080 false/*isVolatile*/, true/*ReadMem*/,
13081 false/*WriteMem*/);
13082 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
13086 // Emit a zeroed vector and insert the desired subvector on its
13088 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13089 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
13090 return DCI.CombineTo(N, InsV);
13093 //===--------------------------------------------------------------------===//
13094 // Combine some shuffles into subvector extracts and inserts:
13097 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13098 if (isShuffleHigh128VectorInsertLow(SVOp)) {
13099 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
13100 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
13101 return DCI.CombineTo(N, InsV);
13104 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13105 if (isShuffleLow128VectorInsertHigh(SVOp)) {
13106 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
13107 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
13108 return DCI.CombineTo(N, InsV);
13114 /// PerformShuffleCombine - Performs several different shuffle combines.
13115 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13116 TargetLowering::DAGCombinerInfo &DCI,
13117 const X86Subtarget *Subtarget) {
13118 DebugLoc dl = N->getDebugLoc();
13119 EVT VT = N->getValueType(0);
13121 // Don't create instructions with illegal types after legalize types has run.
13122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13123 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13126 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13127 if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13128 N->getOpcode() == ISD::VECTOR_SHUFFLE)
13129 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
13131 // Only handle 128 wide vector from here on.
13132 if (VT.getSizeInBits() != 128)
13135 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13136 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13137 // consecutive, non-overlapping, and in the right order.
13138 SmallVector<SDValue, 16> Elts;
13139 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13140 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13142 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13146 /// DCI, PerformTruncateCombine - Converts truncate operation to
13147 /// a sequence of vector shuffle operations.
13148 /// It is possible when we truncate 256-bit vector to 128-bit vector
13150 SDValue X86TargetLowering::PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
13151 DAGCombinerInfo &DCI) const {
13152 if (!DCI.isBeforeLegalizeOps())
13155 if (!Subtarget->hasAVX())
13158 EVT VT = N->getValueType(0);
13159 SDValue Op = N->getOperand(0);
13160 EVT OpVT = Op.getValueType();
13161 DebugLoc dl = N->getDebugLoc();
13163 if ((VT == MVT::v4i32) && (OpVT == MVT::v4i64)) {
13165 if (Subtarget->hasAVX2()) {
13166 // AVX2: v4i64 -> v4i32
13169 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13171 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v8i32, Op);
13172 Op = DAG.getVectorShuffle(MVT::v8i32, dl, Op, DAG.getUNDEF(MVT::v8i32),
13175 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Op,
13176 DAG.getIntPtrConstant(0));
13179 // AVX: v4i64 -> v4i32
13180 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13181 DAG.getIntPtrConstant(0));
13183 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13184 DAG.getIntPtrConstant(2));
13186 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13187 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13190 static const int ShufMask1[] = {0, 2, 0, 0};
13192 OpLo = DAG.getVectorShuffle(VT, dl, OpLo, DAG.getUNDEF(VT), ShufMask1);
13193 OpHi = DAG.getVectorShuffle(VT, dl, OpHi, DAG.getUNDEF(VT), ShufMask1);
13196 static const int ShufMask2[] = {0, 1, 4, 5};
13198 return DAG.getVectorShuffle(VT, dl, OpLo, OpHi, ShufMask2);
13201 if ((VT == MVT::v8i16) && (OpVT == MVT::v8i32)) {
13203 if (Subtarget->hasAVX2()) {
13204 // AVX2: v8i32 -> v8i16
13206 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v32i8, Op);
13209 SmallVector<SDValue,32> pshufbMask;
13210 for (unsigned i = 0; i < 2; ++i) {
13211 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13212 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13213 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13214 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13215 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13216 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13217 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13218 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13219 for (unsigned j = 0; j < 8; ++j)
13220 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13222 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v32i8,
13223 &pshufbMask[0], 32);
13224 Op = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, Op, BV);
13226 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i64, Op);
13228 static const int ShufMask[] = {0, 2, -1, -1};
13229 Op = DAG.getVectorShuffle(MVT::v4i64, dl, Op, DAG.getUNDEF(MVT::v4i64),
13232 Op = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v2i64, Op,
13233 DAG.getIntPtrConstant(0));
13235 return DAG.getNode(ISD::BITCAST, dl, VT, Op);
13238 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13239 DAG.getIntPtrConstant(0));
13241 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i32, Op,
13242 DAG.getIntPtrConstant(4));
13244 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLo);
13245 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpHi);
13248 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
13249 -1, -1, -1, -1, -1, -1, -1, -1};
13251 OpLo = DAG.getVectorShuffle(MVT::v16i8, dl, OpLo, DAG.getUNDEF(MVT::v16i8),
13253 OpHi = DAG.getVectorShuffle(MVT::v16i8, dl, OpHi, DAG.getUNDEF(MVT::v16i8),
13256 OpLo = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpLo);
13257 OpHi = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, OpHi);
13260 static const int ShufMask2[] = {0, 1, 4, 5};
13262 SDValue res = DAG.getVectorShuffle(MVT::v4i32, dl, OpLo, OpHi, ShufMask2);
13263 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, res);
13269 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
13270 /// specific shuffle of a load can be folded into a single element load.
13271 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
13272 /// shuffles have been customed lowered so we need to handle those here.
13273 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
13274 TargetLowering::DAGCombinerInfo &DCI) {
13275 if (DCI.isBeforeLegalizeOps())
13278 SDValue InVec = N->getOperand(0);
13279 SDValue EltNo = N->getOperand(1);
13281 if (!isa<ConstantSDNode>(EltNo))
13284 EVT VT = InVec.getValueType();
13286 bool HasShuffleIntoBitcast = false;
13287 if (InVec.getOpcode() == ISD::BITCAST) {
13288 // Don't duplicate a load with other uses.
13289 if (!InVec.hasOneUse())
13291 EVT BCVT = InVec.getOperand(0).getValueType();
13292 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
13294 InVec = InVec.getOperand(0);
13295 HasShuffleIntoBitcast = true;
13298 if (!isTargetShuffle(InVec.getOpcode()))
13301 // Don't duplicate a load with other uses.
13302 if (!InVec.hasOneUse())
13305 SmallVector<int, 16> ShuffleMask;
13307 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
13311 // Select the input vector, guarding against out of range extract vector.
13312 unsigned NumElems = VT.getVectorNumElements();
13313 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
13314 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
13315 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
13316 : InVec.getOperand(1);
13318 // If inputs to shuffle are the same for both ops, then allow 2 uses
13319 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
13321 if (LdNode.getOpcode() == ISD::BITCAST) {
13322 // Don't duplicate a load with other uses.
13323 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
13326 AllowedUses = 1; // only allow 1 load use if we have a bitcast
13327 LdNode = LdNode.getOperand(0);
13330 if (!ISD::isNormalLoad(LdNode.getNode()))
13333 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
13335 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
13338 if (HasShuffleIntoBitcast) {
13339 // If there's a bitcast before the shuffle, check if the load type and
13340 // alignment is valid.
13341 unsigned Align = LN0->getAlignment();
13342 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13343 unsigned NewAlign = TLI.getTargetData()->
13344 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
13346 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
13350 // All checks match so transform back to vector_shuffle so that DAG combiner
13351 // can finish the job
13352 DebugLoc dl = N->getDebugLoc();
13354 // Create shuffle node taking into account the case that its a unary shuffle
13355 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
13356 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
13357 InVec.getOperand(0), Shuffle,
13359 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
13360 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
13364 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13365 /// generation and convert it from being a bunch of shuffles and extracts
13366 /// to a simple store and scalar loads to extract the elements.
13367 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13368 TargetLowering::DAGCombinerInfo &DCI) {
13369 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
13370 if (NewOp.getNode())
13373 SDValue InputVector = N->getOperand(0);
13375 // Only operate on vectors of 4 elements, where the alternative shuffling
13376 // gets to be more expensive.
13377 if (InputVector.getValueType() != MVT::v4i32)
13380 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13381 // single use which is a sign-extend or zero-extend, and all elements are
13383 SmallVector<SDNode *, 4> Uses;
13384 unsigned ExtractedElements = 0;
13385 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13386 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13387 if (UI.getUse().getResNo() != InputVector.getResNo())
13390 SDNode *Extract = *UI;
13391 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13394 if (Extract->getValueType(0) != MVT::i32)
13396 if (!Extract->hasOneUse())
13398 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13399 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13401 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13404 // Record which element was extracted.
13405 ExtractedElements |=
13406 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13408 Uses.push_back(Extract);
13411 // If not all the elements were used, this may not be worthwhile.
13412 if (ExtractedElements != 15)
13415 // Ok, we've now decided to do the transformation.
13416 DebugLoc dl = InputVector.getDebugLoc();
13418 // Store the value to a temporary stack slot.
13419 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13420 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13421 MachinePointerInfo(), false, false, 0);
13423 // Replace each use (extract) with a load of the appropriate element.
13424 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13425 UE = Uses.end(); UI != UE; ++UI) {
13426 SDNode *Extract = *UI;
13428 // cOMpute the element's address.
13429 SDValue Idx = Extract->getOperand(1);
13431 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13432 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13433 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13434 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13436 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13437 StackPtr, OffsetVal);
13439 // Load the scalar.
13440 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13441 ScalarAddr, MachinePointerInfo(),
13442 false, false, false, 0);
13444 // Replace the exact with the load.
13445 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13448 // The replacement was made in place; don't return anything.
13452 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13454 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13455 TargetLowering::DAGCombinerInfo &DCI,
13456 const X86Subtarget *Subtarget) {
13459 DebugLoc DL = N->getDebugLoc();
13460 SDValue Cond = N->getOperand(0);
13461 // Get the LHS/RHS of the select.
13462 SDValue LHS = N->getOperand(1);
13463 SDValue RHS = N->getOperand(2);
13464 EVT VT = LHS.getValueType();
13466 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13467 // instructions match the semantics of the common C idiom x<y?x:y but not
13468 // x<=y?x:y, because of how they handle negative zero (which can be
13469 // ignored in unsafe-math mode).
13470 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13471 VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13472 (Subtarget->hasSSE2() ||
13473 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13474 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13476 unsigned Opcode = 0;
13477 // Check for x CC y ? x : y.
13478 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13479 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13483 // Converting this to a min would handle NaNs incorrectly, and swapping
13484 // the operands would cause it to handle comparisons between positive
13485 // and negative zero incorrectly.
13486 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13487 if (!DAG.getTarget().Options.UnsafeFPMath &&
13488 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13490 std::swap(LHS, RHS);
13492 Opcode = X86ISD::FMIN;
13495 // Converting this to a min would handle comparisons between positive
13496 // and negative zero incorrectly.
13497 if (!DAG.getTarget().Options.UnsafeFPMath &&
13498 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13500 Opcode = X86ISD::FMIN;
13503 // Converting this to a min would handle both negative zeros and NaNs
13504 // incorrectly, but we can swap the operands to fix both.
13505 std::swap(LHS, RHS);
13509 Opcode = X86ISD::FMIN;
13513 // Converting this to a max would handle comparisons between positive
13514 // and negative zero incorrectly.
13515 if (!DAG.getTarget().Options.UnsafeFPMath &&
13516 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13518 Opcode = X86ISD::FMAX;
13521 // Converting this to a max would handle NaNs incorrectly, and swapping
13522 // the operands would cause it to handle comparisons between positive
13523 // and negative zero incorrectly.
13524 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13525 if (!DAG.getTarget().Options.UnsafeFPMath &&
13526 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13528 std::swap(LHS, RHS);
13530 Opcode = X86ISD::FMAX;
13533 // Converting this to a max would handle both negative zeros and NaNs
13534 // incorrectly, but we can swap the operands to fix both.
13535 std::swap(LHS, RHS);
13539 Opcode = X86ISD::FMAX;
13542 // Check for x CC y ? y : x -- a min/max with reversed arms.
13543 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13544 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13548 // Converting this to a min would handle comparisons between positive
13549 // and negative zero incorrectly, and swapping the operands would
13550 // cause it to handle NaNs incorrectly.
13551 if (!DAG.getTarget().Options.UnsafeFPMath &&
13552 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13553 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13555 std::swap(LHS, RHS);
13557 Opcode = X86ISD::FMIN;
13560 // Converting this to a min would handle NaNs incorrectly.
13561 if (!DAG.getTarget().Options.UnsafeFPMath &&
13562 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13564 Opcode = X86ISD::FMIN;
13567 // Converting this to a min would handle both negative zeros and NaNs
13568 // incorrectly, but we can swap the operands to fix both.
13569 std::swap(LHS, RHS);
13573 Opcode = X86ISD::FMIN;
13577 // Converting this to a max would handle NaNs incorrectly.
13578 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13580 Opcode = X86ISD::FMAX;
13583 // Converting this to a max would handle comparisons between positive
13584 // and negative zero incorrectly, and swapping the operands would
13585 // cause it to handle NaNs incorrectly.
13586 if (!DAG.getTarget().Options.UnsafeFPMath &&
13587 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13588 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13590 std::swap(LHS, RHS);
13592 Opcode = X86ISD::FMAX;
13595 // Converting this to a max would handle both negative zeros and NaNs
13596 // incorrectly, but we can swap the operands to fix both.
13597 std::swap(LHS, RHS);
13601 Opcode = X86ISD::FMAX;
13607 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13610 // If this is a select between two integer constants, try to do some
13612 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13613 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13614 // Don't do this for crazy integer types.
13615 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13616 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13617 // so that TrueC (the true value) is larger than FalseC.
13618 bool NeedsCondInvert = false;
13620 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13621 // Efficiently invertible.
13622 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
13623 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
13624 isa<ConstantSDNode>(Cond.getOperand(1))))) {
13625 NeedsCondInvert = true;
13626 std::swap(TrueC, FalseC);
13629 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
13630 if (FalseC->getAPIntValue() == 0 &&
13631 TrueC->getAPIntValue().isPowerOf2()) {
13632 if (NeedsCondInvert) // Invert the condition if needed.
13633 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13634 DAG.getConstant(1, Cond.getValueType()));
13636 // Zero extend the condition if needed.
13637 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13639 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13640 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13641 DAG.getConstant(ShAmt, MVT::i8));
13644 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13645 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13646 if (NeedsCondInvert) // Invert the condition if needed.
13647 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13648 DAG.getConstant(1, Cond.getValueType()));
13650 // Zero extend the condition if needed.
13651 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13652 FalseC->getValueType(0), Cond);
13653 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13654 SDValue(FalseC, 0));
13657 // Optimize cases that will turn into an LEA instruction. This requires
13658 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13659 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13660 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13661 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13663 bool isFastMultiplier = false;
13665 switch ((unsigned char)Diff) {
13667 case 1: // result = add base, cond
13668 case 2: // result = lea base( , cond*2)
13669 case 3: // result = lea base(cond, cond*2)
13670 case 4: // result = lea base( , cond*4)
13671 case 5: // result = lea base(cond, cond*4)
13672 case 8: // result = lea base( , cond*8)
13673 case 9: // result = lea base(cond, cond*8)
13674 isFastMultiplier = true;
13679 if (isFastMultiplier) {
13680 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13681 if (NeedsCondInvert) // Invert the condition if needed.
13682 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13683 DAG.getConstant(1, Cond.getValueType()));
13685 // Zero extend the condition if needed.
13686 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13688 // Scale the condition by the difference.
13690 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13691 DAG.getConstant(Diff, Cond.getValueType()));
13693 // Add the base if non-zero.
13694 if (FalseC->getAPIntValue() != 0)
13695 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13696 SDValue(FalseC, 0));
13703 // Canonicalize max and min:
13704 // (x > y) ? x : y -> (x >= y) ? x : y
13705 // (x < y) ? x : y -> (x <= y) ? x : y
13706 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
13707 // the need for an extra compare
13708 // against zero. e.g.
13709 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
13711 // testl %edi, %edi
13713 // cmovgl %edi, %eax
13717 // cmovsl %eax, %edi
13718 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
13719 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13720 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13721 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13726 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
13727 Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
13728 Cond.getOperand(0), Cond.getOperand(1), NewCC);
13729 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
13734 // If we know that this node is legal then we know that it is going to be
13735 // matched by one of the SSE/AVX BLEND instructions. These instructions only
13736 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
13737 // to simplify previous instructions.
13738 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13739 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
13740 !DCI.isBeforeLegalize() &&
13741 TLI.isOperationLegal(ISD::VSELECT, VT)) {
13742 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
13743 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
13744 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
13746 APInt KnownZero, KnownOne;
13747 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
13748 DCI.isBeforeLegalizeOps());
13749 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
13750 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
13751 DCI.CommitTargetLoweringOpt(TLO);
13757 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13758 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13759 TargetLowering::DAGCombinerInfo &DCI) {
13760 DebugLoc DL = N->getDebugLoc();
13762 // If the flag operand isn't dead, don't touch this CMOV.
13763 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13766 SDValue FalseOp = N->getOperand(0);
13767 SDValue TrueOp = N->getOperand(1);
13768 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13769 SDValue Cond = N->getOperand(3);
13770 if (CC == X86::COND_E || CC == X86::COND_NE) {
13771 switch (Cond.getOpcode()) {
13775 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13776 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13777 return (CC == X86::COND_E) ? FalseOp : TrueOp;
13781 // If this is a select between two integer constants, try to do some
13782 // optimizations. Note that the operands are ordered the opposite of SELECT
13784 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13785 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13786 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13787 // larger than FalseC (the false value).
13788 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13789 CC = X86::GetOppositeBranchCondition(CC);
13790 std::swap(TrueC, FalseC);
13793 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
13794 // This is efficient for any integer data type (including i8/i16) and
13796 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13797 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13798 DAG.getConstant(CC, MVT::i8), Cond);
13800 // Zero extend the condition if needed.
13801 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13803 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13804 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13805 DAG.getConstant(ShAmt, MVT::i8));
13806 if (N->getNumValues() == 2) // Dead flag value?
13807 return DCI.CombineTo(N, Cond, SDValue());
13811 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
13812 // for any integer data type, including i8/i16.
13813 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13814 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13815 DAG.getConstant(CC, MVT::i8), Cond);
13817 // Zero extend the condition if needed.
13818 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13819 FalseC->getValueType(0), Cond);
13820 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13821 SDValue(FalseC, 0));
13823 if (N->getNumValues() == 2) // Dead flag value?
13824 return DCI.CombineTo(N, Cond, SDValue());
13828 // Optimize cases that will turn into an LEA instruction. This requires
13829 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13830 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13831 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13832 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13834 bool isFastMultiplier = false;
13836 switch ((unsigned char)Diff) {
13838 case 1: // result = add base, cond
13839 case 2: // result = lea base( , cond*2)
13840 case 3: // result = lea base(cond, cond*2)
13841 case 4: // result = lea base( , cond*4)
13842 case 5: // result = lea base(cond, cond*4)
13843 case 8: // result = lea base( , cond*8)
13844 case 9: // result = lea base(cond, cond*8)
13845 isFastMultiplier = true;
13850 if (isFastMultiplier) {
13851 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13852 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13853 DAG.getConstant(CC, MVT::i8), Cond);
13854 // Zero extend the condition if needed.
13855 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13857 // Scale the condition by the difference.
13859 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13860 DAG.getConstant(Diff, Cond.getValueType()));
13862 // Add the base if non-zero.
13863 if (FalseC->getAPIntValue() != 0)
13864 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13865 SDValue(FalseC, 0));
13866 if (N->getNumValues() == 2) // Dead flag value?
13867 return DCI.CombineTo(N, Cond, SDValue());
13877 /// PerformMulCombine - Optimize a single multiply with constant into two
13878 /// in order to implement it with two cheaper instructions, e.g.
13879 /// LEA + SHL, LEA + LEA.
13880 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13881 TargetLowering::DAGCombinerInfo &DCI) {
13882 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13885 EVT VT = N->getValueType(0);
13886 if (VT != MVT::i64)
13889 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13892 uint64_t MulAmt = C->getZExtValue();
13893 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13896 uint64_t MulAmt1 = 0;
13897 uint64_t MulAmt2 = 0;
13898 if ((MulAmt % 9) == 0) {
13900 MulAmt2 = MulAmt / 9;
13901 } else if ((MulAmt % 5) == 0) {
13903 MulAmt2 = MulAmt / 5;
13904 } else if ((MulAmt % 3) == 0) {
13906 MulAmt2 = MulAmt / 3;
13909 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13910 DebugLoc DL = N->getDebugLoc();
13912 if (isPowerOf2_64(MulAmt2) &&
13913 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13914 // If second multiplifer is pow2, issue it first. We want the multiply by
13915 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13917 std::swap(MulAmt1, MulAmt2);
13920 if (isPowerOf2_64(MulAmt1))
13921 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13922 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13924 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13925 DAG.getConstant(MulAmt1, VT));
13927 if (isPowerOf2_64(MulAmt2))
13928 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13929 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13931 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13932 DAG.getConstant(MulAmt2, VT));
13934 // Do not add new nodes to DAG combiner worklist.
13935 DCI.CombineTo(N, NewMul, false);
13940 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13941 SDValue N0 = N->getOperand(0);
13942 SDValue N1 = N->getOperand(1);
13943 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13944 EVT VT = N0.getValueType();
13946 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13947 // since the result of setcc_c is all zero's or all ones.
13948 if (VT.isInteger() && !VT.isVector() &&
13949 N1C && N0.getOpcode() == ISD::AND &&
13950 N0.getOperand(1).getOpcode() == ISD::Constant) {
13951 SDValue N00 = N0.getOperand(0);
13952 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13953 ((N00.getOpcode() == ISD::ANY_EXTEND ||
13954 N00.getOpcode() == ISD::ZERO_EXTEND) &&
13955 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13956 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13957 APInt ShAmt = N1C->getAPIntValue();
13958 Mask = Mask.shl(ShAmt);
13960 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13961 N00, DAG.getConstant(Mask, VT));
13966 // Hardware support for vector shifts is sparse which makes us scalarize the
13967 // vector operations in many cases. Also, on sandybridge ADD is faster than
13969 // (shl V, 1) -> add V,V
13970 if (isSplatVector(N1.getNode())) {
13971 assert(N0.getValueType().isVector() && "Invalid vector shift type");
13972 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13973 // We shift all of the values by one. In many cases we do not have
13974 // hardware support for this operation. This is better expressed as an ADD
13976 if (N1C && (1 == N1C->getZExtValue())) {
13977 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13984 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13986 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13987 TargetLowering::DAGCombinerInfo &DCI,
13988 const X86Subtarget *Subtarget) {
13989 EVT VT = N->getValueType(0);
13990 if (N->getOpcode() == ISD::SHL) {
13991 SDValue V = PerformSHLCombine(N, DAG);
13992 if (V.getNode()) return V;
13995 // On X86 with SSE2 support, we can transform this to a vector shift if
13996 // all elements are shifted by the same amount. We can't do this in legalize
13997 // because the a constant vector is typically transformed to a constant pool
13998 // so we have no knowledge of the shift amount.
13999 if (!Subtarget->hasSSE2())
14002 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
14003 (!Subtarget->hasAVX2() ||
14004 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
14007 SDValue ShAmtOp = N->getOperand(1);
14008 EVT EltVT = VT.getVectorElementType();
14009 DebugLoc DL = N->getDebugLoc();
14010 SDValue BaseShAmt = SDValue();
14011 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
14012 unsigned NumElts = VT.getVectorNumElements();
14014 for (; i != NumElts; ++i) {
14015 SDValue Arg = ShAmtOp.getOperand(i);
14016 if (Arg.getOpcode() == ISD::UNDEF) continue;
14020 // Handle the case where the build_vector is all undef
14021 // FIXME: Should DAG allow this?
14025 for (; i != NumElts; ++i) {
14026 SDValue Arg = ShAmtOp.getOperand(i);
14027 if (Arg.getOpcode() == ISD::UNDEF) continue;
14028 if (Arg != BaseShAmt) {
14032 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
14033 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
14034 SDValue InVec = ShAmtOp.getOperand(0);
14035 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14036 unsigned NumElts = InVec.getValueType().getVectorNumElements();
14038 for (; i != NumElts; ++i) {
14039 SDValue Arg = InVec.getOperand(i);
14040 if (Arg.getOpcode() == ISD::UNDEF) continue;
14044 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14045 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14046 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
14047 if (C->getZExtValue() == SplatIdx)
14048 BaseShAmt = InVec.getOperand(1);
14051 if (BaseShAmt.getNode() == 0) {
14052 // Don't create instructions with illegal types after legalize
14054 if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
14055 !DCI.isBeforeLegalize())
14058 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
14059 DAG.getIntPtrConstant(0));
14064 // The shift amount is an i32.
14065 if (EltVT.bitsGT(MVT::i32))
14066 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
14067 else if (EltVT.bitsLT(MVT::i32))
14068 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
14070 // The shift amount is identical so we can do a vector shift.
14071 SDValue ValOp = N->getOperand(0);
14072 switch (N->getOpcode()) {
14074 llvm_unreachable("Unknown shift opcode!");
14076 switch (VT.getSimpleVT().SimpleTy) {
14077 default: return SDValue();
14084 return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
14087 switch (VT.getSimpleVT().SimpleTy) {
14088 default: return SDValue();
14093 return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
14096 switch (VT.getSimpleVT().SimpleTy) {
14097 default: return SDValue();
14104 return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
14110 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
14111 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
14112 // and friends. Likewise for OR -> CMPNEQSS.
14113 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
14114 TargetLowering::DAGCombinerInfo &DCI,
14115 const X86Subtarget *Subtarget) {
14118 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
14119 // we're requiring SSE2 for both.
14120 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
14121 SDValue N0 = N->getOperand(0);
14122 SDValue N1 = N->getOperand(1);
14123 SDValue CMP0 = N0->getOperand(1);
14124 SDValue CMP1 = N1->getOperand(1);
14125 DebugLoc DL = N->getDebugLoc();
14127 // The SETCCs should both refer to the same CMP.
14128 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
14131 SDValue CMP00 = CMP0->getOperand(0);
14132 SDValue CMP01 = CMP0->getOperand(1);
14133 EVT VT = CMP00.getValueType();
14135 if (VT == MVT::f32 || VT == MVT::f64) {
14136 bool ExpectingFlags = false;
14137 // Check for any users that want flags:
14138 for (SDNode::use_iterator UI = N->use_begin(),
14140 !ExpectingFlags && UI != UE; ++UI)
14141 switch (UI->getOpcode()) {
14146 ExpectingFlags = true;
14148 case ISD::CopyToReg:
14149 case ISD::SIGN_EXTEND:
14150 case ISD::ZERO_EXTEND:
14151 case ISD::ANY_EXTEND:
14155 if (!ExpectingFlags) {
14156 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
14157 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
14159 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
14160 X86::CondCode tmp = cc0;
14165 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
14166 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
14167 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
14168 X86ISD::NodeType NTOperator = is64BitFP ?
14169 X86ISD::FSETCCsd : X86ISD::FSETCCss;
14170 // FIXME: need symbolic constants for these magic numbers.
14171 // See X86ATTInstPrinter.cpp:printSSECC().
14172 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
14173 SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
14174 DAG.getConstant(x86cc, MVT::i8));
14175 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
14177 SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
14178 DAG.getConstant(1, MVT::i32));
14179 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
14180 return OneBitOfTruth;
14188 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
14189 /// so it can be folded inside ANDNP.
14190 static bool CanFoldXORWithAllOnes(const SDNode *N) {
14191 EVT VT = N->getValueType(0);
14193 // Match direct AllOnes for 128 and 256-bit vectors
14194 if (ISD::isBuildVectorAllOnes(N))
14197 // Look through a bit convert.
14198 if (N->getOpcode() == ISD::BITCAST)
14199 N = N->getOperand(0).getNode();
14201 // Sometimes the operand may come from a insert_subvector building a 256-bit
14203 if (VT.getSizeInBits() == 256 &&
14204 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
14205 SDValue V1 = N->getOperand(0);
14206 SDValue V2 = N->getOperand(1);
14208 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
14209 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
14210 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
14211 ISD::isBuildVectorAllOnes(V2.getNode()))
14218 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
14219 TargetLowering::DAGCombinerInfo &DCI,
14220 const X86Subtarget *Subtarget) {
14221 if (DCI.isBeforeLegalizeOps())
14224 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14228 EVT VT = N->getValueType(0);
14230 // Create ANDN, BLSI, and BLSR instructions
14231 // BLSI is X & (-X)
14232 // BLSR is X & (X-1)
14233 if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
14234 SDValue N0 = N->getOperand(0);
14235 SDValue N1 = N->getOperand(1);
14236 DebugLoc DL = N->getDebugLoc();
14238 // Check LHS for not
14239 if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
14240 return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
14241 // Check RHS for not
14242 if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
14243 return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
14245 // Check LHS for neg
14246 if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
14247 isZero(N0.getOperand(0)))
14248 return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
14250 // Check RHS for neg
14251 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
14252 isZero(N1.getOperand(0)))
14253 return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
14255 // Check LHS for X-1
14256 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14257 isAllOnes(N0.getOperand(1)))
14258 return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
14260 // Check RHS for X-1
14261 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14262 isAllOnes(N1.getOperand(1)))
14263 return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
14268 // Want to form ANDNP nodes:
14269 // 1) In the hopes of then easily combining them with OR and AND nodes
14270 // to form PBLEND/PSIGN.
14271 // 2) To match ANDN packed intrinsics
14272 if (VT != MVT::v2i64 && VT != MVT::v4i64)
14275 SDValue N0 = N->getOperand(0);
14276 SDValue N1 = N->getOperand(1);
14277 DebugLoc DL = N->getDebugLoc();
14279 // Check LHS for vnot
14280 if (N0.getOpcode() == ISD::XOR &&
14281 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
14282 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
14283 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
14285 // Check RHS for vnot
14286 if (N1.getOpcode() == ISD::XOR &&
14287 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
14288 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
14289 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
14294 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
14295 TargetLowering::DAGCombinerInfo &DCI,
14296 const X86Subtarget *Subtarget) {
14297 if (DCI.isBeforeLegalizeOps())
14300 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
14304 EVT VT = N->getValueType(0);
14306 SDValue N0 = N->getOperand(0);
14307 SDValue N1 = N->getOperand(1);
14309 // look for psign/blend
14310 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
14311 if (!Subtarget->hasSSSE3() ||
14312 (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
14315 // Canonicalize pandn to RHS
14316 if (N0.getOpcode() == X86ISD::ANDNP)
14318 // or (and (m, y), (pandn m, x))
14319 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
14320 SDValue Mask = N1.getOperand(0);
14321 SDValue X = N1.getOperand(1);
14323 if (N0.getOperand(0) == Mask)
14324 Y = N0.getOperand(1);
14325 if (N0.getOperand(1) == Mask)
14326 Y = N0.getOperand(0);
14328 // Check to see if the mask appeared in both the AND and ANDNP and
14332 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14333 // Look through mask bitcast.
14334 if (Mask.getOpcode() == ISD::BITCAST)
14335 Mask = Mask.getOperand(0);
14336 if (X.getOpcode() == ISD::BITCAST)
14337 X = X.getOperand(0);
14338 if (Y.getOpcode() == ISD::BITCAST)
14339 Y = Y.getOperand(0);
14341 EVT MaskVT = Mask.getValueType();
14343 // Validate that the Mask operand is a vector sra node.
14344 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14345 // there is no psrai.b
14346 if (Mask.getOpcode() != X86ISD::VSRAI)
14349 // Check that the SRA is all signbits.
14350 SDValue SraC = Mask.getOperand(1);
14351 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
14352 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14353 if ((SraAmt + 1) != EltBits)
14356 DebugLoc DL = N->getDebugLoc();
14358 // Now we know we at least have a plendvb with the mask val. See if
14359 // we can form a psignb/w/d.
14360 // psign = x.type == y.type == mask.type && y = sub(0, x);
14361 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14362 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14363 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
14364 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
14365 "Unsupported VT for PSIGN");
14366 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
14367 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14369 // PBLENDVB only available on SSE 4.1
14370 if (!Subtarget->hasSSE41())
14373 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14375 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14376 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14377 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14378 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
14379 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14383 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14386 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14387 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14389 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14391 if (!N0.hasOneUse() || !N1.hasOneUse())
14394 SDValue ShAmt0 = N0.getOperand(1);
14395 if (ShAmt0.getValueType() != MVT::i8)
14397 SDValue ShAmt1 = N1.getOperand(1);
14398 if (ShAmt1.getValueType() != MVT::i8)
14400 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14401 ShAmt0 = ShAmt0.getOperand(0);
14402 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14403 ShAmt1 = ShAmt1.getOperand(0);
14405 DebugLoc DL = N->getDebugLoc();
14406 unsigned Opc = X86ISD::SHLD;
14407 SDValue Op0 = N0.getOperand(0);
14408 SDValue Op1 = N1.getOperand(0);
14409 if (ShAmt0.getOpcode() == ISD::SUB) {
14410 Opc = X86ISD::SHRD;
14411 std::swap(Op0, Op1);
14412 std::swap(ShAmt0, ShAmt1);
14415 unsigned Bits = VT.getSizeInBits();
14416 if (ShAmt1.getOpcode() == ISD::SUB) {
14417 SDValue Sum = ShAmt1.getOperand(0);
14418 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14419 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14420 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14421 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14422 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14423 return DAG.getNode(Opc, DL, VT,
14425 DAG.getNode(ISD::TRUNCATE, DL,
14428 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14429 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14431 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14432 return DAG.getNode(Opc, DL, VT,
14433 N0.getOperand(0), N1.getOperand(0),
14434 DAG.getNode(ISD::TRUNCATE, DL,
14441 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
14442 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14443 TargetLowering::DAGCombinerInfo &DCI,
14444 const X86Subtarget *Subtarget) {
14445 if (DCI.isBeforeLegalizeOps())
14448 EVT VT = N->getValueType(0);
14450 if (VT != MVT::i32 && VT != MVT::i64)
14453 assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
14455 // Create BLSMSK instructions by finding X ^ (X-1)
14456 SDValue N0 = N->getOperand(0);
14457 SDValue N1 = N->getOperand(1);
14458 DebugLoc DL = N->getDebugLoc();
14460 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14461 isAllOnes(N0.getOperand(1)))
14462 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14464 if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14465 isAllOnes(N1.getOperand(1)))
14466 return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14471 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14472 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14473 const X86Subtarget *Subtarget) {
14474 LoadSDNode *Ld = cast<LoadSDNode>(N);
14475 EVT RegVT = Ld->getValueType(0);
14476 EVT MemVT = Ld->getMemoryVT();
14477 DebugLoc dl = Ld->getDebugLoc();
14478 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14480 ISD::LoadExtType Ext = Ld->getExtensionType();
14482 // If this is a vector EXT Load then attempt to optimize it using a
14483 // shuffle. We need SSE4 for the shuffles.
14484 // TODO: It is possible to support ZExt by zeroing the undef values
14485 // during the shuffle phase or after the shuffle.
14486 if (RegVT.isVector() && RegVT.isInteger() &&
14487 Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14488 assert(MemVT != RegVT && "Cannot extend to the same type");
14489 assert(MemVT.isVector() && "Must load a vector from memory");
14491 unsigned NumElems = RegVT.getVectorNumElements();
14492 unsigned RegSz = RegVT.getSizeInBits();
14493 unsigned MemSz = MemVT.getSizeInBits();
14494 assert(RegSz > MemSz && "Register size must be greater than the mem size");
14495 // All sizes must be a power of two
14496 if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14498 // Attempt to load the original value using a single load op.
14499 // Find a scalar type which is equal to the loaded word size.
14500 MVT SclrLoadTy = MVT::i8;
14501 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14502 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14503 MVT Tp = (MVT::SimpleValueType)tp;
14504 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() == MemSz) {
14510 // Proceed if a load word is found.
14511 if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14513 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14514 RegSz/SclrLoadTy.getSizeInBits());
14516 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14517 RegSz/MemVT.getScalarType().getSizeInBits());
14518 // Can't shuffle using an illegal type.
14519 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14521 // Perform a single load.
14522 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14524 Ld->getPointerInfo(), Ld->isVolatile(),
14525 Ld->isNonTemporal(), Ld->isInvariant(),
14526 Ld->getAlignment());
14528 // Insert the word loaded into a vector.
14529 SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14530 LoadUnitVecVT, ScalarLoad);
14532 // Bitcast the loaded value to a vector of the original element type, in
14533 // the size of the target vector type.
14534 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT,
14536 unsigned SizeRatio = RegSz/MemSz;
14538 // Redistribute the loaded elements into the different locations.
14539 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14540 for (unsigned i = 0; i != NumElems; ++i)
14541 ShuffleVec[i*SizeRatio] = i;
14543 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14544 DAG.getUNDEF(WideVecVT),
14547 // Bitcast to the requested type.
14548 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14549 // Replace the original load with the new sequence
14550 // and return the new chain.
14551 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14552 return SDValue(ScalarLoad.getNode(), 1);
14558 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14559 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14560 const X86Subtarget *Subtarget) {
14561 StoreSDNode *St = cast<StoreSDNode>(N);
14562 EVT VT = St->getValue().getValueType();
14563 EVT StVT = St->getMemoryVT();
14564 DebugLoc dl = St->getDebugLoc();
14565 SDValue StoredVal = St->getOperand(1);
14566 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14568 // If we are saving a concatenation of two XMM registers, perform two stores.
14569 // On Sandy Bridge, 256-bit memory operations are executed by two
14570 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
14571 // memory operation.
14572 if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2() &&
14573 StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14574 StoredVal.getNumOperands() == 2) {
14575 SDValue Value0 = StoredVal.getOperand(0);
14576 SDValue Value1 = StoredVal.getOperand(1);
14578 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14579 SDValue Ptr0 = St->getBasePtr();
14580 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14582 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14583 St->getPointerInfo(), St->isVolatile(),
14584 St->isNonTemporal(), St->getAlignment());
14585 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14586 St->getPointerInfo(), St->isVolatile(),
14587 St->isNonTemporal(), St->getAlignment());
14588 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14591 // Optimize trunc store (of multiple scalars) to shuffle and store.
14592 // First, pack all of the elements in one place. Next, store to memory
14593 // in fewer chunks.
14594 if (St->isTruncatingStore() && VT.isVector()) {
14595 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14596 unsigned NumElems = VT.getVectorNumElements();
14597 assert(StVT != VT && "Cannot truncate to the same type");
14598 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14599 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14601 // From, To sizes and ElemCount must be pow of two
14602 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14603 // We are going to use the original vector elt for storing.
14604 // Accumulated smaller vector elements must be a multiple of the store size.
14605 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14607 unsigned SizeRatio = FromSz / ToSz;
14609 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14611 // Create a type on which we perform the shuffle
14612 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14613 StVT.getScalarType(), NumElems*SizeRatio);
14615 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14617 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14618 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14619 for (unsigned i = 0; i != NumElems; ++i)
14620 ShuffleVec[i] = i * SizeRatio;
14622 // Can't shuffle using an illegal type
14623 if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14625 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14626 DAG.getUNDEF(WideVecVT),
14628 // At this point all of the data is stored at the bottom of the
14629 // register. We now need to save it to mem.
14631 // Find the largest store unit
14632 MVT StoreType = MVT::i8;
14633 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14634 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14635 MVT Tp = (MVT::SimpleValueType)tp;
14636 if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14640 // Bitcast the original vector into a vector of store-size units
14641 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14642 StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14643 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14644 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14645 SmallVector<SDValue, 8> Chains;
14646 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14647 TLI.getPointerTy());
14648 SDValue Ptr = St->getBasePtr();
14650 // Perform one or more big stores into memory.
14651 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
14652 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14653 StoreType, ShuffWide,
14654 DAG.getIntPtrConstant(i));
14655 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14656 St->getPointerInfo(), St->isVolatile(),
14657 St->isNonTemporal(), St->getAlignment());
14658 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14659 Chains.push_back(Ch);
14662 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14667 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
14668 // the FP state in cases where an emms may be missing.
14669 // A preferable solution to the general problem is to figure out the right
14670 // places to insert EMMS. This qualifies as a quick hack.
14672 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14673 if (VT.getSizeInBits() != 64)
14676 const Function *F = DAG.getMachineFunction().getFunction();
14677 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14678 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
14679 && Subtarget->hasSSE2();
14680 if ((VT.isVector() ||
14681 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14682 isa<LoadSDNode>(St->getValue()) &&
14683 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14684 St->getChain().hasOneUse() && !St->isVolatile()) {
14685 SDNode* LdVal = St->getValue().getNode();
14686 LoadSDNode *Ld = 0;
14687 int TokenFactorIndex = -1;
14688 SmallVector<SDValue, 8> Ops;
14689 SDNode* ChainVal = St->getChain().getNode();
14690 // Must be a store of a load. We currently handle two cases: the load
14691 // is a direct child, and it's under an intervening TokenFactor. It is
14692 // possible to dig deeper under nested TokenFactors.
14693 if (ChainVal == LdVal)
14694 Ld = cast<LoadSDNode>(St->getChain());
14695 else if (St->getValue().hasOneUse() &&
14696 ChainVal->getOpcode() == ISD::TokenFactor) {
14697 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
14698 if (ChainVal->getOperand(i).getNode() == LdVal) {
14699 TokenFactorIndex = i;
14700 Ld = cast<LoadSDNode>(St->getValue());
14702 Ops.push_back(ChainVal->getOperand(i));
14706 if (!Ld || !ISD::isNormalLoad(Ld))
14709 // If this is not the MMX case, i.e. we are just turning i64 load/store
14710 // into f64 load/store, avoid the transformation if there are multiple
14711 // uses of the loaded value.
14712 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14715 DebugLoc LdDL = Ld->getDebugLoc();
14716 DebugLoc StDL = N->getDebugLoc();
14717 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14718 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14720 if (Subtarget->is64Bit() || F64IsLegal) {
14721 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14722 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14723 Ld->getPointerInfo(), Ld->isVolatile(),
14724 Ld->isNonTemporal(), Ld->isInvariant(),
14725 Ld->getAlignment());
14726 SDValue NewChain = NewLd.getValue(1);
14727 if (TokenFactorIndex != -1) {
14728 Ops.push_back(NewChain);
14729 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14732 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14733 St->getPointerInfo(),
14734 St->isVolatile(), St->isNonTemporal(),
14735 St->getAlignment());
14738 // Otherwise, lower to two pairs of 32-bit loads / stores.
14739 SDValue LoAddr = Ld->getBasePtr();
14740 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14741 DAG.getConstant(4, MVT::i32));
14743 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14744 Ld->getPointerInfo(),
14745 Ld->isVolatile(), Ld->isNonTemporal(),
14746 Ld->isInvariant(), Ld->getAlignment());
14747 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14748 Ld->getPointerInfo().getWithOffset(4),
14749 Ld->isVolatile(), Ld->isNonTemporal(),
14751 MinAlign(Ld->getAlignment(), 4));
14753 SDValue NewChain = LoLd.getValue(1);
14754 if (TokenFactorIndex != -1) {
14755 Ops.push_back(LoLd);
14756 Ops.push_back(HiLd);
14757 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14761 LoAddr = St->getBasePtr();
14762 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14763 DAG.getConstant(4, MVT::i32));
14765 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14766 St->getPointerInfo(),
14767 St->isVolatile(), St->isNonTemporal(),
14768 St->getAlignment());
14769 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14770 St->getPointerInfo().getWithOffset(4),
14772 St->isNonTemporal(),
14773 MinAlign(St->getAlignment(), 4));
14774 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14779 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14780 /// and return the operands for the horizontal operation in LHS and RHS. A
14781 /// horizontal operation performs the binary operation on successive elements
14782 /// of its first operand, then on successive elements of its second operand,
14783 /// returning the resulting values in a vector. For example, if
14784 /// A = < float a0, float a1, float a2, float a3 >
14786 /// B = < float b0, float b1, float b2, float b3 >
14787 /// then the result of doing a horizontal operation on A and B is
14788 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14789 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14790 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14791 /// set to A, RHS to B, and the routine returns 'true'.
14792 /// Note that the binary operation should have the property that if one of the
14793 /// operands is UNDEF then the result is UNDEF.
14794 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
14795 // Look for the following pattern: if
14796 // A = < float a0, float a1, float a2, float a3 >
14797 // B = < float b0, float b1, float b2, float b3 >
14799 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14800 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14801 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14802 // which is A horizontal-op B.
14804 // At least one of the operands should be a vector shuffle.
14805 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14806 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14809 EVT VT = LHS.getValueType();
14811 assert((VT.is128BitVector() || VT.is256BitVector()) &&
14812 "Unsupported vector type for horizontal add/sub");
14814 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
14815 // operate independently on 128-bit lanes.
14816 unsigned NumElts = VT.getVectorNumElements();
14817 unsigned NumLanes = VT.getSizeInBits()/128;
14818 unsigned NumLaneElts = NumElts / NumLanes;
14819 assert((NumLaneElts % 2 == 0) &&
14820 "Vector type should have an even number of elements in each lane");
14821 unsigned HalfLaneElts = NumLaneElts/2;
14823 // View LHS in the form
14824 // LHS = VECTOR_SHUFFLE A, B, LMask
14825 // If LHS is not a shuffle then pretend it is the shuffle
14826 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14827 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14830 SmallVector<int, 16> LMask(NumElts);
14831 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14832 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14833 A = LHS.getOperand(0);
14834 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14835 B = LHS.getOperand(1);
14836 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
14837 std::copy(Mask.begin(), Mask.end(), LMask.begin());
14839 if (LHS.getOpcode() != ISD::UNDEF)
14841 for (unsigned i = 0; i != NumElts; ++i)
14845 // Likewise, view RHS in the form
14846 // RHS = VECTOR_SHUFFLE C, D, RMask
14848 SmallVector<int, 16> RMask(NumElts);
14849 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14850 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14851 C = RHS.getOperand(0);
14852 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14853 D = RHS.getOperand(1);
14854 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
14855 std::copy(Mask.begin(), Mask.end(), RMask.begin());
14857 if (RHS.getOpcode() != ISD::UNDEF)
14859 for (unsigned i = 0; i != NumElts; ++i)
14863 // Check that the shuffles are both shuffling the same vectors.
14864 if (!(A == C && B == D) && !(A == D && B == C))
14867 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14868 if (!A.getNode() && !B.getNode())
14871 // If A and B occur in reverse order in RHS, then "swap" them (which means
14872 // rewriting the mask).
14874 CommuteVectorShuffleMask(RMask, NumElts);
14876 // At this point LHS and RHS are equivalent to
14877 // LHS = VECTOR_SHUFFLE A, B, LMask
14878 // RHS = VECTOR_SHUFFLE A, B, RMask
14879 // Check that the masks correspond to performing a horizontal operation.
14880 for (unsigned i = 0; i != NumElts; ++i) {
14881 int LIdx = LMask[i], RIdx = RMask[i];
14883 // Ignore any UNDEF components.
14884 if (LIdx < 0 || RIdx < 0 ||
14885 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
14886 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
14889 // Check that successive elements are being operated on. If not, this is
14890 // not a horizontal operation.
14891 unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
14892 unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
14893 int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
14894 if (!(LIdx == Index && RIdx == Index + 1) &&
14895 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
14899 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14900 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14904 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14905 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14906 const X86Subtarget *Subtarget) {
14907 EVT VT = N->getValueType(0);
14908 SDValue LHS = N->getOperand(0);
14909 SDValue RHS = N->getOperand(1);
14911 // Try to synthesize horizontal adds from adds of shuffles.
14912 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14913 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14914 isHorizontalBinOp(LHS, RHS, true))
14915 return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14919 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14920 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14921 const X86Subtarget *Subtarget) {
14922 EVT VT = N->getValueType(0);
14923 SDValue LHS = N->getOperand(0);
14924 SDValue RHS = N->getOperand(1);
14926 // Try to synthesize horizontal subs from subs of shuffles.
14927 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
14928 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
14929 isHorizontalBinOp(LHS, RHS, false))
14930 return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14934 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14935 /// X86ISD::FXOR nodes.
14936 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14937 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14938 // F[X]OR(0.0, x) -> x
14939 // F[X]OR(x, 0.0) -> x
14940 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14941 if (C->getValueAPF().isPosZero())
14942 return N->getOperand(1);
14943 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14944 if (C->getValueAPF().isPosZero())
14945 return N->getOperand(0);
14949 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14950 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14951 // FAND(0.0, x) -> 0.0
14952 // FAND(x, 0.0) -> 0.0
14953 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14954 if (C->getValueAPF().isPosZero())
14955 return N->getOperand(0);
14956 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14957 if (C->getValueAPF().isPosZero())
14958 return N->getOperand(1);
14962 static SDValue PerformBTCombine(SDNode *N,
14964 TargetLowering::DAGCombinerInfo &DCI) {
14965 // BT ignores high bits in the bit index operand.
14966 SDValue Op1 = N->getOperand(1);
14967 if (Op1.hasOneUse()) {
14968 unsigned BitWidth = Op1.getValueSizeInBits();
14969 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14970 APInt KnownZero, KnownOne;
14971 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14972 !DCI.isBeforeLegalizeOps());
14973 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14974 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14975 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14976 DCI.CommitTargetLoweringOpt(TLO);
14981 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14982 SDValue Op = N->getOperand(0);
14983 if (Op.getOpcode() == ISD::BITCAST)
14984 Op = Op.getOperand(0);
14985 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14986 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14987 VT.getVectorElementType().getSizeInBits() ==
14988 OpVT.getVectorElementType().getSizeInBits()) {
14989 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14994 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
14995 TargetLowering::DAGCombinerInfo &DCI,
14996 const X86Subtarget *Subtarget) {
14997 if (!DCI.isBeforeLegalizeOps())
15000 if (!Subtarget->hasAVX())
15003 EVT VT = N->getValueType(0);
15004 SDValue Op = N->getOperand(0);
15005 EVT OpVT = Op.getValueType();
15006 DebugLoc dl = N->getDebugLoc();
15008 if ((VT == MVT::v4i64 && OpVT == MVT::v4i32) ||
15009 (VT == MVT::v8i32 && OpVT == MVT::v8i16)) {
15011 if (Subtarget->hasAVX2())
15012 return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, Op);
15014 // Optimize vectors in AVX mode
15015 // Sign extend v8i16 to v8i32 and
15018 // Divide input vector into two parts
15019 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
15020 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
15021 // concat the vectors to original VT
15023 unsigned NumElems = OpVT.getVectorNumElements();
15024 SmallVector<int,8> ShufMask1(NumElems, -1);
15025 for (unsigned i = 0; i != NumElems/2; ++i)
15028 SDValue OpLo = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15031 SmallVector<int,8> ShufMask2(NumElems, -1);
15032 for (unsigned i = 0; i != NumElems/2; ++i)
15033 ShufMask2[i] = i + NumElems/2;
15035 SDValue OpHi = DAG.getVectorShuffle(OpVT, dl, Op, DAG.getUNDEF(OpVT),
15038 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
15039 VT.getVectorNumElements()/2);
15041 OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
15042 OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
15044 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15049 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
15050 TargetLowering::DAGCombinerInfo &DCI,
15051 const X86Subtarget *Subtarget) {
15052 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
15053 // (and (i32 x86isd::setcc_carry), 1)
15054 // This eliminates the zext. This transformation is necessary because
15055 // ISD::SETCC is always legalized to i8.
15056 DebugLoc dl = N->getDebugLoc();
15057 SDValue N0 = N->getOperand(0);
15058 EVT VT = N->getValueType(0);
15059 EVT OpVT = N0.getValueType();
15061 if (N0.getOpcode() == ISD::AND &&
15063 N0.getOperand(0).hasOneUse()) {
15064 SDValue N00 = N0.getOperand(0);
15065 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
15067 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
15068 if (!C || C->getZExtValue() != 1)
15070 return DAG.getNode(ISD::AND, dl, VT,
15071 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
15072 N00.getOperand(0), N00.getOperand(1)),
15073 DAG.getConstant(1, VT));
15076 // Optimize vectors in AVX mode:
15079 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
15080 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
15081 // Concat upper and lower parts.
15084 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
15085 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
15086 // Concat upper and lower parts.
15088 if (!DCI.isBeforeLegalizeOps())
15091 if (!Subtarget->hasAVX())
15094 if (((VT == MVT::v8i32) && (OpVT == MVT::v8i16)) ||
15095 ((VT == MVT::v4i64) && (OpVT == MVT::v4i32))) {
15097 if (Subtarget->hasAVX2())
15098 return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, N0);
15100 SDValue ZeroVec = getZeroVector(OpVT, Subtarget, DAG, dl);
15101 SDValue OpLo = getUnpackl(DAG, dl, OpVT, N0, ZeroVec);
15102 SDValue OpHi = getUnpackh(DAG, dl, OpVT, N0, ZeroVec);
15104 EVT HVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
15105 VT.getVectorNumElements()/2);
15107 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
15108 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
15110 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
15116 // Optimize x == -y --> x+y == 0
15117 // x != -y --> x+y != 0
15118 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15119 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15120 SDValue LHS = N->getOperand(0);
15121 SDValue RHS = N->getOperand(1);
15123 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
15124 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
15125 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
15126 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15127 LHS.getValueType(), RHS, LHS.getOperand(1));
15128 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15129 addV, DAG.getConstant(0, addV.getValueType()), CC);
15131 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
15132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
15133 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
15134 SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
15135 RHS.getValueType(), LHS, RHS.getOperand(1));
15136 return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
15137 addV, DAG.getConstant(0, addV.getValueType()), CC);
15142 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
15143 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
15144 unsigned X86CC = N->getConstantOperandVal(0);
15145 SDValue EFLAG = N->getOperand(1);
15146 DebugLoc DL = N->getDebugLoc();
15148 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
15149 // a zext and produces an all-ones bit which is more useful than 0/1 in some
15151 if (X86CC == X86::COND_B)
15152 return DAG.getNode(ISD::AND, DL, MVT::i8,
15153 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
15154 DAG.getConstant(X86CC, MVT::i8), EFLAG),
15155 DAG.getConstant(1, MVT::i8));
15160 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG) {
15161 SDValue Op0 = N->getOperand(0);
15162 EVT InVT = Op0->getValueType(0);
15164 // UINT_TO_FP(v4i8) -> SINT_TO_FP(ZEXT(v4i8 to v4i32))
15165 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15166 DebugLoc dl = N->getDebugLoc();
15167 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15168 SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
15169 // Notice that we use SINT_TO_FP because we know that the high bits
15170 // are zero and SINT_TO_FP is better supported by the hardware.
15171 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15177 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
15178 const X86TargetLowering *XTLI) {
15179 SDValue Op0 = N->getOperand(0);
15180 EVT InVT = Op0->getValueType(0);
15182 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
15183 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
15184 DebugLoc dl = N->getDebugLoc();
15185 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15186 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
15187 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
15190 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
15191 // a 32-bit target where SSE doesn't support i64->FP operations.
15192 if (Op0.getOpcode() == ISD::LOAD) {
15193 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
15194 EVT VT = Ld->getValueType(0);
15195 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
15196 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
15197 !XTLI->getSubtarget()->is64Bit() &&
15198 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15199 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
15200 Ld->getChain(), Op0, DAG);
15201 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
15208 static SDValue PerformFP_TO_SINTCombine(SDNode *N, SelectionDAG &DAG) {
15209 EVT VT = N->getValueType(0);
15211 // v4i8 = FP_TO_SINT() -> v4i8 = TRUNCATE (V4i32 = FP_TO_SINT()
15212 if (VT == MVT::v8i8 || VT == MVT::v4i8) {
15213 DebugLoc dl = N->getDebugLoc();
15214 MVT DstVT = VT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
15215 SDValue I = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, N->getOperand(0));
15216 return DAG.getNode(ISD::TRUNCATE, dl, VT, I);
15222 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
15223 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
15224 X86TargetLowering::DAGCombinerInfo &DCI) {
15225 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
15226 // the result is either zero or one (depending on the input carry bit).
15227 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
15228 if (X86::isZeroNode(N->getOperand(0)) &&
15229 X86::isZeroNode(N->getOperand(1)) &&
15230 // We don't have a good way to replace an EFLAGS use, so only do this when
15232 SDValue(N, 1).use_empty()) {
15233 DebugLoc DL = N->getDebugLoc();
15234 EVT VT = N->getValueType(0);
15235 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
15236 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
15237 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
15238 DAG.getConstant(X86::COND_B,MVT::i8),
15240 DAG.getConstant(1, VT));
15241 return DCI.CombineTo(N, Res1, CarryOut);
15247 // fold (add Y, (sete X, 0)) -> adc 0, Y
15248 // (add Y, (setne X, 0)) -> sbb -1, Y
15249 // (sub (sete X, 0), Y) -> sbb 0, Y
15250 // (sub (setne X, 0), Y) -> adc -1, Y
15251 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
15252 DebugLoc DL = N->getDebugLoc();
15254 // Look through ZExts.
15255 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
15256 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
15259 SDValue SetCC = Ext.getOperand(0);
15260 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
15263 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
15264 if (CC != X86::COND_E && CC != X86::COND_NE)
15267 SDValue Cmp = SetCC.getOperand(1);
15268 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
15269 !X86::isZeroNode(Cmp.getOperand(1)) ||
15270 !Cmp.getOperand(0).getValueType().isInteger())
15273 SDValue CmpOp0 = Cmp.getOperand(0);
15274 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
15275 DAG.getConstant(1, CmpOp0.getValueType()));
15277 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
15278 if (CC == X86::COND_NE)
15279 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
15280 DL, OtherVal.getValueType(), OtherVal,
15281 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
15282 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
15283 DL, OtherVal.getValueType(), OtherVal,
15284 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
15287 /// PerformADDCombine - Do target-specific dag combines on integer adds.
15288 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
15289 const X86Subtarget *Subtarget) {
15290 EVT VT = N->getValueType(0);
15291 SDValue Op0 = N->getOperand(0);
15292 SDValue Op1 = N->getOperand(1);
15294 // Try to synthesize horizontal adds from adds of shuffles.
15295 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15296 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15297 isHorizontalBinOp(Op0, Op1, true))
15298 return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
15300 return OptimizeConditionalInDecrement(N, DAG);
15303 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
15304 const X86Subtarget *Subtarget) {
15305 SDValue Op0 = N->getOperand(0);
15306 SDValue Op1 = N->getOperand(1);
15308 // X86 can't encode an immediate LHS of a sub. See if we can push the
15309 // negation into a preceding instruction.
15310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
15311 // If the RHS of the sub is a XOR with one use and a constant, invert the
15312 // immediate. Then add one to the LHS of the sub so we can turn
15313 // X-Y -> X+~Y+1, saving one register.
15314 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
15315 isa<ConstantSDNode>(Op1.getOperand(1))) {
15316 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
15317 EVT VT = Op0.getValueType();
15318 SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
15320 DAG.getConstant(~XorC, VT));
15321 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
15322 DAG.getConstant(C->getAPIntValue()+1, VT));
15326 // Try to synthesize horizontal adds from adds of shuffles.
15327 EVT VT = N->getValueType(0);
15328 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
15329 (Subtarget->hasAVX2() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
15330 isHorizontalBinOp(Op0, Op1, true))
15331 return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
15333 return OptimizeConditionalInDecrement(N, DAG);
15336 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
15337 DAGCombinerInfo &DCI) const {
15338 SelectionDAG &DAG = DCI.DAG;
15339 switch (N->getOpcode()) {
15341 case ISD::EXTRACT_VECTOR_ELT:
15342 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
15344 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
15345 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
15346 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
15347 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
15348 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
15349 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
15352 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
15353 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
15354 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
15355 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
15356 case ISD::LOAD: return PerformLOADCombine(N, DAG, Subtarget);
15357 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
15358 case ISD::UINT_TO_FP: return PerformUINT_TO_FPCombine(N, DAG);
15359 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
15360 case ISD::FP_TO_SINT: return PerformFP_TO_SINTCombine(N, DAG);
15361 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
15362 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
15364 case X86ISD::FOR: return PerformFORCombine(N, DAG);
15365 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
15366 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
15367 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
15368 case ISD::ANY_EXTEND:
15369 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
15370 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
15371 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG, DCI);
15372 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG);
15373 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
15374 case X86ISD::SHUFP: // Handle all target specific shuffles
15375 case X86ISD::PALIGN:
15376 case X86ISD::UNPCKH:
15377 case X86ISD::UNPCKL:
15378 case X86ISD::MOVHLPS:
15379 case X86ISD::MOVLHPS:
15380 case X86ISD::PSHUFD:
15381 case X86ISD::PSHUFHW:
15382 case X86ISD::PSHUFLW:
15383 case X86ISD::MOVSS:
15384 case X86ISD::MOVSD:
15385 case X86ISD::VPERMILP:
15386 case X86ISD::VPERM2X128:
15387 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
15393 /// isTypeDesirableForOp - Return true if the target has native support for
15394 /// the specified value type and it is 'desirable' to use the type for the
15395 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
15396 /// instruction encodings are longer and some i16 instructions are slow.
15397 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
15398 if (!isTypeLegal(VT))
15400 if (VT != MVT::i16)
15407 case ISD::SIGN_EXTEND:
15408 case ISD::ZERO_EXTEND:
15409 case ISD::ANY_EXTEND:
15422 /// IsDesirableToPromoteOp - This method query the target whether it is
15423 /// beneficial for dag combiner to promote the specified node. If true, it
15424 /// should return the desired promotion type by reference.
15425 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
15426 EVT VT = Op.getValueType();
15427 if (VT != MVT::i16)
15430 bool Promote = false;
15431 bool Commute = false;
15432 switch (Op.getOpcode()) {
15435 LoadSDNode *LD = cast<LoadSDNode>(Op);
15436 // If the non-extending load has a single use and it's not live out, then it
15437 // might be folded.
15438 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
15439 Op.hasOneUse()*/) {
15440 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
15441 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
15442 // The only case where we'd want to promote LOAD (rather then it being
15443 // promoted as an operand is when it's only use is liveout.
15444 if (UI->getOpcode() != ISD::CopyToReg)
15451 case ISD::SIGN_EXTEND:
15452 case ISD::ZERO_EXTEND:
15453 case ISD::ANY_EXTEND:
15458 SDValue N0 = Op.getOperand(0);
15459 // Look out for (store (shl (load), x)).
15460 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
15473 SDValue N0 = Op.getOperand(0);
15474 SDValue N1 = Op.getOperand(1);
15475 if (!Commute && MayFoldLoad(N1))
15477 // Avoid disabling potential load folding opportunities.
15478 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15480 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15490 //===----------------------------------------------------------------------===//
15491 // X86 Inline Assembly Support
15492 //===----------------------------------------------------------------------===//
15495 // Helper to match a string separated by whitespace.
15496 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
15497 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
15499 for (unsigned i = 0, e = args.size(); i != e; ++i) {
15500 StringRef piece(*args[i]);
15501 if (!s.startswith(piece)) // Check if the piece matches.
15504 s = s.substr(piece.size());
15505 StringRef::size_type pos = s.find_first_not_of(" \t");
15506 if (pos == 0) // We matched a prefix.
15514 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
15517 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15518 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15520 std::string AsmStr = IA->getAsmString();
15522 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15523 if (!Ty || Ty->getBitWidth() % 16 != 0)
15526 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15527 SmallVector<StringRef, 4> AsmPieces;
15528 SplitString(AsmStr, AsmPieces, ";\n");
15530 switch (AsmPieces.size()) {
15531 default: return false;
15533 // FIXME: this should verify that we are targeting a 486 or better. If not,
15534 // we will turn this bswap into something that will be lowered to logical
15535 // ops instead of emitting the bswap asm. For now, we don't support 486 or
15536 // lower so don't worry about this.
15538 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
15539 matchAsm(AsmPieces[0], "bswapl", "$0") ||
15540 matchAsm(AsmPieces[0], "bswapq", "$0") ||
15541 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
15542 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
15543 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
15544 // No need to check constraints, nothing other than the equivalent of
15545 // "=r,0" would be valid here.
15546 return IntrinsicLowering::LowerToByteSwap(CI);
15549 // rorw $$8, ${0:w} --> llvm.bswap.i16
15550 if (CI->getType()->isIntegerTy(16) &&
15551 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15552 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
15553 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
15555 const std::string &ConstraintsStr = IA->getConstraintString();
15556 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15557 std::sort(AsmPieces.begin(), AsmPieces.end());
15558 if (AsmPieces.size() == 4 &&
15559 AsmPieces[0] == "~{cc}" &&
15560 AsmPieces[1] == "~{dirflag}" &&
15561 AsmPieces[2] == "~{flags}" &&
15562 AsmPieces[3] == "~{fpsr}")
15563 return IntrinsicLowering::LowerToByteSwap(CI);
15567 if (CI->getType()->isIntegerTy(32) &&
15568 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
15569 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
15570 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
15571 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
15573 const std::string &ConstraintsStr = IA->getConstraintString();
15574 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15575 std::sort(AsmPieces.begin(), AsmPieces.end());
15576 if (AsmPieces.size() == 4 &&
15577 AsmPieces[0] == "~{cc}" &&
15578 AsmPieces[1] == "~{dirflag}" &&
15579 AsmPieces[2] == "~{flags}" &&
15580 AsmPieces[3] == "~{fpsr}")
15581 return IntrinsicLowering::LowerToByteSwap(CI);
15584 if (CI->getType()->isIntegerTy(64)) {
15585 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15586 if (Constraints.size() >= 2 &&
15587 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15588 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15589 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
15590 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
15591 matchAsm(AsmPieces[1], "bswap", "%edx") &&
15592 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
15593 return IntrinsicLowering::LowerToByteSwap(CI);
15603 /// getConstraintType - Given a constraint letter, return the type of
15604 /// constraint it is for this target.
15605 X86TargetLowering::ConstraintType
15606 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15607 if (Constraint.size() == 1) {
15608 switch (Constraint[0]) {
15619 return C_RegisterClass;
15643 return TargetLowering::getConstraintType(Constraint);
15646 /// Examine constraint type and operand type and determine a weight value.
15647 /// This object must already have been set up with the operand type
15648 /// and the current alternative constraint selected.
15649 TargetLowering::ConstraintWeight
15650 X86TargetLowering::getSingleConstraintMatchWeight(
15651 AsmOperandInfo &info, const char *constraint) const {
15652 ConstraintWeight weight = CW_Invalid;
15653 Value *CallOperandVal = info.CallOperandVal;
15654 // If we don't have a value, we can't do a match,
15655 // but allow it at the lowest weight.
15656 if (CallOperandVal == NULL)
15658 Type *type = CallOperandVal->getType();
15659 // Look at the constraint type.
15660 switch (*constraint) {
15662 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15673 if (CallOperandVal->getType()->isIntegerTy())
15674 weight = CW_SpecificReg;
15679 if (type->isFloatingPointTy())
15680 weight = CW_SpecificReg;
15683 if (type->isX86_MMXTy() && Subtarget->hasMMX())
15684 weight = CW_SpecificReg;
15688 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
15689 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasAVX()))
15690 weight = CW_Register;
15693 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15694 if (C->getZExtValue() <= 31)
15695 weight = CW_Constant;
15699 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15700 if (C->getZExtValue() <= 63)
15701 weight = CW_Constant;
15705 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15706 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15707 weight = CW_Constant;
15711 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15712 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15713 weight = CW_Constant;
15717 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15718 if (C->getZExtValue() <= 3)
15719 weight = CW_Constant;
15723 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15724 if (C->getZExtValue() <= 0xff)
15725 weight = CW_Constant;
15730 if (dyn_cast<ConstantFP>(CallOperandVal)) {
15731 weight = CW_Constant;
15735 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15736 if ((C->getSExtValue() >= -0x80000000LL) &&
15737 (C->getSExtValue() <= 0x7fffffffLL))
15738 weight = CW_Constant;
15742 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15743 if (C->getZExtValue() <= 0xffffffff)
15744 weight = CW_Constant;
15751 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15752 /// with another that has more specific requirements based on the type of the
15753 /// corresponding operand.
15754 const char *X86TargetLowering::
15755 LowerXConstraint(EVT ConstraintVT) const {
15756 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15757 // 'f' like normal targets.
15758 if (ConstraintVT.isFloatingPoint()) {
15759 if (Subtarget->hasSSE2())
15761 if (Subtarget->hasSSE1())
15765 return TargetLowering::LowerXConstraint(ConstraintVT);
15768 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15769 /// vector. If it is invalid, don't add anything to Ops.
15770 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15771 std::string &Constraint,
15772 std::vector<SDValue>&Ops,
15773 SelectionDAG &DAG) const {
15774 SDValue Result(0, 0);
15776 // Only support length 1 constraints for now.
15777 if (Constraint.length() > 1) return;
15779 char ConstraintLetter = Constraint[0];
15780 switch (ConstraintLetter) {
15783 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15784 if (C->getZExtValue() <= 31) {
15785 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15791 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15792 if (C->getZExtValue() <= 63) {
15793 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15799 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15800 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15801 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15807 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15808 if (C->getZExtValue() <= 255) {
15809 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15815 // 32-bit signed value
15816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15817 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15818 C->getSExtValue())) {
15819 // Widen to 64 bits here to get it sign extended.
15820 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15823 // FIXME gcc accepts some relocatable values here too, but only in certain
15824 // memory models; it's complicated.
15829 // 32-bit unsigned value
15830 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15831 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15832 C->getZExtValue())) {
15833 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15837 // FIXME gcc accepts some relocatable values here too, but only in certain
15838 // memory models; it's complicated.
15842 // Literal immediates are always ok.
15843 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15844 // Widen to 64 bits here to get it sign extended.
15845 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15849 // In any sort of PIC mode addresses need to be computed at runtime by
15850 // adding in a register or some sort of table lookup. These can't
15851 // be used as immediates.
15852 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15855 // If we are in non-pic codegen mode, we allow the address of a global (with
15856 // an optional displacement) to be used with 'i'.
15857 GlobalAddressSDNode *GA = 0;
15858 int64_t Offset = 0;
15860 // Match either (GA), (GA+C), (GA+C1+C2), etc.
15862 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15863 Offset += GA->getOffset();
15865 } else if (Op.getOpcode() == ISD::ADD) {
15866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15867 Offset += C->getZExtValue();
15868 Op = Op.getOperand(0);
15871 } else if (Op.getOpcode() == ISD::SUB) {
15872 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15873 Offset += -C->getZExtValue();
15874 Op = Op.getOperand(0);
15879 // Otherwise, this isn't something we can handle, reject it.
15883 const GlobalValue *GV = GA->getGlobal();
15884 // If we require an extra load to get this address, as in PIC mode, we
15885 // can't accept it.
15886 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15887 getTargetMachine())))
15890 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15891 GA->getValueType(0), Offset);
15896 if (Result.getNode()) {
15897 Ops.push_back(Result);
15900 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15903 std::pair<unsigned, const TargetRegisterClass*>
15904 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15906 // First, see if this is a constraint that directly corresponds to an LLVM
15908 if (Constraint.size() == 1) {
15909 // GCC Constraint Letters
15910 switch (Constraint[0]) {
15912 // TODO: Slight differences here in allocation order and leaving
15913 // RIP in the class. Do they matter any more here than they do
15914 // in the normal allocation?
15915 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15916 if (Subtarget->is64Bit()) {
15917 if (VT == MVT::i32 || VT == MVT::f32)
15918 return std::make_pair(0U, &X86::GR32RegClass);
15919 if (VT == MVT::i16)
15920 return std::make_pair(0U, &X86::GR16RegClass);
15921 if (VT == MVT::i8 || VT == MVT::i1)
15922 return std::make_pair(0U, &X86::GR8RegClass);
15923 if (VT == MVT::i64 || VT == MVT::f64)
15924 return std::make_pair(0U, &X86::GR64RegClass);
15927 // 32-bit fallthrough
15928 case 'Q': // Q_REGS
15929 if (VT == MVT::i32 || VT == MVT::f32)
15930 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
15931 if (VT == MVT::i16)
15932 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
15933 if (VT == MVT::i8 || VT == MVT::i1)
15934 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
15935 if (VT == MVT::i64)
15936 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
15938 case 'r': // GENERAL_REGS
15939 case 'l': // INDEX_REGS
15940 if (VT == MVT::i8 || VT == MVT::i1)
15941 return std::make_pair(0U, &X86::GR8RegClass);
15942 if (VT == MVT::i16)
15943 return std::make_pair(0U, &X86::GR16RegClass);
15944 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15945 return std::make_pair(0U, &X86::GR32RegClass);
15946 return std::make_pair(0U, &X86::GR64RegClass);
15947 case 'R': // LEGACY_REGS
15948 if (VT == MVT::i8 || VT == MVT::i1)
15949 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
15950 if (VT == MVT::i16)
15951 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
15952 if (VT == MVT::i32 || !Subtarget->is64Bit())
15953 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
15954 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
15955 case 'f': // FP Stack registers.
15956 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15957 // value to the correct fpstack register class.
15958 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15959 return std::make_pair(0U, &X86::RFP32RegClass);
15960 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15961 return std::make_pair(0U, &X86::RFP64RegClass);
15962 return std::make_pair(0U, &X86::RFP80RegClass);
15963 case 'y': // MMX_REGS if MMX allowed.
15964 if (!Subtarget->hasMMX()) break;
15965 return std::make_pair(0U, &X86::VR64RegClass);
15966 case 'Y': // SSE_REGS if SSE2 allowed
15967 if (!Subtarget->hasSSE2()) break;
15969 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
15970 if (!Subtarget->hasSSE1()) break;
15972 switch (VT.getSimpleVT().SimpleTy) {
15974 // Scalar SSE types.
15977 return std::make_pair(0U, &X86::FR32RegClass);
15980 return std::make_pair(0U, &X86::FR64RegClass);
15988 return std::make_pair(0U, &X86::VR128RegClass);
15996 return std::make_pair(0U, &X86::VR256RegClass);
16002 // Use the default implementation in TargetLowering to convert the register
16003 // constraint into a member of a register class.
16004 std::pair<unsigned, const TargetRegisterClass*> Res;
16005 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
16007 // Not found as a standard register?
16008 if (Res.second == 0) {
16009 // Map st(0) -> st(7) -> ST0
16010 if (Constraint.size() == 7 && Constraint[0] == '{' &&
16011 tolower(Constraint[1]) == 's' &&
16012 tolower(Constraint[2]) == 't' &&
16013 Constraint[3] == '(' &&
16014 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
16015 Constraint[5] == ')' &&
16016 Constraint[6] == '}') {
16018 Res.first = X86::ST0+Constraint[4]-'0';
16019 Res.second = &X86::RFP80RegClass;
16023 // GCC allows "st(0)" to be called just plain "st".
16024 if (StringRef("{st}").equals_lower(Constraint)) {
16025 Res.first = X86::ST0;
16026 Res.second = &X86::RFP80RegClass;
16031 if (StringRef("{flags}").equals_lower(Constraint)) {
16032 Res.first = X86::EFLAGS;
16033 Res.second = &X86::CCRRegClass;
16037 // 'A' means EAX + EDX.
16038 if (Constraint == "A") {
16039 Res.first = X86::EAX;
16040 Res.second = &X86::GR32_ADRegClass;
16046 // Otherwise, check to see if this is a register class of the wrong value
16047 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
16048 // turn into {ax},{dx}.
16049 if (Res.second->hasType(VT))
16050 return Res; // Correct type already, nothing to do.
16052 // All of the single-register GCC register classes map their values onto
16053 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
16054 // really want an 8-bit or 32-bit register, map to the appropriate register
16055 // class and return the appropriate register.
16056 if (Res.second == &X86::GR16RegClass) {
16057 if (VT == MVT::i8) {
16058 unsigned DestReg = 0;
16059 switch (Res.first) {
16061 case X86::AX: DestReg = X86::AL; break;
16062 case X86::DX: DestReg = X86::DL; break;
16063 case X86::CX: DestReg = X86::CL; break;
16064 case X86::BX: DestReg = X86::BL; break;
16067 Res.first = DestReg;
16068 Res.second = &X86::GR8RegClass;
16070 } else if (VT == MVT::i32) {
16071 unsigned DestReg = 0;
16072 switch (Res.first) {
16074 case X86::AX: DestReg = X86::EAX; break;
16075 case X86::DX: DestReg = X86::EDX; break;
16076 case X86::CX: DestReg = X86::ECX; break;
16077 case X86::BX: DestReg = X86::EBX; break;
16078 case X86::SI: DestReg = X86::ESI; break;
16079 case X86::DI: DestReg = X86::EDI; break;
16080 case X86::BP: DestReg = X86::EBP; break;
16081 case X86::SP: DestReg = X86::ESP; break;
16084 Res.first = DestReg;
16085 Res.second = &X86::GR32RegClass;
16087 } else if (VT == MVT::i64) {
16088 unsigned DestReg = 0;
16089 switch (Res.first) {
16091 case X86::AX: DestReg = X86::RAX; break;
16092 case X86::DX: DestReg = X86::RDX; break;
16093 case X86::CX: DestReg = X86::RCX; break;
16094 case X86::BX: DestReg = X86::RBX; break;
16095 case X86::SI: DestReg = X86::RSI; break;
16096 case X86::DI: DestReg = X86::RDI; break;
16097 case X86::BP: DestReg = X86::RBP; break;
16098 case X86::SP: DestReg = X86::RSP; break;
16101 Res.first = DestReg;
16102 Res.second = &X86::GR64RegClass;
16105 } else if (Res.second == &X86::FR32RegClass ||
16106 Res.second == &X86::FR64RegClass ||
16107 Res.second == &X86::VR128RegClass) {
16108 // Handle references to XMM physical registers that got mapped into the
16109 // wrong class. This can happen with constraints like {xmm0} where the
16110 // target independent register mapper will just pick the first match it can
16111 // find, ignoring the required type.
16112 if (VT == MVT::f32)
16113 Res.second = &X86::FR32RegClass;
16114 else if (VT == MVT::f64)
16115 Res.second = &X86::FR64RegClass;
16116 else if (X86::VR128RegClass.hasType(VT))
16117 Res.second = &X86::VR128RegClass;