LLVM  8.0.0svn
X86ISelLowering.cpp
Go to the documentation of this file.
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "X86TargetObjectFile.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/IR/CallSite.h"
41 #include "llvm/IR/CallingConv.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/IR/DiagnosticInfo.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/MC/MCAsmInfo.h"
51 #include "llvm/MC/MCContext.h"
52 #include "llvm/MC/MCExpr.h"
53 #include "llvm/MC/MCSymbol.h"
55 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/KnownBits.h"
60 #include <algorithm>
61 #include <bitset>
62 #include <cctype>
63 #include <numeric>
64 using namespace llvm;
65 
66 #define DEBUG_TYPE "x86-isel"
67 
68 STATISTIC(NumTailCalls, "Number of tail calls");
69 
71  "x86-experimental-vector-widening-legalization", cl::init(false),
72  cl::desc("Enable an experimental vector type legalization through widening "
73  "rather than promotion."),
74  cl::Hidden);
75 
77  "x86-experimental-pref-loop-alignment", cl::init(4),
78  cl::desc("Sets the preferable loop alignment for experiments "
79  "(the last x86-experimental-pref-loop-alignment bits"
80  " of the loop header PC will be 0)."),
81  cl::Hidden);
82 
84  "mul-constant-optimization", cl::init(true),
85  cl::desc("Replace 'mul x, Const' with more effective instructions like "
86  "SHIFT, LEA, etc."),
87  cl::Hidden);
88 
89 /// Call this when the user attempts to do something unsupported, like
90 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
91 /// report_fatal_error, so calling code should attempt to recover without
92 /// crashing.
93 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
94  const char *Msg) {
96  DAG.getContext()->diagnose(
98 }
99 
101  const X86Subtarget &STI)
102  : TargetLowering(TM), Subtarget(STI) {
103  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
104  X86ScalarSSEf64 = Subtarget.hasSSE2();
105  X86ScalarSSEf32 = Subtarget.hasSSE1();
107 
108  // Set up the TargetLowering object.
109 
110  // X86 is weird. It always uses i8 for shift amounts and setcc results.
112  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
114 
115  // For 64-bit, since we have so many registers, use the ILP scheduler.
116  // For 32-bit, use the register pressure specific scheduling.
117  // For Atom, always use ILP scheduling.
118  if (Subtarget.isAtom())
120  else if (Subtarget.is64Bit())
122  else
124  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
126 
127  // Bypass expensive divides and use cheaper ones.
128  if (TM.getOptLevel() >= CodeGenOpt::Default) {
129  if (Subtarget.hasSlowDivide32())
130  addBypassSlowDiv(32, 8);
131  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
132  addBypassSlowDiv(64, 32);
133  }
134 
135  if (Subtarget.isTargetKnownWindowsMSVC() ||
136  Subtarget.isTargetWindowsItanium()) {
137  // Setup Windows compiler runtime calls.
138  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
139  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
140  setLibcallName(RTLIB::SREM_I64, "_allrem");
141  setLibcallName(RTLIB::UREM_I64, "_aullrem");
142  setLibcallName(RTLIB::MUL_I64, "_allmul");
148  }
149 
150  if (Subtarget.isTargetDarwin()) {
151  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
152  setUseUnderscoreSetJmp(false);
154  } else if (Subtarget.isTargetWindowsGNU()) {
155  // MS runtime is weird: it exports _setjmp, but longjmp!
158  } else {
161  }
162 
163  // Set up the register classes.
164  addRegisterClass(MVT::i8, &X86::GR8RegClass);
165  addRegisterClass(MVT::i16, &X86::GR16RegClass);
166  addRegisterClass(MVT::i32, &X86::GR32RegClass);
167  if (Subtarget.is64Bit())
168  addRegisterClass(MVT::i64, &X86::GR64RegClass);
169 
170  for (MVT VT : MVT::integer_valuetypes())
172 
173  // We don't accept any truncstore of integer registers.
180 
182 
183  // SETOEQ and SETUNE require checking two conditions.
190 
191  // Integer absolute.
192  if (Subtarget.hasCMov()) {
195  if (Subtarget.is64Bit())
197  }
198 
199  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
200  // operation.
204 
205  if (Subtarget.is64Bit()) {
206  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
207  // f32/f64 are legal, f80 is custom.
209  else
212  } else if (!Subtarget.useSoftFloat()) {
213  // We have an algorithm for SSE2->double, and we turn this into a
214  // 64-bit FILD followed by conditional FADD for other targets.
216  // We have an algorithm for SSE2, and we turn this into a 64-bit
217  // FILD or VCVTUSI2SS/SD for other targets.
219  } else {
221  }
222 
223  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
224  // this operation.
227 
228  if (!Subtarget.useSoftFloat()) {
229  // SSE has no i16 to fp conversion, only i32.
230  if (X86ScalarSSEf32) {
232  // f32 and f64 cases are Legal, f80 case is not
234  } else {
237  }
238  } else {
241  }
242 
243  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
244  // this operation.
247 
248  if (!Subtarget.useSoftFloat()) {
249  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
250  // are Legal, f80 is custom lowered.
253 
254  if (X86ScalarSSEf32) {
256  // f32 and f64 cases are Legal, f80 case is not
258  } else {
261  }
262  } else {
266  }
267 
268  // Handle FP_TO_UINT by promoting the destination to a larger signed
269  // conversion.
273 
274  if (Subtarget.is64Bit()) {
275  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
276  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
279  } else {
282  }
283  } else if (!Subtarget.useSoftFloat()) {
284  // Since AVX is a superset of SSE3, only check for SSE here.
285  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
286  // Expand FP_TO_UINT into a select.
287  // FIXME: We would like to use a Custom expander here eventually to do
288  // the optimal thing for SSE vs. the default expansion in the legalizer.
290  else
291  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
292  // With SSE3 we can use fisttpll to convert to a signed i64; without
293  // SSE, we're stuck with a fistpll.
295 
297  }
298 
299  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
300  if (!X86ScalarSSEf64) {
303  if (Subtarget.is64Bit()) {
305  // Without SSE, i64->f64 goes through memory.
307  }
308  } else if (!Subtarget.is64Bit())
310 
311  // Scalar integer divide and remainder are lowered to use operations that
312  // produce two results, to match the available instructions. This exposes
313  // the two-result form to trivial CSE, which is able to combine x/y and x%y
314  // into a single instruction.
315  //
316  // Scalar integer multiply-high is also lowered to use two-result
317  // operations, to match the available instructions. However, plain multiply
318  // (low) operations are left as Legal, as there are single-result
319  // instructions for this in x86. Using the two-result multiply instructions
320  // when both high and low results are needed must be arranged by dagcombine.
321  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
328  }
329 
332  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
336  }
337  if (Subtarget.is64Bit())
343 
348 
349  // Promote the i8 variants and force them on up to i32 which has a shorter
350  // encoding.
353  if (!Subtarget.hasBMI()) {
358  if (Subtarget.is64Bit()) {
361  }
362  }
363 
364  if (Subtarget.hasLZCNT()) {
365  // When promoting the i8 variants, force them to i32 for a shorter
366  // encoding.
369  } else {
376  if (Subtarget.is64Bit()) {
379  }
380  }
381 
382  // Special handling for half-precision floating point conversions.
383  // If we don't have F16C support, then lower half float conversions
384  // into library calls.
385  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
388  }
389 
390  // There's never any support for operations beyond MVT::f32.
395 
402 
403  if (Subtarget.hasPOPCNT()) {
405  } else {
409  if (Subtarget.is64Bit())
411  }
412 
414 
415  if (!Subtarget.hasMOVBE())
417 
418  // These should be promoted to a larger select which is supported.
420  // X86 wants to expand cmov itself.
421  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
424  }
425  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
426  if (VT == MVT::i64 && !Subtarget.is64Bit())
427  continue;
430  }
431 
432  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
435 
437  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
438  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
443  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
444 
445  // Darwin ABI issue.
446  for (auto VT : { MVT::i32, MVT::i64 }) {
447  if (VT == MVT::i64 && !Subtarget.is64Bit())
448  continue;
455  }
456 
457  // 64-bit shl, sra, srl (iff 32-bit x86)
458  for (auto VT : { MVT::i32, MVT::i64 }) {
459  if (VT == MVT::i64 && !Subtarget.is64Bit())
460  continue;
464  }
465 
466  if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
468 
470 
471  // Expand certain atomics
472  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
480  }
481 
482  if (Subtarget.hasCmpxchg16b()) {
484  }
485 
486  // FIXME - use subtarget debug flags
487  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
488  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
491  }
492 
495 
498 
501 
502  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
505  bool Is64Bit = Subtarget.is64Bit();
507  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
508 
511 
513 
514  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
517 
518  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
519  // f32 and f64 use SSE.
520  // Set up the FP register classes.
521  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
522  : &X86::FR32RegClass);
523  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
524  : &X86::FR64RegClass);
525 
526  for (auto VT : { MVT::f32, MVT::f64 }) {
527  // Use ANDPD to simulate FABS.
529 
530  // Use XORP to simulate FNEG.
532 
533  // Use ANDPD and ORPD to simulate FCOPYSIGN.
535 
536  // We don't support sin/cos/fmod
537  setOperationAction(ISD::FSIN , VT, Expand);
538  setOperationAction(ISD::FCOS , VT, Expand);
539  setOperationAction(ISD::FSINCOS, VT, Expand);
540  }
541 
542  // Lower this to MOVMSK plus an AND.
545 
546  // Expand FP immediates into loads from the stack, except for the special
547  // cases we handle.
548  addLegalFPImmediate(APFloat(+0.0)); // xorpd
549  addLegalFPImmediate(APFloat(+0.0f)); // xorps
550  } else if (UseX87 && X86ScalarSSEf32) {
551  // Use SSE for f32, x87 for f64.
552  // Set up the FP register classes.
553  addRegisterClass(MVT::f32, &X86::FR32RegClass);
554  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
555 
556  // Use ANDPS to simulate FABS.
558 
559  // Use XORP to simulate FNEG.
561 
563 
564  // Use ANDPS and ORPS to simulate FCOPYSIGN.
567 
568  // We don't support sin/cos/fmod
572 
573  // Special cases we handle for FP constants.
574  addLegalFPImmediate(APFloat(+0.0f)); // xorps
575  addLegalFPImmediate(APFloat(+0.0)); // FLD0
576  addLegalFPImmediate(APFloat(+1.0)); // FLD1
577  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
578  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
579 
580  // Always expand sin/cos functions even though x87 has an instruction.
584  } else if (UseX87) {
585  // f32 and f64 in x87.
586  // Set up the FP register classes.
587  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
588  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
589 
590  for (auto VT : { MVT::f32, MVT::f64 }) {
591  setOperationAction(ISD::UNDEF, VT, Expand);
592  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
593 
594  // Always expand sin/cos functions even though x87 has an instruction.
595  setOperationAction(ISD::FSIN , VT, Expand);
596  setOperationAction(ISD::FCOS , VT, Expand);
597  setOperationAction(ISD::FSINCOS, VT, Expand);
598  }
599  addLegalFPImmediate(APFloat(+0.0)); // FLD0
600  addLegalFPImmediate(APFloat(+1.0)); // FLD1
601  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
602  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
603  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
604  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
605  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
606  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
607  }
608 
609  // We don't support FMA.
612 
613  // Long double always uses X87, except f128 in MMX.
614  if (UseX87) {
615  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
616  addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
617  : &X86::VR128RegClass);
622  }
623 
624  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
627  {
629  addLegalFPImmediate(TmpFlt); // FLD0
630  TmpFlt.changeSign();
631  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
632 
633  bool ignored;
634  APFloat TmpFlt2(+1.0);
636  &ignored);
637  addLegalFPImmediate(TmpFlt2); // FLD1
638  TmpFlt2.changeSign();
639  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
640  }
641 
642  // Always expand sin/cos functions even though x87 has an instruction.
646 
653  }
654 
655  // Always use a library call for pow.
659 
667 
668  // Some FP actions are always expanded for vector types.
669  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
671  setOperationAction(ISD::FSIN, VT, Expand);
672  setOperationAction(ISD::FSINCOS, VT, Expand);
673  setOperationAction(ISD::FCOS, VT, Expand);
674  setOperationAction(ISD::FREM, VT, Expand);
675  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
676  setOperationAction(ISD::FPOW, VT, Expand);
677  setOperationAction(ISD::FLOG, VT, Expand);
678  setOperationAction(ISD::FLOG2, VT, Expand);
679  setOperationAction(ISD::FLOG10, VT, Expand);
680  setOperationAction(ISD::FEXP, VT, Expand);
681  setOperationAction(ISD::FEXP2, VT, Expand);
682  }
683 
684  // First set operation action for all vector types to either promote
685  // (for widening) or expand (for scalarization). Then we will selectively
686  // turn on ones that can be effectively codegen'd.
687  for (MVT VT : MVT::vector_valuetypes()) {
688  setOperationAction(ISD::SDIV, VT, Expand);
689  setOperationAction(ISD::UDIV, VT, Expand);
690  setOperationAction(ISD::SREM, VT, Expand);
691  setOperationAction(ISD::UREM, VT, Expand);
696  setOperationAction(ISD::FMA, VT, Expand);
697  setOperationAction(ISD::FFLOOR, VT, Expand);
698  setOperationAction(ISD::FCEIL, VT, Expand);
699  setOperationAction(ISD::FTRUNC, VT, Expand);
700  setOperationAction(ISD::FRINT, VT, Expand);
701  setOperationAction(ISD::FNEARBYINT, VT, Expand);
702  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
703  setOperationAction(ISD::MULHS, VT, Expand);
704  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
705  setOperationAction(ISD::MULHU, VT, Expand);
706  setOperationAction(ISD::SDIVREM, VT, Expand);
707  setOperationAction(ISD::UDIVREM, VT, Expand);
708  setOperationAction(ISD::CTPOP, VT, Expand);
709  setOperationAction(ISD::CTTZ, VT, Expand);
710  setOperationAction(ISD::CTLZ, VT, Expand);
711  setOperationAction(ISD::ROTL, VT, Expand);
712  setOperationAction(ISD::ROTR, VT, Expand);
713  setOperationAction(ISD::BSWAP, VT, Expand);
714  setOperationAction(ISD::SETCC, VT, Expand);
715  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
716  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
717  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
718  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
720  setOperationAction(ISD::TRUNCATE, VT, Expand);
723  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
724  setOperationAction(ISD::SELECT_CC, VT, Expand);
725  for (MVT InnerVT : MVT::vector_valuetypes()) {
726  setTruncStoreAction(InnerVT, VT, Expand);
727 
728  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
729  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
730 
731  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
732  // types, we have to deal with them whether we ask for Expansion or not.
733  // Setting Expand causes its own optimisation problems though, so leave
734  // them legal.
735  if (VT.getVectorElementType() == MVT::i1)
736  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
737 
738  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
739  // split/scalarized right now.
740  if (VT.getVectorElementType() == MVT::f16)
741  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
742  }
743  }
744 
745  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
746  // with -msoft-float, disable use of MMX as well.
747  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
748  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
749  // No operations on x86mmx supported, everything uses intrinsics.
750  }
751 
752  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
753  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
754  : &X86::VR128RegClass);
755 
765  }
766 
767  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
768  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
769  : &X86::VR128RegClass);
770 
771  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
772  // registers cannot be used even for integer operations.
773  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
774  : &X86::VR128RegClass);
775  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
776  : &X86::VR128RegClass);
777  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
778  : &X86::VR128RegClass);
779  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
780  : &X86::VR128RegClass);
781 
786 
800 
801  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
803  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
804  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
805  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
806  }
807 
811 
812  // Provide custom widening for v2f32 setcc. This is really for VLX when
813  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
814  // type legalization changing the result type to v4i1 during widening.
815  // It works fine for SSE2 and is probably faster so no need to qualify with
816  // VLX support.
818 
819  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
823 
824  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
825  // setcc all the way to isel and prefer SETGT in some isel patterns.
828  }
829 
830  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
836  }
837 
838  // We support custom legalizing of sext and anyext loads for specific
839  // memory vector types which we can load as a scalar (or sequence of
840  // scalars) and extend in-register to a legal 128-bit vector type. For sext
841  // loads these must work with a single scalar load.
842  for (MVT VT : MVT::integer_vector_valuetypes()) {
852  }
853 
854  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
858 
859  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
860  continue;
861 
864  }
865 
866  // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
867  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
873  }
874 
875  // Custom lower v2i64 and v2f64 selects.
878 
881 
884 
886 
887  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
889 
892 
893  for (MVT VT : MVT::fp_vector_valuetypes())
895 
899  if (!Subtarget.hasAVX512())
901 
905 
906  // In the customized shift lowering, the legal v4i32/v2i64 cases
907  // in AVX2 will be recognized.
908  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
912  }
913 
917  }
918 
919  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
928  }
929 
930  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
931  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
932  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
933  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
934  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
935  setOperationAction(ISD::FRINT, RoundedTy, Legal);
937  }
938 
947 
948  // FIXME: Do we need to handle scalar-to-vector here?
950 
951  // We directly match byte blends in the backend as they match the VSELECT
952  // condition form.
954 
955  // SSE41 brings specific instructions for doing vector sign extend even in
956  // cases where we don't have SRA.
957  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
960  }
961 
962  for (MVT VT : MVT::integer_vector_valuetypes()) {
966  }
967 
968  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
969  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
977  }
978 
979  // i8 vectors are custom because the source register and source
980  // source memory operand types are not the same width.
982  }
983 
984  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
985  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
988 
989  // XOP can efficiently perform BITREVERSE with VPPERM.
990  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
992 
993  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
996  }
997 
998  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
999  bool HasInt256 = Subtarget.hasInt256();
1000 
1001  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1002  : &X86::VR256RegClass);
1003  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1004  : &X86::VR256RegClass);
1005  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1006  : &X86::VR256RegClass);
1007  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1008  : &X86::VR256RegClass);
1009  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1010  : &X86::VR256RegClass);
1011  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1012  : &X86::VR256RegClass);
1013 
1014  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1023  }
1024 
1025  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1026  // even though v8i16 is a legal type.
1030 
1033 
1034  if (!Subtarget.hasAVX512())
1036 
1037  for (MVT VT : MVT::fp_vector_valuetypes())
1039 
1040  // In the customized shift lowering, the legal v8i32/v4i64 cases
1041  // in AVX2 will be recognized.
1042  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1046  }
1047 
1051 
1055 
1056  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1060  }
1061 
1066 
1067  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1072 
1073  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1074  // setcc all the way to isel and prefer SETGT in some isel patterns.
1077  }
1078 
1079  if (Subtarget.hasAnyFMA()) {
1080  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1083  }
1084 
1085  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1086  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1087  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1088  }
1089 
1092  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1094 
1097  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1098  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1101 
1106 
1107  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1108  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1109  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1110  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1111  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1112  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1113  }
1114 
1115  if (HasInt256) {
1119 
1120  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1121  // when we have a 256bit-wide blend with immediate.
1123 
1124  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1125  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1132  }
1133  }
1134 
1135  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1139  }
1140 
1141  // Extract subvector is special because the value type
1142  // (result) is 128-bit but the source is 256-bit wide.
1143  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1144  MVT::v4f32, MVT::v2f64 }) {
1146  }
1147 
1148  // Custom lower several nodes for 256-bit types.
1150  MVT::v8f32, MVT::v4f64 }) {
1153  setOperationAction(ISD::VSELECT, VT, Custom);
1159  }
1160 
1161  if (HasInt256)
1163 
1164  // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1165  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1171  }
1172 
1173  if (HasInt256) {
1174  // Custom legalize 2x32 to get a little better code.
1177 
1178  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1180  setOperationAction(ISD::MGATHER, VT, Custom);
1181  }
1182  }
1183 
1184  // This block controls legalization of the mask vector sizes that are
1185  // available with AVX512. 512-bit vectors are in a separate block controlled
1186  // by useAVX512Regs.
1187  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1188  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1189  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1190  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1191  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1192  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1193 
1197 
1204 
1205  // There is no byte sized k-register load or store without AVX512DQ.
1206  if (!Subtarget.hasDQI()) {
1211 
1216  }
1217 
1218  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1219  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1223  }
1224 
1225  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1232 
1237  setOperationAction(ISD::VSELECT, VT, Expand);
1238  }
1239 
1247  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1249  }
1250 
1251  // This block controls legalization for 512-bit operations with 32/64 bit
1252  // elements. 512-bits can be disabled based on prefer-vector-width and
1253  // required-vector-width function attributes.
1254  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1255  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1256  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1257  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1258  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1259 
1260  for (MVT VT : MVT::fp_vector_valuetypes())
1262 
1263  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1269  }
1270 
1271  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1276  }
1277 
1288 
1294 
1295  if (!Subtarget.hasVLX()) {
1296  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1297  // to 512-bit rather than use the AVX2 instructions so that we can use
1298  // k-masks.
1299  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1303  }
1304  }
1305 
1314 
1315  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1321  }
1322 
1325 
1326  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1329 
1334 
1337 
1340 
1344 
1345  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1359 
1360  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1361  // setcc all the way to isel and prefer SETGT in some isel patterns.
1364  }
1365 
1366  // Need to promote to 64-bit even though we have 32-bit masked instructions
1367  // because the IR optimizers rearrange bitcasts around logic ops leaving
1368  // too many variations to handle if we don't promote them.
1372 
1373  if (Subtarget.hasDQI()) {
1378 
1380  }
1381 
1382  if (Subtarget.hasCDI()) {
1383  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1384  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1387  }
1388  } // Subtarget.hasCDI()
1389 
1390  if (Subtarget.hasVPOPCNTDQ()) {
1391  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1393  }
1394 
1395  // Extract subvector is special because the value type
1396  // (result) is 256-bit but the source is 512-bit wide.
1397  // 128-bit was made Legal under AVX1.
1398  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1401 
1402  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1414  }
1415  for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1418  }
1419 
1420  // Need to custom split v32i16/v64i8 bitcasts.
1421  if (!Subtarget.hasBWI()) {
1424  }
1425  }// has AVX-512
1426 
1427  // This block controls legalization for operations that don't have
1428  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1429  // narrower widths.
1430  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1431  // These operations are handled on non-VLX by artificially widening in
1432  // isel patterns.
1433  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1434 
1440 
1441  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1447  }
1448 
1449  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1452  }
1453 
1454  // Custom legalize 2x32 to get a little better code.
1457 
1458  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1461 
1462  if (Subtarget.hasDQI()) {
1463  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1468 
1470  }
1471  }
1472 
1473  if (Subtarget.hasCDI()) {
1474  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1477  }
1478  } // Subtarget.hasCDI()
1479 
1480  if (Subtarget.hasVPOPCNTDQ()) {
1481  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1483  }
1484  }
1485 
1486  // This block control legalization of v32i1/v64i1 which are available with
1487  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1488  // useBWIRegs.
1489  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1490  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1491  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1492 
1493  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1497  setOperationAction(ISD::VSELECT, VT, Expand);
1498 
1506  }
1507 
1512  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1514 
1515  // Extends from v32i1 masks to 256-bit vectors.
1519  }
1520 
1521  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1522  // disabled based on prefer-vector-width and required-vector-width function
1523  // attributes.
1524  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1525  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1526  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1527 
1528  // Extends from v64i1 masks to 512-bit vectors.
1532 
1556 
1558 
1560 
1561  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1578 
1582 
1583  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1584  // setcc all the way to isel and prefer SETGT in some isel patterns.
1587  }
1588 
1589  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1591  }
1592 
1593  if (Subtarget.hasBITALG()) {
1594  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1596  }
1597  }
1598 
1599  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1600  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1601  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1602  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1603  }
1604 
1605  // These operations are handled on non-VLX by artificially widening in
1606  // isel patterns.
1607  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1608 
1609  if (Subtarget.hasBITALG()) {
1610  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1612  }
1613  }
1614 
1615  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1621 
1627 
1628  if (Subtarget.hasDQI()) {
1629  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1630  // v2f32 UINT_TO_FP is already custom under SSE2.
1633  "Unexpected operation action!");
1634  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1637  }
1638 
1639  if (Subtarget.hasBWI()) {
1642  }
1643  }
1644 
1645  // We want to custom lower some of our intrinsics.
1649  if (!Subtarget.is64Bit()) {
1652  }
1653 
1654  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1655  // handle type legalization for these operations here.
1656  //
1657  // FIXME: We really should do custom legalization for addition and
1658  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1659  // than generic legalization for 64-bit multiplication-with-overflow, though.
1660  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1661  if (VT == MVT::i64 && !Subtarget.is64Bit())
1662  continue;
1663  // Add/Sub/Mul with overflow operations are custom lowered.
1670 
1671  // Support carry in as value rather than glue.
1675  }
1676 
1677  if (!Subtarget.is64Bit()) {
1678  // These libcalls are not available in 32-bit.
1679  setLibcallName(RTLIB::SHL_I128, nullptr);
1680  setLibcallName(RTLIB::SRL_I128, nullptr);
1681  setLibcallName(RTLIB::SRA_I128, nullptr);
1682  setLibcallName(RTLIB::MUL_I128, nullptr);
1683  }
1684 
1685  // Combine sin / cos into _sincos_stret if it is available.
1686  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1687  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1690  }
1691 
1692  if (Subtarget.isTargetWin64()) {
1699  }
1700 
1701  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1702  // is. We should promote the value to 64-bits to solve this.
1703  // This is what the CRT headers do - `fmodf` is an inline header
1704  // function casting to f64 and calling `fmod`.
1705  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1706  Subtarget.isTargetWindowsItanium()))
1707  for (ISD::NodeType Op :
1712 
1713  // We have target-specific dag combine patterns for the following nodes:
1753 
1755 
1756  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1758  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1760  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1762 
1763  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1764  // that needs to benchmarked and balanced with the potential use of vector
1765  // load/store types (PR33329, PR33914).
1766  MaxLoadsPerMemcmp = 2;
1768 
1769  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1771 
1772  // An out-of-order CPU can speculatively execute past a predictable branch,
1773  // but a conditional move could be stalled by an expensive earlier operation.
1774  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1775  EnableExtLdPromotion = true;
1776  setPrefFunctionAlignment(4); // 2^4 bytes.
1777 
1779 }
1780 
1781 // This has so far only been implemented for 64-bit MachO.
1783  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1784 }
1785 
1787  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1788  return Subtarget.getTargetTriple().isOSMSVCRT();
1789 }
1790 
1792  const SDLoc &DL) const {
1793  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1794  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1795  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1796  return SDValue(Node, 0);
1797 }
1798 
1801  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1802  return TypeSplitVector;
1803 
1805  VT.getVectorNumElements() != 1 &&
1807  return TypeWidenVector;
1808 
1810 }
1811 
1813  CallingConv::ID CC,
1814  EVT VT) const {
1815  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1816  return MVT::v32i8;
1817  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1818 }
1819 
1821  CallingConv::ID CC,
1822  EVT VT) const {
1823  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1824  return 1;
1825  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1826 }
1827 
1830  EVT VT) const {
1831  if (!VT.isVector())
1832  return MVT::i8;
1833 
1834  if (Subtarget.hasAVX512()) {
1835  const unsigned NumElts = VT.getVectorNumElements();
1836 
1837  // Figure out what this type will be legalized to.
1838  EVT LegalVT = VT;
1839  while (getTypeAction(Context, LegalVT) != TypeLegal)
1840  LegalVT = getTypeToTransformTo(Context, LegalVT);
1841 
1842  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1843  if (LegalVT.getSimpleVT().is512BitVector())
1844  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1845 
1846  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1847  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1848  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1849  // vXi16/vXi8.
1850  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1851  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1852  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1853  }
1854  }
1855 
1857 }
1858 
1859 /// Helper for getByValTypeAlignment to determine
1860 /// the desired ByVal argument alignment.
1861 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1862  if (MaxAlign == 16)
1863  return;
1864  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1865  if (VTy->getBitWidth() == 128)
1866  MaxAlign = 16;
1867  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1868  unsigned EltAlign = 0;
1869  getMaxByValAlign(ATy->getElementType(), EltAlign);
1870  if (EltAlign > MaxAlign)
1871  MaxAlign = EltAlign;
1872  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1873  for (auto *EltTy : STy->elements()) {
1874  unsigned EltAlign = 0;
1875  getMaxByValAlign(EltTy, EltAlign);
1876  if (EltAlign > MaxAlign)
1877  MaxAlign = EltAlign;
1878  if (MaxAlign == 16)
1879  break;
1880  }
1881  }
1882 }
1883 
1884 /// Return the desired alignment for ByVal aggregate
1885 /// function arguments in the caller parameter area. For X86, aggregates
1886 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1887 /// are at 4-byte boundaries.
1889  const DataLayout &DL) const {
1890  if (Subtarget.is64Bit()) {
1891  // Max of 8 and alignment of type.
1892  unsigned TyAlign = DL.getABITypeAlignment(Ty);
1893  if (TyAlign > 8)
1894  return TyAlign;
1895  return 8;
1896  }
1897 
1898  unsigned Align = 4;
1899  if (Subtarget.hasSSE1())
1900  getMaxByValAlign(Ty, Align);
1901  return Align;
1902 }
1903 
1904 /// Returns the target specific optimal type for load
1905 /// and store operations as a result of memset, memcpy, and memmove
1906 /// lowering. If DstAlign is zero that means it's safe to destination
1907 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1908 /// means there isn't a need to check it against alignment requirement,
1909 /// probably because the source does not need to be loaded. If 'IsMemset' is
1910 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1911 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1912 /// source is constant so it does not need to be loaded.
1913 /// It returns EVT::Other if the type should be determined using generic
1914 /// target-independent logic.
1915 EVT
1917  unsigned DstAlign, unsigned SrcAlign,
1918  bool IsMemset, bool ZeroMemset,
1919  bool MemcpyStrSrc,
1920  MachineFunction &MF) const {
1921  const Function &F = MF.getFunction();
1922  if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
1923  if (Size >= 16 &&
1924  (!Subtarget.isUnalignedMem16Slow() ||
1925  ((DstAlign == 0 || DstAlign >= 16) &&
1926  (SrcAlign == 0 || SrcAlign >= 16)))) {
1927  // FIXME: Check if unaligned 32-byte accesses are slow.
1928  if (Size >= 32 && Subtarget.hasAVX()) {
1929  // Although this isn't a well-supported type for AVX1, we'll let
1930  // legalization and shuffle lowering produce the optimal codegen. If we
1931  // choose an optimal type with a vector element larger than a byte,
1932  // getMemsetStores() may create an intermediate splat (using an integer
1933  // multiply) before we splat as a vector.
1934  return MVT::v32i8;
1935  }
1936  if (Subtarget.hasSSE2())
1937  return MVT::v16i8;
1938  // TODO: Can SSE1 handle a byte vector?
1939  if (Subtarget.hasSSE1())
1940  return MVT::v4f32;
1941  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1942  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1943  // Do not use f64 to lower memcpy if source is string constant. It's
1944  // better to use i32 to avoid the loads.
1945  // Also, do not use f64 to lower memset unless this is a memset of zeros.
1946  // The gymnastics of splatting a byte value into an XMM register and then
1947  // only using 8-byte stores (because this is a CPU with slow unaligned
1948  // 16-byte accesses) makes that a loser.
1949  return MVT::f64;
1950  }
1951  }
1952  // This is a compromise. If we reach here, unaligned accesses may be slow on
1953  // this target. However, creating smaller, aligned accesses could be even
1954  // slower and would certainly be a lot more code.
1955  if (Subtarget.is64Bit() && Size >= 8)
1956  return MVT::i64;
1957  return MVT::i32;
1958 }
1959 
1961  if (VT == MVT::f32)
1962  return X86ScalarSSEf32;
1963  else if (VT == MVT::f64)
1964  return X86ScalarSSEf64;
1965  return true;
1966 }
1967 
1968 bool
1970  unsigned,
1971  unsigned,
1972  bool *Fast) const {
1973  if (Fast) {
1974  switch (VT.getSizeInBits()) {
1975  default:
1976  // 8-byte and under are always assumed to be fast.
1977  *Fast = true;
1978  break;
1979  case 128:
1980  *Fast = !Subtarget.isUnalignedMem16Slow();
1981  break;
1982  case 256:
1983  *Fast = !Subtarget.isUnalignedMem32Slow();
1984  break;
1985  // TODO: What about AVX-512 (512-bit) accesses?
1986  }
1987  }
1988  // Misaligned accesses of any size are always allowed.
1989  return true;
1990 }
1991 
1992 /// Return the entry encoding for a jump table in the
1993 /// current function. The returned value is a member of the
1994 /// MachineJumpTableInfo::JTEntryKind enum.
1996  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1997  // symbol.
1998  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2000 
2001  // Otherwise, use the normal jump table encoding heuristics.
2003 }
2004 
2006  return Subtarget.useSoftFloat();
2007 }
2008 
2010  ArgListTy &Args) const {
2011 
2012  // Only relabel X86-32 for C / Stdcall CCs.
2013  if (Subtarget.is64Bit())
2014  return;
2015  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2016  return;
2017  unsigned ParamRegs = 0;
2018  if (auto *M = MF->getFunction().getParent())
2019  ParamRegs = M->getNumberRegisterParameters();
2020 
2021  // Mark the first N int arguments as having reg
2022  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2023  Type *T = Args[Idx].Ty;
2024  if (T->isIntOrPtrTy())
2025  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2026  unsigned numRegs = 1;
2027  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2028  numRegs = 2;
2029  if (ParamRegs < numRegs)
2030  return;
2031  ParamRegs -= numRegs;
2032  Args[Idx].IsInReg = true;
2033  }
2034  }
2035 }
2036 
2037 const MCExpr *
2039  const MachineBasicBlock *MBB,
2040  unsigned uid,MCContext &Ctx) const{
2041  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2042  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2043  // entries.
2044  return MCSymbolRefExpr::create(MBB->getSymbol(),
2046 }
2047 
2048 /// Returns relocation base for the given PIC jumptable.
2050  SelectionDAG &DAG) const {
2051  if (!Subtarget.is64Bit())
2052  // This doesn't have SDLoc associated with it, but is not really the
2053  // same as a Register.
2054  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2055  getPointerTy(DAG.getDataLayout()));
2056  return Table;
2057 }
2058 
2059 /// This returns the relocation base for the given PIC jumptable,
2060 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2063  MCContext &Ctx) const {
2064  // X86-64 uses RIP relative addressing based on the jump table label.
2065  if (Subtarget.isPICStyleRIPRel())
2066  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2067 
2068  // Otherwise, the reference is relative to the PIC base.
2069  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2070 }
2071 
2072 std::pair<const TargetRegisterClass *, uint8_t>
2074  MVT VT) const {
2075  const TargetRegisterClass *RRC = nullptr;
2076  uint8_t Cost = 1;
2077  switch (VT.SimpleTy) {
2078  default:
2080  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2081  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2082  break;
2083  case MVT::x86mmx:
2084  RRC = &X86::VR64RegClass;
2085  break;
2086  case MVT::f32: case MVT::f64:
2087  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2088  case MVT::v4f32: case MVT::v2f64:
2089  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2090  case MVT::v8f32: case MVT::v4f64:
2091  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2092  case MVT::v16f32: case MVT::v8f64:
2093  RRC = &X86::VR128XRegClass;
2094  break;
2095  }
2096  return std::make_pair(RRC, Cost);
2097 }
2098 
2099 unsigned X86TargetLowering::getAddressSpace() const {
2100  if (Subtarget.is64Bit())
2101  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2102  return 256;
2103 }
2104 
2105 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2106  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2107  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2108 }
2109 
2111  unsigned Offset, unsigned AddressSpace) {
2114  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2115 }
2116 
2118  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2119  // tcbhead_t; use it instead of the usual global variable (see
2120  // sysdeps/{i386,x86_64}/nptl/tls.h)
2121  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2122  if (Subtarget.isTargetFuchsia()) {
2123  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2124  return SegmentOffset(IRB, 0x10, getAddressSpace());
2125  } else {
2126  // %fs:0x28, unless we're using a Kernel code model, in which case
2127  // it's %gs:0x28. gs:0x14 on i386.
2128  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2129  return SegmentOffset(IRB, Offset, getAddressSpace());
2130  }
2131  }
2132 
2133  return TargetLowering::getIRStackGuard(IRB);
2134 }
2135 
2137  // MSVC CRT provides functionalities for stack protection.
2138  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2140  // MSVC CRT has a global variable holding security cookie.
2141  M.getOrInsertGlobal("__security_cookie",
2143 
2144  // MSVC CRT has a function to validate security cookie.
2145  auto *SecurityCheckCookie = cast<Function>(
2146  M.getOrInsertFunction("__security_check_cookie",
2149  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2150  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2151  return;
2152  }
2153  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2154  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2155  return;
2157 }
2158 
2160  // MSVC CRT has a global variable holding security cookie.
2161  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2163  return M.getGlobalVariable("__security_cookie");
2164  }
2166 }
2167 
2169  // MSVC CRT has a function to validate security cookie.
2170  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2172  return M.getFunction("__security_check_cookie");
2173  }
2175 }
2176 
2178  if (Subtarget.getTargetTriple().isOSContiki())
2179  return getDefaultSafeStackPointerLocation(IRB, false);
2180 
2181  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2182  // definition of TLS_SLOT_SAFESTACK in
2183  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2184  if (Subtarget.isTargetAndroid()) {
2185  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2186  // %gs:0x24 on i386
2187  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2188  return SegmentOffset(IRB, Offset, getAddressSpace());
2189  }
2190 
2191  // Fuchsia is similar.
2192  if (Subtarget.isTargetFuchsia()) {
2193  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2194  return SegmentOffset(IRB, 0x18, getAddressSpace());
2195  }
2196 
2198 }
2199 
2201  unsigned DestAS) const {
2202  assert(SrcAS != DestAS && "Expected different address spaces!");
2203 
2204  return SrcAS < 256 && DestAS < 256;
2205 }
2206 
2207 //===----------------------------------------------------------------------===//
2208 // Return Value Calling Convention Implementation
2209 //===----------------------------------------------------------------------===//
2210 
2211 #include "X86GenCallingConv.inc"
2212 
2213 bool X86TargetLowering::CanLowerReturn(
2214  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2215  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2217  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2218  return CCInfo.CheckReturn(Outs, RetCC_X86);
2219 }
2220 
2221 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2222  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2223  return ScratchRegs;
2224 }
2225 
2226 /// Lowers masks values (v*i1) to the local register values
2227 /// \returns DAG node after lowering to register type
2228 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2229  const SDLoc &Dl, SelectionDAG &DAG) {
2230  EVT ValVT = ValArg.getValueType();
2231 
2232  if (ValVT == MVT::v1i1)
2233  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2234  DAG.getIntPtrConstant(0, Dl));
2235 
2236  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2237  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2238  // Two stage lowering might be required
2239  // bitcast: v8i1 -> i8 / v16i1 -> i16
2240  // anyextend: i8 -> i32 / i16 -> i32
2241  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2242  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2243  if (ValLoc == MVT::i32)
2244  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2245  return ValToCopy;
2246  }
2247 
2248  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2249  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2250  // One stage lowering is required
2251  // bitcast: v32i1 -> i32 / v64i1 -> i64
2252  return DAG.getBitcast(ValLoc, ValArg);
2253  }
2254 
2255  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2256 }
2257 
2258 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2260  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2261  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2262  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2263  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2264  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2265  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2266  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2267  "The value should reside in two registers");
2268 
2269  // Before splitting the value we cast it to i64
2270  Arg = DAG.getBitcast(MVT::i64, Arg);
2271 
2272  // Splitting the value into two i32 types
2273  SDValue Lo, Hi;
2274  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2275  DAG.getConstant(0, Dl, MVT::i32));
2276  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2277  DAG.getConstant(1, Dl, MVT::i32));
2278 
2279  // Attach the two i32 types into corresponding registers
2280  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2281  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2282 }
2283 
2284 SDValue
2285 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2286  bool isVarArg,
2287  const SmallVectorImpl<ISD::OutputArg> &Outs,
2288  const SmallVectorImpl<SDValue> &OutVals,
2289  const SDLoc &dl, SelectionDAG &DAG) const {
2290  MachineFunction &MF = DAG.getMachineFunction();
2292 
2293  // In some cases we need to disable registers from the default CSR list.
2294  // For example, when they are used for argument passing.
2295  bool ShouldDisableCalleeSavedRegister =
2296  CallConv == CallingConv::X86_RegCall ||
2297  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2298 
2299  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2300  report_fatal_error("X86 interrupts may not return any value");
2301 
2303  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2304  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2305 
2306  SDValue Flag;
2307  SmallVector<SDValue, 6> RetOps;
2308  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2309  // Operand #1 = Bytes To Pop
2310  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2311  MVT::i32));
2312 
2313  // Copy the result values into the output registers.
2314  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2315  ++I, ++OutsIndex) {
2316  CCValAssign &VA = RVLocs[I];
2317  assert(VA.isRegLoc() && "Can only return in registers!");
2318 
2319  // Add the register to the CalleeSaveDisableRegs list.
2320  if (ShouldDisableCalleeSavedRegister)
2322 
2323  SDValue ValToCopy = OutVals[OutsIndex];
2324  EVT ValVT = ValToCopy.getValueType();
2325 
2326  // Promote values to the appropriate types.
2327  if (VA.getLocInfo() == CCValAssign::SExt)
2328  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2329  else if (VA.getLocInfo() == CCValAssign::ZExt)
2330  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2331  else if (VA.getLocInfo() == CCValAssign::AExt) {
2332  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2333  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2334  else
2335  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2336  }
2337  else if (VA.getLocInfo() == CCValAssign::BCvt)
2338  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2339 
2341  "Unexpected FP-extend for return value.");
2342 
2343  // If this is x86-64, and we disabled SSE, we can't return FP values,
2344  // or SSE or MMX vectors.
2345  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2346  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2347  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2348  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2349  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2350  } else if (ValVT == MVT::f64 &&
2351  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2352  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2353  // llvm-gcc has never done it right and no one has noticed, so this
2354  // should be OK for now.
2355  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2356  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2357  }
2358 
2359  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2360  // the RET instruction and handled by the FP Stackifier.
2361  if (VA.getLocReg() == X86::FP0 ||
2362  VA.getLocReg() == X86::FP1) {
2363  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2364  // change the value to the FP stack register class.
2365  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2366  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2367  RetOps.push_back(ValToCopy);
2368  // Don't emit a copytoreg.
2369  continue;
2370  }
2371 
2372  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2373  // which is returned in RAX / RDX.
2374  if (Subtarget.is64Bit()) {
2375  if (ValVT == MVT::x86mmx) {
2376  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2377  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2378  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2379  ValToCopy);
2380  // If we don't have SSE2 available, convert to v4f32 so the generated
2381  // register is legal.
2382  if (!Subtarget.hasSSE2())
2383  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2384  }
2385  }
2386  }
2387 
2389 
2390  if (VA.needsCustom()) {
2391  assert(VA.getValVT() == MVT::v64i1 &&
2392  "Currently the only custom case is when we split v64i1 to 2 regs");
2393 
2394  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2395  Subtarget);
2396 
2397  assert(2 == RegsToPass.size() &&
2398  "Expecting two registers after Pass64BitArgInRegs");
2399 
2400  // Add the second register to the CalleeSaveDisableRegs list.
2401  if (ShouldDisableCalleeSavedRegister)
2402  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2403  } else {
2404  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2405  }
2406 
2407  // Add nodes to the DAG and add the values into the RetOps list
2408  for (auto &Reg : RegsToPass) {
2409  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2410  Flag = Chain.getValue(1);
2411  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2412  }
2413  }
2414 
2415  // Swift calling convention does not require we copy the sret argument
2416  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2417 
2418  // All x86 ABIs require that for returning structs by value we copy
2419  // the sret argument into %rax/%eax (depending on ABI) for the return.
2420  // We saved the argument into a virtual register in the entry block,
2421  // so now we copy the value out and into %rax/%eax.
2422  //
2423  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2424  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2425  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2426  // either case FuncInfo->setSRetReturnReg() will have been called.
2427  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2428  // When we have both sret and another return value, we should use the
2429  // original Chain stored in RetOps[0], instead of the current Chain updated
2430  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2431 
2432  // For the case of sret and another return value, we have
2433  // Chain_0 at the function entry
2434  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2435  // If we use Chain_1 in getCopyFromReg, we will have
2436  // Val = getCopyFromReg(Chain_1)
2437  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2438 
2439  // getCopyToReg(Chain_0) will be glued together with
2440  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2441  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2442  // Data dependency from Unit B to Unit A due to usage of Val in
2443  // getCopyToReg(Chain_1, Val)
2444  // Chain dependency from Unit A to Unit B
2445 
2446  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2447  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2448  getPointerTy(MF.getDataLayout()));
2449 
2450  unsigned RetValReg
2451  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2452  X86::RAX : X86::EAX;
2453  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2454  Flag = Chain.getValue(1);
2455 
2456  // RAX/EAX now acts like a return value.
2457  RetOps.push_back(
2458  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2459 
2460  // Add the returned register to the CalleeSaveDisableRegs list.
2461  if (ShouldDisableCalleeSavedRegister)
2462  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2463  }
2464 
2465  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2466  const MCPhysReg *I =
2468  if (I) {
2469  for (; *I; ++I) {
2470  if (X86::GR64RegClass.contains(*I))
2471  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2472  else
2473  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2474  }
2475  }
2476 
2477  RetOps[0] = Chain; // Update chain.
2478 
2479  // Add the flag if we have it.
2480  if (Flag.getNode())
2481  RetOps.push_back(Flag);
2482 
2484  if (CallConv == CallingConv::X86_INTR)
2485  opcode = X86ISD::IRET;
2486  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2487 }
2488 
2489 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2490  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2491  return false;
2492 
2493  SDValue TCChain = Chain;
2494  SDNode *Copy = *N->use_begin();
2495  if (Copy->getOpcode() == ISD::CopyToReg) {
2496  // If the copy has a glue operand, we conservatively assume it isn't safe to
2497  // perform a tail call.
2498  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2499  return false;
2500  TCChain = Copy->getOperand(0);
2501  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2502  return false;
2503 
2504  bool HasRet = false;
2505  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2506  UI != UE; ++UI) {
2507  if (UI->getOpcode() != X86ISD::RET_FLAG)
2508  return false;
2509  // If we are returning more than one value, we can definitely
2510  // not make a tail call see PR19530
2511  if (UI->getNumOperands() > 4)
2512  return false;
2513  if (UI->getNumOperands() == 4 &&
2514  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2515  return false;
2516  HasRet = true;
2517  }
2518 
2519  if (!HasRet)
2520  return false;
2521 
2522  Chain = TCChain;
2523  return true;
2524 }
2525 
2526 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2527  ISD::NodeType ExtendKind) const {
2528  MVT ReturnMVT = MVT::i32;
2529 
2530  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2531  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2532  // The ABI does not require i1, i8 or i16 to be extended.
2533  //
2534  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2535  // always extending i8/i16 return values, so keep doing that for now.
2536  // (PR26665).
2537  ReturnMVT = MVT::i8;
2538  }
2539 
2540  EVT MinVT = getRegisterType(Context, ReturnMVT);
2541  return VT.bitsLT(MinVT) ? MinVT : VT;
2542 }
2543 
2544 /// Reads two 32 bit registers and creates a 64 bit mask value.
2545 /// \param VA The current 32 bit value that need to be assigned.
2546 /// \param NextVA The next 32 bit value that need to be assigned.
2547 /// \param Root The parent DAG node.
2548 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2549 /// glue purposes. In the case the DAG is already using
2550 /// physical register instead of virtual, we should glue
2551 /// our new SDValue to InFlag SDvalue.
2552 /// \return a new SDvalue of size 64bit.
2554  SDValue &Root, SelectionDAG &DAG,
2555  const SDLoc &Dl, const X86Subtarget &Subtarget,
2556  SDValue *InFlag = nullptr) {
2557  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2558  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2559  assert(VA.getValVT() == MVT::v64i1 &&
2560  "Expecting first location of 64 bit width type");
2561  assert(NextVA.getValVT() == VA.getValVT() &&
2562  "The locations should have the same type");
2563  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2564  "The values should reside in two registers");
2565 
2566  SDValue Lo, Hi;
2567  unsigned Reg;
2568  SDValue ArgValueLo, ArgValueHi;
2569 
2570  MachineFunction &MF = DAG.getMachineFunction();
2571  const TargetRegisterClass *RC = &X86::GR32RegClass;
2572 
2573  // Read a 32 bit value from the registers.
2574  if (nullptr == InFlag) {
2575  // When no physical register is present,
2576  // create an intermediate virtual register.
2577  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2578  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2579  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2580  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2581  } else {
2582  // When a physical register is available read the value from it and glue
2583  // the reads together.
2584  ArgValueLo =
2585  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2586  *InFlag = ArgValueLo.getValue(2);
2587  ArgValueHi =
2588  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2589  *InFlag = ArgValueHi.getValue(2);
2590  }
2591 
2592  // Convert the i32 type into v32i1 type.
2593  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2594 
2595  // Convert the i32 type into v32i1 type.
2596  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2597 
2598  // Concatenate the two values together.
2599  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2600 }
2601 
2602 /// The function will lower a register of various sizes (8/16/32/64)
2603 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2604 /// \returns a DAG node contains the operand after lowering to mask type.
2605 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2606  const EVT &ValLoc, const SDLoc &Dl,
2607  SelectionDAG &DAG) {
2608  SDValue ValReturned = ValArg;
2609 
2610  if (ValVT == MVT::v1i1)
2611  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2612 
2613  if (ValVT == MVT::v64i1) {
2614  // In 32 bit machine, this case is handled by getv64i1Argument
2615  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2616  // In 64 bit machine, There is no need to truncate the value only bitcast
2617  } else {
2618  MVT maskLen;
2619  switch (ValVT.getSimpleVT().SimpleTy) {
2620  case MVT::v8i1:
2621  maskLen = MVT::i8;
2622  break;
2623  case MVT::v16i1:
2624  maskLen = MVT::i16;
2625  break;
2626  case MVT::v32i1:
2627  maskLen = MVT::i32;
2628  break;
2629  default:
2630  llvm_unreachable("Expecting a vector of i1 types");
2631  }
2632 
2633  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2634  }
2635  return DAG.getBitcast(ValVT, ValReturned);
2636 }
2637 
2638 /// Lower the result values of a call into the
2639 /// appropriate copies out of appropriate physical registers.
2640 ///
2641 SDValue X86TargetLowering::LowerCallResult(
2642  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2643  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2644  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2645  uint32_t *RegMask) const {
2646 
2647  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2648  // Assign locations to each value returned by this call.
2650  bool Is64Bit = Subtarget.is64Bit();
2651  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2652  *DAG.getContext());
2653  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2654 
2655  // Copy all of the result registers out of their specified physreg.
2656  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2657  ++I, ++InsIndex) {
2658  CCValAssign &VA = RVLocs[I];
2659  EVT CopyVT = VA.getLocVT();
2660 
2661  // In some calling conventions we need to remove the used registers
2662  // from the register mask.
2663  if (RegMask) {
2664  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2665  SubRegs.isValid(); ++SubRegs)
2666  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2667  }
2668 
2669  // If this is x86-64, and we disabled SSE, we can't return FP values
2670  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2671  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2672  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2673  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2674  }
2675 
2676  // If we prefer to use the value in xmm registers, copy it out as f80 and
2677  // use a truncate to move it from fp stack reg to xmm reg.
2678  bool RoundAfterCopy = false;
2679  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2681  if (!Subtarget.hasX87())
2682  report_fatal_error("X87 register return with X87 disabled");
2683  CopyVT = MVT::f80;
2684  RoundAfterCopy = (CopyVT != VA.getLocVT());
2685  }
2686 
2687  SDValue Val;
2688  if (VA.needsCustom()) {
2689  assert(VA.getValVT() == MVT::v64i1 &&
2690  "Currently the only custom case is when we split v64i1 to 2 regs");
2691  Val =
2692  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2693  } else {
2694  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2695  .getValue(1);
2696  Val = Chain.getValue(0);
2697  InFlag = Chain.getValue(2);
2698  }
2699 
2700  if (RoundAfterCopy)
2701  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2702  // This truncation won't change the value.
2703  DAG.getIntPtrConstant(1, dl));
2704 
2705  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2706  if (VA.getValVT().isVector() &&
2707  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2708  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2709  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2710  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2711  } else
2712  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2713  }
2714 
2715  InVals.push_back(Val);
2716  }
2717 
2718  return Chain;
2719 }
2720 
2721 //===----------------------------------------------------------------------===//
2722 // C & StdCall & Fast Calling Convention implementation
2723 //===----------------------------------------------------------------------===//
2724 // StdCall calling convention seems to be standard for many Windows' API
2725 // routines and around. It differs from C calling convention just a little:
2726 // callee should clean up the stack, not caller. Symbols should be also
2727 // decorated in some fancy way :) It doesn't support any vector arguments.
2728 // For info on fast calling convention see Fast Calling Convention (tail call)
2729 // implementation LowerX86_32FastCCCallTo.
2730 
2731 /// CallIsStructReturn - Determines whether a call uses struct return
2732 /// semantics.
2737 };
2738 static StructReturnType
2740  if (Outs.empty())
2741  return NotStructReturn;
2742 
2743  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2744  if (!Flags.isSRet())
2745  return NotStructReturn;
2746  if (Flags.isInReg() || IsMCU)
2747  return RegStructReturn;
2748  return StackStructReturn;
2749 }
2750 
2751 /// Determines whether a function uses struct return semantics.
2752 static StructReturnType
2754  if (Ins.empty())
2755  return NotStructReturn;
2756 
2757  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2758  if (!Flags.isSRet())
2759  return NotStructReturn;
2760  if (Flags.isInReg() || IsMCU)
2761  return RegStructReturn;
2762  return StackStructReturn;
2763 }
2764 
2765 /// Make a copy of an aggregate at address specified by "Src" to address
2766 /// "Dst" with size and alignment information specified by the specific
2767 /// parameter attribute. The copy will be passed as a byval function parameter.
2769  SDValue Chain, ISD::ArgFlagsTy Flags,
2770  SelectionDAG &DAG, const SDLoc &dl) {
2771  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2772 
2773  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2774  /*isVolatile*/false, /*AlwaysInline=*/true,
2775  /*isTailCall*/false,
2777 }
2778 
2779 /// Return true if the calling convention is one that we can guarantee TCO for.
2781  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2783  CC == CallingConv::HHVM);
2784 }
2785 
2786 /// Return true if we might ever do TCO for calls with this calling convention.
2788  switch (CC) {
2789  // C calling conventions:
2790  case CallingConv::C:
2791  case CallingConv::Win64:
2793  // Callee pop conventions:
2798  return true;
2799  default:
2800  return canGuaranteeTCO(CC);
2801  }
2802 }
2803 
2804 /// Return true if the function is being made into a tailcall target by
2805 /// changing its ABI.
2806 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2807  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2808 }
2809 
2810 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2811  auto Attr =
2812  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2813  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2814  return false;
2815 
2816  ImmutableCallSite CS(CI);
2817  CallingConv::ID CalleeCC = CS.getCallingConv();
2818  if (!mayTailCallThisCC(CalleeCC))
2819  return false;
2820 
2821  return true;
2822 }
2823 
2824 SDValue
2825 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2826  const SmallVectorImpl<ISD::InputArg> &Ins,
2827  const SDLoc &dl, SelectionDAG &DAG,
2828  const CCValAssign &VA,
2829  MachineFrameInfo &MFI, unsigned i) const {
2830  // Create the nodes corresponding to a load from this parameter slot.
2831  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2832  bool AlwaysUseMutable = shouldGuaranteeTCO(
2833  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2834  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2835  EVT ValVT;
2836  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2837 
2838  // If value is passed by pointer we have address passed instead of the value
2839  // itself. No need to extend if the mask value and location share the same
2840  // absolute size.
2841  bool ExtendedInMem =
2842  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2843  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2844 
2845  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2846  ValVT = VA.getLocVT();
2847  else
2848  ValVT = VA.getValVT();
2849 
2850  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2851  // taken by a return address.
2852  int Offset = 0;
2853  if (CallConv == CallingConv::X86_INTR) {
2854  // X86 interrupts may take one or two arguments.
2855  // On the stack there will be no return address as in regular call.
2856  // Offset of last argument need to be set to -4/-8 bytes.
2857  // Where offset of the first argument out of two, should be set to 0 bytes.
2858  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2859  if (Subtarget.is64Bit() && Ins.size() == 2) {
2860  // The stack pointer needs to be realigned for 64 bit handlers with error
2861  // code, so the argument offset changes by 8 bytes.
2862  Offset += 8;
2863  }
2864  }
2865 
2866  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2867  // changed with more analysis.
2868  // In case of tail call optimization mark all arguments mutable. Since they
2869  // could be overwritten by lowering of arguments in case of a tail call.
2870  if (Flags.isByVal()) {
2871  unsigned Bytes = Flags.getByValSize();
2872  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2873 
2874  // FIXME: For now, all byval parameter objects are marked as aliasing. This
2875  // can be improved with deeper analysis.
2876  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2877  /*isAliased=*/true);
2878  // Adjust SP offset of interrupt parameter.
2879  if (CallConv == CallingConv::X86_INTR) {
2880  MFI.setObjectOffset(FI, Offset);
2881  }
2882  return DAG.getFrameIndex(FI, PtrVT);
2883  }
2884 
2885  // This is an argument in memory. We might be able to perform copy elision.
2886  if (Flags.isCopyElisionCandidate()) {
2887  EVT ArgVT = Ins[i].ArgVT;
2888  SDValue PartAddr;
2889  if (Ins[i].PartOffset == 0) {
2890  // If this is a one-part value or the first part of a multi-part value,
2891  // create a stack object for the entire argument value type and return a
2892  // load from our portion of it. This assumes that if the first part of an
2893  // argument is in memory, the rest will also be in memory.
2894  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2895  /*Immutable=*/false);
2896  PartAddr = DAG.getFrameIndex(FI, PtrVT);
2897  return DAG.getLoad(
2898  ValVT, dl, Chain, PartAddr,
2900  } else {
2901  // This is not the first piece of an argument in memory. See if there is
2902  // already a fixed stack object including this offset. If so, assume it
2903  // was created by the PartOffset == 0 branch above and create a load from
2904  // the appropriate offset into it.
2905  int64_t PartBegin = VA.getLocMemOffset();
2906  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2907  int FI = MFI.getObjectIndexBegin();
2908  for (; MFI.isFixedObjectIndex(FI); ++FI) {
2909  int64_t ObjBegin = MFI.getObjectOffset(FI);
2910  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2911  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2912  break;
2913  }
2914  if (MFI.isFixedObjectIndex(FI)) {
2915  SDValue Addr =
2916  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2917  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2918  return DAG.getLoad(
2919  ValVT, dl, Chain, Addr,
2921  Ins[i].PartOffset));
2922  }
2923  }
2924  }
2925 
2926  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2927  VA.getLocMemOffset(), isImmutable);
2928 
2929  // Set SExt or ZExt flag.
2930  if (VA.getLocInfo() == CCValAssign::ZExt) {
2931  MFI.setObjectZExt(FI, true);
2932  } else if (VA.getLocInfo() == CCValAssign::SExt) {
2933  MFI.setObjectSExt(FI, true);
2934  }
2935 
2936  // Adjust SP offset of interrupt parameter.
2937  if (CallConv == CallingConv::X86_INTR) {
2938  MFI.setObjectOffset(FI, Offset);
2939  }
2940 
2941  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2942  SDValue Val = DAG.getLoad(
2943  ValVT, dl, Chain, FIN,
2945  return ExtendedInMem
2946  ? (VA.getValVT().isVector()
2947  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2948  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2949  : Val;
2950 }
2951 
2952 // FIXME: Get this from tablegen.
2954  const X86Subtarget &Subtarget) {
2955  assert(Subtarget.is64Bit());
2956 
2957  if (Subtarget.isCallingConvWin64(CallConv)) {
2958  static const MCPhysReg GPR64ArgRegsWin64[] = {
2959  X86::RCX, X86::RDX, X86::R8, X86::R9
2960  };
2961  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2962  }
2963 
2964  static const MCPhysReg GPR64ArgRegs64Bit[] = {
2965  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2966  };
2967  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2968 }
2969 
2970 // FIXME: Get this from tablegen.
2972  CallingConv::ID CallConv,
2973  const X86Subtarget &Subtarget) {
2974  assert(Subtarget.is64Bit());
2975  if (Subtarget.isCallingConvWin64(CallConv)) {
2976  // The XMM registers which might contain var arg parameters are shadowed
2977  // in their paired GPR. So we only need to save the GPR to their home
2978  // slots.
2979  // TODO: __vectorcall will change this.
2980  return None;
2981  }
2982 
2983  const Function &F = MF.getFunction();
2984  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
2985  bool isSoftFloat = Subtarget.useSoftFloat();
2986  assert(!(isSoftFloat && NoImplicitFloatOps) &&
2987  "SSE register cannot be used when SSE is disabled!");
2988  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2989  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2990  // registers.
2991  return None;
2992 
2993  static const MCPhysReg XMMArgRegs64Bit[] = {
2994  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2995  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2996  };
2997  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2998 }
2999 
3000 #ifndef NDEBUG
3002  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3003  [](const CCValAssign &A, const CCValAssign &B) -> bool {
3004  return A.getValNo() < B.getValNo();
3005  });
3006 }
3007 #endif
3008 
3009 SDValue X86TargetLowering::LowerFormalArguments(
3010  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3011  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3012  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3013  MachineFunction &MF = DAG.getMachineFunction();
3015  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3016 
3017  const Function &F = MF.getFunction();
3018  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3019  F.getName() == "main")
3020  FuncInfo->setForceFramePointer(true);
3021 
3022  MachineFrameInfo &MFI = MF.getFrameInfo();
3023  bool Is64Bit = Subtarget.is64Bit();
3024  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3025 
3026  assert(
3027  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3028  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3029 
3030  if (CallConv == CallingConv::X86_INTR) {
3031  bool isLegal = Ins.size() == 1 ||
3032  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3033  (!Is64Bit && Ins[1].VT == MVT::i32)));
3034  if (!isLegal)
3035  report_fatal_error("X86 interrupts may take one or two arguments");
3036  }
3037 
3038  // Assign locations to all of the incoming arguments.
3040  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3041 
3042  // Allocate shadow area for Win64.
3043  if (IsWin64)
3044  CCInfo.AllocateStack(32, 8);
3045 
3046  CCInfo.AnalyzeArguments(Ins, CC_X86);
3047 
3048  // In vectorcall calling convention a second pass is required for the HVA
3049  // types.
3050  if (CallingConv::X86_VectorCall == CallConv) {
3051  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3052  }
3053 
3054  // The next loop assumes that the locations are in the same order of the
3055  // input arguments.
3056  assert(isSortedByValueNo(ArgLocs) &&
3057  "Argument Location list must be sorted before lowering");
3058 
3059  SDValue ArgValue;
3060  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3061  ++I, ++InsIndex) {
3062  assert(InsIndex < Ins.size() && "Invalid Ins index");
3063  CCValAssign &VA = ArgLocs[I];
3064 
3065  if (VA.isRegLoc()) {
3066  EVT RegVT = VA.getLocVT();
3067  if (VA.needsCustom()) {
3068  assert(
3069  VA.getValVT() == MVT::v64i1 &&
3070  "Currently the only custom case is when we split v64i1 to 2 regs");
3071 
3072  // v64i1 values, in regcall calling convention, that are
3073  // compiled to 32 bit arch, are split up into two registers.
3074  ArgValue =
3075  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3076  } else {
3077  const TargetRegisterClass *RC;
3078  if (RegVT == MVT::i8)
3079  RC = &X86::GR8RegClass;
3080  else if (RegVT == MVT::i16)
3081  RC = &X86::GR16RegClass;
3082  else if (RegVT == MVT::i32)
3083  RC = &X86::GR32RegClass;
3084  else if (Is64Bit && RegVT == MVT::i64)
3085  RC = &X86::GR64RegClass;
3086  else if (RegVT == MVT::f32)
3087  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3088  else if (RegVT == MVT::f64)
3089  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3090  else if (RegVT == MVT::f80)
3091  RC = &X86::RFP80RegClass;
3092  else if (RegVT == MVT::f128)
3093  RC = &X86::VR128RegClass;
3094  else if (RegVT.is512BitVector())
3095  RC = &X86::VR512RegClass;
3096  else if (RegVT.is256BitVector())
3097  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3098  else if (RegVT.is128BitVector())
3099  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3100  else if (RegVT == MVT::x86mmx)
3101  RC = &X86::VR64RegClass;
3102  else if (RegVT == MVT::v1i1)
3103  RC = &X86::VK1RegClass;
3104  else if (RegVT == MVT::v8i1)
3105  RC = &X86::VK8RegClass;
3106  else if (RegVT == MVT::v16i1)
3107  RC = &X86::VK16RegClass;
3108  else if (RegVT == MVT::v32i1)
3109  RC = &X86::VK32RegClass;
3110  else if (RegVT == MVT::v64i1)
3111  RC = &X86::VK64RegClass;
3112  else
3113  llvm_unreachable("Unknown argument type!");
3114 
3115  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3116  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3117  }
3118 
3119  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3120  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3121  // right size.
3122  if (VA.getLocInfo() == CCValAssign::SExt)
3123  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3124  DAG.getValueType(VA.getValVT()));
3125  else if (VA.getLocInfo() == CCValAssign::ZExt)
3126  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3127  DAG.getValueType(VA.getValVT()));
3128  else if (VA.getLocInfo() == CCValAssign::BCvt)
3129  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3130 
3131  if (VA.isExtInLoc()) {
3132  // Handle MMX values passed in XMM regs.
3133  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3134  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3135  else if (VA.getValVT().isVector() &&
3136  VA.getValVT().getScalarType() == MVT::i1 &&
3137  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3138  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3139  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3140  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3141  } else
3142  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3143  }
3144  } else {
3145  assert(VA.isMemLoc());
3146  ArgValue =
3147  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3148  }
3149 
3150  // If value is passed via pointer - do a load.
3151  if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3152  ArgValue =
3153  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3154 
3155  InVals.push_back(ArgValue);
3156  }
3157 
3158  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3159  // Swift calling convention does not require we copy the sret argument
3160  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3161  if (CallConv == CallingConv::Swift)
3162  continue;
3163 
3164  // All x86 ABIs require that for returning structs by value we copy the
3165  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3166  // the argument into a virtual register so that we can access it from the
3167  // return points.
3168  if (Ins[I].Flags.isSRet()) {
3169  unsigned Reg = FuncInfo->getSRetReturnReg();
3170  if (!Reg) {
3171  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3172  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3173  FuncInfo->setSRetReturnReg(Reg);
3174  }
3175  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3176  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3177  break;
3178  }
3179  }
3180 
3181  unsigned StackSize = CCInfo.getNextStackOffset();
3182  // Align stack specially for tail calls.
3183  if (shouldGuaranteeTCO(CallConv,
3185  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3186 
3187  // If the function takes variable number of arguments, make a frame index for
3188  // the start of the first vararg value... for expansion of llvm.va_start. We
3189  // can skip this if there are no va_start calls.
3190  if (MFI.hasVAStart() &&
3191  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3192  CallConv != CallingConv::X86_ThisCall))) {
3193  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3194  }
3195 
3196  // Figure out if XMM registers are in use.
3197  assert(!(Subtarget.useSoftFloat() &&
3198  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3199  "SSE register cannot be used when SSE is disabled!");
3200 
3201  // 64-bit calling conventions support varargs and register parameters, so we
3202  // have to do extra work to spill them in the prologue.
3203  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3204  // Find the first unallocated argument registers.
3205  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3206  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3207  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3208  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3209  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3210  "SSE register cannot be used when SSE is disabled!");
3211 
3212  // Gather all the live in physical registers.
3213  SmallVector<SDValue, 6> LiveGPRs;
3214  SmallVector<SDValue, 8> LiveXMMRegs;
3215  SDValue ALVal;
3216  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3217  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3218  LiveGPRs.push_back(
3219  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3220  }
3221  if (!ArgXMMs.empty()) {
3222  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3223  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3224  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3225  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3226  LiveXMMRegs.push_back(
3227  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3228  }
3229  }
3230 
3231  if (IsWin64) {
3232  // Get to the caller-allocated home save location. Add 8 to account
3233  // for the return address.
3234  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3235  FuncInfo->setRegSaveFrameIndex(
3236  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3237  // Fixup to set vararg frame on shadow area (4 x i64).
3238  if (NumIntRegs < 4)
3239  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3240  } else {
3241  // For X86-64, if there are vararg parameters that are passed via
3242  // registers, then we must store them to their spots on the stack so
3243  // they may be loaded by dereferencing the result of va_next.
3244  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3245  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3247  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3248  }
3249 
3250  // Store the integer parameter registers.
3251  SmallVector<SDValue, 8> MemOps;
3252  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3253  getPointerTy(DAG.getDataLayout()));
3254  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3255  for (SDValue Val : LiveGPRs) {
3256  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3257  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3258  SDValue Store =
3259  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3261  DAG.getMachineFunction(),
3262  FuncInfo->getRegSaveFrameIndex(), Offset));
3263  MemOps.push_back(Store);
3264  Offset += 8;
3265  }
3266 
3267  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3268  // Now store the XMM (fp + vector) parameter registers.
3269  SmallVector<SDValue, 12> SaveXMMOps;
3270  SaveXMMOps.push_back(Chain);
3271  SaveXMMOps.push_back(ALVal);
3272  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3273  FuncInfo->getRegSaveFrameIndex(), dl));
3274  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3275  FuncInfo->getVarArgsFPOffset(), dl));
3276  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3277  LiveXMMRegs.end());
3279  MVT::Other, SaveXMMOps));
3280  }
3281 
3282  if (!MemOps.empty())
3283  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3284  }
3285 
3286  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3287  // Find the largest legal vector type.
3288  MVT VecVT = MVT::Other;
3289  // FIXME: Only some x86_32 calling conventions support AVX512.
3290  if (Subtarget.hasAVX512() &&
3291  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3292  CallConv == CallingConv::Intel_OCL_BI)))
3293  VecVT = MVT::v16f32;
3294  else if (Subtarget.hasAVX())
3295  VecVT = MVT::v8f32;
3296  else if (Subtarget.hasSSE2())
3297  VecVT = MVT::v4f32;
3298 
3299  // We forward some GPRs and some vector types.
3300  SmallVector<MVT, 2> RegParmTypes;
3301  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3302  RegParmTypes.push_back(IntVT);
3303  if (VecVT != MVT::Other)
3304  RegParmTypes.push_back(VecVT);
3305 
3306  // Compute the set of forwarded registers. The rest are scratch.
3308  FuncInfo->getForwardedMustTailRegParms();
3309  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3310 
3311  // Conservatively forward AL on x86_64, since it might be used for varargs.
3312  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3313  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3314  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3315  }
3316 
3317  // Copy all forwards from physical to virtual registers.
3318  for (ForwardedRegister &F : Forwards) {
3319  // FIXME: Can we use a less constrained schedule?
3320  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3321  F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3322  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3323  }
3324  }
3325 
3326  // Some CCs need callee pop.
3327  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3329  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3330  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3331  // X86 interrupts must pop the error code (and the alignment padding) if
3332  // present.
3333  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3334  } else {
3335  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3336  // If this is an sret function, the return should pop the hidden pointer.
3337  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3338  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3339  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3340  FuncInfo->setBytesToPopOnReturn(4);
3341  }
3342 
3343  if (!Is64Bit) {
3344  // RegSaveFrameIndex is X86-64 only.
3345  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3346  if (CallConv == CallingConv::X86_FastCall ||
3347  CallConv == CallingConv::X86_ThisCall)
3348  // fastcc functions can't have varargs.
3349  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3350  }
3351 
3352  FuncInfo->setArgumentStackSize(StackSize);
3353 
3354  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3356  if (Personality == EHPersonality::CoreCLR) {
3357  assert(Is64Bit);
3358  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3359  // that we'd prefer this slot be allocated towards the bottom of the frame
3360  // (i.e. near the stack pointer after allocating the frame). Every
3361  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3362  // offset from the bottom of this and each funclet's frame must be the
3363  // same, so the size of funclets' (mostly empty) frames is dictated by
3364  // how far this slot is from the bottom (since they allocate just enough
3365  // space to accommodate holding this slot at the correct offset).
3366  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3367  EHInfo->PSPSymFrameIdx = PSPSymFI;
3368  }
3369  }
3370 
3371  if (CallConv == CallingConv::X86_RegCall ||
3372  F.hasFnAttribute("no_caller_saved_registers")) {
3374  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3375  MRI.disableCalleeSavedRegister(Pair.first);
3376  }
3377 
3378  return Chain;
3379 }
3380 
3381 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3382  SDValue Arg, const SDLoc &dl,
3383  SelectionDAG &DAG,
3384  const CCValAssign &VA,
3385  ISD::ArgFlagsTy Flags) const {
3386  unsigned LocMemOffset = VA.getLocMemOffset();
3387  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3388  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3389  StackPtr, PtrOff);
3390  if (Flags.isByVal())
3391  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3392 
3393  return DAG.getStore(
3394  Chain, dl, Arg, PtrOff,
3395  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3396 }
3397 
3398 /// Emit a load of return address if tail call
3399 /// optimization is performed and it is required.
3400 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3401  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3402  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3403  // Adjust the Return address stack slot.
3404  EVT VT = getPointerTy(DAG.getDataLayout());
3405  OutRetAddr = getReturnAddressFrameIndex(DAG);
3406 
3407  // Load the "old" Return address.
3408  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3409  return SDValue(OutRetAddr.getNode(), 1);
3410 }
3411 
3412 /// Emit a store of the return address if tail call
3413 /// optimization is performed and it is required (FPDiff!=0).
3415  SDValue Chain, SDValue RetAddrFrIdx,
3416  EVT PtrVT, unsigned SlotSize,
3417  int FPDiff, const SDLoc &dl) {
3418  // Store the return address to the appropriate stack slot.
3419  if (!FPDiff) return Chain;
3420  // Calculate the new stack slot for the return address.
3421  int NewReturnAddrFI =
3422  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3423  false);
3424  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3425  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3427  DAG.getMachineFunction(), NewReturnAddrFI));
3428  return Chain;
3429 }
3430 
3431 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3432 /// operation of specified width.
3433 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3434  SDValue V2) {
3435  unsigned NumElems = VT.getVectorNumElements();
3437  Mask.push_back(NumElems);
3438  for (unsigned i = 1; i != NumElems; ++i)
3439  Mask.push_back(i);
3440  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3441 }
3442 
3443 SDValue
3444 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3445  SmallVectorImpl<SDValue> &InVals) const {
3446  SelectionDAG &DAG = CLI.DAG;
3447  SDLoc &dl = CLI.DL;
3449  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3451  SDValue Chain = CLI.Chain;
3452  SDValue Callee = CLI.Callee;
3453  CallingConv::ID CallConv = CLI.CallConv;
3454  bool &isTailCall = CLI.IsTailCall;
3455  bool isVarArg = CLI.IsVarArg;
3456 
3457  MachineFunction &MF = DAG.getMachineFunction();
3458  bool Is64Bit = Subtarget.is64Bit();
3459  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3460  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3461  bool IsSibcall = false;
3463  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3464  const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3465  const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3466  bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3467  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3468  const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3469  bool HasNoCfCheck =
3470  (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3471  const Module *M = MF.getMMI().getModule();
3472  Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3473 
3474  if (CallConv == CallingConv::X86_INTR)
3475  report_fatal_error("X86 interrupts may not be called directly");
3476 
3477  if (Attr.getValueAsString() == "true")
3478  isTailCall = false;
3479 
3480  if (Subtarget.isPICStyleGOT() &&
3482  // If we are using a GOT, disable tail calls to external symbols with
3483  // default visibility. Tail calling such a symbol requires using a GOT
3484  // relocation, which forces early binding of the symbol. This breaks code
3485  // that require lazy function symbol resolution. Using musttail or
3486  // GuaranteedTailCallOpt will override this.
3488  if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3490  isTailCall = false;
3491  }
3492 
3493  bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3494  if (IsMustTail) {
3495  // Force this to be a tail call. The verifier rules are enough to ensure
3496  // that we can lower this successfully without moving the return address
3497  // around.
3498  isTailCall = true;
3499  } else if (isTailCall) {
3500  // Check if it's really possible to do a tail call.
3501  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3502  isVarArg, SR != NotStructReturn,
3503  MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3504  Outs, OutVals, Ins, DAG);
3505 
3506  // Sibcalls are automatically detected tailcalls which do not require
3507  // ABI changes.
3508  if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3509  IsSibcall = true;
3510 
3511  if (isTailCall)
3512  ++NumTailCalls;
3513  }
3514 
3515  assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3516  "Var args not supported with calling convention fastcc, ghc or hipe");
3517 
3518  // Analyze operands of the call, assigning locations to each operand.
3520  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3521 
3522  // Allocate shadow area for Win64.
3523  if (IsWin64)
3524  CCInfo.AllocateStack(32, 8);
3525 
3526  CCInfo.AnalyzeArguments(Outs, CC_X86);
3527 
3528  // In vectorcall calling convention a second pass is required for the HVA
3529  // types.
3530  if (CallingConv::X86_VectorCall == CallConv) {
3531  CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3532  }
3533 
3534  // Get a count of how many bytes are to be pushed on the stack.
3535  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3536  if (IsSibcall)
3537  // This is a sibcall. The memory operands are available in caller's
3538  // own caller's stack.
3539  NumBytes = 0;
3540  else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3541  canGuaranteeTCO(CallConv))
3542  NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3543 
3544  int FPDiff = 0;
3545  if (isTailCall && !IsSibcall && !IsMustTail) {
3546  // Lower arguments at fp - stackoffset + fpdiff.
3547  unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3548 
3549  FPDiff = NumBytesCallerPushed - NumBytes;
3550 
3551  // Set the delta of movement of the returnaddr stackslot.
3552  // But only set if delta is greater than previous delta.
3553  if (FPDiff < X86Info->getTCReturnAddrDelta())
3554  X86Info->setTCReturnAddrDelta(FPDiff);
3555  }
3556 
3557  unsigned NumBytesToPush = NumBytes;
3558  unsigned NumBytesToPop = NumBytes;
3559 
3560  // If we have an inalloca argument, all stack space has already been allocated
3561  // for us and be right at the top of the stack. We don't support multiple
3562  // arguments passed in memory when using inalloca.
3563  if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3564  NumBytesToPush = 0;
3565  if (!ArgLocs.back().isMemLoc())
3566  report_fatal_error("cannot use inalloca attribute on a register "
3567  "parameter");
3568  if (ArgLocs.back().getLocMemOffset() != 0)
3569  report_fatal_error("any parameter with the inalloca attribute must be "
3570  "the only memory argument");
3571  }
3572 
3573  if (!IsSibcall)
3574  Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3575  NumBytes - NumBytesToPush, dl);
3576 
3577  SDValue RetAddrFrIdx;
3578  // Load return address for tail calls.
3579  if (isTailCall && FPDiff)
3580  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3581  Is64Bit, FPDiff, dl);
3582 
3584  SmallVector<SDValue, 8> MemOpChains;
3585  SDValue StackPtr;
3586 
3587  // The next loop assumes that the locations are in the same order of the
3588  // input arguments.
3589  assert(isSortedByValueNo(ArgLocs) &&
3590  "Argument Location list must be sorted before lowering");
3591 
3592  // Walk the register/memloc assignments, inserting copies/loads. In the case
3593  // of tail call optimization arguments are handle later.
3594  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3595  for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3596  ++I, ++OutIndex) {
3597  assert(OutIndex < Outs.size() && "Invalid Out index");
3598  // Skip inalloca arguments, they have already been written.
3599  ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3600  if (Flags.isInAlloca())
3601  continue;
3602 
3603  CCValAssign &VA = ArgLocs[I];
3604  EVT RegVT = VA.getLocVT();
3605  SDValue Arg = OutVals[OutIndex];
3606  bool isByVal = Flags.isByVal();
3607 
3608  // Promote the value if needed.
3609  switch (VA.getLocInfo()) {
3610  default: llvm_unreachable("Unknown loc info!");
3611  case CCValAssign::Full: break;
3612  case CCValAssign::SExt:
3613  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3614  break;
3615  case CCValAssign::ZExt:
3616  Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3617  break;
3618  case CCValAssign::AExt:
3619  if (Arg.getValueType().isVector() &&
3621  Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3622  else if (RegVT.is128BitVector()) {
3623  // Special case: passing MMX values in XMM registers.
3624  Arg = DAG.getBitcast(MVT::i64, Arg);
3625  Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3626  Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3627  } else
3628  Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3629  break;
3630  case CCValAssign::BCvt:
3631  Arg = DAG.getBitcast(RegVT, Arg);
3632  break;
3633  case CCValAssign::Indirect: {
3634  if (isByVal) {
3635  // Memcpy the argument to a temporary stack slot to prevent
3636  // the caller from seeing any modifications the callee may make
3637  // as guaranteed by the `byval` attribute.
3638  int FrameIdx = MF.getFrameInfo().CreateStackObject(
3639  Flags.getByValSize(), std::max(16, (int)Flags.getByValAlign()),
3640  false);
3641  SDValue StackSlot =
3642  DAG.getFrameIndex(FrameIdx, getPointerTy(DAG.getDataLayout()));
3643  Chain =
3644  CreateCopyOfByValArgument(Arg, StackSlot, Chain, Flags, DAG, dl);
3645  // From now on treat this as a regular pointer
3646  Arg = StackSlot;
3647  isByVal = false;
3648  } else {
3649  // Store the argument.
3650  SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3651  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3652  Chain = DAG.getStore(
3653  Chain, dl, Arg, SpillSlot,
3655  Arg = SpillSlot;
3656  }
3657  break;
3658  }
3659  }
3660 
3661  if (VA.needsCustom()) {
3662  assert(VA.getValVT() == MVT::v64i1 &&
3663  "Currently the only custom case is when we split v64i1 to 2 regs");
3664  // Split v64i1 value into two registers
3665  Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3666  Subtarget);
3667  } else if (VA.isRegLoc()) {
3668  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3669  if (isVarArg && IsWin64) {
3670  // Win64 ABI requires argument XMM reg to be copied to the corresponding
3671  // shadow reg if callee is a varargs function.
3672  unsigned ShadowReg = 0;
3673  switch (VA.getLocReg()) {
3674  case X86::XMM0: ShadowReg = X86::RCX; break;
3675  case X86::XMM1: ShadowReg = X86::RDX; break;
3676  case X86::XMM2: ShadowReg = X86::R8; break;
3677  case X86::XMM3: ShadowReg = X86::R9; break;
3678  }
3679  if (ShadowReg)
3680  RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3681  }
3682  } else if (!IsSibcall && (!isTailCall || isByVal)) {
3683  assert(VA.isMemLoc());
3684  if (!StackPtr.getNode())
3685  StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3686  getPointerTy(DAG.getDataLayout()));
3687  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3688  dl, DAG, VA, Flags));
3689  }
3690  }
3691 
3692  if (!MemOpChains.empty())
3693  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3694 
3695  if (Subtarget.isPICStyleGOT()) {
3696  // ELF / PIC requires GOT in the EBX register before function calls via PLT
3697  // GOT pointer.
3698  if (!isTailCall) {
3699  RegsToPass.push_back(std::make_pair(
3700  unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3701  getPointerTy(DAG.getDataLayout()))));
3702  } else {