LLVM  10.0.0svn
X86ISelLowering.cpp
Go to the documentation of this file.
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that X86 uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "X86ISelLowering.h"
15 #include "Utils/X86ShuffleDecode.h"
16 #include "X86CallingConv.h"
17 #include "X86FrameLowering.h"
18 #include "X86InstrBuilder.h"
19 #include "X86IntrinsicsInfo.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/IR/CallSite.h"
39 #include "llvm/IR/CallingConv.h"
40 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/Instructions.h"
47 #include "llvm/IR/Intrinsics.h"
48 #include "llvm/MC/MCAsmInfo.h"
49 #include "llvm/MC/MCContext.h"
50 #include "llvm/MC/MCExpr.h"
51 #include "llvm/MC/MCSymbol.h"
53 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/KnownBits.h"
58 #include <algorithm>
59 #include <bitset>
60 #include <cctype>
61 #include <numeric>
62 using namespace llvm;
63 
64 #define DEBUG_TYPE "x86-isel"
65 
66 STATISTIC(NumTailCalls, "Number of tail calls");
67 
69  "x86-experimental-vector-widening-legalization", cl::init(false),
70  cl::desc("Enable an experimental vector type legalization through widening "
71  "rather than promotion."),
72  cl::Hidden);
73 
75  "x86-experimental-pref-loop-alignment", cl::init(4),
76  cl::desc("Sets the preferable loop alignment for experiments "
77  "(the last x86-experimental-pref-loop-alignment bits"
78  " of the loop header PC will be 0)."),
79  cl::Hidden);
80 
82  "mul-constant-optimization", cl::init(true),
83  cl::desc("Replace 'mul x, Const' with more effective instructions like "
84  "SHIFT, LEA, etc."),
85  cl::Hidden);
86 
87 /// Call this when the user attempts to do something unsupported, like
88 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
89 /// report_fatal_error, so calling code should attempt to recover without
90 /// crashing.
91 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
92  const char *Msg) {
94  DAG.getContext()->diagnose(
96 }
97 
99  const X86Subtarget &STI)
100  : TargetLowering(TM), Subtarget(STI) {
101  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
102  X86ScalarSSEf64 = Subtarget.hasSSE2();
103  X86ScalarSSEf32 = Subtarget.hasSSE1();
105 
106  // Set up the TargetLowering object.
107 
108  // X86 is weird. It always uses i8 for shift amounts and setcc results.
110  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
112 
113  // For 64-bit, since we have so many registers, use the ILP scheduler.
114  // For 32-bit, use the register pressure specific scheduling.
115  // For Atom, always use ILP scheduling.
116  if (Subtarget.isAtom())
118  else if (Subtarget.is64Bit())
120  else
122  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
124 
125  // Bypass expensive divides and use cheaper ones.
126  if (TM.getOptLevel() >= CodeGenOpt::Default) {
127  if (Subtarget.hasSlowDivide32())
128  addBypassSlowDiv(32, 8);
129  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
130  addBypassSlowDiv(64, 32);
131  }
132 
133  if (Subtarget.isTargetWindowsMSVC() ||
134  Subtarget.isTargetWindowsItanium()) {
135  // Setup Windows compiler runtime calls.
136  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
137  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
138  setLibcallName(RTLIB::SREM_I64, "_allrem");
139  setLibcallName(RTLIB::UREM_I64, "_aullrem");
140  setLibcallName(RTLIB::MUL_I64, "_allmul");
146  }
147 
148  if (Subtarget.isTargetDarwin()) {
149  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
150  setUseUnderscoreSetJmp(false);
152  } else if (Subtarget.isTargetWindowsGNU()) {
153  // MS runtime is weird: it exports _setjmp, but longjmp!
156  } else {
159  }
160 
161  // If we don't have cmpxchg8b(meaing this is a 386/486), limit atomic size to
162  // 32 bits so the AtomicExpandPass will expand it so we don't need cmpxchg8b.
163  // FIXME: Should we be limitting the atomic size on other configs? Default is
164  // 1024.
165  if (!Subtarget.hasCmpxchg8b())
167 
168  // Set up the register classes.
169  addRegisterClass(MVT::i8, &X86::GR8RegClass);
170  addRegisterClass(MVT::i16, &X86::GR16RegClass);
171  addRegisterClass(MVT::i32, &X86::GR32RegClass);
172  if (Subtarget.is64Bit())
173  addRegisterClass(MVT::i64, &X86::GR64RegClass);
174 
175  for (MVT VT : MVT::integer_valuetypes())
177 
178  // We don't accept any truncstore of integer registers.
185 
187 
188  // SETOEQ and SETUNE require checking two conditions.
195 
196  // Integer absolute.
197  if (Subtarget.hasCMov()) {
200  }
202 
203  // Funnel shifts.
204  for (auto ShiftOp : {ISD::FSHL, ISD::FSHR}) {
205  setOperationAction(ShiftOp , MVT::i16 , Custom);
206  setOperationAction(ShiftOp , MVT::i32 , Custom);
207  if (Subtarget.is64Bit())
208  setOperationAction(ShiftOp , MVT::i64 , Custom);
209  }
210 
211  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
212  // operation.
216 
217  if (Subtarget.is64Bit()) {
218  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
219  // f32/f64 are legal, f80 is custom.
221  else
224  } else if (!Subtarget.useSoftFloat()) {
225  // We have an algorithm for SSE2->double, and we turn this into a
226  // 64-bit FILD followed by conditional FADD for other targets.
228  // We have an algorithm for SSE2, and we turn this into a 64-bit
229  // FILD or VCVTUSI2SS/SD for other targets.
231  } else {
233  }
234 
235  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
236  // this operation.
239 
240  if (!Subtarget.useSoftFloat()) {
241  // SSE has no i16 to fp conversion, only i32.
242  if (X86ScalarSSEf32) {
244  // f32 and f64 cases are Legal, f80 case is not
246  } else {
249  }
250  } else {
253  }
254 
255  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
256  // this operation.
259 
260  if (!Subtarget.useSoftFloat()) {
261  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
262  // are Legal, f80 is custom lowered.
265 
268  } else {
272  }
273 
274  // Handle FP_TO_UINT by promoting the destination to a larger signed
275  // conversion.
279 
280  if (Subtarget.is64Bit()) {
281  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
282  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
285  } else {
288  }
289  } else if (!Subtarget.useSoftFloat()) {
290  // Since AVX is a superset of SSE3, only check for SSE here.
291  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
292  // Expand FP_TO_UINT into a select.
293  // FIXME: We would like to use a Custom expander here eventually to do
294  // the optimal thing for SSE vs. the default expansion in the legalizer.
296  else
297  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
298  // With SSE3 we can use fisttpll to convert to a signed i64; without
299  // SSE, we're stuck with a fistpll.
301 
303  }
304 
305  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
306  if (!X86ScalarSSEf64) {
309  if (Subtarget.is64Bit()) {
311  // Without SSE, i64->f64 goes through memory.
313  }
314  } else if (!Subtarget.is64Bit())
316 
317  // Scalar integer divide and remainder are lowered to use operations that
318  // produce two results, to match the available instructions. This exposes
319  // the two-result form to trivial CSE, which is able to combine x/y and x%y
320  // into a single instruction.
321  //
322  // Scalar integer multiply-high is also lowered to use two-result
323  // operations, to match the available instructions. However, plain multiply
324  // (low) operations are left as Legal, as there are single-result
325  // instructions for this in x86. Using the two-result multiply instructions
326  // when both high and low results are needed must be arranged by dagcombine.
327  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
334  }
335 
338  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
342  }
343  if (Subtarget.is64Bit())
349 
354 
355  // Promote the i8 variants and force them on up to i32 which has a shorter
356  // encoding.
359  if (!Subtarget.hasBMI()) {
364  if (Subtarget.is64Bit()) {
367  }
368  }
369 
370  if (Subtarget.hasLZCNT()) {
371  // When promoting the i8 variants, force them to i32 for a shorter
372  // encoding.
375  } else {
382  if (Subtarget.is64Bit()) {
385  }
386  }
387 
388  // Special handling for half-precision floating point conversions.
389  // If we don't have F16C support, then lower half float conversions
390  // into library calls.
391  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
394  }
395 
396  // There's never any support for operations beyond MVT::f32.
401 
408 
409  if (Subtarget.hasPOPCNT()) {
411  } else {
415  if (Subtarget.is64Bit())
417  else
419  }
420 
422 
423  if (!Subtarget.hasMOVBE())
425 
426  // These should be promoted to a larger select which is supported.
428  // X86 wants to expand cmov itself.
429  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
432  }
433  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
434  if (VT == MVT::i64 && !Subtarget.is64Bit())
435  continue;
438  }
439 
440  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
443 
445  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
446  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
451  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
452 
453  // Darwin ABI issue.
454  for (auto VT : { MVT::i32, MVT::i64 }) {
455  if (VT == MVT::i64 && !Subtarget.is64Bit())
456  continue;
463  }
464 
465  // 64-bit shl, sra, srl (iff 32-bit x86)
466  for (auto VT : { MVT::i32, MVT::i64 }) {
467  if (VT == MVT::i64 && !Subtarget.is64Bit())
468  continue;
472  }
473 
474  if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
476 
478 
479  // Expand certain atomics
480  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
488  }
489 
490  if (!Subtarget.is64Bit())
492 
493  if (Subtarget.hasCmpxchg16b()) {
495  }
496 
497  // FIXME - use subtarget debug flags
498  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
499  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
502  }
503 
506 
509 
512 
513  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
516  bool Is64Bit = Subtarget.is64Bit();
518  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
519 
522 
524 
525  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
528 
529  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
530  // f32 and f64 use SSE.
531  // Set up the FP register classes.
532  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
533  : &X86::FR32RegClass);
534  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
535  : &X86::FR64RegClass);
536 
537  // Disable f32->f64 extload as we can only generate this in one instruction
538  // under optsize. So its easier to pattern match (fpext (load)) for that
539  // case instead of needing to emit 2 instructions for extload in the
540  // non-optsize case.
542 
543  for (auto VT : { MVT::f32, MVT::f64 }) {
544  // Use ANDPD to simulate FABS.
546 
547  // Use XORP to simulate FNEG.
549 
550  // Use ANDPD and ORPD to simulate FCOPYSIGN.
552 
553  // These might be better off as horizontal vector ops.
556 
557  // We don't support sin/cos/fmod
558  setOperationAction(ISD::FSIN , VT, Expand);
559  setOperationAction(ISD::FCOS , VT, Expand);
560  setOperationAction(ISD::FSINCOS, VT, Expand);
561  }
562 
563  // Lower this to MOVMSK plus an AND.
566 
567  } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
568  // Use SSE for f32, x87 for f64.
569  // Set up the FP register classes.
570  addRegisterClass(MVT::f32, &X86::FR32RegClass);
571  if (UseX87)
572  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
573 
574  // Use ANDPS to simulate FABS.
576 
577  // Use XORP to simulate FNEG.
579 
580  if (UseX87)
582 
583  // Use ANDPS and ORPS to simulate FCOPYSIGN.
584  if (UseX87)
587 
588  // We don't support sin/cos/fmod
592 
593  if (UseX87) {
594  // Always expand sin/cos functions even though x87 has an instruction.
598  }
599  } else if (UseX87) {
600  // f32 and f64 in x87.
601  // Set up the FP register classes.
602  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
603  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
604 
605  for (auto VT : { MVT::f32, MVT::f64 }) {
606  setOperationAction(ISD::UNDEF, VT, Expand);
607  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
608 
609  // Always expand sin/cos functions even though x87 has an instruction.
610  setOperationAction(ISD::FSIN , VT, Expand);
611  setOperationAction(ISD::FCOS , VT, Expand);
612  setOperationAction(ISD::FSINCOS, VT, Expand);
613  }
614  }
615 
616  // Expand FP32 immediates into loads from the stack, save special cases.
617  if (isTypeLegal(MVT::f32)) {
618  if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
619  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
620  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
621  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
622  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
623  } else // SSE immediates.
624  addLegalFPImmediate(APFloat(+0.0f)); // xorps
625  }
626  // Expand FP64 immediates into loads from the stack, save special cases.
627  if (isTypeLegal(MVT::f64)) {
628  if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
629  addLegalFPImmediate(APFloat(+0.0)); // FLD0
630  addLegalFPImmediate(APFloat(+1.0)); // FLD1
631  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
632  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
633  } else // SSE immediates.
634  addLegalFPImmediate(APFloat(+0.0)); // xorpd
635  }
636 
637  // We don't support FMA.
640 
641  // Long double always uses X87, except f128 in MMX.
642  if (UseX87) {
643  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
644  addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
645  : &X86::VR128RegClass);
650  }
651 
652  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
655  {
657  addLegalFPImmediate(TmpFlt); // FLD0
658  TmpFlt.changeSign();
659  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
660 
661  bool ignored;
662  APFloat TmpFlt2(+1.0);
664  &ignored);
665  addLegalFPImmediate(TmpFlt2); // FLD1
666  TmpFlt2.changeSign();
667  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
668  }
669 
670  // Always expand sin/cos functions even though x87 has an instruction.
674 
685  }
686 
687  // Always use a library call for pow.
691 
699 
700  // Some FP actions are always expanded for vector types.
701  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
703  setOperationAction(ISD::FSIN, VT, Expand);
704  setOperationAction(ISD::FSINCOS, VT, Expand);
705  setOperationAction(ISD::FCOS, VT, Expand);
706  setOperationAction(ISD::FREM, VT, Expand);
707  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
708  setOperationAction(ISD::FPOW, VT, Expand);
709  setOperationAction(ISD::FLOG, VT, Expand);
710  setOperationAction(ISD::FLOG2, VT, Expand);
711  setOperationAction(ISD::FLOG10, VT, Expand);
712  setOperationAction(ISD::FEXP, VT, Expand);
713  setOperationAction(ISD::FEXP2, VT, Expand);
714  }
715 
716  // First set operation action for all vector types to either promote
717  // (for widening) or expand (for scalarization). Then we will selectively
718  // turn on ones that can be effectively codegen'd.
719  for (MVT VT : MVT::vector_valuetypes()) {
720  setOperationAction(ISD::SDIV, VT, Expand);
721  setOperationAction(ISD::UDIV, VT, Expand);
722  setOperationAction(ISD::SREM, VT, Expand);
723  setOperationAction(ISD::UREM, VT, Expand);
728  setOperationAction(ISD::FMA, VT, Expand);
729  setOperationAction(ISD::FFLOOR, VT, Expand);
730  setOperationAction(ISD::FCEIL, VT, Expand);
731  setOperationAction(ISD::FTRUNC, VT, Expand);
732  setOperationAction(ISD::FRINT, VT, Expand);
733  setOperationAction(ISD::FNEARBYINT, VT, Expand);
734  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
735  setOperationAction(ISD::MULHS, VT, Expand);
736  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
737  setOperationAction(ISD::MULHU, VT, Expand);
738  setOperationAction(ISD::SDIVREM, VT, Expand);
739  setOperationAction(ISD::UDIVREM, VT, Expand);
740  setOperationAction(ISD::CTPOP, VT, Expand);
741  setOperationAction(ISD::CTTZ, VT, Expand);
742  setOperationAction(ISD::CTLZ, VT, Expand);
743  setOperationAction(ISD::ROTL, VT, Expand);
744  setOperationAction(ISD::ROTR, VT, Expand);
745  setOperationAction(ISD::BSWAP, VT, Expand);
746  setOperationAction(ISD::SETCC, VT, Expand);
747  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
748  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
749  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
750  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
752  setOperationAction(ISD::TRUNCATE, VT, Expand);
755  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
756  setOperationAction(ISD::SELECT_CC, VT, Expand);
757  for (MVT InnerVT : MVT::vector_valuetypes()) {
758  setTruncStoreAction(InnerVT, VT, Expand);
759 
760  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
761  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
762 
763  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
764  // types, we have to deal with them whether we ask for Expansion or not.
765  // Setting Expand causes its own optimisation problems though, so leave
766  // them legal.
767  if (VT.getVectorElementType() == MVT::i1)
768  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
769 
770  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
771  // split/scalarized right now.
772  if (VT.getVectorElementType() == MVT::f16)
773  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
774  }
775  }
776 
777  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
778  // with -msoft-float, disable use of MMX as well.
779  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
780  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
781  // No operations on x86mmx supported, everything uses intrinsics.
782  }
783 
784  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
785  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
786  : &X86::VR128RegClass);
787 
797 
800  }
801 
802  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
803  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
804  : &X86::VR128RegClass);
805 
806  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
807  // registers cannot be used even for integer operations.
808  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
809  : &X86::VR128RegClass);
810  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
811  : &X86::VR128RegClass);
812  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
813  : &X86::VR128RegClass);
814  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
815  : &X86::VR128RegClass);
816 
817  for (auto VT : { MVT::v2i8, MVT::v4i8, MVT::v8i8,
823  }
824 
831 
845 
846  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
848  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
849  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
850  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
851  }
852 
865 
867  // Use widening instead of promotion.
868  for (auto VT : { MVT::v8i8, MVT::v4i8, MVT::v2i8,
869  MVT::v4i16, MVT::v2i16 }) {
874  }
875  }
876 
880 
881  // Provide custom widening for v2f32 setcc. This is really for VLX when
882  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
883  // type legalization changing the result type to v4i1 during widening.
884  // It works fine for SSE2 and is probably faster so no need to qualify with
885  // VLX support.
887 
888  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
892 
893  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
894  // setcc all the way to isel and prefer SETGT in some isel patterns.
897  }
898 
899  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
905  }
906 
907  // We support custom legalizing of sext and anyext loads for specific
908  // memory vector types which we can load as a scalar (or sequence of
909  // scalars) and extend in-register to a legal 128-bit vector type. For sext
910  // loads these must work with a single scalar load.
911  for (MVT VT : MVT::integer_vector_valuetypes()) {
918  }
919 
920  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
924 
925  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
926  continue;
927 
930  }
931 
932  // Custom lower v2i64 and v2f64 selects.
938 
942 
943  // Custom legalize these to avoid over promotion or custom promotion.
954 
955  // By marking FP_TO_SINT v8i16 as Custom, will trick type legalization into
956  // promoting v8i8 FP_TO_UINT into FP_TO_SINT. When the v8i16 FP_TO_SINT is
957  // split again based on the input type, this will cause an AssertSExt i16 to
958  // be emitted instead of an AssertZExt. This will allow packssdw followed by
959  // packuswb to be used to truncate to v8i8. This is necessary since packusdw
960  // isn't available until sse4.1.
962 
965 
967 
968  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
970 
973 
974  // We want to legalize this to an f64 load rather than an i64 load on
975  // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
976  // store.
983 
987  if (!Subtarget.hasAVX512())
989 
993 
996 
1003  } else {
1005  }
1006 
1007  // In the customized shift lowering, the legal v4i32/v2i64 cases
1008  // in AVX2 will be recognized.
1009  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1013  }
1014 
1017 
1018  // With AVX512, expanding (and promoting the shifts) is better.
1019  if (!Subtarget.hasAVX512())
1021  }
1022 
1023  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
1032 
1033  // These might be better off as horizontal vector ops.
1038  }
1039 
1040  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
1041  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
1042  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
1043  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
1044  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
1045  setOperationAction(ISD::FRINT, RoundedTy, Legal);
1047  }
1048 
1057 
1058  // FIXME: Do we need to handle scalar-to-vector here?
1060 
1061  // We directly match byte blends in the backend as they match the VSELECT
1062  // condition form.
1064 
1065  // SSE41 brings specific instructions for doing vector sign extend even in
1066  // cases where we don't have SRA.
1067  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1070  }
1071 
1073  // Avoid narrow result types when widening. The legal types are listed
1074  // in the next loop.
1075  for (MVT VT : MVT::integer_vector_valuetypes()) {
1079  }
1080  }
1081 
1082  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1083  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1092  }
1093 
1094  // i8 vectors are custom because the source register and source
1095  // source memory operand types are not the same width.
1097  }
1098 
1099  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1100  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1103 
1104  // XOP can efficiently perform BITREVERSE with VPPERM.
1105  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1107 
1108  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1111  }
1112 
1113  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1114  bool HasInt256 = Subtarget.hasInt256();
1115 
1116  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1117  : &X86::VR256RegClass);
1118  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1119  : &X86::VR256RegClass);
1120  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1121  : &X86::VR256RegClass);
1122  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1123  : &X86::VR256RegClass);
1124  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1125  : &X86::VR256RegClass);
1126  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1127  : &X86::VR256RegClass);
1128 
1129  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1138  }
1139 
1140  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1141  // even though v8i16 is a legal type.
1145 
1147 
1148  if (!Subtarget.hasAVX512())
1150 
1151  // In the customized shift lowering, the legal v8i32/v4i64 cases
1152  // in AVX2 will be recognized.
1153  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1157  }
1158 
1159  // These types need custom splitting if their input is a 128-bit vector.
1164 
1167 
1168  // With BWI, expanding (and promoting the shifts) is the better.
1169  if (!Subtarget.hasBWI())
1171 
1178 
1179  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1183  }
1184 
1189 
1190  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1194 
1195  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1196  // setcc all the way to isel and prefer SETGT in some isel patterns.
1199  }
1200 
1201  if (Subtarget.hasAnyFMA()) {
1202  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1205  }
1206 
1207  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1208  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1209  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1210  }
1211 
1214  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1216 
1219  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1220  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1223 
1229 
1230  setOperationAction(ISD::UADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1231  setOperationAction(ISD::SADDSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1232  setOperationAction(ISD::USUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1233  setOperationAction(ISD::SSUBSAT, MVT::v32i8, HasInt256 ? Legal : Custom);
1234  setOperationAction(ISD::UADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1235  setOperationAction(ISD::SADDSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1236  setOperationAction(ISD::USUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1237  setOperationAction(ISD::SSUBSAT, MVT::v16i16, HasInt256 ? Legal : Custom);
1238 
1239  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1240  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1241  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1242  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1243  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1244  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1245  }
1246 
1247  for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1250  }
1251 
1252  if (HasInt256) {
1253  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1254  // when we have a 256bit-wide blend with immediate.
1256 
1257  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1258  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1265  }
1266  }
1267 
1268  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1270  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1272  }
1273 
1274  // Extract subvector is special because the value type
1275  // (result) is 128-bit but the source is 256-bit wide.
1276  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1277  MVT::v4f32, MVT::v2f64 }) {
1279  }
1280 
1281  // Custom lower several nodes for 256-bit types.
1283  MVT::v8f32, MVT::v4f64 }) {
1286  setOperationAction(ISD::VSELECT, VT, Custom);
1292  setOperationAction(ISD::STORE, VT, Custom);
1293  }
1294 
1295  if (HasInt256)
1297 
1298  if (HasInt256) {
1299  // Custom legalize 2x32 to get a little better code.
1302 
1303  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1305  setOperationAction(ISD::MGATHER, VT, Custom);
1306  }
1307  }
1308 
1309  // This block controls legalization of the mask vector sizes that are
1310  // available with AVX512. 512-bit vectors are in a separate block controlled
1311  // by useAVX512Regs.
1312  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1313  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1314  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1315  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1316  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1317  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1318 
1322 
1329 
1330  // There is no byte sized k-register load or store without AVX512DQ.
1331  if (!Subtarget.hasDQI()) {
1336 
1341  }
1342 
1343  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1344  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1348  }
1349 
1350  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1361 
1368  setOperationAction(ISD::VSELECT, VT, Expand);
1369  }
1370 
1371  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1373  }
1374 
1375  // This block controls legalization for 512-bit operations with 32/64 bit
1376  // elements. 512-bits can be disabled based on prefer-vector-width and
1377  // required-vector-width function attributes.
1378  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1379  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1380  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1381  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1382  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1383 
1384  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1390  }
1391 
1392  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1397  }
1398 
1409 
1415 
1416  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1417  // to 512-bit rather than use the AVX2 instructions so that we can use
1418  // k-masks.
1419  if (!Subtarget.hasVLX()) {
1420  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1424  }
1425  }
1426 
1435 
1437  // Need to custom widen this if we don't have AVX512BW.
1441  }
1442 
1443  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1449 
1451  }
1452 
1453  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1454  for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1457  }
1458 
1463 
1466 
1469 
1470  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1484 
1485  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1486  // setcc all the way to isel and prefer SETGT in some isel patterns.
1489  }
1490 
1491  if (Subtarget.hasDQI()) {
1496 
1498  }
1499 
1500  if (Subtarget.hasCDI()) {
1501  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1502  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1504  }
1505  } // Subtarget.hasCDI()
1506 
1507  if (Subtarget.hasVPOPCNTDQ()) {
1508  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1510  }
1511 
1512  // Extract subvector is special because the value type
1513  // (result) is 256-bit but the source is 512-bit wide.
1514  // 128-bit was made Legal under AVX1.
1515  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1518 
1519  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1531  }
1532  // Need to custom split v32i16/v64i8 bitcasts.
1533  if (!Subtarget.hasBWI()) {
1536  }
1537 
1538  if (Subtarget.hasVBMI2()) {
1539  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1542  }
1543  }
1544  }// has AVX-512
1545 
1546  // This block controls legalization for operations that don't have
1547  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1548  // narrower widths.
1549  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1550  // These operations are handled on non-VLX by artificially widening in
1551  // isel patterns.
1552  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1553 
1559 
1560  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1566  }
1567 
1568  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1571  }
1572 
1573  // Custom legalize 2x32 to get a little better code.
1576 
1577  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1580 
1581  if (Subtarget.hasDQI()) {
1582  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1587 
1589  }
1590  }
1591 
1592  if (Subtarget.hasCDI()) {
1593  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1595  }
1596  } // Subtarget.hasCDI()
1597 
1598  if (Subtarget.hasVPOPCNTDQ()) {
1599  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1601  }
1602  }
1603 
1604  // This block control legalization of v32i1/v64i1 which are available with
1605  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1606  // useBWIRegs.
1607  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1608  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1609  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1610 
1611  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1615  setOperationAction(ISD::VSELECT, VT, Expand);
1620 
1628  }
1629 
1634  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1636 
1637  // Extends from v32i1 masks to 256-bit vectors.
1641  }
1642 
1643  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1644  // disabled based on prefer-vector-width and required-vector-width function
1645  // attributes.
1646  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1647  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1648  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1649 
1650  // Extends from v64i1 masks to 512-bit vectors.
1654 
1678 
1681 
1683 
1684  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1705 
1706  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1707  // setcc all the way to isel and prefer SETGT in some isel patterns.
1710  }
1711 
1712  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1714  }
1715 
1716  if (Subtarget.hasBITALG()) {
1717  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1719  }
1720 
1721  if (Subtarget.hasVBMI2()) {
1724  }
1725  }
1726 
1727  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1728  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1729  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1730  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1731  }
1732 
1733  // These operations are handled on non-VLX by artificially widening in
1734  // isel patterns.
1735  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1736 
1737  if (Subtarget.hasBITALG()) {
1738  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1740  }
1741  }
1742 
1743  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1749 
1755 
1756  if (Subtarget.hasDQI()) {
1757  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1758  // v2f32 UINT_TO_FP is already custom under SSE2.
1761  "Unexpected operation action!");
1762  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1765  }
1766 
1767  if (Subtarget.hasBWI()) {
1770  }
1771 
1772  if (Subtarget.hasVBMI2()) {
1773  // TODO: Make these legal even without VLX?
1774  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64,
1778  }
1779  }
1780  }
1781 
1782  // We want to custom lower some of our intrinsics.
1786  if (!Subtarget.is64Bit()) {
1788  }
1789 
1790  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1791  // handle type legalization for these operations here.
1792  //
1793  // FIXME: We really should do custom legalization for addition and
1794  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1795  // than generic legalization for 64-bit multiplication-with-overflow, though.
1796  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1797  if (VT == MVT::i64 && !Subtarget.is64Bit())
1798  continue;
1799  // Add/Sub/Mul with overflow operations are custom lowered.
1806 
1807  // Support carry in as value rather than glue.
1811  }
1812 
1813  if (!Subtarget.is64Bit()) {
1814  // These libcalls are not available in 32-bit.
1815  setLibcallName(RTLIB::SHL_I128, nullptr);
1816  setLibcallName(RTLIB::SRL_I128, nullptr);
1817  setLibcallName(RTLIB::SRA_I128, nullptr);
1818  setLibcallName(RTLIB::MUL_I128, nullptr);
1819  }
1820 
1821  // Combine sin / cos into _sincos_stret if it is available.
1822  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1823  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1826  }
1827 
1828  if (Subtarget.isTargetWin64()) {
1835  }
1836 
1837  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1838  // is. We should promote the value to 64-bits to solve this.
1839  // This is what the CRT headers do - `fmodf` is an inline header
1840  // function casting to f64 and calling `fmod`.
1841  if (Subtarget.is32Bit() &&
1842  (Subtarget.isTargetWindowsMSVC() || Subtarget.isTargetWindowsItanium()))
1843  for (ISD::NodeType Op :
1848 
1849  // We have target-specific dag combine patterns for the following nodes:
1891 
1893 
1894  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1896  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1898  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1900 
1901  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1902  // that needs to benchmarked and balanced with the potential use of vector
1903  // load/store types (PR33329, PR33914).
1904  MaxLoadsPerMemcmp = 2;
1906 
1907  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1909 
1910  // An out-of-order CPU can speculatively execute past a predictable branch,
1911  // but a conditional move could be stalled by an expensive earlier operation.
1912  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1913  EnableExtLdPromotion = true;
1914  setPrefFunctionAlignment(4); // 2^4 bytes.
1915 
1917 }
1918 
1919 // This has so far only been implemented for 64-bit MachO.
1921  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1922 }
1923 
1925  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1926  return Subtarget.getTargetTriple().isOSMSVCRT();
1927 }
1928 
1930  const SDLoc &DL) const {
1931  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1932  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1933  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1934  return SDValue(Node, 0);
1935 }
1936 
1939  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1940  return TypeSplitVector;
1941 
1943  VT.getVectorNumElements() != 1 &&
1944  VT.getVectorElementType() != MVT::i1)
1945  return TypeWidenVector;
1946 
1948 }
1949 
1951  CallingConv::ID CC,
1952  EVT VT) const {
1953  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1954  return MVT::v32i8;
1955  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1956 }
1957 
1959  CallingConv::ID CC,
1960  EVT VT) const {
1961  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1962  return 1;
1963  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1964 }
1965 
1968  EVT VT) const {
1969  if (!VT.isVector())
1970  return MVT::i8;
1971 
1972  if (Subtarget.hasAVX512()) {
1973  const unsigned NumElts = VT.getVectorNumElements();
1974 
1975  // Figure out what this type will be legalized to.
1976  EVT LegalVT = VT;
1977  while (getTypeAction(Context, LegalVT) != TypeLegal)
1978  LegalVT = getTypeToTransformTo(Context, LegalVT);
1979 
1980  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1981  if (LegalVT.getSimpleVT().is512BitVector())
1982  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1983 
1984  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1985  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1986  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1987  // vXi16/vXi8.
1988  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1989  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1990  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1991  }
1992  }
1993 
1995 }
1996 
1997 /// Helper for getByValTypeAlignment to determine
1998 /// the desired ByVal argument alignment.
1999 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
2000  if (MaxAlign == 16)
2001  return;
2002  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
2003  if (VTy->getBitWidth() == 128)
2004  MaxAlign = 16;
2005  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
2006  unsigned EltAlign = 0;
2007  getMaxByValAlign(ATy->getElementType(), EltAlign);
2008  if (EltAlign > MaxAlign)
2009  MaxAlign = EltAlign;
2010  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
2011  for (auto *EltTy : STy->elements()) {
2012  unsigned EltAlign = 0;
2013  getMaxByValAlign(EltTy, EltAlign);
2014  if (EltAlign > MaxAlign)
2015  MaxAlign = EltAlign;
2016  if (MaxAlign == 16)
2017  break;
2018  }
2019  }
2020 }
2021 
2022 /// Return the desired alignment for ByVal aggregate
2023 /// function arguments in the caller parameter area. For X86, aggregates
2024 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
2025 /// are at 4-byte boundaries.
2027  const DataLayout &DL) const {
2028  if (Subtarget.is64Bit()) {
2029  // Max of 8 and alignment of type.
2030  unsigned TyAlign = DL.getABITypeAlignment(Ty);
2031  if (TyAlign > 8)
2032  return TyAlign;
2033  return 8;
2034  }
2035 
2036  unsigned Align = 4;
2037  if (Subtarget.hasSSE1())
2038  getMaxByValAlign(Ty, Align);
2039  return Align;
2040 }
2041 
2042 /// Returns the target specific optimal type for load
2043 /// and store operations as a result of memset, memcpy, and memmove
2044 /// lowering. If DstAlign is zero that means it's safe to destination
2045 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
2046 /// means there isn't a need to check it against alignment requirement,
2047 /// probably because the source does not need to be loaded. If 'IsMemset' is
2048 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
2049 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
2050 /// source is constant so it does not need to be loaded.
2051 /// It returns EVT::Other if the type should be determined using generic
2052 /// target-independent logic.
2053 /// For vector ops we check that the overall size isn't larger than our
2054 /// preferred vector width.
2056  uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
2057  bool ZeroMemset, bool MemcpyStrSrc,
2058  const AttributeList &FuncAttributes) const {
2059  if (!FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
2060  if (Size >= 16 && (!Subtarget.isUnalignedMem16Slow() ||
2061  ((DstAlign == 0 || DstAlign >= 16) &&
2062  (SrcAlign == 0 || SrcAlign >= 16)))) {
2063  // FIXME: Check if unaligned 32-byte accesses are slow.
2064  if (Size >= 32 && Subtarget.hasAVX() &&
2065  (Subtarget.getPreferVectorWidth() >= 256)) {
2066  // Although this isn't a well-supported type for AVX1, we'll let
2067  // legalization and shuffle lowering produce the optimal codegen. If we
2068  // choose an optimal type with a vector element larger than a byte,
2069  // getMemsetStores() may create an intermediate splat (using an integer
2070  // multiply) before we splat as a vector.
2071  return MVT::v32i8;
2072  }
2073  if (Subtarget.hasSSE2() && (Subtarget.getPreferVectorWidth() >= 128))
2074  return MVT::v16i8;
2075  // TODO: Can SSE1 handle a byte vector?
2076  // If we have SSE1 registers we should be able to use them.
2077  if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()) &&
2078  (Subtarget.getPreferVectorWidth() >= 128))
2079  return MVT::v4f32;
2080  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
2081  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
2082  // Do not use f64 to lower memcpy if source is string constant. It's
2083  // better to use i32 to avoid the loads.
2084  // Also, do not use f64 to lower memset unless this is a memset of zeros.
2085  // The gymnastics of splatting a byte value into an XMM register and then
2086  // only using 8-byte stores (because this is a CPU with slow unaligned
2087  // 16-byte accesses) makes that a loser.
2088  return MVT::f64;
2089  }
2090  }
2091  // This is a compromise. If we reach here, unaligned accesses may be slow on
2092  // this target. However, creating smaller, aligned accesses could be even
2093  // slower and would certainly be a lot more code.
2094  if (Subtarget.is64Bit() && Size >= 8)
2095  return MVT::i64;
2096  return MVT::i32;
2097 }
2098 
2100  if (VT == MVT::f32)
2101  return X86ScalarSSEf32;
2102  else if (VT == MVT::f64)
2103  return X86ScalarSSEf64;
2104  return true;
2105 }
2106 
2108  EVT VT, unsigned, unsigned Align, MachineMemOperand::Flags Flags,
2109  bool *Fast) const {
2110  if (Fast) {
2111  switch (VT.getSizeInBits()) {
2112  default:
2113  // 8-byte and under are always assumed to be fast.
2114  *Fast = true;
2115  break;
2116  case 128:
2117  *Fast = !Subtarget.isUnalignedMem16Slow();
2118  break;
2119  case 256:
2120  *Fast = !Subtarget.isUnalignedMem32Slow();
2121  break;
2122  // TODO: What about AVX-512 (512-bit) accesses?
2123  }
2124  }
2125  // NonTemporal vector memory ops must be aligned.
2126  if (!!(Flags & MachineMemOperand::MONonTemporal) && VT.isVector()) {
2127  // NT loads can only be vector aligned, so if its less aligned than the
2128  // minimum vector size (which we can split the vector down to), we might as
2129  // well use a regular unaligned vector load.
2130  // We don't have any NT loads pre-SSE41.
2131  if (!!(Flags & MachineMemOperand::MOLoad))
2132  return (Align < 16 || !Subtarget.hasSSE41());
2133  return false;
2134  }
2135  // Misaligned accesses of any size are always allowed.
2136  return true;
2137 }
2138 
2139 /// Return the entry encoding for a jump table in the
2140 /// current function. The returned value is a member of the
2141 /// MachineJumpTableInfo::JTEntryKind enum.
2143  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2144  // symbol.
2145  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2147 
2148  // Otherwise, use the normal jump table encoding heuristics.
2150 }
2151 
2153  return Subtarget.useSoftFloat();
2154 }
2155 
2157  ArgListTy &Args) const {
2158 
2159  // Only relabel X86-32 for C / Stdcall CCs.
2160  if (Subtarget.is64Bit())
2161  return;
2162  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2163  return;
2164  unsigned ParamRegs = 0;
2165  if (auto *M = MF->getFunction().getParent())
2166  ParamRegs = M->getNumberRegisterParameters();
2167 
2168  // Mark the first N int arguments as having reg
2169  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2170  Type *T = Args[Idx].Ty;
2171  if (T->isIntOrPtrTy())
2172  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2173  unsigned numRegs = 1;
2174  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2175  numRegs = 2;
2176  if (ParamRegs < numRegs)
2177  return;
2178  ParamRegs -= numRegs;
2179  Args[Idx].IsInReg = true;
2180  }
2181  }
2182 }
2183 
2184 const MCExpr *
2186  const MachineBasicBlock *MBB,
2187  unsigned uid,MCContext &Ctx) const{
2188  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2189  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2190  // entries.
2191  return MCSymbolRefExpr::create(MBB->getSymbol(),
2193 }
2194 
2195 /// Returns relocation base for the given PIC jumptable.
2197  SelectionDAG &DAG) const {
2198  if (!Subtarget.is64Bit())
2199  // This doesn't have SDLoc associated with it, but is not really the
2200  // same as a Register.
2201  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2202  getPointerTy(DAG.getDataLayout()));
2203  return Table;
2204 }
2205 
2206 /// This returns the relocation base for the given PIC jumptable,
2207 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2210  MCContext &Ctx) const {
2211  // X86-64 uses RIP relative addressing based on the jump table label.
2212  if (Subtarget.isPICStyleRIPRel())
2213  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2214 
2215  // Otherwise, the reference is relative to the PIC base.
2216  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2217 }
2218 
2219 std::pair<const TargetRegisterClass *, uint8_t>
2221  MVT VT) const {
2222  const TargetRegisterClass *RRC = nullptr;
2223  uint8_t Cost = 1;
2224  switch (VT.SimpleTy) {
2225  default:
2227  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2228  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2229  break;
2230  case MVT::x86mmx:
2231  RRC = &X86::VR64RegClass;
2232  break;
2233  case MVT::f32: case MVT::f64:
2234  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2235  case MVT::v4f32: case MVT::v2f64:
2236  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2237  case MVT::v8f32: case MVT::v4f64:
2238  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2239  case MVT::v16f32: case MVT::v8f64:
2240  RRC = &X86::VR128XRegClass;
2241  break;
2242  }
2243  return std::make_pair(RRC, Cost);
2244 }
2245 
2246 unsigned X86TargetLowering::getAddressSpace() const {
2247  if (Subtarget.is64Bit())
2248  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2249  return 256;
2250 }
2251 
2252 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2253  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2254  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2255 }
2256 
2258  unsigned Offset, unsigned AddressSpace) {
2261  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2262 }
2263 
2265  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2266  // tcbhead_t; use it instead of the usual global variable (see
2267  // sysdeps/{i386,x86_64}/nptl/tls.h)
2268  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2269  if (Subtarget.isTargetFuchsia()) {
2270  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2271  return SegmentOffset(IRB, 0x10, getAddressSpace());
2272  } else {
2273  // %fs:0x28, unless we're using a Kernel code model, in which case
2274  // it's %gs:0x28. gs:0x14 on i386.
2275  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2276  return SegmentOffset(IRB, Offset, getAddressSpace());
2277  }
2278  }
2279 
2280  return TargetLowering::getIRStackGuard(IRB);
2281 }
2282 
2284  // MSVC CRT provides functionalities for stack protection.
2285  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2287  // MSVC CRT has a global variable holding security cookie.
2288  M.getOrInsertGlobal("__security_cookie",
2290 
2291  // MSVC CRT has a function to validate security cookie.
2292  FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
2293  "__security_check_cookie", Type::getVoidTy(M.getContext()),
2295  if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
2296  F->setCallingConv(CallingConv::X86_FastCall);
2297  F->addAttribute(1, Attribute::AttrKind::InReg);
2298  }
2299  return;
2300  }
2301  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2302  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2303  return;
2305 }
2306 
2308  // MSVC CRT has a global variable holding security cookie.
2309  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2311  return M.getGlobalVariable("__security_cookie");
2312  }
2314 }
2315 
2317  // MSVC CRT has a function to validate security cookie.
2318  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2320  return M.getFunction("__security_check_cookie");
2321  }
2323 }
2324 
2326  if (Subtarget.getTargetTriple().isOSContiki())
2327  return getDefaultSafeStackPointerLocation(IRB, false);
2328 
2329  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2330  // definition of TLS_SLOT_SAFESTACK in
2331  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2332  if (Subtarget.isTargetAndroid()) {
2333  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2334  // %gs:0x24 on i386
2335  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2336  return SegmentOffset(IRB, Offset, getAddressSpace());
2337  }
2338 
2339  // Fuchsia is similar.
2340  if (Subtarget.isTargetFuchsia()) {
2341  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2342  return SegmentOffset(IRB, 0x18, getAddressSpace());
2343  }
2344 
2346 }
2347 
2349  unsigned DestAS) const {
2350  assert(SrcAS != DestAS && "Expected different address spaces!");
2351 
2352  return SrcAS < 256 && DestAS < 256;
2353 }
2354 
2355 //===----------------------------------------------------------------------===//
2356 // Return Value Calling Convention Implementation
2357 //===----------------------------------------------------------------------===//
2358 
2359 bool X86TargetLowering::CanLowerReturn(
2360  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2361  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2363  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2364  return CCInfo.CheckReturn(Outs, RetCC_X86);
2365 }
2366 
2367 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2368  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2369  return ScratchRegs;
2370 }
2371 
2372 /// Lowers masks values (v*i1) to the local register values
2373 /// \returns DAG node after lowering to register type
2374 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2375  const SDLoc &Dl, SelectionDAG &DAG) {
2376  EVT ValVT = ValArg.getValueType();
2377 
2378  if (ValVT == MVT::v1i1)
2379  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2380  DAG.getIntPtrConstant(0, Dl));
2381 
2382  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2383  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2384  // Two stage lowering might be required
2385  // bitcast: v8i1 -> i8 / v16i1 -> i16
2386  // anyextend: i8 -> i32 / i16 -> i32
2387  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2388  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2389  if (ValLoc == MVT::i32)
2390  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2391  return ValToCopy;
2392  }
2393 
2394  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2395  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2396  // One stage lowering is required
2397  // bitcast: v32i1 -> i32 / v64i1 -> i64
2398  return DAG.getBitcast(ValLoc, ValArg);
2399  }
2400 
2401  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2402 }
2403 
2404 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2406  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2407  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2408  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2409  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2410  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2411  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2412  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2413  "The value should reside in two registers");
2414 
2415  // Before splitting the value we cast it to i64
2416  Arg = DAG.getBitcast(MVT::i64, Arg);
2417 
2418  // Splitting the value into two i32 types
2419  SDValue Lo, Hi;
2420  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2421  DAG.getConstant(0, Dl, MVT::i32));
2422  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2423  DAG.getConstant(1, Dl, MVT::i32));
2424 
2425  // Attach the two i32 types into corresponding registers
2426  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2427  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2428 }
2429 
2430 SDValue
2431 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2432  bool isVarArg,
2433  const SmallVectorImpl<ISD::OutputArg> &Outs,
2434  const SmallVectorImpl<SDValue> &OutVals,
2435  const SDLoc &dl, SelectionDAG &DAG) const {
2436  MachineFunction &MF = DAG.getMachineFunction();
2438 
2439  // In some cases we need to disable registers from the default CSR list.
2440  // For example, when they are used for argument passing.
2441  bool ShouldDisableCalleeSavedRegister =
2442  CallConv == CallingConv::X86_RegCall ||
2443  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2444 
2445  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2446  report_fatal_error("X86 interrupts may not return any value");
2447 
2449  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2450  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2451 
2452  SDValue Flag;
2453  SmallVector<SDValue, 6> RetOps;
2454  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2455  // Operand #1 = Bytes To Pop
2456  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2457  MVT::i32));
2458 
2459  // Copy the result values into the output registers.
2460  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2461  ++I, ++OutsIndex) {
2462  CCValAssign &VA = RVLocs[I];
2463  assert(VA.isRegLoc() && "Can only return in registers!");
2464 
2465  // Add the register to the CalleeSaveDisableRegs list.
2466  if (ShouldDisableCalleeSavedRegister)
2468 
2469  SDValue ValToCopy = OutVals[OutsIndex];
2470  EVT ValVT = ValToCopy.getValueType();
2471 
2472  // Promote values to the appropriate types.
2473  if (VA.getLocInfo() == CCValAssign::SExt)
2474  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2475  else if (VA.getLocInfo() == CCValAssign::ZExt)
2476  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2477  else if (VA.getLocInfo() == CCValAssign::AExt) {
2478  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2479  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2480  else
2481  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2482  }
2483  else if (VA.getLocInfo() == CCValAssign::BCvt)
2484  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2485 
2487  "Unexpected FP-extend for return value.");
2488 
2489  // If this is x86-64, and we disabled SSE, we can't return FP values,
2490  // or SSE or MMX vectors.
2491  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2492  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2493  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2494  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2495  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2496  } else if (ValVT == MVT::f64 &&
2497  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2498  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2499  // llvm-gcc has never done it right and no one has noticed, so this
2500  // should be OK for now.
2501  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2502  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2503  }
2504 
2505  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2506  // the RET instruction and handled by the FP Stackifier.
2507  if (VA.getLocReg() == X86::FP0 ||
2508  VA.getLocReg() == X86::FP1) {
2509  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2510  // change the value to the FP stack register class.
2511  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2512  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2513  RetOps.push_back(ValToCopy);
2514  // Don't emit a copytoreg.
2515  continue;
2516  }
2517 
2518  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2519  // which is returned in RAX / RDX.
2520  if (Subtarget.is64Bit()) {
2521  if (ValVT == MVT::x86mmx) {
2522  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2523  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2524  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2525  ValToCopy);
2526  // If we don't have SSE2 available, convert to v4f32 so the generated
2527  // register is legal.
2528  if (!Subtarget.hasSSE2())
2529  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2530  }
2531  }
2532  }
2533 
2535 
2536  if (VA.needsCustom()) {
2537  assert(VA.getValVT() == MVT::v64i1 &&
2538  "Currently the only custom case is when we split v64i1 to 2 regs");
2539 
2540  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2541  Subtarget);
2542 
2543  assert(2 == RegsToPass.size() &&
2544  "Expecting two registers after Pass64BitArgInRegs");
2545 
2546  // Add the second register to the CalleeSaveDisableRegs list.
2547  if (ShouldDisableCalleeSavedRegister)
2548  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2549  } else {
2550  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2551  }
2552 
2553  // Add nodes to the DAG and add the values into the RetOps list
2554  for (auto &Reg : RegsToPass) {
2555  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2556  Flag = Chain.getValue(1);
2557  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2558  }
2559  }
2560 
2561  // Swift calling convention does not require we copy the sret argument
2562  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2563 
2564  // All x86 ABIs require that for returning structs by value we copy
2565  // the sret argument into %rax/%eax (depending on ABI) for the return.
2566  // We saved the argument into a virtual register in the entry block,
2567  // so now we copy the value out and into %rax/%eax.
2568  //
2569  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2570  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2571  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2572  // either case FuncInfo->setSRetReturnReg() will have been called.
2573  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2574  // When we have both sret and another return value, we should use the
2575  // original Chain stored in RetOps[0], instead of the current Chain updated
2576  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2577 
2578  // For the case of sret and another return value, we have
2579  // Chain_0 at the function entry
2580  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2581  // If we use Chain_1 in getCopyFromReg, we will have
2582  // Val = getCopyFromReg(Chain_1)
2583  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2584 
2585  // getCopyToReg(Chain_0) will be glued together with
2586  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2587  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2588  // Data dependency from Unit B to Unit A due to usage of Val in
2589  // getCopyToReg(Chain_1, Val)
2590  // Chain dependency from Unit A to Unit B
2591 
2592  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2593  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2594  getPointerTy(MF.getDataLayout()));
2595 
2596  unsigned RetValReg
2597  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2598  X86::RAX : X86::EAX;
2599  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2600  Flag = Chain.getValue(1);
2601 
2602  // RAX/EAX now acts like a return value.
2603  RetOps.push_back(
2604  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2605 
2606  // Add the returned register to the CalleeSaveDisableRegs list.
2607  if (ShouldDisableCalleeSavedRegister)
2608  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2609  }
2610 
2611  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2612  const MCPhysReg *I =
2614  if (I) {
2615  for (; *I; ++I) {
2616  if (X86::GR64RegClass.contains(*I))
2617  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2618  else
2619  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2620  }
2621  }
2622 
2623  RetOps[0] = Chain; // Update chain.
2624 
2625  // Add the flag if we have it.
2626  if (Flag.getNode())
2627  RetOps.push_back(Flag);
2628 
2630  if (CallConv == CallingConv::X86_INTR)
2631  opcode = X86ISD::IRET;
2632  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2633 }
2634 
2635 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2636  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2637  return false;
2638 
2639  SDValue TCChain = Chain;
2640  SDNode *Copy = *N->use_begin();
2641  if (Copy->getOpcode() == ISD::CopyToReg) {
2642  // If the copy has a glue operand, we conservatively assume it isn't safe to
2643  // perform a tail call.
2644  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2645  return false;
2646  TCChain = Copy->getOperand(0);
2647  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2648  return false;
2649 
2650  bool HasRet = false;
2651  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2652  UI != UE; ++UI) {
2653  if (UI->getOpcode() != X86ISD::RET_FLAG)
2654  return false;
2655  // If we are returning more than one value, we can definitely
2656  // not make a tail call see PR19530
2657  if (UI->getNumOperands() > 4)
2658  return false;
2659  if (UI->getNumOperands() == 4 &&
2660  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2661  return false;
2662  HasRet = true;
2663  }
2664 
2665  if (!HasRet)
2666  return false;
2667 
2668  Chain = TCChain;
2669  return true;
2670 }
2671 
2672 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2673  ISD::NodeType ExtendKind) const {
2674  MVT ReturnMVT = MVT::i32;
2675 
2676  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2677  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2678  // The ABI does not require i1, i8 or i16 to be extended.
2679  //
2680  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2681  // always extending i8/i16 return values, so keep doing that for now.
2682  // (PR26665).
2683  ReturnMVT = MVT::i8;
2684  }
2685 
2686  EVT MinVT = getRegisterType(Context, ReturnMVT);
2687  return VT.bitsLT(MinVT) ? MinVT : VT;
2688 }
2689 
2690 /// Reads two 32 bit registers and creates a 64 bit mask value.
2691 /// \param VA The current 32 bit value that need to be assigned.
2692 /// \param NextVA The next 32 bit value that need to be assigned.
2693 /// \param Root The parent DAG node.
2694 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2695 /// glue purposes. In the case the DAG is already using
2696 /// physical register instead of virtual, we should glue
2697 /// our new SDValue to InFlag SDvalue.
2698 /// \return a new SDvalue of size 64bit.
2700  SDValue &Root, SelectionDAG &DAG,
2701  const SDLoc &Dl, const X86Subtarget &Subtarget,
2702  SDValue *InFlag = nullptr) {
2703  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2704  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2705  assert(VA.getValVT() == MVT::v64i1 &&
2706  "Expecting first location of 64 bit width type");
2707  assert(NextVA.getValVT() == VA.getValVT() &&
2708  "The locations should have the same type");
2709  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2710  "The values should reside in two registers");
2711 
2712  SDValue Lo, Hi;
2713  SDValue ArgValueLo, ArgValueHi;
2714 
2715  MachineFunction &MF = DAG.getMachineFunction();
2716  const TargetRegisterClass *RC = &X86::GR32RegClass;
2717 
2718  // Read a 32 bit value from the registers.
2719  if (nullptr == InFlag) {
2720  // When no physical register is present,
2721  // create an intermediate virtual register.
2722  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2723  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2724  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2725  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2726  } else {
2727  // When a physical register is available read the value from it and glue
2728  // the reads together.
2729  ArgValueLo =
2730  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2731  *InFlag = ArgValueLo.getValue(2);
2732  ArgValueHi =
2733  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2734  *InFlag = ArgValueHi.getValue(2);
2735  }
2736 
2737  // Convert the i32 type into v32i1 type.
2738  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2739 
2740  // Convert the i32 type into v32i1 type.
2741  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2742 
2743  // Concatenate the two values together.
2744  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2745 }
2746 
2747 /// The function will lower a register of various sizes (8/16/32/64)
2748 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2749 /// \returns a DAG node contains the operand after lowering to mask type.
2750 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2751  const EVT &ValLoc, const SDLoc &Dl,
2752  SelectionDAG &DAG) {
2753  SDValue ValReturned = ValArg;
2754 
2755  if (ValVT == MVT::v1i1)
2756  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2757 
2758  if (ValVT == MVT::v64i1) {
2759  // In 32 bit machine, this case is handled by getv64i1Argument
2760  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2761  // In 64 bit machine, There is no need to truncate the value only bitcast
2762  } else {
2763  MVT maskLen;
2764  switch (ValVT.getSimpleVT().SimpleTy) {
2765  case MVT::v8i1:
2766  maskLen = MVT::i8;
2767  break;
2768  case MVT::v16i1:
2769  maskLen = MVT::i16;
2770  break;
2771  case MVT::v32i1:
2772  maskLen = MVT::i32;
2773  break;
2774  default:
2775  llvm_unreachable("Expecting a vector of i1 types");
2776  }
2777 
2778  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2779  }
2780  return DAG.getBitcast(ValVT, ValReturned);
2781 }
2782 
2783 /// Lower the result values of a call into the
2784 /// appropriate copies out of appropriate physical registers.
2785 ///
2786 SDValue X86TargetLowering::LowerCallResult(
2787  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2788  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2789  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2790  uint32_t *RegMask) const {
2791 
2792  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2793  // Assign locations to each value returned by this call.
2795  bool Is64Bit = Subtarget.is64Bit();
2796  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2797  *DAG.getContext());
2798  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2799 
2800  // Copy all of the result registers out of their specified physreg.
2801  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2802  ++I, ++InsIndex) {
2803  CCValAssign &VA = RVLocs[I];
2804  EVT CopyVT = VA.getLocVT();
2805 
2806  // In some calling conventions we need to remove the used registers
2807  // from the register mask.
2808  if (RegMask) {
2809  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2810  SubRegs.isValid(); ++SubRegs)
2811  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2812  }
2813 
2814  // If this is x86-64, and we disabled SSE, we can't return FP values
2815  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2816  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2817  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2818  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2819  }
2820 
2821  // If we prefer to use the value in xmm registers, copy it out as f80 and
2822  // use a truncate to move it from fp stack reg to xmm reg.
2823  bool RoundAfterCopy = false;
2824  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2826  if (!Subtarget.hasX87())
2827  report_fatal_error("X87 register return with X87 disabled");
2828  CopyVT = MVT::f80;
2829  RoundAfterCopy = (CopyVT != VA.getLocVT());
2830  }
2831 
2832  SDValue Val;
2833  if (VA.needsCustom()) {
2834  assert(VA.getValVT() == MVT::v64i1 &&
2835  "Currently the only custom case is when we split v64i1 to 2 regs");
2836  Val =
2837  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2838  } else {
2839  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2840  .getValue(1);
2841  Val = Chain.getValue(0);
2842  InFlag = Chain.getValue(2);
2843  }
2844 
2845  if (RoundAfterCopy)
2846  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2847  // This truncation won't change the value.
2848  DAG.getIntPtrConstant(1, dl));
2849 
2850  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2851  if (VA.getValVT().isVector() &&
2852  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2853  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2854  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2855  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2856  } else
2857  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2858  }
2859 
2860  InVals.push_back(Val);
2861  }
2862 
2863  return Chain;
2864 }
2865 
2866 //===----------------------------------------------------------------------===//
2867 // C & StdCall & Fast Calling Convention implementation
2868 //===----------------------------------------------------------------------===//
2869 // StdCall calling convention seems to be standard for many Windows' API
2870 // routines and around. It differs from C calling convention just a little:
2871 // callee should clean up the stack, not caller. Symbols should be also
2872 // decorated in some fancy way :) It doesn't support any vector arguments.
2873 // For info on fast calling convention see Fast Calling Convention (tail call)
2874 // implementation LowerX86_32FastCCCallTo.
2875 
2876 /// CallIsStructReturn - Determines whether a call uses struct return
2877 /// semantics.
2882 };
2883 static StructReturnType
2885  if (Outs.empty())
2886  return NotStructReturn;
2887 
2888  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2889  if (!Flags.isSRet())
2890  return NotStructReturn;
2891  if (Flags.isInReg() || IsMCU)
2892  return RegStructReturn;
2893  return StackStructReturn;
2894 }
2895 
2896 /// Determines whether a function uses struct return semantics.
2897 static StructReturnType
2899  if (Ins.empty())
2900  return NotStructReturn;
2901 
2902  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2903  if (!Flags.isSRet())
2904  return NotStructReturn;
2905  if (Flags.isInReg() || IsMCU)
2906  return RegStructReturn;
2907  return StackStructReturn;
2908 }
2909 
2910 /// Make a copy of an aggregate at address specified by "Src" to address
2911 /// "Dst" with size and alignment information specified by the specific
2912 /// parameter attribute. The copy will be passed as a byval function parameter.
2914  SDValue Chain, ISD::ArgFlagsTy Flags,
2915  SelectionDAG &DAG, const SDLoc &dl) {
2916  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2917 
2918  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2919  /*isVolatile*/false, /*AlwaysInline=*/true,
2920  /*isTailCall*/false,
2922 }
2923 
2924 /// Return true if the calling convention is one that we can guarantee TCO for.
2926  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2928  CC == CallingConv::HHVM);
2929 }
2930 
2931 /// Return true if we might ever do TCO for calls with this calling convention.
2933  switch (CC) {
2934  // C calling conventions:
2935  case CallingConv::C:
2936  case CallingConv::Win64:
2938  // Callee pop conventions:
2943  // Swift:
2944  case CallingConv::Swift:
2945  return true;
2946  default:
2947  return canGuaranteeTCO(CC);
2948  }
2949 }
2950 
2951 /// Return true if the function is being made into a tailcall target by
2952 /// changing its ABI.
2953 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2954  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2955 }
2956 
2957 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2958  auto Attr =
2959  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2960  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2961  return false;
2962 
2963  ImmutableCallSite CS(CI);
2964  CallingConv::ID CalleeCC = CS.getCallingConv();
2965  if (!mayTailCallThisCC(CalleeCC))
2966  return false;
2967 
2968  return true;
2969 }
2970 
2971 SDValue
2972 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2973  const SmallVectorImpl<ISD::InputArg> &Ins,
2974  const SDLoc &dl, SelectionDAG &DAG,
2975  const CCValAssign &VA,
2976  MachineFrameInfo &MFI, unsigned i) const {
2977  // Create the nodes corresponding to a load from this parameter slot.
2978  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2979  bool AlwaysUseMutable = shouldGuaranteeTCO(
2980  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2981  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2982  EVT ValVT;
2983  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2984 
2985  // If value is passed by pointer we have address passed instead of the value
2986  // itself. No need to extend if the mask value and location share the same
2987  // absolute size.
2988  bool ExtendedInMem =
2989  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2990  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2991 
2992  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2993  ValVT = VA.getLocVT();
2994  else
2995  ValVT = VA.getValVT();
2996 
2997  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2998  // changed with more analysis.
2999  // In case of tail call optimization mark all arguments mutable. Since they
3000  // could be overwritten by lowering of arguments in case of a tail call.
3001  if (Flags.isByVal()) {
3002  unsigned Bytes = Flags.getByValSize();
3003  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
3004 
3005  // FIXME: For now, all byval parameter objects are marked as aliasing. This
3006  // can be improved with deeper analysis.
3007  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
3008  /*isAliased=*/true);
3009  return DAG.getFrameIndex(FI, PtrVT);
3010  }
3011 
3012  // This is an argument in memory. We might be able to perform copy elision.
3013  // If the argument is passed directly in memory without any extension, then we
3014  // can perform copy elision. Large vector types, for example, may be passed
3015  // indirectly by pointer.
3016  if (Flags.isCopyElisionCandidate() &&
3017  VA.getLocInfo() != CCValAssign::Indirect && !ExtendedInMem) {
3018  EVT ArgVT = Ins[i].ArgVT;
3019  SDValue PartAddr;
3020  if (Ins[i].PartOffset == 0) {
3021  // If this is a one-part value or the first part of a multi-part value,
3022  // create a stack object for the entire argument value type and return a
3023  // load from our portion of it. This assumes that if the first part of an
3024  // argument is in memory, the rest will also be in memory.
3025  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
3026  /*IsImmutable=*/false);
3027  PartAddr = DAG.getFrameIndex(FI, PtrVT);
3028  return DAG.getLoad(
3029  ValVT, dl, Chain, PartAddr,
3031  } else {
3032  // This is not the first piece of an argument in memory. See if there is
3033  // already a fixed stack object including this offset. If so, assume it
3034  // was created by the PartOffset == 0 branch above and create a load from
3035  // the appropriate offset into it.
3036  int64_t PartBegin = VA.getLocMemOffset();
3037  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
3038  int FI = MFI.getObjectIndexBegin();
3039  for (; MFI.isFixedObjectIndex(FI); ++FI) {
3040  int64_t ObjBegin = MFI.getObjectOffset(FI);
3041  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
3042  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
3043  break;
3044  }
3045  if (MFI.isFixedObjectIndex(FI)) {
3046  SDValue Addr =
3047  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
3048  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
3049  return DAG.getLoad(
3050  ValVT, dl, Chain, Addr,
3052  Ins[i].PartOffset));
3053  }
3054  }
3055  }
3056 
3057  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
3058  VA.getLocMemOffset(), isImmutable);
3059 
3060  // Set SExt or ZExt flag.
3061  if (VA.getLocInfo() == CCValAssign::ZExt) {
3062  MFI.setObjectZExt(FI, true);
3063  } else if (VA.getLocInfo() == CCValAssign::SExt) {
3064  MFI.setObjectSExt(FI, true);
3065  }
3066 
3067  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3068  SDValue Val = DAG.getLoad(
3069  ValVT, dl, Chain, FIN,
3071  return ExtendedInMem
3072  ? (VA.getValVT().isVector()
3073  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
3074  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
3075  : Val;
3076 }
3077 
3078 // FIXME: Get this from tablegen.
3080  const X86Subtarget &Subtarget) {
3081  assert(Subtarget.is64Bit());
3082 
3083  if (Subtarget.isCallingConvWin64(CallConv)) {
3084  static const MCPhysReg GPR64ArgRegsWin64[] = {
3085  X86::RCX, X86::RDX, X86::R8, X86::R9
3086  };
3087  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3088  }
3089 
3090  static const MCPhysReg GPR64ArgRegs64Bit[] = {
3091  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3092  };
3093  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3094 }
3095 
3096 // FIXME: Get this from tablegen.
3098  CallingConv::ID CallConv,
3099  const X86Subtarget &Subtarget) {
3100  assert(Subtarget.is64Bit());
3101  if (Subtarget.isCallingConvWin64(CallConv)) {
3102  // The XMM registers which might contain var arg parameters are shadowed
3103  // in their paired GPR. So we only need to save the GPR to their home
3104  // slots.
3105  // TODO: __vectorcall will change this.
3106  return None;
3107  }
3108 
3109  const Function &F = MF.getFunction();
3110  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3111  bool isSoftFloat = Subtarget.useSoftFloat();
3112  assert(!(isSoftFloat && NoImplicitFloatOps) &&
3113  "SSE register cannot be used when SSE is disabled!");
3114  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3115  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3116  // registers.
3117  return None;
3118 
3119  static const MCPhysReg XMMArgRegs64Bit[] = {
3120  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3121  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3122  };
3123  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3124 }
3125 
3126 #ifndef NDEBUG
3128  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3129  [](const CCValAssign &A, const CCValAssign &B) -> bool {
3130  return A.getValNo() < B.getValNo();
3131  });
3132 }
3133 #endif
3134 
3135 SDValue X86TargetLowering::LowerFormalArguments(
3136  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3137  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3138  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3139  MachineFunction &MF = DAG.getMachineFunction();
3141  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3142 
3143  const Function &F = MF.getFunction();
3144  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3145  F.getName() == "main")
3146  FuncInfo->setForceFramePointer(true);
3147 
3148  MachineFrameInfo &MFI = MF.getFrameInfo();
3149  bool Is64Bit = Subtarget.is64Bit();
3150  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3151 
3152  assert(
3153  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3154  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3155 
3156  // Assign locations to all of the incoming arguments.
3158  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3159 
3160  // Allocate shadow area for Win64.
3161  if (IsWin64)
3162  CCInfo.AllocateStack(32, 8);
3163 
3164  CCInfo.AnalyzeArguments(Ins, CC_X86);
3165 
3166  // In vectorcall calling convention a second pass is required for the HVA
3167  // types.
3168  if (CallingConv::X86_VectorCall == CallConv) {
3169  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3170  }
3171 
3172  // The next loop assumes that the locations are in the same order of the
3173  // input arguments.
3174  assert(isSortedByValueNo(ArgLocs) &&
3175  "Argument Location list must be sorted before lowering");
3176 
3177  SDValue ArgValue;
3178  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3179  ++I, ++InsIndex) {
3180  assert(InsIndex < Ins.size() && "Invalid Ins index");
3181  CCValAssign &VA = ArgLocs[I];
3182 
3183  if (VA.isRegLoc()) {
3184  EVT RegVT = VA.getLocVT();
3185  if (VA.needsCustom()) {
3186  assert(
3187  VA.getValVT() == MVT::v64i1 &&
3188  "Currently the only custom case is when we split v64i1 to 2 regs");
3189 
3190  // v64i1 values, in regcall calling convention, that are
3191  // compiled to 32 bit arch, are split up into two registers.
3192  ArgValue =
3193  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3194  } else {
3195  const TargetRegisterClass *RC;
3196  if (RegVT == MVT::i8)
3197  RC = &X86::GR8RegClass;
3198  else if (RegVT == MVT::i16)
3199  RC = &X86::GR16RegClass;
3200  else if (RegVT == MVT::i32)
3201  RC = &X86::GR32RegClass;
3202  else if (Is64Bit && RegVT == MVT::i64)
3203  RC = &X86::GR64RegClass;
3204  else if (RegVT == MVT::f32)
3205  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3206  else if (RegVT == MVT::f64)
3207  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3208  else if (RegVT == MVT::f80)
3209  RC = &X86::RFP80RegClass;
3210  else if (RegVT == MVT::f128)
3211  RC = &X86::VR128RegClass;
3212  else if (RegVT.is512BitVector())
3213  RC = &X86::VR512RegClass;
3214  else if (RegVT.is256BitVector())
3215  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3216  else if (RegVT.is128BitVector())
3217  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3218  else if (RegVT == MVT::x86mmx)
3219  RC = &X86::VR64RegClass;
3220  else if (RegVT == MVT::v1i1)
3221  RC = &X86::VK1RegClass;
3222  else if (RegVT == MVT::v8i1)
3223  RC = &X86::VK8RegClass;
3224  else if (RegVT == MVT::v16i1)
3225  RC = &X86::VK16RegClass;
3226  else if (RegVT == MVT::v32i1)
3227  RC = &X86::VK32RegClass;
3228  else if (RegVT == MVT::v64i1)
3229  RC = &X86::VK64RegClass;
3230  else
3231  llvm_unreachable("Unknown argument type!");
3232 
3233  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3234  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3235  }
3236 
3237  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3238  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3239  // right size.
3240  if (VA.getLocInfo() == CCValAssign::SExt)
3241  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3242  DAG.getValueType(VA.getValVT()));
3243  else if (VA.getLocInfo() == CCValAssign::ZExt)
3244  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3245  DAG.getValueType(VA.getValVT()));
3246  else if (VA.getLocInfo() == CCValAssign::BCvt)
3247  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3248 
3249  if (VA.isExtInLoc()) {
3250  // Handle MMX values passed in XMM regs.
3251  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3252  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3253  else if (VA.getValVT().isVector() &&
3254  VA.getValVT().getScalarType() == MVT::i1 &&
3255  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3256  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3257  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3258  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3259  } else
3260  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3261  }
3262  } else {
3263  assert(VA.isMemLoc());
3264  ArgValue =
3265  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3266  }
3267 
3268  // If value is passed via pointer - do a load.
3269  if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3270  ArgValue =
3271  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3272 
3273  InVals.push_back(ArgValue);
3274  }
3275 
3276  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3277  // Swift calling convention does not require we copy the sret argument
3278  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3279  if (CallConv == CallingConv::Swift)
3280  continue;
3281 
3282  // All x86 ABIs require that for returning structs by value we copy the
3283  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3284  // the argument into a virtual register so that we can access it from the
3285  // return points.
3286  if (Ins[I].Flags.isSRet()) {
3287  unsigned Reg = FuncInfo->getSRetReturnReg();
3288  if (!Reg) {
3289  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3290  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3291  FuncInfo->setSRetReturnReg(Reg);
3292  }
3293  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3294  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3295  break;
3296  }
3297  }
3298 
3299  unsigned StackSize = CCInfo.getNextStackOffset();
3300  // Align stack specially for tail calls.
3301  if (shouldGuaranteeTCO(CallConv,
3303  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3304 
3305  // If the function takes variable number of arguments, make a frame index for
3306  // the start of the first vararg value... for expansion of llvm.va_start. We
3307  // can skip this if there are no va_start calls.
3308  if (MFI.hasVAStart() &&
3309  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3310  CallConv != CallingConv::X86_ThisCall))) {
3311  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3312  }
3313 
3314  // Figure out if XMM registers are in use.
3315  assert(!(Subtarget.useSoftFloat() &&
3316  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3317  "SSE register cannot be used when SSE is disabled!");
3318 
3319  // 64-bit calling conventions support varargs and register parameters, so we
3320  // have to do extra work to spill them in the prologue.
3321  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3322  // Find the first unallocated argument registers.
3323  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3324  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3325  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3326  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3327  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3328  "SSE register cannot be used when SSE is disabled!");
3329 
3330  // Gather all the live in physical registers.
3331  SmallVector<SDValue, 6> LiveGPRs;
3332  SmallVector<SDValue, 8> LiveXMMRegs;
3333  SDValue ALVal;
3334  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3335  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3336  LiveGPRs.push_back(
3337  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3338  }
3339  if (!ArgXMMs.empty()) {
3340  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3341  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3342  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3343  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3344  LiveXMMRegs.push_back(
3345  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3346  }
3347  }
3348 
3349  if (IsWin64) {
3350  // Get to the caller-allocated home save location. Add 8 to account
3351  // for the return address.
3352  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3353  FuncInfo->setRegSaveFrameIndex(
3354  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3355  // Fixup to set vararg frame on shadow area (4 x i64).
3356  if (NumIntRegs < 4)
3357  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3358  } else {
3359  // For X86-64, if there are vararg parameters that are passed via
3360  // registers, then we must store them to their spots on the stack so
3361  // they may be loaded by dereferencing the result of va_next.
3362  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3363  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3365  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3366  }
3367 
3368  // Store the integer parameter registers.
3369  SmallVector<SDValue, 8> MemOps;
3370  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3371  getPointerTy(DAG.getDataLayout()));
3372  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3373  for (SDValue Val : LiveGPRs) {
3374  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3375  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3376  SDValue Store =
3377  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3379  DAG.getMachineFunction(),
3380  FuncInfo->getRegSaveFrameIndex(), Offset));
3381  MemOps.push_back(Store);
3382  Offset += 8;
3383  }
3384 
3385  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3386  // Now store the XMM (fp + vector) parameter registers.
3387  SmallVector<SDValue, 12> SaveXMMOps;
3388  SaveXMMOps.push_back(Chain);
3389  SaveXMMOps.push_back(ALVal);
3390  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3391  FuncInfo->getRegSaveFrameIndex(), dl));
3392  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3393  FuncInfo->getVarArgsFPOffset(), dl));
3394  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3395  LiveXMMRegs.end());
3397  MVT::Other, SaveXMMOps));
3398  }
3399 
3400  if (!MemOps.empty())
3401  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3402  }
3403 
3404  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3405  // Find the largest legal vector type.
3406  MVT VecVT = MVT::Other;
3407  // FIXME: Only some x86_32 calling conventions support AVX512.
3408  if (Subtarget.hasAVX512() &&
3409  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3410  CallConv == CallingConv::Intel_OCL_BI)))
3411  VecVT = MVT::v16f32;
3412  else if (Subtarget.hasAVX())
3413  VecVT = MVT::v8f32;
3414  else if (Subtarget.hasSSE2())
3415  VecVT = MVT::v4f32;
3416 
3417  // We forward some GPRs and some vector types.
3418  SmallVector<MVT, 2> RegParmTypes;
3419  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3420  RegParmTypes.push_back(IntVT);
3421  if (VecVT != MVT::Other)
3422  RegParmTypes.push_back(VecVT);
3423 
3424  // Compute the set of forwarded registers. The rest are scratch.
3426  FuncInfo->getForwardedMustTailRegParms();
3427  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3428 
3429  // Conservatively forward AL on x86_64, since it might be used for varargs.
3430  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3431  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3432  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3433  }
3434 
3435  // Copy all forwards from physical to virtual registers.
3436  for (ForwardedRegister &FR : Forwards) {
3437  // FIXME: Can we use a less constrained schedule?
3438  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, FR.VReg, FR.VT);
3439  FR.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(FR.VT));
3440  Chain = DAG.getCopyToReg(Chain, dl, FR.VReg, RegVal);
3441  }
3442  }
3443 
3444  // Some CCs need callee pop.
3445  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3447  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3448  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3449  // X86 interrupts must pop the error code (and the alignment padding) if
3450  // present.
3451  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3452  } else {
3453  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3454  // If this is an sret function, the return should pop the hidden pointer.
3455  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3456  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3457  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3458  FuncInfo->setBytesToPopOnReturn(4);
3459  }
3460 
3461  if (!Is64Bit) {
3462  // RegSaveFrameIndex is X86-64 only.
3463  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3464  if (CallConv == CallingConv::X86_FastCall ||
3465  CallConv == CallingConv::X86_ThisCall)
3466  // fastcc functions can't have varargs.
3467  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3468  }
3469 
3470  FuncInfo->setArgumentStackSize(StackSize);
3471 
3472  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3474  if (Personality == EHPersonality::CoreCLR) {
3475  assert(Is64Bit);
3476  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3477  // that we'd prefer this slot be allocated towards the bottom of the frame
3478  // (i.e. near the stack pointer after allocating the frame). Every
3479  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3480  // offset from the bottom of this and each funclet's frame must be the
3481  // same, so the size of funclets' (mostly empty) frames is dictated by
3482  // how far this slot is from the bottom (since they allocate just enough
3483  // space to accommodate holding this slot at the correct offset).
3484  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3485  EHInfo->PSPSymFrameIdx = PSPSymFI;
3486  }
3487  }
3488 
3489  if (CallConv == CallingConv::X86_RegCall ||
3490  F.hasFnAttribute("no_caller_saved_registers")) {
3492  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3493  MRI.disableCalleeSavedRegister(Pair.first);
3494  }
3495 
3496  return Chain;
3497 }
3498 
3499 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3500  SDValue Arg, const SDLoc &dl,
3501  SelectionDAG &DAG,
3502  const CCValAssign &VA,
3503  ISD::ArgFlagsTy Flags) const {
3504  unsigned LocMemOffset = VA.getLocMemOffset();
3505  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3506  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3507  StackPtr, PtrOff);
3508  if (Flags.isByVal())
3509  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3510 
3511  return DAG.getStore(
3512  Chain, dl, Arg, PtrOff,
3513  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3514 }
3515 
3516 /// Emit a load of return address if tail call
3517 /// optimization is performed and it is required.
3518 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3519  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3520  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3521  // Adjust the Return address stack slot.
3522  EVT VT = getPointerTy(DAG.getDataLayout());
3523  OutRetAddr = getReturnAddressFrameIndex(DAG);
3524 
3525  // Load the "old" Return address.
3526  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3527  return SDValue(OutRetAddr.getNode(), 1);
3528 }
3529 
3530 /// Emit a store of the return address if tail call
3531 /// optimization is performed and it is required (FPDiff!=0).
3533  SDValue Chain, SDValue RetAddrFrIdx,
3534  EVT PtrVT, unsigned SlotSize,
3535  int FPDiff, const SDLoc &dl) {
3536  // Store the return address to the appropriate stack slot.
3537  if (!FPDiff) return Chain;
3538  // Calculate the new stack slot for the return address.
3539  int NewReturnAddrFI =
3540  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3541  false);
3542  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3543  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3545  DAG.getMachineFunction(), NewReturnAddrFI));
3546  return Chain;
3547 }
3548 
3549 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3550 /// operation of specified width.
3551 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3552  SDValue V2) {
3553  unsigned NumElems = VT.getVectorNumElements();
3555  Mask.push_back(NumElems);
3556  for (unsigned i = 1; i != NumElems; ++i)
3557  Mask.push_back(i);
3558  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3559 }
3560 
3561 SDValue
3562 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3563  SmallVectorImpl<SDValue> &InVals) const {
3564  SelectionDAG &DAG = CLI.DAG;
3565  SDLoc &dl = CLI.DL;
3567  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3569  SDValue Chain = CLI.Chain;
3570  SDValue Callee = CLI.Callee;
3571  CallingConv::ID CallConv = CLI.CallConv;
3572  bool &isTailCall = CLI.IsTailCall;
3573  bool isVarArg = CLI.IsVarArg;
3574 
3575  MachineFunction &MF = DAG.getMachineFunction();
3576  bool Is64Bit = Subtarget.is64Bit();
3577  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3578  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());