LLVM  7.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, &X86::VR128RegClass);
621  }
622 
623  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
626  {
628  addLegalFPImmediate(TmpFlt); // FLD0
629  TmpFlt.changeSign();
630  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
631 
632  bool ignored;
633  APFloat TmpFlt2(+1.0);
635  &ignored);
636  addLegalFPImmediate(TmpFlt2); // FLD1
637  TmpFlt2.changeSign();
638  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
639  }
640 
641  // Always expand sin/cos functions even though x87 has an instruction.
645 
652  }
653 
654  // Always use a library call for pow.
658 
666 
667  // Some FP actions are always expanded for vector types.
668  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
670  setOperationAction(ISD::FSIN, VT, Expand);
671  setOperationAction(ISD::FSINCOS, VT, Expand);
672  setOperationAction(ISD::FCOS, VT, Expand);
673  setOperationAction(ISD::FREM, VT, Expand);
674  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
675  setOperationAction(ISD::FPOW, VT, Expand);
676  setOperationAction(ISD::FLOG, VT, Expand);
677  setOperationAction(ISD::FLOG2, VT, Expand);
678  setOperationAction(ISD::FLOG10, VT, Expand);
679  setOperationAction(ISD::FEXP, VT, Expand);
680  setOperationAction(ISD::FEXP2, VT, Expand);
681  }
682 
683  // First set operation action for all vector types to either promote
684  // (for widening) or expand (for scalarization). Then we will selectively
685  // turn on ones that can be effectively codegen'd.
686  for (MVT VT : MVT::vector_valuetypes()) {
687  setOperationAction(ISD::SDIV, VT, Expand);
688  setOperationAction(ISD::UDIV, VT, Expand);
689  setOperationAction(ISD::SREM, VT, Expand);
690  setOperationAction(ISD::UREM, VT, Expand);
695  setOperationAction(ISD::FMA, VT, Expand);
696  setOperationAction(ISD::FFLOOR, VT, Expand);
697  setOperationAction(ISD::FCEIL, VT, Expand);
698  setOperationAction(ISD::FTRUNC, VT, Expand);
699  setOperationAction(ISD::FRINT, VT, Expand);
700  setOperationAction(ISD::FNEARBYINT, VT, Expand);
701  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
702  setOperationAction(ISD::MULHS, VT, Expand);
703  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
704  setOperationAction(ISD::MULHU, VT, Expand);
705  setOperationAction(ISD::SDIVREM, VT, Expand);
706  setOperationAction(ISD::UDIVREM, VT, Expand);
707  setOperationAction(ISD::CTPOP, VT, Expand);
708  setOperationAction(ISD::CTTZ, VT, Expand);
709  setOperationAction(ISD::CTLZ, VT, Expand);
710  setOperationAction(ISD::ROTL, VT, Expand);
711  setOperationAction(ISD::ROTR, VT, Expand);
712  setOperationAction(ISD::BSWAP, VT, Expand);
713  setOperationAction(ISD::SETCC, VT, Expand);
714  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
715  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
716  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
717  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
719  setOperationAction(ISD::TRUNCATE, VT, Expand);
722  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
723  setOperationAction(ISD::SELECT_CC, VT, Expand);
724  for (MVT InnerVT : MVT::vector_valuetypes()) {
725  setTruncStoreAction(InnerVT, VT, Expand);
726 
727  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
728  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
729 
730  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
731  // types, we have to deal with them whether we ask for Expansion or not.
732  // Setting Expand causes its own optimisation problems though, so leave
733  // them legal.
734  if (VT.getVectorElementType() == MVT::i1)
735  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
736 
737  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
738  // split/scalarized right now.
739  if (VT.getVectorElementType() == MVT::f16)
740  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
741  }
742  }
743 
744  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
745  // with -msoft-float, disable use of MMX as well.
746  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
747  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
748  // No operations on x86mmx supported, everything uses intrinsics.
749  }
750 
751  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
752  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
753  : &X86::VR128RegClass);
754 
764  }
765 
766  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
767  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
768  : &X86::VR128RegClass);
769 
770  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
771  // registers cannot be used even for integer operations.
772  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
773  : &X86::VR128RegClass);
774  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
775  : &X86::VR128RegClass);
776  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
777  : &X86::VR128RegClass);
778  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
779  : &X86::VR128RegClass);
780 
794 
795  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
797  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
798  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
799  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
800  }
801 
805 
806  // Provide custom widening for v2f32 setcc. This is really for VLX when
807  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
808  // type legalization changing the result type to v4i1 during widening.
809  // It works fine for SSE2 and is probably faster so no need to qualify with
810  // VLX support.
812 
813  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
817 
818  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
819  // setcc all the way to isel and prefer SETGT in some isel patterns.
822  }
823 
824  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
830  }
831 
832  // We support custom legalizing of sext and anyext loads for specific
833  // memory vector types which we can load as a scalar (or sequence of
834  // scalars) and extend in-register to a legal 128-bit vector type. For sext
835  // loads these must work with a single scalar load.
836  for (MVT VT : MVT::integer_vector_valuetypes()) {
846  }
847 
848  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
852 
853  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
854  continue;
855 
858  }
859 
860  // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
861  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
867  }
868 
869  // Custom lower v2i64 and v2f64 selects.
872 
875 
878 
880 
881  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
883 
886 
887  for (MVT VT : MVT::fp_vector_valuetypes())
889 
893  if (!Subtarget.hasAVX512())
895 
899 
900  // In the customized shift lowering, the legal v4i32/v2i64 cases
901  // in AVX2 will be recognized.
902  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
906  }
907 
911  }
912 
913  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
922  }
923 
924  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
925  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
926  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
927  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
928  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
929  setOperationAction(ISD::FRINT, RoundedTy, Legal);
931  }
932 
941 
942  // FIXME: Do we need to handle scalar-to-vector here?
944 
945  // We directly match byte blends in the backend as they match the VSELECT
946  // condition form.
948 
949  // SSE41 brings specific instructions for doing vector sign extend even in
950  // cases where we don't have SRA.
951  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
954  }
955 
956  for (MVT VT : MVT::integer_vector_valuetypes()) {
960  }
961 
962  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
963  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
971  }
972 
973  // i8 vectors are custom because the source register and source
974  // source memory operand types are not the same width.
976  }
977 
978  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
979  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
982 
983  // XOP can efficiently perform BITREVERSE with VPPERM.
984  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
986 
987  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
990  }
991 
992  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
993  bool HasInt256 = Subtarget.hasInt256();
994 
995  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
996  : &X86::VR256RegClass);
997  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
998  : &X86::VR256RegClass);
999  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1000  : &X86::VR256RegClass);
1001  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1002  : &X86::VR256RegClass);
1003  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1004  : &X86::VR256RegClass);
1005  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1006  : &X86::VR256RegClass);
1007 
1008  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1017  }
1018 
1019  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1020  // even though v8i16 is a legal type.
1024 
1027 
1028  if (!Subtarget.hasAVX512())
1030 
1031  for (MVT VT : MVT::fp_vector_valuetypes())
1033 
1034  // In the customized shift lowering, the legal v8i32/v4i64 cases
1035  // in AVX2 will be recognized.
1036  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1040  }
1041 
1045 
1049 
1050  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1054  }
1055 
1060 
1061  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1066 
1067  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1068  // setcc all the way to isel and prefer SETGT in some isel patterns.
1071  }
1072 
1073  if (Subtarget.hasAnyFMA()) {
1074  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1077  }
1078 
1079  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1080  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1081  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1082  }
1083 
1086  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1088 
1091 
1092  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1093  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1096 
1101 
1102  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1103  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1104  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1105  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1106  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1107  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1108  }
1109 
1110  if (HasInt256) {
1114 
1115  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1116  // when we have a 256bit-wide blend with immediate.
1118 
1119  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1120  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1127  }
1128  }
1129 
1130  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1134  }
1135 
1136  // Extract subvector is special because the value type
1137  // (result) is 128-bit but the source is 256-bit wide.
1138  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1139  MVT::v4f32, MVT::v2f64 }) {
1141  }
1142 
1143  // Custom lower several nodes for 256-bit types.
1145  MVT::v8f32, MVT::v4f64 }) {
1148  setOperationAction(ISD::VSELECT, VT, Custom);
1154  }
1155 
1156  if (HasInt256)
1158 
1159  // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1160  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1166  }
1167 
1168  if (HasInt256) {
1169  // Custom legalize 2x32 to get a little better code.
1172 
1173  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1175  setOperationAction(ISD::MGATHER, VT, Custom);
1176  }
1177  }
1178 
1179  // This block controls legalization of the mask vector sizes that are
1180  // available with AVX512. 512-bit vectors are in a separate block controlled
1181  // by useAVX512Regs.
1182  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1183  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1184  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1185  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1186  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1187  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1188 
1192 
1199 
1200  // There is no byte sized k-register load or store without AVX512DQ.
1201  if (!Subtarget.hasDQI()) {
1206 
1211  }
1212 
1213  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1214  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1218  }
1219 
1220  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1227 
1232  setOperationAction(ISD::VSELECT, VT, Expand);
1233  }
1234 
1242  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1244  }
1245 
1246  // This block controls legalization for 512-bit operations with 32/64 bit
1247  // elements. 512-bits can be disabled based on prefer-vector-width and
1248  // required-vector-width function attributes.
1249  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1250  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1251  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1252  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1253  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1254 
1255  for (MVT VT : MVT::fp_vector_valuetypes())
1257 
1258  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1264  }
1265 
1266  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1271  }
1272 
1283 
1289 
1290  if (!Subtarget.hasVLX()) {
1291  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1292  // to 512-bit rather than use the AVX2 instructions so that we can use
1293  // k-masks.
1294  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1298  }
1299  }
1300 
1309 
1310  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1316  }
1317 
1320 
1321  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1324 
1329 
1332 
1335 
1339 
1340  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1354 
1355  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1356  // setcc all the way to isel and prefer SETGT in some isel patterns.
1359  }
1360 
1361  // Need to promote to 64-bit even though we have 32-bit masked instructions
1362  // because the IR optimizers rearrange bitcasts around logic ops leaving
1363  // too many variations to handle if we don't promote them.
1367 
1368  if (Subtarget.hasDQI()) {
1373 
1375  }
1376 
1377  if (Subtarget.hasCDI()) {
1378  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1379  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1382  }
1383  } // Subtarget.hasCDI()
1384 
1385  if (Subtarget.hasVPOPCNTDQ()) {
1386  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1388  }
1389 
1390  // Extract subvector is special because the value type
1391  // (result) is 256-bit but the source is 512-bit wide.
1392  // 128-bit was made Legal under AVX1.
1393  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1396 
1397  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1409  }
1410  for (auto VT : { MVT::v64i8, MVT::v32i16, MVT::v16i32 }) {
1413  }
1414 
1415  // Need to custom split v32i16/v64i8 bitcasts.
1416  if (!Subtarget.hasBWI()) {
1419  }
1420  }// has AVX-512
1421 
1422  // This block controls legalization for operations that don't have
1423  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1424  // narrower widths.
1425  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1426  // These operations are handled on non-VLX by artificially widening in
1427  // isel patterns.
1428  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1429 
1435 
1436  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1442  }
1443 
1444  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1447  }
1448 
1449  // Custom legalize 2x32 to get a little better code.
1452 
1453  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1456 
1457  if (Subtarget.hasDQI()) {
1458  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1463 
1465  }
1466  }
1467 
1468  if (Subtarget.hasCDI()) {
1469  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1472  }
1473  } // Subtarget.hasCDI()
1474 
1475  if (Subtarget.hasVPOPCNTDQ()) {
1476  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1478  }
1479  }
1480 
1481  // This block control legalization of v32i1/v64i1 which are available with
1482  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1483  // useBWIRegs.
1484  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1485  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1486  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1487 
1488  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1492  setOperationAction(ISD::VSELECT, VT, Expand);
1493 
1501  }
1502 
1507  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1509 
1510  // Extends from v32i1 masks to 256-bit vectors.
1514  }
1515 
1516  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1517  // disabled based on prefer-vector-width and required-vector-width function
1518  // attributes.
1519  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1520  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1521  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1522 
1523  // Extends from v64i1 masks to 512-bit vectors.
1527 
1551 
1553 
1555 
1556  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1573 
1577  }
1578 
1579  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1581  }
1582 
1583  if (Subtarget.hasBITALG()) {
1584  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1586  }
1587  }
1588 
1589  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1590  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1591  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1592  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1593  }
1594 
1595  // These operations are handled on non-VLX by artificially widening in
1596  // isel patterns.
1597  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1598 
1599  if (Subtarget.hasBITALG()) {
1600  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1602  }
1603  }
1604 
1605  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1611 
1617 
1618  if (Subtarget.hasDQI()) {
1619  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1620  // v2f32 UINT_TO_FP is already custom under SSE2.
1623  "Unexpected operation action!");
1624  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1627  }
1628 
1629  if (Subtarget.hasBWI()) {
1632  }
1633  }
1634 
1635  // We want to custom lower some of our intrinsics.
1639  if (!Subtarget.is64Bit()) {
1642  }
1643 
1644  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1645  // handle type legalization for these operations here.
1646  //
1647  // FIXME: We really should do custom legalization for addition and
1648  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1649  // than generic legalization for 64-bit multiplication-with-overflow, though.
1650  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1651  if (VT == MVT::i64 && !Subtarget.is64Bit())
1652  continue;
1653  // Add/Sub/Mul with overflow operations are custom lowered.
1660 
1661  // Support carry in as value rather than glue.
1665  }
1666 
1667  if (!Subtarget.is64Bit()) {
1668  // These libcalls are not available in 32-bit.
1669  setLibcallName(RTLIB::SHL_I128, nullptr);
1670  setLibcallName(RTLIB::SRL_I128, nullptr);
1671  setLibcallName(RTLIB::SRA_I128, nullptr);
1672  setLibcallName(RTLIB::MUL_I128, nullptr);
1673  }
1674 
1675  // Combine sin / cos into _sincos_stret if it is available.
1676  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1677  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1680  }
1681 
1682  if (Subtarget.isTargetWin64()) {
1689  }
1690 
1691  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1692  // is. We should promote the value to 64-bits to solve this.
1693  // This is what the CRT headers do - `fmodf` is an inline header
1694  // function casting to f64 and calling `fmod`.
1695  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1696  Subtarget.isTargetWindowsItanium()))
1697  for (ISD::NodeType Op :
1702 
1703  // We have target-specific dag combine patterns for the following nodes:
1743 
1745 
1746  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1748  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1750  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1752 
1753  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1754  // that needs to benchmarked and balanced with the potential use of vector
1755  // load/store types (PR33329, PR33914).
1756  MaxLoadsPerMemcmp = 2;
1758 
1759  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1761 
1762  // An out-of-order CPU can speculatively execute past a predictable branch,
1763  // but a conditional move could be stalled by an expensive earlier operation.
1764  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1765  EnableExtLdPromotion = true;
1766  setPrefFunctionAlignment(4); // 2^4 bytes.
1767 
1769 }
1770 
1771 // This has so far only been implemented for 64-bit MachO.
1773  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1774 }
1775 
1777  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1778  return Subtarget.getTargetTriple().isOSMSVCRT();
1779 }
1780 
1782  const SDLoc &DL) const {
1783  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1784  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1785  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1786  return SDValue(Node, 0);
1787 }
1788 
1791  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1792  return TypeSplitVector;
1793 
1795  VT.getVectorNumElements() != 1 &&
1797  return TypeWidenVector;
1798 
1800 }
1801 
1803  EVT VT) const {
1804  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1805  return MVT::v32i8;
1807 }
1808 
1810  EVT VT) const {
1811  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1812  return 1;
1814 }
1815 
1818  EVT VT) const {
1819  if (!VT.isVector())
1820  return MVT::i8;
1821 
1822  if (Subtarget.hasAVX512()) {
1823  const unsigned NumElts = VT.getVectorNumElements();
1824 
1825  // Figure out what this type will be legalized to.
1826  EVT LegalVT = VT;
1827  while (getTypeAction(Context, LegalVT) != TypeLegal)
1828  LegalVT = getTypeToTransformTo(Context, LegalVT);
1829 
1830  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1831  if (LegalVT.getSimpleVT().is512BitVector())
1832  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1833 
1834  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1835  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1836  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1837  // vXi16/vXi8.
1838  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1839  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1840  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1841  }
1842  }
1843 
1845 }
1846 
1847 /// Helper for getByValTypeAlignment to determine
1848 /// the desired ByVal argument alignment.
1849 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1850  if (MaxAlign == 16)
1851  return;
1852  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1853  if (VTy->getBitWidth() == 128)
1854  MaxAlign = 16;
1855  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1856  unsigned EltAlign = 0;
1857  getMaxByValAlign(ATy->getElementType(), EltAlign);
1858  if (EltAlign > MaxAlign)
1859  MaxAlign = EltAlign;
1860  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1861  for (auto *EltTy : STy->elements()) {
1862  unsigned EltAlign = 0;
1863  getMaxByValAlign(EltTy, EltAlign);
1864  if (EltAlign > MaxAlign)
1865  MaxAlign = EltAlign;
1866  if (MaxAlign == 16)
1867  break;
1868  }
1869  }
1870 }
1871 
1872 /// Return the desired alignment for ByVal aggregate
1873 /// function arguments in the caller parameter area. For X86, aggregates
1874 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1875 /// are at 4-byte boundaries.
1877  const DataLayout &DL) const {
1878  if (Subtarget.is64Bit()) {
1879  // Max of 8 and alignment of type.
1880  unsigned TyAlign = DL.getABITypeAlignment(Ty);
1881  if (TyAlign > 8)
1882  return TyAlign;
1883  return 8;
1884  }
1885 
1886  unsigned Align = 4;
1887  if (Subtarget.hasSSE1())
1888  getMaxByValAlign(Ty, Align);
1889  return Align;
1890 }
1891 
1892 /// Returns the target specific optimal type for load
1893 /// and store operations as a result of memset, memcpy, and memmove
1894 /// lowering. If DstAlign is zero that means it's safe to destination
1895 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1896 /// means there isn't a need to check it against alignment requirement,
1897 /// probably because the source does not need to be loaded. If 'IsMemset' is
1898 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1899 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1900 /// source is constant so it does not need to be loaded.
1901 /// It returns EVT::Other if the type should be determined using generic
1902 /// target-independent logic.
1903 EVT
1905  unsigned DstAlign, unsigned SrcAlign,
1906  bool IsMemset, bool ZeroMemset,
1907  bool MemcpyStrSrc,
1908  MachineFunction &MF) const {
1909  const Function &F = MF.getFunction();
1910  if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
1911  if (Size >= 16 &&
1912  (!Subtarget.isUnalignedMem16Slow() ||
1913  ((DstAlign == 0 || DstAlign >= 16) &&
1914  (SrcAlign == 0 || SrcAlign >= 16)))) {
1915  // FIXME: Check if unaligned 32-byte accesses are slow.
1916  if (Size >= 32 && Subtarget.hasAVX()) {
1917  // Although this isn't a well-supported type for AVX1, we'll let
1918  // legalization and shuffle lowering produce the optimal codegen. If we
1919  // choose an optimal type with a vector element larger than a byte,
1920  // getMemsetStores() may create an intermediate splat (using an integer
1921  // multiply) before we splat as a vector.
1922  return MVT::v32i8;
1923  }
1924  if (Subtarget.hasSSE2())
1925  return MVT::v16i8;
1926  // TODO: Can SSE1 handle a byte vector?
1927  if (Subtarget.hasSSE1())
1928  return MVT::v4f32;
1929  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1930  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1931  // Do not use f64 to lower memcpy if source is string constant. It's
1932  // better to use i32 to avoid the loads.
1933  // Also, do not use f64 to lower memset unless this is a memset of zeros.
1934  // The gymnastics of splatting a byte value into an XMM register and then
1935  // only using 8-byte stores (because this is a CPU with slow unaligned
1936  // 16-byte accesses) makes that a loser.
1937  return MVT::f64;
1938  }
1939  }
1940  // This is a compromise. If we reach here, unaligned accesses may be slow on
1941  // this target. However, creating smaller, aligned accesses could be even
1942  // slower and would certainly be a lot more code.
1943  if (Subtarget.is64Bit() && Size >= 8)
1944  return MVT::i64;
1945  return MVT::i32;
1946 }
1947 
1949  if (VT == MVT::f32)
1950  return X86ScalarSSEf32;
1951  else if (VT == MVT::f64)
1952  return X86ScalarSSEf64;
1953  return true;
1954 }
1955 
1956 bool
1958  unsigned,
1959  unsigned,
1960  bool *Fast) const {
1961  if (Fast) {
1962  switch (VT.getSizeInBits()) {
1963  default:
1964  // 8-byte and under are always assumed to be fast.
1965  *Fast = true;
1966  break;
1967  case 128:
1968  *Fast = !Subtarget.isUnalignedMem16Slow();
1969  break;
1970  case 256:
1971  *Fast = !Subtarget.isUnalignedMem32Slow();
1972  break;
1973  // TODO: What about AVX-512 (512-bit) accesses?
1974  }
1975  }
1976  // Misaligned accesses of any size are always allowed.
1977  return true;
1978 }
1979 
1980 /// Return the entry encoding for a jump table in the
1981 /// current function. The returned value is a member of the
1982 /// MachineJumpTableInfo::JTEntryKind enum.
1984  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1985  // symbol.
1986  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
1988 
1989  // Otherwise, use the normal jump table encoding heuristics.
1991 }
1992 
1994  return Subtarget.useSoftFloat();
1995 }
1996 
1998  ArgListTy &Args) const {
1999 
2000  // Only relabel X86-32 for C / Stdcall CCs.
2001  if (Subtarget.is64Bit())
2002  return;
2003  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2004  return;
2005  unsigned ParamRegs = 0;
2006  if (auto *M = MF->getFunction().getParent())
2007  ParamRegs = M->getNumberRegisterParameters();
2008 
2009  // Mark the first N int arguments as having reg
2010  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2011  Type *T = Args[Idx].Ty;
2012  if (T->isIntOrPtrTy())
2013  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2014  unsigned numRegs = 1;
2015  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2016  numRegs = 2;
2017  if (ParamRegs < numRegs)
2018  return;
2019  ParamRegs -= numRegs;
2020  Args[Idx].IsInReg = true;
2021  }
2022  }
2023 }
2024 
2025 const MCExpr *
2027  const MachineBasicBlock *MBB,
2028  unsigned uid,MCContext &Ctx) const{
2029  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2030  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2031  // entries.
2032  return MCSymbolRefExpr::create(MBB->getSymbol(),
2034 }
2035 
2036 /// Returns relocation base for the given PIC jumptable.
2038  SelectionDAG &DAG) const {
2039  if (!Subtarget.is64Bit())
2040  // This doesn't have SDLoc associated with it, but is not really the
2041  // same as a Register.
2042  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2043  getPointerTy(DAG.getDataLayout()));
2044  return Table;
2045 }
2046 
2047 /// This returns the relocation base for the given PIC jumptable,
2048 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2051  MCContext &Ctx) const {
2052  // X86-64 uses RIP relative addressing based on the jump table label.
2053  if (Subtarget.isPICStyleRIPRel())
2054  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2055 
2056  // Otherwise, the reference is relative to the PIC base.
2057  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2058 }
2059 
2060 std::pair<const TargetRegisterClass *, uint8_t>
2062  MVT VT) const {
2063  const TargetRegisterClass *RRC = nullptr;
2064  uint8_t Cost = 1;
2065  switch (VT.SimpleTy) {
2066  default:
2068  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2069  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2070  break;
2071  case MVT::x86mmx:
2072  RRC = &X86::VR64RegClass;
2073  break;
2074  case MVT::f32: case MVT::f64:
2075  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2076  case MVT::v4f32: case MVT::v2f64:
2077  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2078  case MVT::v8f32: case MVT::v4f64:
2079  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2080  case MVT::v16f32: case MVT::v8f64:
2081  RRC = &X86::VR128XRegClass;
2082  break;
2083  }
2084  return std::make_pair(RRC, Cost);
2085 }
2086 
2087 unsigned X86TargetLowering::getAddressSpace() const {
2088  if (Subtarget.is64Bit())
2089  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2090  return 256;
2091 }
2092 
2093 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2094  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2095  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2096 }
2097 
2099  unsigned Offset, unsigned AddressSpace) {
2102  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2103 }
2104 
2106  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2107  // tcbhead_t; use it instead of the usual global variable (see
2108  // sysdeps/{i386,x86_64}/nptl/tls.h)
2109  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2110  if (Subtarget.isTargetFuchsia()) {
2111  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2112  return SegmentOffset(IRB, 0x10, getAddressSpace());
2113  } else {
2114  // %fs:0x28, unless we're using a Kernel code model, in which case
2115  // it's %gs:0x28. gs:0x14 on i386.
2116  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2117  return SegmentOffset(IRB, Offset, getAddressSpace());
2118  }
2119  }
2120 
2121  return TargetLowering::getIRStackGuard(IRB);
2122 }
2123 
2125  // MSVC CRT provides functionalities for stack protection.
2126  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2128  // MSVC CRT has a global variable holding security cookie.
2129  M.getOrInsertGlobal("__security_cookie",
2131 
2132  // MSVC CRT has a function to validate security cookie.
2133  auto *SecurityCheckCookie = cast<Function>(
2134  M.getOrInsertFunction("__security_check_cookie",
2137  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2138  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2139  return;
2140  }
2141  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2142  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2143  return;
2145 }
2146 
2148  // MSVC CRT has a global variable holding security cookie.
2149  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2151  return M.getGlobalVariable("__security_cookie");
2152  }
2154 }
2155 
2157  // MSVC CRT has a function to validate security cookie.
2158  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2160  return M.getFunction("__security_check_cookie");
2161  }
2163 }
2164 
2166  if (Subtarget.getTargetTriple().isOSContiki())
2167  return getDefaultSafeStackPointerLocation(IRB, false);
2168 
2169  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2170  // definition of TLS_SLOT_SAFESTACK in
2171  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2172  if (Subtarget.isTargetAndroid()) {
2173  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2174  // %gs:0x24 on i386
2175  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2176  return SegmentOffset(IRB, Offset, getAddressSpace());
2177  }
2178 
2179  // Fuchsia is similar.
2180  if (Subtarget.isTargetFuchsia()) {
2181  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2182  return SegmentOffset(IRB, 0x18, getAddressSpace());
2183  }
2184 
2186 }
2187 
2189  unsigned DestAS) const {
2190  assert(SrcAS != DestAS && "Expected different address spaces!");
2191 
2192  return SrcAS < 256 && DestAS < 256;
2193 }
2194 
2195 //===----------------------------------------------------------------------===//
2196 // Return Value Calling Convention Implementation
2197 //===----------------------------------------------------------------------===//
2198 
2199 #include "X86GenCallingConv.inc"
2200 
2201 bool X86TargetLowering::CanLowerReturn(
2202  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2203  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2205  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2206  return CCInfo.CheckReturn(Outs, RetCC_X86);
2207 }
2208 
2209 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2210  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2211  return ScratchRegs;
2212 }
2213 
2214 /// Lowers masks values (v*i1) to the local register values
2215 /// \returns DAG node after lowering to register type
2216 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2217  const SDLoc &Dl, SelectionDAG &DAG) {
2218  EVT ValVT = ValArg.getValueType();
2219 
2220  if (ValVT == MVT::v1i1)
2221  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2222  DAG.getIntPtrConstant(0, Dl));
2223 
2224  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2225  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2226  // Two stage lowering might be required
2227  // bitcast: v8i1 -> i8 / v16i1 -> i16
2228  // anyextend: i8 -> i32 / i16 -> i32
2229  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2230  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2231  if (ValLoc == MVT::i32)
2232  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2233  return ValToCopy;
2234  }
2235 
2236  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2237  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2238  // One stage lowering is required
2239  // bitcast: v32i1 -> i32 / v64i1 -> i64
2240  return DAG.getBitcast(ValLoc, ValArg);
2241  }
2242 
2243  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2244 }
2245 
2246 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2248  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2249  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2250  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2251  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2252  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2253  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2254  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2255  "The value should reside in two registers");
2256 
2257  // Before splitting the value we cast it to i64
2258  Arg = DAG.getBitcast(MVT::i64, Arg);
2259 
2260  // Splitting the value into two i32 types
2261  SDValue Lo, Hi;
2262  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2263  DAG.getConstant(0, Dl, MVT::i32));
2264  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2265  DAG.getConstant(1, Dl, MVT::i32));
2266 
2267  // Attach the two i32 types into corresponding registers
2268  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2269  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2270 }
2271 
2272 SDValue
2273 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2274  bool isVarArg,
2275  const SmallVectorImpl<ISD::OutputArg> &Outs,
2276  const SmallVectorImpl<SDValue> &OutVals,
2277  const SDLoc &dl, SelectionDAG &DAG) const {
2278  MachineFunction &MF = DAG.getMachineFunction();
2280 
2281  // In some cases we need to disable registers from the default CSR list.
2282  // For example, when they are used for argument passing.
2283  bool ShouldDisableCalleeSavedRegister =
2284  CallConv == CallingConv::X86_RegCall ||
2285  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2286 
2287  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2288  report_fatal_error("X86 interrupts may not return any value");
2289 
2291  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2292  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2293 
2294  SDValue Flag;
2295  SmallVector<SDValue, 6> RetOps;
2296  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2297  // Operand #1 = Bytes To Pop
2298  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2299  MVT::i32));
2300 
2301  // Copy the result values into the output registers.
2302  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2303  ++I, ++OutsIndex) {
2304  CCValAssign &VA = RVLocs[I];
2305  assert(VA.isRegLoc() && "Can only return in registers!");
2306 
2307  // Add the register to the CalleeSaveDisableRegs list.
2308  if (ShouldDisableCalleeSavedRegister)
2310 
2311  SDValue ValToCopy = OutVals[OutsIndex];
2312  EVT ValVT = ValToCopy.getValueType();
2313 
2314  // Promote values to the appropriate types.
2315  if (VA.getLocInfo() == CCValAssign::SExt)
2316  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2317  else if (VA.getLocInfo() == CCValAssign::ZExt)
2318  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2319  else if (VA.getLocInfo() == CCValAssign::AExt) {
2320  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2321  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2322  else
2323  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2324  }
2325  else if (VA.getLocInfo() == CCValAssign::BCvt)
2326  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2327 
2329  "Unexpected FP-extend for return value.");
2330 
2331  // If this is x86-64, and we disabled SSE, we can't return FP values,
2332  // or SSE or MMX vectors.
2333  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2334  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2335  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2336  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2337  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2338  } else if (ValVT == MVT::f64 &&
2339  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2340  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2341  // llvm-gcc has never done it right and no one has noticed, so this
2342  // should be OK for now.
2343  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2344  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2345  }
2346 
2347  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2348  // the RET instruction and handled by the FP Stackifier.
2349  if (VA.getLocReg() == X86::FP0 ||
2350  VA.getLocReg() == X86::FP1) {
2351  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2352  // change the value to the FP stack register class.
2353  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2354  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2355  RetOps.push_back(ValToCopy);
2356  // Don't emit a copytoreg.
2357  continue;
2358  }
2359 
2360  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2361  // which is returned in RAX / RDX.
2362  if (Subtarget.is64Bit()) {
2363  if (ValVT == MVT::x86mmx) {
2364  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2365  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2366  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2367  ValToCopy);
2368  // If we don't have SSE2 available, convert to v4f32 so the generated
2369  // register is legal.
2370  if (!Subtarget.hasSSE2())
2371  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2372  }
2373  }
2374  }
2375 
2377 
2378  if (VA.needsCustom()) {
2379  assert(VA.getValVT() == MVT::v64i1 &&
2380  "Currently the only custom case is when we split v64i1 to 2 regs");
2381 
2382  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2383  Subtarget);
2384 
2385  assert(2 == RegsToPass.size() &&
2386  "Expecting two registers after Pass64BitArgInRegs");
2387 
2388  // Add the second register to the CalleeSaveDisableRegs list.
2389  if (ShouldDisableCalleeSavedRegister)
2390  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2391  } else {
2392  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2393  }
2394 
2395  // Add nodes to the DAG and add the values into the RetOps list
2396  for (auto &Reg : RegsToPass) {
2397  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2398  Flag = Chain.getValue(1);
2399  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2400  }
2401  }
2402 
2403  // Swift calling convention does not require we copy the sret argument
2404  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2405 
2406  // All x86 ABIs require that for returning structs by value we copy
2407  // the sret argument into %rax/%eax (depending on ABI) for the return.
2408  // We saved the argument into a virtual register in the entry block,
2409  // so now we copy the value out and into %rax/%eax.
2410  //
2411  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2412  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2413  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2414  // either case FuncInfo->setSRetReturnReg() will have been called.
2415  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2416  // When we have both sret and another return value, we should use the
2417  // original Chain stored in RetOps[0], instead of the current Chain updated
2418  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2419 
2420  // For the case of sret and another return value, we have
2421  // Chain_0 at the function entry
2422  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2423  // If we use Chain_1 in getCopyFromReg, we will have
2424  // Val = getCopyFromReg(Chain_1)
2425  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2426 
2427  // getCopyToReg(Chain_0) will be glued together with
2428  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2429  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2430  // Data dependency from Unit B to Unit A due to usage of Val in
2431  // getCopyToReg(Chain_1, Val)
2432  // Chain dependency from Unit A to Unit B
2433 
2434  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2435  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2436  getPointerTy(MF.getDataLayout()));
2437 
2438  unsigned RetValReg
2439  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2440  X86::RAX : X86::EAX;
2441  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2442  Flag = Chain.getValue(1);
2443 
2444  // RAX/EAX now acts like a return value.
2445  RetOps.push_back(
2446  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2447 
2448  // Add the returned register to the CalleeSaveDisableRegs list.
2449  if (ShouldDisableCalleeSavedRegister)
2450  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2451  }
2452 
2453  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2454  const MCPhysReg *I =
2456  if (I) {
2457  for (; *I; ++I) {
2458  if (X86::GR64RegClass.contains(*I))
2459  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2460  else
2461  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2462  }
2463  }
2464 
2465  RetOps[0] = Chain; // Update chain.
2466 
2467  // Add the flag if we have it.
2468  if (Flag.getNode())
2469  RetOps.push_back(Flag);
2470 
2472  if (CallConv == CallingConv::X86_INTR)
2473  opcode = X86ISD::IRET;
2474  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2475 }
2476 
2477 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2478  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2479  return false;
2480 
2481  SDValue TCChain = Chain;
2482  SDNode *Copy = *N->use_begin();
2483  if (Copy->getOpcode() == ISD::CopyToReg) {
2484  // If the copy has a glue operand, we conservatively assume it isn't safe to
2485  // perform a tail call.
2486  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2487  return false;
2488  TCChain = Copy->getOperand(0);
2489  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2490  return false;
2491 
2492  bool HasRet = false;
2493  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2494  UI != UE; ++UI) {
2495  if (UI->getOpcode() != X86ISD::RET_FLAG)
2496  return false;
2497  // If we are returning more than one value, we can definitely
2498  // not make a tail call see PR19530
2499  if (UI->getNumOperands() > 4)
2500  return false;
2501  if (UI->getNumOperands() == 4 &&
2502  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2503  return false;
2504  HasRet = true;
2505  }
2506 
2507  if (!HasRet)
2508  return false;
2509 
2510  Chain = TCChain;
2511  return true;
2512 }
2513 
2514 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2515  ISD::NodeType ExtendKind) const {
2516  MVT ReturnMVT = MVT::i32;
2517 
2518  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2519  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2520  // The ABI does not require i1, i8 or i16 to be extended.
2521  //
2522  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2523  // always extending i8/i16 return values, so keep doing that for now.
2524  // (PR26665).
2525  ReturnMVT = MVT::i8;
2526  }
2527 
2528  EVT MinVT = getRegisterType(Context, ReturnMVT);
2529  return VT.bitsLT(MinVT) ? MinVT : VT;
2530 }
2531 
2532 /// Reads two 32 bit registers and creates a 64 bit mask value.
2533 /// \param VA The current 32 bit value that need to be assigned.
2534 /// \param NextVA The next 32 bit value that need to be assigned.
2535 /// \param Root The parent DAG node.
2536 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2537 /// glue purposes. In the case the DAG is already using
2538 /// physical register instead of virtual, we should glue
2539 /// our new SDValue to InFlag SDvalue.
2540 /// \return a new SDvalue of size 64bit.
2542  SDValue &Root, SelectionDAG &DAG,
2543  const SDLoc &Dl, const X86Subtarget &Subtarget,
2544  SDValue *InFlag = nullptr) {
2545  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2546  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2547  assert(VA.getValVT() == MVT::v64i1 &&
2548  "Expecting first location of 64 bit width type");
2549  assert(NextVA.getValVT() == VA.getValVT() &&
2550  "The locations should have the same type");
2551  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2552  "The values should reside in two registers");
2553 
2554  SDValue Lo, Hi;
2555  unsigned Reg;
2556  SDValue ArgValueLo, ArgValueHi;
2557 
2558  MachineFunction &MF = DAG.getMachineFunction();
2559  const TargetRegisterClass *RC = &X86::GR32RegClass;
2560 
2561  // Read a 32 bit value from the registers.
2562  if (nullptr == InFlag) {
2563  // When no physical register is present,
2564  // create an intermediate virtual register.
2565  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2566  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2567  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2568  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2569  } else {
2570  // When a physical register is available read the value from it and glue
2571  // the reads together.
2572  ArgValueLo =
2573  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2574  *InFlag = ArgValueLo.getValue(2);
2575  ArgValueHi =
2576  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2577  *InFlag = ArgValueHi.getValue(2);
2578  }
2579 
2580  // Convert the i32 type into v32i1 type.
2581  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2582 
2583  // Convert the i32 type into v32i1 type.
2584  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2585 
2586  // Concatenate the two values together.
2587  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2588 }
2589 
2590 /// The function will lower a register of various sizes (8/16/32/64)
2591 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2592 /// \returns a DAG node contains the operand after lowering to mask type.
2593 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2594  const EVT &ValLoc, const SDLoc &Dl,
2595  SelectionDAG &DAG) {
2596  SDValue ValReturned = ValArg;
2597 
2598  if (ValVT == MVT::v1i1)
2599  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2600 
2601  if (ValVT == MVT::v64i1) {
2602  // In 32 bit machine, this case is handled by getv64i1Argument
2603  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2604  // In 64 bit machine, There is no need to truncate the value only bitcast
2605  } else {
2606  MVT maskLen;
2607  switch (ValVT.getSimpleVT().SimpleTy) {
2608  case MVT::v8i1:
2609  maskLen = MVT::i8;
2610  break;
2611  case MVT::v16i1:
2612  maskLen = MVT::i16;
2613  break;
2614  case MVT::v32i1:
2615  maskLen = MVT::i32;
2616  break;
2617  default:
2618  llvm_unreachable("Expecting a vector of i1 types");
2619  }
2620 
2621  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2622  }
2623  return DAG.getBitcast(ValVT, ValReturned);
2624 }
2625 
2626 /// Lower the result values of a call into the
2627 /// appropriate copies out of appropriate physical registers.
2628 ///
2629 SDValue X86TargetLowering::LowerCallResult(
2630  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2631  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2632  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2633  uint32_t *RegMask) const {
2634 
2635  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2636  // Assign locations to each value returned by this call.
2638  bool Is64Bit = Subtarget.is64Bit();
2639  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2640  *DAG.getContext());
2641  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2642 
2643  // Copy all of the result registers out of their specified physreg.
2644  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2645  ++I, ++InsIndex) {
2646  CCValAssign &VA = RVLocs[I];
2647  EVT CopyVT = VA.getLocVT();
2648 
2649  // In some calling conventions we need to remove the used registers
2650  // from the register mask.
2651  if (RegMask) {
2652  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2653  SubRegs.isValid(); ++SubRegs)
2654  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2655  }
2656 
2657  // If this is x86-64, and we disabled SSE, we can't return FP values
2658  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2659  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2660  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2661  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2662  }
2663 
2664  // If we prefer to use the value in xmm registers, copy it out as f80 and
2665  // use a truncate to move it from fp stack reg to xmm reg.
2666  bool RoundAfterCopy = false;
2667  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2669  if (!Subtarget.hasX87())
2670  report_fatal_error("X87 register return with X87 disabled");
2671  CopyVT = MVT::f80;
2672  RoundAfterCopy = (CopyVT != VA.getLocVT());
2673  }
2674 
2675  SDValue Val;
2676  if (VA.needsCustom()) {
2677  assert(VA.getValVT() == MVT::v64i1 &&
2678  "Currently the only custom case is when we split v64i1 to 2 regs");
2679  Val =
2680  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2681  } else {
2682  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2683  .getValue(1);
2684  Val = Chain.getValue(0);
2685  InFlag = Chain.getValue(2);
2686  }
2687 
2688  if (RoundAfterCopy)
2689  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2690  // This truncation won't change the value.
2691  DAG.getIntPtrConstant(1, dl));
2692 
2693  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2694  if (VA.getValVT().isVector() &&
2695  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2696  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2697  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2698  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2699  } else
2700  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2701  }
2702 
2703  InVals.push_back(Val);
2704  }
2705 
2706  return Chain;
2707 }
2708 
2709 //===----------------------------------------------------------------------===//
2710 // C & StdCall & Fast Calling Convention implementation
2711 //===----------------------------------------------------------------------===//
2712 // StdCall calling convention seems to be standard for many Windows' API
2713 // routines and around. It differs from C calling convention just a little:
2714 // callee should clean up the stack, not caller. Symbols should be also
2715 // decorated in some fancy way :) It doesn't support any vector arguments.
2716 // For info on fast calling convention see Fast Calling Convention (tail call)
2717 // implementation LowerX86_32FastCCCallTo.
2718 
2719 /// CallIsStructReturn - Determines whether a call uses struct return
2720 /// semantics.
2725 };
2726 static StructReturnType
2728  if (Outs.empty())
2729  return NotStructReturn;
2730 
2731  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2732  if (!Flags.isSRet())
2733  return NotStructReturn;
2734  if (Flags.isInReg() || IsMCU)
2735  return RegStructReturn;
2736  return StackStructReturn;
2737 }
2738 
2739 /// Determines whether a function uses struct return semantics.
2740 static StructReturnType
2742  if (Ins.empty())
2743  return NotStructReturn;
2744 
2745  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2746  if (!Flags.isSRet())
2747  return NotStructReturn;
2748  if (Flags.isInReg() || IsMCU)
2749  return RegStructReturn;
2750  return StackStructReturn;
2751 }
2752 
2753 /// Make a copy of an aggregate at address specified by "Src" to address
2754 /// "Dst" with size and alignment information specified by the specific
2755 /// parameter attribute. The copy will be passed as a byval function parameter.
2757  SDValue Chain, ISD::ArgFlagsTy Flags,
2758  SelectionDAG &DAG, const SDLoc &dl) {
2759  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2760 
2761  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2762  /*isVolatile*/false, /*AlwaysInline=*/true,
2763  /*isTailCall*/false,
2765 }
2766 
2767 /// Return true if the calling convention is one that we can guarantee TCO for.
2769  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2771  CC == CallingConv::HHVM);
2772 }
2773 
2774 /// Return true if we might ever do TCO for calls with this calling convention.
2776  switch (CC) {
2777  // C calling conventions:
2778  case CallingConv::C:
2779  case CallingConv::Win64:
2781  // Callee pop conventions:
2786  return true;
2787  default:
2788  return canGuaranteeTCO(CC);
2789  }
2790 }
2791 
2792 /// Return true if the function is being made into a tailcall target by
2793 /// changing its ABI.
2794 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2795  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2796 }
2797 
2798 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2799  auto Attr =
2800  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2801  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2802  return false;
2803 
2804  ImmutableCallSite CS(CI);
2805  CallingConv::ID CalleeCC = CS.getCallingConv();
2806  if (!mayTailCallThisCC(CalleeCC))
2807  return false;
2808 
2809  return true;
2810 }
2811 
2812 SDValue
2813 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2814  const SmallVectorImpl<ISD::InputArg> &Ins,
2815  const SDLoc &dl, SelectionDAG &DAG,
2816  const CCValAssign &VA,
2817  MachineFrameInfo &MFI, unsigned i) const {
2818  // Create the nodes corresponding to a load from this parameter slot.
2819  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2820  bool AlwaysUseMutable = shouldGuaranteeTCO(
2821  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2822  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2823  EVT ValVT;
2824  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2825 
2826  // If value is passed by pointer we have address passed instead of the value
2827  // itself. No need to extend if the mask value and location share the same
2828  // absolute size.
2829  bool ExtendedInMem =
2830  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2831  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2832 
2833  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2834  ValVT = VA.getLocVT();
2835  else
2836  ValVT = VA.getValVT();
2837 
2838  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2839  // taken by a return address.
2840  int Offset = 0;
2841  if (CallConv == CallingConv::X86_INTR) {
2842  // X86 interrupts may take one or two arguments.
2843  // On the stack there will be no return address as in regular call.
2844  // Offset of last argument need to be set to -4/-8 bytes.
2845  // Where offset of the first argument out of two, should be set to 0 bytes.
2846  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2847  if (Subtarget.is64Bit() && Ins.size() == 2) {
2848  // The stack pointer needs to be realigned for 64 bit handlers with error
2849  // code, so the argument offset changes by 8 bytes.
2850  Offset += 8;
2851  }
2852  }
2853 
2854  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2855  // changed with more analysis.
2856  // In case of tail call optimization mark all arguments mutable. Since they
2857  // could be overwritten by lowering of arguments in case of a tail call.
2858  if (Flags.isByVal()) {
2859  unsigned Bytes = Flags.getByValSize();
2860  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2861 
2862  // FIXME: For now, all byval parameter objects are marked as aliasing. This
2863  // can be improved with deeper analysis.
2864  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2865  /*isAliased=*/true);
2866  // Adjust SP offset of interrupt parameter.
2867  if (CallConv == CallingConv::X86_INTR) {
2868  MFI.setObjectOffset(FI, Offset);
2869  }
2870  return DAG.getFrameIndex(FI, PtrVT);
2871  }
2872 
2873  // This is an argument in memory. We might be able to perform copy elision.
2874  if (Flags.isCopyElisionCandidate()) {
2875  EVT ArgVT = Ins[i].ArgVT;
2876  SDValue PartAddr;
2877  if (Ins[i].PartOffset == 0) {
2878  // If this is a one-part value or the first part of a multi-part value,
2879  // create a stack object for the entire argument value type and return a
2880  // load from our portion of it. This assumes that if the first part of an
2881  // argument is in memory, the rest will also be in memory.
2882  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2883  /*Immutable=*/false);
2884  PartAddr = DAG.getFrameIndex(FI, PtrVT);
2885  return DAG.getLoad(
2886  ValVT, dl, Chain, PartAddr,
2888  } else {
2889  // This is not the first piece of an argument in memory. See if there is
2890  // already a fixed stack object including this offset. If so, assume it
2891  // was created by the PartOffset == 0 branch above and create a load from
2892  // the appropriate offset into it.
2893  int64_t PartBegin = VA.getLocMemOffset();
2894  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2895  int FI = MFI.getObjectIndexBegin();
2896  for (; MFI.isFixedObjectIndex(FI); ++FI) {
2897  int64_t ObjBegin = MFI.getObjectOffset(FI);
2898  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2899  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2900  break;
2901  }
2902  if (MFI.isFixedObjectIndex(FI)) {
2903  SDValue Addr =
2904  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2905  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2906  return DAG.getLoad(
2907  ValVT, dl, Chain, Addr,
2909  Ins[i].PartOffset));
2910  }
2911  }
2912  }
2913 
2914  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2915  VA.getLocMemOffset(), isImmutable);
2916 
2917  // Set SExt or ZExt flag.
2918  if (VA.getLocInfo() == CCValAssign::ZExt) {
2919  MFI.setObjectZExt(FI, true);
2920  } else if (VA.getLocInfo() == CCValAssign::SExt) {
2921  MFI.setObjectSExt(FI, true);
2922  }
2923 
2924  // Adjust SP offset of interrupt parameter.
2925  if (CallConv == CallingConv::X86_INTR) {
2926  MFI.setObjectOffset(FI, Offset);
2927  }
2928 
2929  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2930  SDValue Val = DAG.getLoad(
2931  ValVT, dl, Chain, FIN,
2933  return ExtendedInMem
2934  ? (VA.getValVT().isVector()
2935  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2936  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2937  : Val;
2938 }
2939 
2940 // FIXME: Get this from tablegen.
2942  const X86Subtarget &Subtarget) {
2943  assert(Subtarget.is64Bit());
2944 
2945  if (Subtarget.isCallingConvWin64(CallConv)) {
2946  static const MCPhysReg GPR64ArgRegsWin64[] = {
2947  X86::RCX, X86::RDX, X86::R8, X86::R9
2948  };
2949  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2950  }
2951 
2952  static const MCPhysReg GPR64ArgRegs64Bit[] = {
2953  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2954  };
2955  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2956 }
2957 
2958 // FIXME: Get this from tablegen.
2960  CallingConv::ID CallConv,
2961  const X86Subtarget &Subtarget) {
2962  assert(Subtarget.is64Bit());
2963  if (Subtarget.isCallingConvWin64(CallConv)) {
2964  // The XMM registers which might contain var arg parameters are shadowed
2965  // in their paired GPR. So we only need to save the GPR to their home
2966  // slots.
2967  // TODO: __vectorcall will change this.
2968  return None;
2969  }
2970 
2971  const Function &F = MF.getFunction();
2972  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
2973  bool isSoftFloat = Subtarget.useSoftFloat();
2974  assert(!(isSoftFloat && NoImplicitFloatOps) &&
2975  "SSE register cannot be used when SSE is disabled!");
2976  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
2977  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2978  // registers.
2979  return None;
2980 
2981  static const MCPhysReg XMMArgRegs64Bit[] = {
2982  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2983  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2984  };
2985  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2986 }
2987 
2988 #ifndef NDEBUG
2990  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
2991  [](const CCValAssign &A, const CCValAssign &B) -> bool {
2992  return A.getValNo() < B.getValNo();
2993  });
2994 }
2995 #endif
2996 
2997 SDValue X86TargetLowering::LowerFormalArguments(
2998  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2999  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3000  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3001  MachineFunction &MF = DAG.getMachineFunction();
3003  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3004 
3005  const Function &F = MF.getFunction();
3006  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3007  F.getName() == "main")
3008  FuncInfo->setForceFramePointer(true);
3009 
3010  MachineFrameInfo &MFI = MF.getFrameInfo();
3011  bool Is64Bit = Subtarget.is64Bit();
3012  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3013 
3014  assert(
3015  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3016  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3017 
3018  if (CallConv == CallingConv::X86_INTR) {
3019  bool isLegal = Ins.size() == 1 ||
3020  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3021  (!Is64Bit && Ins[1].VT == MVT::i32)));
3022  if (!isLegal)
3023  report_fatal_error("X86 interrupts may take one or two arguments");
3024  }
3025 
3026  // Assign locations to all of the incoming arguments.
3028  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3029 
3030  // Allocate shadow area for Win64.
3031  if (IsWin64)
3032  CCInfo.AllocateStack(32, 8);
3033 
3034  CCInfo.AnalyzeArguments(Ins, CC_X86);
3035 
3036  // In vectorcall calling convention a second pass is required for the HVA
3037  // types.
3038  if (CallingConv::X86_VectorCall == CallConv) {
3039  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3040  }
3041 
3042  // The next loop assumes that the locations are in the same order of the
3043  // input arguments.
3044  assert(isSortedByValueNo(ArgLocs) &&
3045  "Argument Location list must be sorted before lowering");
3046 
3047  SDValue ArgValue;
3048  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3049  ++I, ++InsIndex) {
3050  assert(InsIndex < Ins.size() && "Invalid Ins index");
3051  CCValAssign &VA = ArgLocs[I];
3052 
3053  if (VA.isRegLoc()) {
3054  EVT RegVT = VA.getLocVT();
3055  if (VA.needsCustom()) {
3056  assert(
3057  VA.getValVT() == MVT::v64i1 &&
3058  "Currently the only custom case is when we split v64i1 to 2 regs");
3059 
3060  // v64i1 values, in regcall calling convention, that are
3061  // compiled to 32 bit arch, are split up into two registers.
3062  ArgValue =
3063  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3064  } else {
3065  const TargetRegisterClass *RC;
3066  if (RegVT == MVT::i8)
3067  RC = &X86::GR8RegClass;
3068  else if (RegVT == MVT::i16)
3069  RC = &X86::GR16RegClass;
3070  else if (RegVT == MVT::i32)
3071  RC = &X86::GR32RegClass;
3072  else if (Is64Bit && RegVT == MVT::i64)
3073  RC = &X86::GR64RegClass;
3074  else if (RegVT == MVT::f32)
3075  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3076  else if (RegVT == MVT::f64)
3077  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3078  else if (RegVT == MVT::f80)
3079  RC = &X86::RFP80RegClass;
3080  else if (RegVT == MVT::f128)
3081  RC = &X86::VR128RegClass;
3082  else if (RegVT.is512BitVector())
3083  RC = &X86::VR512RegClass;
3084  else if (RegVT.is256BitVector())
3085  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3086  else if (RegVT.is128BitVector())
3087  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3088  else if (RegVT == MVT::x86mmx)
3089  RC = &X86::VR64RegClass;
3090  else if (RegVT == MVT::v1i1)
3091  RC = &X86::VK1RegClass;
3092  else if (RegVT == MVT::v8i1)
3093  RC = &X86::VK8RegClass;
3094  else if (RegVT == MVT::v16i1)
3095  RC = &X86::VK16RegClass;
3096  else if (RegVT == MVT::v32i1)
3097  RC = &X86::VK32RegClass;
3098  else if (RegVT == MVT::v64i1)
3099  RC = &X86::VK64RegClass;
3100  else
3101  llvm_unreachable("Unknown argument type!");
3102 
3103  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3104  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3105  }
3106 
3107  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3108  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3109  // right size.
3110  if (VA.getLocInfo() == CCValAssign::SExt)
3111  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3112  DAG.getValueType(VA.getValVT()));
3113  else if (VA.getLocInfo() == CCValAssign::ZExt)
3114  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3115  DAG.getValueType(VA.getValVT()));
3116  else if (VA.getLocInfo() == CCValAssign::BCvt)
3117  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3118 
3119  if (VA.isExtInLoc()) {
3120  // Handle MMX values passed in XMM regs.
3121  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3122  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3123  else if (VA.getValVT().isVector() &&
3124  VA.getValVT().getScalarType() == MVT::i1 &&
3125  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3126  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3127  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3128  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3129  } else
3130  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3131  }
3132  } else {
3133  assert(VA.isMemLoc());
3134  ArgValue =
3135  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3136  }
3137 
3138  // If value is passed via pointer - do a load.
3139  if (VA.getLocInfo() == CCValAssign::Indirect)
3140  ArgValue =
3141  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3142 
3143  InVals.push_back(ArgValue);
3144  }
3145 
3146  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3147  // Swift calling convention does not require we copy the sret argument
3148  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3149  if (CallConv == CallingConv::Swift)
3150  continue;
3151 
3152  // All x86 ABIs require that for returning structs by value we copy the
3153  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3154  // the argument into a virtual register so that we can access it from the
3155  // return points.
3156  if (Ins[I].Flags.isSRet()) {
3157  unsigned Reg = FuncInfo->getSRetReturnReg();
3158  if (!Reg) {
3159  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3160  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3161  FuncInfo->setSRetReturnReg(Reg);
3162  }
3163  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3164  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3165  break;
3166  }
3167  }
3168 
3169  unsigned StackSize = CCInfo.getNextStackOffset();
3170  // Align stack specially for tail calls.
3171  if (shouldGuaranteeTCO(CallConv,
3173  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3174 
3175  // If the function takes variable number of arguments, make a frame index for
3176  // the start of the first vararg value... for expansion of llvm.va_start. We
3177  // can skip this if there are no va_start calls.
3178  if (MFI.hasVAStart() &&
3179  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3180  CallConv != CallingConv::X86_ThisCall))) {
3181  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3182  }
3183 
3184  // Figure out if XMM registers are in use.
3185  assert(!(Subtarget.useSoftFloat() &&
3186  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3187  "SSE register cannot be used when SSE is disabled!");
3188 
3189  // 64-bit calling conventions support varargs and register parameters, so we
3190  // have to do extra work to spill them in the prologue.
3191  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3192  // Find the first unallocated argument registers.
3193  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3194  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3195  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3196  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3197  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3198  "SSE register cannot be used when SSE is disabled!");
3199 
3200  // Gather all the live in physical registers.
3201  SmallVector<SDValue, 6> LiveGPRs;
3202  SmallVector<SDValue, 8> LiveXMMRegs;
3203  SDValue ALVal;
3204  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3205  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3206  LiveGPRs.push_back(
3207  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3208  }
3209  if (!ArgXMMs.empty()) {
3210  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3211  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3212  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3213  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3214  LiveXMMRegs.push_back(
3215  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3216  }
3217  }
3218 
3219  if (IsWin64) {
3220  // Get to the caller-allocated home save location. Add 8 to account
3221  // for the return address.
3222  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3223  FuncInfo->setRegSaveFrameIndex(
3224  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3225  // Fixup to set vararg frame on shadow area (4 x i64).
3226  if (NumIntRegs < 4)
3227  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3228  } else {
3229  // For X86-64, if there are vararg parameters that are passed via
3230  // registers, then we must store them to their spots on the stack so
3231  // they may be loaded by dereferencing the result of va_next.
3232  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3233  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3235  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3236  }
3237 
3238  // Store the integer parameter registers.
3239  SmallVector<SDValue, 8> MemOps;
3240  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3241  getPointerTy(DAG.getDataLayout()));
3242  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3243  for (SDValue Val : LiveGPRs) {
3244  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3245  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3246  SDValue Store =
3247  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3249  DAG.getMachineFunction(),
3250  FuncInfo->getRegSaveFrameIndex(), Offset));
3251  MemOps.push_back(Store);
3252  Offset += 8;
3253  }
3254 
3255  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3256  // Now store the XMM (fp + vector) parameter registers.
3257  SmallVector<SDValue, 12> SaveXMMOps;
3258  SaveXMMOps.push_back(Chain);
3259  SaveXMMOps.push_back(ALVal);
3260  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3261  FuncInfo->getRegSaveFrameIndex(), dl));
3262  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3263  FuncInfo->getVarArgsFPOffset(), dl));
3264  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3265  LiveXMMRegs.end());
3267  MVT::Other, SaveXMMOps));
3268  }
3269 
3270  if (!MemOps.empty())
3271  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3272  }
3273 
3274  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3275  // Find the largest legal vector type.
3276  MVT VecVT = MVT::Other;
3277  // FIXME: Only some x86_32 calling conventions support AVX512.
3278  if (Subtarget.hasAVX512() &&
3279  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3280  CallConv == CallingConv::Intel_OCL_BI)))
3281  VecVT = MVT::v16f32;
3282  else if (Subtarget.hasAVX())
3283  VecVT = MVT::v8f32;
3284  else if (Subtarget.hasSSE2())
3285  VecVT = MVT::v4f32;
3286 
3287  // We forward some GPRs and some vector types.
3288  SmallVector<MVT, 2> RegParmTypes;
3289  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3290  RegParmTypes.push_back(IntVT);
3291  if (VecVT != MVT::Other)
3292  RegParmTypes.push_back(VecVT);
3293 
3294  // Compute the set of forwarded registers. The rest are scratch.
3296  FuncInfo->getForwardedMustTailRegParms();
3297  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3298 
3299  // Conservatively forward AL on x86_64, since it might be used for varargs.
3300  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3301  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3302  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3303  }
3304 
3305  // Copy all forwards from physical to virtual registers.
3306  for (ForwardedRegister &F : Forwards) {
3307  // FIXME: Can we use a less constrained schedule?
3308  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3309  F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3310  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3311  }
3312  }
3313 
3314  // Some CCs need callee pop.
3315  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3317  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3318  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3319  // X86 interrupts must pop the error code (and the alignment padding) if
3320  // present.
3321  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3322  } else {
3323  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3324  // If this is an sret function, the return should pop the hidden pointer.
3325  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3326  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3327  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3328  FuncInfo->setBytesToPopOnReturn(4);
3329  }
3330 
3331  if (!Is64Bit) {
3332  // RegSaveFrameIndex is X86-64 only.
3333  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3334  if (CallConv == CallingConv::X86_FastCall ||
3335  CallConv == CallingConv::X86_ThisCall)
3336  // fastcc functions can't have varargs.
3337  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3338  }
3339 
3340  FuncInfo->setArgumentStackSize(StackSize);
3341 
3342  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3344  if (Personality == EHPersonality::CoreCLR) {
3345  assert(Is64Bit);
3346  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3347  // that we'd prefer this slot be allocated towards the bottom of the frame
3348  // (i.e. near the stack pointer after allocating the frame). Every
3349  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3350  // offset from the bottom of this and each funclet's frame must be the
3351  // same, so the size of funclets' (mostly empty) frames is dictated by
3352  // how far this slot is from the bottom (since they allocate just enough
3353  // space to accommodate holding this slot at the correct offset).
3354  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3355  EHInfo->PSPSymFrameIdx = PSPSymFI;
3356  }
3357  }
3358 
3359  if (CallConv == CallingConv::X86_RegCall ||
3360  F.hasFnAttribute("no_caller_saved_registers")) {
3362  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3363  MRI.disableCalleeSavedRegister(Pair.first);
3364  }
3365 
3366  return Chain;
3367 }
3368 
3369 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3370  SDValue Arg, const SDLoc &dl,
3371  SelectionDAG &DAG,
3372  const CCValAssign &VA,
3373  ISD::ArgFlagsTy Flags) const {
3374  unsigned LocMemOffset = VA.getLocMemOffset();
3375  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3376  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3377  StackPtr, PtrOff);
3378  if (Flags.isByVal())
3379  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3380 
3381  return DAG.getStore(
3382  Chain, dl, Arg, PtrOff,
3383  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3384 }
3385 
3386 /// Emit a load of return address if tail call
3387 /// optimization is performed and it is required.
3388 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3389  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3390  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3391  // Adjust the Return address stack slot.
3392  EVT VT = getPointerTy(DAG.getDataLayout());
3393  OutRetAddr = getReturnAddressFrameIndex(DAG);
3394 
3395  // Load the "old" Return address.
3396  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3397  return SDValue(OutRetAddr.getNode(), 1);
3398 }
3399 
3400 /// Emit a store of the return address if tail call
3401 /// optimization is performed and it is required (FPDiff!=0).
3403  SDValue Chain, SDValue RetAddrFrIdx,
3404  EVT PtrVT, unsigned SlotSize,
3405  int FPDiff, const SDLoc &dl) {
3406  // Store the return address to the appropriate stack slot.
3407  if (!FPDiff) return Chain;
3408  // Calculate the new stack slot for the return address.
3409  int NewReturnAddrFI =
3410  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3411  false);
3412  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3413  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3415  DAG.getMachineFunction(), NewReturnAddrFI));
3416  return Chain;
3417 }
3418 
3419 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3420 /// operation of specified width.
3421 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3422  SDValue V2) {
3423  unsigned NumElems = VT.getVectorNumElements();
3425  Mask.push_back(NumElems);
3426  for (unsigned i = 1; i != NumElems; ++i)
3427  Mask.push_back(i);
3428  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3429 }
3430 
3431 SDValue
3432 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3433  SmallVectorImpl<SDValue> &InVals) const {
3434  SelectionDAG &DAG = CLI.DAG;
3435  SDLoc &dl = CLI.DL;
3437  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3439  SDValue Chain = CLI.Chain;
3440  SDValue Callee = CLI.Callee;
3441  CallingConv::ID CallConv = CLI.CallConv;
3442  bool &isTailCall = CLI.IsTailCall;
3443  bool isVarArg = CLI.IsVarArg;
3444 
3445  MachineFunction &MF = DAG.getMachineFunction();
3446  bool Is64Bit = Subtarget.is64Bit();
3447  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3448  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3449  bool IsSibcall = false;
3451  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3452  const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3453  const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3454  bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3455  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3456  const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3457  bool HasNoCfCheck =
3458  (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3459  const Module *M = MF.getMMI().getModule();
3460  Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3461 
3462  if (CallConv == CallingConv::X86_INTR)
3463  report_fatal_error("X86 interrupts may not be called directly");
3464 
3465  if (Attr.getValueAsString() == "true")
3466  isTailCall = false;
3467 
3468  if (Subtarget.isPICStyleGOT() &&
3470  // If we are using a GOT, disable tail calls to external symbols with
3471  // default visibility. Tail calling such a symbol requires using a GOT
3472  // relocation, which forces early binding of the symbol. This breaks code
3473  // that require lazy function symbol resolution. Using musttail or
3474  // GuaranteedTailCallOpt will override this.
3476  if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3478  isTailCall = false;
3479  }
3480 
3481  bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3482  if (IsMustTail) {
3483  // Force this to be a tail call. The verifier rules are enough to ensure
3484  // that we can lower this successfully without moving the return address
3485  // around.
3486  isTailCall = true;
3487  } else if (isTailCall) {
3488  // Check if it's really possible to do a tail call.
3489  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3490  isVarArg, SR != NotStructReturn,
3491  MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3492  Outs, OutVals, Ins, DAG);
3493 
3494  // Sibcalls are automatically detected tailcalls which do not require
3495  // ABI changes.
3496  if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3497  IsSibcall = true;
3498 
3499  if (isTailCall)
3500  ++NumTailCalls;
3501  }
3502 
3503  assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3504  "Var args not supported with calling convention fastcc, ghc or hipe");
3505 
3506  // Analyze operands of the call, assigning locations to each operand.
3508  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3509 
3510  // Allocate shadow area for Win64.
3511  if (IsWin64)
3512  CCInfo.AllocateStack(32, 8);
3513 
3514  CCInfo.AnalyzeArguments(Outs, CC_X86);
3515 
3516  // In vectorcall calling convention a second pass is required for the HVA
3517  // types.
3518  if (CallingConv::X86_VectorCall == CallConv) {
3519  CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3520  }
3521 
3522  // Get a count of how many bytes are to be pushed on the stack.
3523  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3524  if (IsSibcall)
3525  // This is a sibcall. The memory operands are available in caller's
3526  // own caller's stack.
3527  NumBytes = 0;
3528  else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3529  canGuaranteeTCO(CallConv))
3530  NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3531 
3532  int FPDiff = 0;
3533  if (isTailCall && !IsSibcall && !IsMustTail) {
3534  // Lower arguments at fp - stackoffset + fpdiff.
3535  unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3536 
3537  FPDiff = NumBytesCallerPushed - NumBytes;
3538 
3539  // Set the delta of movement of the returnaddr stackslot.
3540  // But only set if delta is greater than previous delta.
3541  if (FPDiff < X86Info->getTCReturnAddrDelta())
3542  X86Info->setTCReturnAddrDelta(FPDiff);
3543  }
3544 
3545  unsigned NumBytesToPush = NumBytes;
3546  unsigned NumBytesToPop = NumBytes;
3547 
3548  // If we have an inalloca argument, all stack space has already been allocated
3549  // for us and be right at the top of the stack. We don't support multiple
3550  // arguments passed in memory when using inalloca.
3551  if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3552  NumBytesToPush = 0;
3553  if (!ArgLocs.back().isMemLoc())
3554  report_fatal_error("cannot use inalloca attribute on a register "
3555  "parameter");
3556  if (ArgLocs.back().getLocMemOffset() != 0)
3557  report_fatal_error("any parameter with the inalloca attribute must be "
3558  "the only memory argument");
3559  }
3560 
3561  if (!IsSibcall)
3562  Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3563  NumBytes - NumBytesToPush, dl);
3564 
3565  SDValue RetAddrFrIdx;
3566  // Load return address for tail calls.
3567  if (isTailCall && FPDiff)
3568  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3569  Is64Bit, FPDiff, dl);
3570 
3572  SmallVector<SDValue, 8> MemOpChains;
3573  SDValue StackPtr;
3574 
3575  // The next loop assumes that the locations are in the same order of the
3576  // input arguments.
3577  assert(isSortedByValueNo(ArgLocs) &&
3578  "Argument Location list must be sorted before lowering");
3579 
3580  // Walk the register/memloc assignments, inserting copies/loads. In the case
3581  // of tail call optimization arguments are handle later.
3582  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3583  for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3584  ++I, ++OutIndex) {
3585  assert(OutIndex < Outs.size() && "Invalid Out index");
3586  // Skip inalloca arguments, they have already been written.
3587  ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3588  if (Flags.isInAlloca())
3589  continue;
3590 
3591  CCValAssign &VA = ArgLocs[I];
3592  EVT RegVT = VA.getLocVT();
3593  SDValue Arg = OutVals[OutIndex];
3594  bool isByVal = Flags.isByVal();
3595 
3596  // Promote the value if needed.
3597  switch (VA.getLocInfo()) {
3598  default: llvm_unreachable("Unknown loc info!");
3599  case CCValAssign::Full: break;
3600  case CCValAssign::SExt:
3601  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3602  break;
3603  case CCValAssign::ZExt:
3604  Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3605  break;
3606  case CCValAssign::AExt:
3607  if (Arg.getValueType().isVector() &&
3609  Arg = lowerMasksToReg(Arg, RegVT, dl, DAG);
3610  else if (RegVT.is128BitVector()) {
3611  // Special case: passing MMX values in XMM registers.
3612  Arg = DAG.getBitcast(MVT::i64, Arg);
3613  Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3614  Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3615  } else
3616  Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3617  break;
3618  case CCValAssign::BCvt:
3619  Arg = DAG.getBitcast(RegVT, Arg);
3620  break;
3621  case CCValAssign::Indirect: {
3622  // Store the argument.
3623  SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3624  int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3625  Chain = DAG.getStore(
3626  Chain, dl, Arg, SpillSlot,
3628  Arg = SpillSlot;
3629  break;
3630  }
3631  }
3632 
3633  if (VA.needsCustom()) {
3634  assert(VA.getValVT() == MVT::v64i1 &&
3635  "Currently the only custom case is when we split v64i1 to 2 regs");
3636  // Split v64i1 value into two registers
3637  Passv64i1ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++I],
3638  Subtarget);
3639  } else if (VA.isRegLoc()) {
3640  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3641  if (isVarArg && IsWin64) {
3642  // Win64 ABI requires argument XMM reg to be copied to the corresponding
3643  // shadow reg if callee is a varargs function.
3644  unsigned ShadowReg = 0;
3645  switch (VA.getLocReg()) {
3646  case X86::XMM0: ShadowReg = X86::RCX; break;
3647  case X86::XMM1: ShadowReg = X86::RDX; break;
3648  case X86::XMM2: ShadowReg = X86::R8; break;
3649  case X86::XMM3: ShadowReg = X86::R9; break;
3650  }
3651  if (ShadowReg)
3652  RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3653  }
3654  } else if (!IsSibcall && (!isTailCall || isByVal)) {
3655  assert(VA.isMemLoc());
3656  if (!StackPtr.getNode())
3657  StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3658  getPointerTy(DAG.getDataLayout()));
3659  MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3660  dl, DAG, VA, Flags));
3661  }
3662  }
3663 
3664  if (!MemOpChains.empty())
3665  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3666 
3667  if (Subtarget.isPICStyleGOT()) {
3668  // ELF / PIC requires GOT in the EBX register before function calls via PLT
3669  // GOT pointer.
3670  if (!isTailCall) {
3671  RegsToPass.push_back(std::make_pair(
3672  unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3673  getPointerTy(DAG.getDataLayout()))));
3674  } else {
3675  // If we are tail calling and generating PIC/GOT style code load the
3676  // address of the callee into ECX. The value in ecx is used as target of
3677  // the tail jump. This is done to circumvent the ebx/callee-saved problem
3678  // for tail calls on PIC/GOT architectures. Normally we would just put the
3679  // address of GOT into ebx and then call target@PLT. But for tail calls
3680  // ebx would be restored (since ebx is callee saved) before jumping to the
3681  // target@PLT.
3682 
3683  // Note: The actual moving to ECX is done further down.
3685  if (G && !G->getGlobal()->hasLocalLinkage() &&
3687  Callee = LowerGlobalAddress(Callee, DAG);
3688  else if (isa<ExternalSymbolSDNode>(Callee))
3689  Callee = LowerExternalSymbol(Callee, DAG);
3690  }
3691  }
3692 
3693  if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3694  // From AMD64 ABI document:
3695  // For calls that may call functions that use varargs or stdargs
3696  // (prototype-less calls or calls to functions containing ellipsis (...) in
3697  // the declaration) %al is used as hidden argument to specify the number
3698  // of SSE registers used. The contents of %al do not need to match exactly
3699  // the number of registers, but must be an ubound on the number of SSE
3700  // registers used and is in the range 0 - 8 inclusive.
3701 
3702  // Count the number of XMM registers allocated.
3703  static const MCPhysReg XMMArgRegs[] = {
3704  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3705  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3706  };
3707  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3708  assert((Subtarget.hasSSE1() || !NumXMMRegs)
3709  && "SSE registers cannot be used when SSE is disabled");
3710 
3711  RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3712  DAG.getConstant(NumXMMRegs, dl,
3713  MVT::i8)));
3714  }
3715 
3716  if (isVarArg && IsMustTail) {
3717  const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3718</