LLVM  8.0.0svn
X86ISelLowering.cpp
Go to the documentation of this file.
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86IntrinsicsInfo.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86TargetMachine.h"
23 #include "X86TargetObjectFile.h"
25 #include "llvm/ADT/SmallSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/IR/CallSite.h"
40 #include "llvm/IR/CallingConv.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/DiagnosticInfo.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GlobalAlias.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/Intrinsics.h"
49 #include "llvm/MC/MCAsmInfo.h"
50 #include "llvm/MC/MCContext.h"
51 #include "llvm/MC/MCExpr.h"
52 #include "llvm/MC/MCSymbol.h"
54 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/KnownBits.h"
59 #include <algorithm>
60 #include <bitset>
61 #include <cctype>
62 #include <numeric>
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "x86-isel"
66 
67 STATISTIC(NumTailCalls, "Number of tail calls");
68 
70  "x86-experimental-vector-widening-legalization", cl::init(false),
71  cl::desc("Enable an experimental vector type legalization through widening "
72  "rather than promotion."),
73  cl::Hidden);
74 
76  "x86-experimental-pref-loop-alignment", cl::init(4),
77  cl::desc("Sets the preferable loop alignment for experiments "
78  "(the last x86-experimental-pref-loop-alignment bits"
79  " of the loop header PC will be 0)."),
80  cl::Hidden);
81 
83  "mul-constant-optimization", cl::init(true),
84  cl::desc("Replace 'mul x, Const' with more effective instructions like "
85  "SHIFT, LEA, etc."),
86  cl::Hidden);
87 
88 /// Call this when the user attempts to do something unsupported, like
89 /// returning a double without SSE2 enabled on x86_64. This is not fatal, unlike
90 /// report_fatal_error, so calling code should attempt to recover without
91 /// crashing.
92 static void errorUnsupported(SelectionDAG &DAG, const SDLoc &dl,
93  const char *Msg) {
95  DAG.getContext()->diagnose(
97 }
98 
100  const X86Subtarget &STI)
101  : TargetLowering(TM), Subtarget(STI) {
102  bool UseX87 = !Subtarget.useSoftFloat() && Subtarget.hasX87();
103  X86ScalarSSEf64 = Subtarget.hasSSE2();
104  X86ScalarSSEf32 = Subtarget.hasSSE1();
106 
107  // Set up the TargetLowering object.
108 
109  // X86 is weird. It always uses i8 for shift amounts and setcc results.
111  // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
113 
114  // For 64-bit, since we have so many registers, use the ILP scheduler.
115  // For 32-bit, use the register pressure specific scheduling.
116  // For Atom, always use ILP scheduling.
117  if (Subtarget.isAtom())
119  else if (Subtarget.is64Bit())
121  else
123  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
125 
126  // Bypass expensive divides and use cheaper ones.
127  if (TM.getOptLevel() >= CodeGenOpt::Default) {
128  if (Subtarget.hasSlowDivide32())
129  addBypassSlowDiv(32, 8);
130  if (Subtarget.hasSlowDivide64() && Subtarget.is64Bit())
131  addBypassSlowDiv(64, 32);
132  }
133 
134  if (Subtarget.isTargetKnownWindowsMSVC() ||
135  Subtarget.isTargetWindowsItanium()) {
136  // Setup Windows compiler runtime calls.
137  setLibcallName(RTLIB::SDIV_I64, "_alldiv");
138  setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
139  setLibcallName(RTLIB::SREM_I64, "_allrem");
140  setLibcallName(RTLIB::UREM_I64, "_aullrem");
141  setLibcallName(RTLIB::MUL_I64, "_allmul");
147  }
148 
149  if (Subtarget.isTargetDarwin()) {
150  // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
151  setUseUnderscoreSetJmp(false);
153  } else if (Subtarget.isTargetWindowsGNU()) {
154  // MS runtime is weird: it exports _setjmp, but longjmp!
157  } else {
160  }
161 
162  // Set up the register classes.
163  addRegisterClass(MVT::i8, &X86::GR8RegClass);
164  addRegisterClass(MVT::i16, &X86::GR16RegClass);
165  addRegisterClass(MVT::i32, &X86::GR32RegClass);
166  if (Subtarget.is64Bit())
167  addRegisterClass(MVT::i64, &X86::GR64RegClass);
168 
169  for (MVT VT : MVT::integer_valuetypes())
171 
172  // We don't accept any truncstore of integer registers.
179 
181 
182  // SETOEQ and SETUNE require checking two conditions.
189 
190  // Integer absolute.
191  if (Subtarget.hasCMov()) {
194  if (Subtarget.is64Bit())
196  }
197 
198  // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
199  // operation.
203 
204  if (Subtarget.is64Bit()) {
205  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512())
206  // f32/f64 are legal, f80 is custom.
208  else
211  } else if (!Subtarget.useSoftFloat()) {
212  // We have an algorithm for SSE2->double, and we turn this into a
213  // 64-bit FILD followed by conditional FADD for other targets.
215  // We have an algorithm for SSE2, and we turn this into a 64-bit
216  // FILD or VCVTUSI2SS/SD for other targets.
218  } else {
220  }
221 
222  // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
223  // this operation.
226 
227  if (!Subtarget.useSoftFloat()) {
228  // SSE has no i16 to fp conversion, only i32.
229  if (X86ScalarSSEf32) {
231  // f32 and f64 cases are Legal, f80 case is not
233  } else {
236  }
237  } else {
240  }
241 
242  // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
243  // this operation.
246 
247  if (!Subtarget.useSoftFloat()) {
248  // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
249  // are Legal, f80 is custom lowered.
252 
253  if (X86ScalarSSEf32) {
255  // f32 and f64 cases are Legal, f80 case is not
257  } else {
260  }
261  } else {
265  }
266 
267  // Handle FP_TO_UINT by promoting the destination to a larger signed
268  // conversion.
272 
273  if (Subtarget.is64Bit()) {
274  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
275  // FP_TO_UINT-i32/i64 is legal for f32/f64, but custom for f80.
278  } else {
281  }
282  } else if (!Subtarget.useSoftFloat()) {
283  // Since AVX is a superset of SSE3, only check for SSE here.
284  if (Subtarget.hasSSE1() && !Subtarget.hasSSE3())
285  // Expand FP_TO_UINT into a select.
286  // FIXME: We would like to use a Custom expander here eventually to do
287  // the optimal thing for SSE vs. the default expansion in the legalizer.
289  else
290  // With AVX512 we can use vcvts[ds]2usi for f32/f64->i32, f80 is custom.
291  // With SSE3 we can use fisttpll to convert to a signed i64; without
292  // SSE, we're stuck with a fistpll.
294 
296  }
297 
298  // TODO: when we have SSE, these could be more efficient, by using movd/movq.
299  if (!X86ScalarSSEf64) {
302  if (Subtarget.is64Bit()) {
304  // Without SSE, i64->f64 goes through memory.
306  }
307  } else if (!Subtarget.is64Bit())
309 
310  // Scalar integer divide and remainder are lowered to use operations that
311  // produce two results, to match the available instructions. This exposes
312  // the two-result form to trivial CSE, which is able to combine x/y and x%y
313  // into a single instruction.
314  //
315  // Scalar integer multiply-high is also lowered to use two-result
316  // operations, to match the available instructions. However, plain multiply
317  // (low) operations are left as Legal, as there are single-result
318  // instructions for this in x86. Using the two-result multiply instructions
319  // when both high and low results are needed must be arranged by dagcombine.
320  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
327  }
328 
331  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128,
335  }
336  if (Subtarget.is64Bit())
342 
347 
348  // Promote the i8 variants and force them on up to i32 which has a shorter
349  // encoding.
352  if (!Subtarget.hasBMI()) {
357  if (Subtarget.is64Bit()) {
360  }
361  }
362 
363  if (Subtarget.hasLZCNT()) {
364  // When promoting the i8 variants, force them to i32 for a shorter
365  // encoding.
368  } else {
375  if (Subtarget.is64Bit()) {
378  }
379  }
380 
381  // Special handling for half-precision floating point conversions.
382  // If we don't have F16C support, then lower half float conversions
383  // into library calls.
384  if (Subtarget.useSoftFloat() || !Subtarget.hasF16C()) {
387  }
388 
389  // There's never any support for operations beyond MVT::f32.
394 
401 
402  if (Subtarget.hasPOPCNT()) {
404  } else {
408  if (Subtarget.is64Bit())
410  }
411 
413 
414  if (!Subtarget.hasMOVBE())
416 
417  // These should be promoted to a larger select which is supported.
419  // X86 wants to expand cmov itself.
420  for (auto VT : { MVT::f32, MVT::f64, MVT::f80, MVT::f128 }) {
423  }
424  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
425  if (VT == MVT::i64 && !Subtarget.is64Bit())
426  continue;
429  }
430 
431  // Custom action for SELECT MMX and expand action for SELECT_CC MMX
434 
436  // NOTE: EH_SJLJ_SETJMP/_LONGJMP are not recommended, since
437  // LLVM/Clang supports zero-cost DWARF and SEH exception handling.
442  setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
443 
444  // Darwin ABI issue.
445  for (auto VT : { MVT::i32, MVT::i64 }) {
446  if (VT == MVT::i64 && !Subtarget.is64Bit())
447  continue;
454  }
455 
456  // 64-bit shl, sra, srl (iff 32-bit x86)
457  for (auto VT : { MVT::i32, MVT::i64 }) {
458  if (VT == MVT::i64 && !Subtarget.is64Bit())
459  continue;
463  }
464 
465  if (Subtarget.hasSSEPrefetch() || Subtarget.has3DNow())
467 
469 
470  // Expand certain atomics
471  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
479  }
480 
481  if (Subtarget.hasCmpxchg16b()) {
483  }
484 
485  // FIXME - use subtarget debug flags
486  if (!Subtarget.isTargetDarwin() && !Subtarget.isTargetELF() &&
487  !Subtarget.isTargetCygMing() && !Subtarget.isTargetWin64() &&
490  }
491 
494 
497 
500 
501  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
504  bool Is64Bit = Subtarget.is64Bit();
506  setOperationAction(ISD::VACOPY, MVT::Other, Is64Bit ? Custom : Expand);
507 
510 
512 
513  // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
516 
517  if (!Subtarget.useSoftFloat() && X86ScalarSSEf64) {
518  // f32 and f64 use SSE.
519  // Set up the FP register classes.
520  addRegisterClass(MVT::f32, Subtarget.hasAVX512() ? &X86::FR32XRegClass
521  : &X86::FR32RegClass);
522  addRegisterClass(MVT::f64, Subtarget.hasAVX512() ? &X86::FR64XRegClass
523  : &X86::FR64RegClass);
524 
525  for (auto VT : { MVT::f32, MVT::f64 }) {
526  // Use ANDPD to simulate FABS.
528 
529  // Use XORP to simulate FNEG.
531 
532  // Use ANDPD and ORPD to simulate FCOPYSIGN.
534 
535  // We don't support sin/cos/fmod
536  setOperationAction(ISD::FSIN , VT, Expand);
537  setOperationAction(ISD::FCOS , VT, Expand);
538  setOperationAction(ISD::FSINCOS, VT, Expand);
539  }
540 
541  // Lower this to MOVMSK plus an AND.
544 
545  } else if (!useSoftFloat() && X86ScalarSSEf32 && (UseX87 || Is64Bit)) {
546  // Use SSE for f32, x87 for f64.
547  // Set up the FP register classes.
548  addRegisterClass(MVT::f32, &X86::FR32RegClass);
549  if (UseX87)
550  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
551 
552  // Use ANDPS to simulate FABS.
554 
555  // Use XORP to simulate FNEG.
557 
558  if (UseX87)
560 
561  // Use ANDPS and ORPS to simulate FCOPYSIGN.
562  if (UseX87)
565 
566  // We don't support sin/cos/fmod
570 
571  if (UseX87) {
572  // Always expand sin/cos functions even though x87 has an instruction.
576  }
577  } else if (UseX87) {
578  // f32 and f64 in x87.
579  // Set up the FP register classes.
580  addRegisterClass(MVT::f64, &X86::RFP64RegClass);
581  addRegisterClass(MVT::f32, &X86::RFP32RegClass);
582 
583  for (auto VT : { MVT::f32, MVT::f64 }) {
584  setOperationAction(ISD::UNDEF, VT, Expand);
585  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
586 
587  // Always expand sin/cos functions even though x87 has an instruction.
588  setOperationAction(ISD::FSIN , VT, Expand);
589  setOperationAction(ISD::FCOS , VT, Expand);
590  setOperationAction(ISD::FSINCOS, VT, Expand);
591  }
592  }
593 
594  // Expand FP32 immediates into loads from the stack, save special cases.
595  if (isTypeLegal(MVT::f32)) {
596  if (UseX87 && (getRegClassFor(MVT::f32) == &X86::RFP32RegClass)) {
597  addLegalFPImmediate(APFloat(+0.0f)); // FLD0
598  addLegalFPImmediate(APFloat(+1.0f)); // FLD1
599  addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
600  addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
601  } else // SSE immediates.
602  addLegalFPImmediate(APFloat(+0.0f)); // xorps
603  }
604  // Expand FP64 immediates into loads from the stack, save special cases.
605  if (isTypeLegal(MVT::f64)) {
606  if (UseX87 && getRegClassFor(MVT::f64) == &X86::RFP64RegClass) {
607  addLegalFPImmediate(APFloat(+0.0)); // FLD0
608  addLegalFPImmediate(APFloat(+1.0)); // FLD1
609  addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
610  addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
611  } else // SSE immediates.
612  addLegalFPImmediate(APFloat(+0.0)); // xorpd
613  }
614 
615  // We don't support FMA.
618 
619  // Long double always uses X87, except f128 in MMX.
620  if (UseX87) {
621  if (Subtarget.is64Bit() && Subtarget.hasMMX()) {
622  addRegisterClass(MVT::f128, Subtarget.hasVLX() ? &X86::VR128XRegClass
623  : &X86::VR128RegClass);
628  }
629 
630  addRegisterClass(MVT::f80, &X86::RFP80RegClass);
633  {
635  addLegalFPImmediate(TmpFlt); // FLD0
636  TmpFlt.changeSign();
637  addLegalFPImmediate(TmpFlt); // FLD0/FCHS
638 
639  bool ignored;
640  APFloat TmpFlt2(+1.0);
642  &ignored);
643  addLegalFPImmediate(TmpFlt2); // FLD1
644  TmpFlt2.changeSign();
645  addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
646  }
647 
648  // Always expand sin/cos functions even though x87 has an instruction.
652 
659  }
660 
661  // Always use a library call for pow.
665 
673 
674  // Some FP actions are always expanded for vector types.
675  for (auto VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32,
677  setOperationAction(ISD::FSIN, VT, Expand);
678  setOperationAction(ISD::FSINCOS, VT, Expand);
679  setOperationAction(ISD::FCOS, VT, Expand);
680  setOperationAction(ISD::FREM, VT, Expand);
681  setOperationAction(ISD::FCOPYSIGN, VT, Expand);
682  setOperationAction(ISD::FPOW, VT, Expand);
683  setOperationAction(ISD::FLOG, VT, Expand);
684  setOperationAction(ISD::FLOG2, VT, Expand);
685  setOperationAction(ISD::FLOG10, VT, Expand);
686  setOperationAction(ISD::FEXP, VT, Expand);
687  setOperationAction(ISD::FEXP2, VT, Expand);
688  }
689 
690  // First set operation action for all vector types to either promote
691  // (for widening) or expand (for scalarization). Then we will selectively
692  // turn on ones that can be effectively codegen'd.
693  for (MVT VT : MVT::vector_valuetypes()) {
694  setOperationAction(ISD::SDIV, VT, Expand);
695  setOperationAction(ISD::UDIV, VT, Expand);
696  setOperationAction(ISD::SREM, VT, Expand);
697  setOperationAction(ISD::UREM, VT, Expand);
702  setOperationAction(ISD::FMA, VT, Expand);
703  setOperationAction(ISD::FFLOOR, VT, Expand);
704  setOperationAction(ISD::FCEIL, VT, Expand);
705  setOperationAction(ISD::FTRUNC, VT, Expand);
706  setOperationAction(ISD::FRINT, VT, Expand);
707  setOperationAction(ISD::FNEARBYINT, VT, Expand);
708  setOperationAction(ISD::SMUL_LOHI, VT, Expand);
709  setOperationAction(ISD::MULHS, VT, Expand);
710  setOperationAction(ISD::UMUL_LOHI, VT, Expand);
711  setOperationAction(ISD::MULHU, VT, Expand);
712  setOperationAction(ISD::SDIVREM, VT, Expand);
713  setOperationAction(ISD::UDIVREM, VT, Expand);
714  setOperationAction(ISD::CTPOP, VT, Expand);
715  setOperationAction(ISD::CTTZ, VT, Expand);
716  setOperationAction(ISD::CTLZ, VT, Expand);
717  setOperationAction(ISD::ROTL, VT, Expand);
718  setOperationAction(ISD::ROTR, VT, Expand);
719  setOperationAction(ISD::BSWAP, VT, Expand);
720  setOperationAction(ISD::SETCC, VT, Expand);
721  setOperationAction(ISD::FP_TO_UINT, VT, Expand);
722  setOperationAction(ISD::FP_TO_SINT, VT, Expand);
723  setOperationAction(ISD::UINT_TO_FP, VT, Expand);
724  setOperationAction(ISD::SINT_TO_FP, VT, Expand);
726  setOperationAction(ISD::TRUNCATE, VT, Expand);
729  setOperationAction(ISD::ANY_EXTEND, VT, Expand);
730  setOperationAction(ISD::SELECT_CC, VT, Expand);
731  for (MVT InnerVT : MVT::vector_valuetypes()) {
732  setTruncStoreAction(InnerVT, VT, Expand);
733 
734  setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
735  setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
736 
737  // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
738  // types, we have to deal with them whether we ask for Expansion or not.
739  // Setting Expand causes its own optimisation problems though, so leave
740  // them legal.
741  if (VT.getVectorElementType() == MVT::i1)
742  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
743 
744  // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
745  // split/scalarized right now.
746  if (VT.getVectorElementType() == MVT::f16)
747  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
748  }
749  }
750 
751  // FIXME: In order to prevent SSE instructions being expanded to MMX ones
752  // with -msoft-float, disable use of MMX as well.
753  if (!Subtarget.useSoftFloat() && Subtarget.hasMMX()) {
754  addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
755  // No operations on x86mmx supported, everything uses intrinsics.
756  }
757 
758  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE1()) {
759  addRegisterClass(MVT::v4f32, Subtarget.hasVLX() ? &X86::VR128XRegClass
760  : &X86::VR128RegClass);
761 
771  }
772 
773  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE2()) {
774  addRegisterClass(MVT::v2f64, Subtarget.hasVLX() ? &X86::VR128XRegClass
775  : &X86::VR128RegClass);
776 
777  // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
778  // registers cannot be used even for integer operations.
779  addRegisterClass(MVT::v16i8, Subtarget.hasVLX() ? &X86::VR128XRegClass
780  : &X86::VR128RegClass);
781  addRegisterClass(MVT::v8i16, Subtarget.hasVLX() ? &X86::VR128XRegClass
782  : &X86::VR128RegClass);
783  addRegisterClass(MVT::v4i32, Subtarget.hasVLX() ? &X86::VR128XRegClass
784  : &X86::VR128RegClass);
785  addRegisterClass(MVT::v2i64, Subtarget.hasVLX() ? &X86::VR128XRegClass
786  : &X86::VR128RegClass);
787 
792 
799 
813 
814  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
816  setOperationAction(ISD::SMIN, VT, VT == MVT::v8i16 ? Legal : Custom);
817  setOperationAction(ISD::UMAX, VT, VT == MVT::v16i8 ? Legal : Custom);
818  setOperationAction(ISD::UMIN, VT, VT == MVT::v16i8 ? Legal : Custom);
819  }
820 
824 
825  // Provide custom widening for v2f32 setcc. This is really for VLX when
826  // setcc result type returns v2i1/v4i1 vector for v2f32/v4f32 leading to
827  // type legalization changing the result type to v4i1 during widening.
828  // It works fine for SSE2 and is probably faster so no need to qualify with
829  // VLX support.
831 
832  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
835 
836  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
837  // setcc all the way to isel and prefer SETGT in some isel patterns.
840  }
841 
842  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
848  }
849 
850  // We support custom legalizing of sext and anyext loads for specific
851  // memory vector types which we can load as a scalar (or sequence of
852  // scalars) and extend in-register to a legal 128-bit vector type. For sext
853  // loads these must work with a single scalar load.
854  for (MVT VT : MVT::integer_vector_valuetypes()) {
856  // We don't want narrow result types here when widening.
860  }
867  }
868 
870  // Explicitly code the list so we don't use narrow result types.
878  }
879 
880  for (auto VT : { MVT::v2f64, MVT::v2i64 }) {
884 
885  if (VT == MVT::v2i64 && !Subtarget.is64Bit())
886  continue;
887 
890  }
891 
892  // Custom lower v2i64 and v2f64 selects.
898 
902 
903  // Custom legalize these to avoid over promotion or custom promotion.
914 
917 
919 
920  // Fast v2f32 UINT_TO_FP( v2i32 ) custom conversion.
922 
925 
926  for (MVT VT : MVT::fp_vector_valuetypes())
928 
929  // We want to legalize this to an f64 load rather than an i64 load on
930  // 64-bit targets and two 32-bit loads on a 32-bit target. Similar for
931  // store.
940 
944  if (!Subtarget.hasAVX512())
946 
950 
958  }
959 
960  // In the customized shift lowering, the legal v4i32/v2i64 cases
961  // in AVX2 will be recognized.
962  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
966  }
967 
971  }
972 
973  if (!Subtarget.useSoftFloat() && Subtarget.hasSSSE3()) {
982  }
983 
984  if (!Subtarget.useSoftFloat() && Subtarget.hasSSE41()) {
985  for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
986  setOperationAction(ISD::FFLOOR, RoundedTy, Legal);
987  setOperationAction(ISD::FCEIL, RoundedTy, Legal);
988  setOperationAction(ISD::FTRUNC, RoundedTy, Legal);
989  setOperationAction(ISD::FRINT, RoundedTy, Legal);
991  }
992 
1001 
1002  // FIXME: Do we need to handle scalar-to-vector here?
1004 
1005  // We directly match byte blends in the backend as they match the VSELECT
1006  // condition form.
1008 
1009  // SSE41 brings specific instructions for doing vector sign extend even in
1010  // cases where we don't have SRA.
1011  for (auto VT : { MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1014  }
1015 
1017  // Avoid narrow result types when widening. The legal types are listed
1018  // in the next loop.
1019  for (MVT VT : MVT::integer_vector_valuetypes()) {
1023  }
1024  }
1025 
1026  // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
1027  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1036  }
1037 
1038  // i8 vectors are custom because the source register and source
1039  // source memory operand types are not the same width.
1041  }
1042 
1043  if (!Subtarget.useSoftFloat() && Subtarget.hasXOP()) {
1044  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1047 
1048  // XOP can efficiently perform BITREVERSE with VPPERM.
1049  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 })
1051 
1052  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1055  }
1056 
1057  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX()) {
1058  bool HasInt256 = Subtarget.hasInt256();
1059 
1060  addRegisterClass(MVT::v32i8, Subtarget.hasVLX() ? &X86::VR256XRegClass
1061  : &X86::VR256RegClass);
1062  addRegisterClass(MVT::v16i16, Subtarget.hasVLX() ? &X86::VR256XRegClass
1063  : &X86::VR256RegClass);
1064  addRegisterClass(MVT::v8i32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1065  : &X86::VR256RegClass);
1066  addRegisterClass(MVT::v8f32, Subtarget.hasVLX() ? &X86::VR256XRegClass
1067  : &X86::VR256RegClass);
1068  addRegisterClass(MVT::v4i64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1069  : &X86::VR256RegClass);
1070  addRegisterClass(MVT::v4f64, Subtarget.hasVLX() ? &X86::VR256XRegClass
1071  : &X86::VR256RegClass);
1072 
1073  for (auto VT : { MVT::v8f32, MVT::v4f64 }) {
1082  }
1083 
1084  // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1085  // even though v8i16 is a legal type.
1089 
1092 
1093  if (!Subtarget.hasAVX512())
1095 
1096  for (MVT VT : MVT::fp_vector_valuetypes())
1098 
1099  // In the customized shift lowering, the legal v8i32/v4i64 cases
1100  // in AVX2 will be recognized.
1101  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1105  }
1106 
1110 
1117 
1118  for (auto VT : { MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1122  }
1123 
1128 
1129  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1133 
1134  // TODO - remove this once 256-bit X86ISD::ANDNP correctly split.
1135  setOperationAction(ISD::CTTZ, VT, HasInt256 ? Expand : Custom);
1136 
1137  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1138  // setcc all the way to isel and prefer SETGT in some isel patterns.
1139  setCondCodeAction(ISD::SETLT, VT, Custom);
1140  setCondCodeAction(ISD::SETLE, VT, Custom);
1141  }
1142 
1143  if (Subtarget.hasAnyFMA()) {
1144  for (auto VT : { MVT::f32, MVT::f64, MVT::v4f32, MVT::v8f32,
1147  }
1148 
1149  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64 }) {
1150  setOperationAction(ISD::ADD, VT, HasInt256 ? Legal : Custom);
1151  setOperationAction(ISD::SUB, VT, HasInt256 ? Legal : Custom);
1152  }
1153 
1156  setOperationAction(ISD::MUL, MVT::v16i16, HasInt256 ? Legal : Custom);
1158 
1161  setOperationAction(ISD::MULHU, MVT::v16i16, HasInt256 ? Legal : Custom);
1162  setOperationAction(ISD::MULHS, MVT::v16i16, HasInt256 ? Legal : Custom);
1165 
1170 
1171  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32 }) {
1172  setOperationAction(ISD::ABS, VT, HasInt256 ? Legal : Custom);
1173  setOperationAction(ISD::SMAX, VT, HasInt256 ? Legal : Custom);
1174  setOperationAction(ISD::UMAX, VT, HasInt256 ? Legal : Custom);
1175  setOperationAction(ISD::SMIN, VT, HasInt256 ? Legal : Custom);
1176  setOperationAction(ISD::UMIN, VT, HasInt256 ? Legal : Custom);
1177  }
1178 
1179  for (auto VT : {MVT::v16i16, MVT::v8i32, MVT::v4i64}) {
1182  }
1183 
1184  if (HasInt256) {
1185  // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1186  // when we have a 256bit-wide blend with immediate.
1188 
1189  // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1190  for (auto LoadExtOp : { ISD::SEXTLOAD, ISD::ZEXTLOAD }) {
1197  }
1198  }
1199 
1200  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1204  }
1205 
1206  // Extract subvector is special because the value type
1207  // (result) is 128-bit but the source is 256-bit wide.
1208  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64,
1209  MVT::v4f32, MVT::v2f64 }) {
1211  }
1212 
1213  // Custom lower several nodes for 256-bit types.
1215  MVT::v8f32, MVT::v4f64 }) {
1218  setOperationAction(ISD::VSELECT, VT, Custom);
1224  }
1225 
1226  if (HasInt256)
1228 
1229  if (HasInt256) {
1230  // Custom legalize 2x32 to get a little better code.
1233 
1234  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1236  setOperationAction(ISD::MGATHER, VT, Custom);
1237  }
1238  }
1239 
1240  // This block controls legalization of the mask vector sizes that are
1241  // available with AVX512. 512-bit vectors are in a separate block controlled
1242  // by useAVX512Regs.
1243  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1244  addRegisterClass(MVT::v1i1, &X86::VK1RegClass);
1245  addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1246  addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1247  addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1248  addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1249 
1253 
1260 
1261  // There is no byte sized k-register load or store without AVX512DQ.
1262  if (!Subtarget.hasDQI()) {
1267 
1272  }
1273 
1274  // Extends of v16i1/v8i1/v4i1/v2i1 to 128-bit vectors.
1275  for (auto VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
1279  }
1280 
1281  for (auto VT : { MVT::v2i1, MVT::v4i1, MVT::v8i1, MVT::v16i1 }) {
1288 
1293  setOperationAction(ISD::VSELECT, VT, Expand);
1294  }
1295 
1303  for (auto VT : { MVT::v1i1, MVT::v2i1, MVT::v4i1, MVT::v8i1 })
1305  }
1306 
1307  // This block controls legalization for 512-bit operations with 32/64 bit
1308  // elements. 512-bits can be disabled based on prefer-vector-width and
1309  // required-vector-width function attributes.
1310  if (!Subtarget.useSoftFloat() && Subtarget.useAVX512Regs()) {
1311  addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1312  addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1313  addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1314  addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1315 
1316  for (MVT VT : MVT::fp_vector_valuetypes())
1318 
1319  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1325  }
1326 
1327  for (MVT VT : { MVT::v16f32, MVT::v8f64 }) {
1332  }
1333 
1344 
1350 
1351  if (!Subtarget.hasVLX()) {
1352  // With 512-bit vectors and no VLX, we prefer to widen MLOAD/MSTORE
1353  // to 512-bit rather than use the AVX2 instructions so that we can use
1354  // k-masks.
1355  for (auto VT : {MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1359  }
1360  }
1361 
1370 
1371  for (auto VT : { MVT::v16f32, MVT::v8f64 }) {
1377  }
1378 
1379  // Without BWI we need to use custom lowering to handle MVT::v64i8 input.
1380  for (auto VT : {MVT::v16i32, MVT::v8i64, MVT::v64i8}) {
1383  }
1384 
1389 
1392 
1395 
1402 
1403  for (auto VT : { MVT::v16i32, MVT::v8i64 }) {
1416 
1417  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1418  // setcc all the way to isel and prefer SETGT in some isel patterns.
1421  }
1422 
1423  if (Subtarget.hasDQI()) {
1428 
1430  }
1431 
1432  if (Subtarget.hasCDI()) {
1433  // NonVLX sub-targets extend 128/256 vectors to use the 512 version.
1434  for (auto VT : { MVT::v16i32, MVT::v8i64} ) {
1436  }
1437  } // Subtarget.hasCDI()
1438 
1439  if (Subtarget.hasVPOPCNTDQ()) {
1440  for (auto VT : { MVT::v16i32, MVT::v8i64 })
1442  }
1443 
1444  // Extract subvector is special because the value type
1445  // (result) is 256-bit but the source is 512-bit wide.
1446  // 128-bit was made Legal under AVX1.
1447  for (auto VT : { MVT::v32i8, MVT::v16i16, MVT::v8i32, MVT::v4i64,
1450 
1451  for (auto VT : { MVT::v16i32, MVT::v8i64, MVT::v16f32, MVT::v8f64 }) {
1463  }
1464  // Need to custom split v32i16/v64i8 bitcasts.
1465  if (!Subtarget.hasBWI()) {
1468  }
1469  }// has AVX-512
1470 
1471  // This block controls legalization for operations that don't have
1472  // pre-AVX512 equivalents. Without VLX we use 512-bit operations for
1473  // narrower widths.
1474  if (!Subtarget.useSoftFloat() && Subtarget.hasAVX512()) {
1475  // These operations are handled on non-VLX by artificially widening in
1476  // isel patterns.
1477  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1478 
1484 
1485  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1491  }
1492 
1493  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1496  }
1497 
1498  // Custom legalize 2x32 to get a little better code.
1501 
1502  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64,
1505 
1506  if (Subtarget.hasDQI()) {
1507  for (auto VT : { MVT::v2i64, MVT::v4i64 }) {
1512 
1514  }
1515  }
1516 
1517  if (Subtarget.hasCDI()) {
1518  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 }) {
1520  }
1521  } // Subtarget.hasCDI()
1522 
1523  if (Subtarget.hasVPOPCNTDQ()) {
1524  for (auto VT : { MVT::v4i32, MVT::v8i32, MVT::v2i64, MVT::v4i64 })
1526  }
1527  }
1528 
1529  // This block control legalization of v32i1/v64i1 which are available with
1530  // AVX512BW. 512-bit v32i16 and v64i8 vector legalization is controlled with
1531  // useBWIRegs.
1532  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1533  addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1534  addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 
1536  for (auto VT : { MVT::v32i1, MVT::v64i1 }) {
1540  setOperationAction(ISD::VSELECT, VT, Expand);
1541 
1549  }
1550 
1555  for (auto VT : { MVT::v16i1, MVT::v32i1 })
1557 
1558  // Extends from v32i1 masks to 256-bit vectors.
1562  }
1563 
1564  // This block controls legalization for v32i16 and v64i8. 512-bits can be
1565  // disabled based on prefer-vector-width and required-vector-width function
1566  // attributes.
1567  if (!Subtarget.useSoftFloat() && Subtarget.useBWIRegs()) {
1568  addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1569  addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1570 
1571  // Extends from v64i1 masks to 512-bit vectors.
1575 
1599 
1602 
1604 
1605  for (auto VT : { MVT::v64i8, MVT::v32i16 }) {
1621 
1622  // The condition codes aren't legal in SSE/AVX and under AVX512 we use
1623  // setcc all the way to isel and prefer SETGT in some isel patterns.
1626  }
1627 
1628  for (auto ExtType : {ISD::ZEXTLOAD, ISD::SEXTLOAD}) {
1630  }
1631 
1632  if (Subtarget.hasBITALG()) {
1633  for (auto VT : { MVT::v64i8, MVT::v32i16 })
1635  }
1636  }
1637 
1638  if (!Subtarget.useSoftFloat() && Subtarget.hasBWI()) {
1639  for (auto VT : { MVT::v32i8, MVT::v16i8, MVT::v16i16, MVT::v8i16 }) {
1640  setOperationAction(ISD::MLOAD, VT, Subtarget.hasVLX() ? Legal : Custom);
1641  setOperationAction(ISD::MSTORE, VT, Subtarget.hasVLX() ? Legal : Custom);
1642  }
1643 
1644  // These operations are handled on non-VLX by artificially widening in
1645  // isel patterns.
1646  // TODO: Custom widen in lowering on non-VLX and drop the isel patterns?
1647 
1648  if (Subtarget.hasBITALG()) {
1649  for (auto VT : { MVT::v16i8, MVT::v32i8, MVT::v8i16, MVT::v16i16 })
1651  }
1652  }
1653 
1654  if (!Subtarget.useSoftFloat() && Subtarget.hasVLX()) {
1660 
1666 
1667  if (Subtarget.hasDQI()) {
1668  // Fast v2f32 SINT_TO_FP( v2i64 ) custom conversion.
1669  // v2f32 UINT_TO_FP is already custom under SSE2.
1672  "Unexpected operation action!");
1673  // v2i64 FP_TO_S/UINT(v2f32) custom conversion.
1676  }
1677 
1678  if (Subtarget.hasBWI()) {
1681  }
1682  }
1683 
1684  // We want to custom lower some of our intrinsics.
1688  if (!Subtarget.is64Bit()) {
1691  }
1692 
1693  // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1694  // handle type legalization for these operations here.
1695  //
1696  // FIXME: We really should do custom legalization for addition and
1697  // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1698  // than generic legalization for 64-bit multiplication-with-overflow, though.
1699  for (auto VT : { MVT::i8, MVT::i16, MVT::i32, MVT::i64 }) {
1700  if (VT == MVT::i64 && !Subtarget.is64Bit())
1701  continue;
1702  // Add/Sub/Mul with overflow operations are custom lowered.
1709 
1710  // Support carry in as value rather than glue.
1714  }
1715 
1716  if (!Subtarget.is64Bit()) {
1717  // These libcalls are not available in 32-bit.
1718  setLibcallName(RTLIB::SHL_I128, nullptr);
1719  setLibcallName(RTLIB::SRL_I128, nullptr);
1720  setLibcallName(RTLIB::SRA_I128, nullptr);
1721  setLibcallName(RTLIB::MUL_I128, nullptr);
1722  }
1723 
1724  // Combine sin / cos into _sincos_stret if it is available.
1725  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1726  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1729  }
1730 
1731  if (Subtarget.isTargetWin64()) {
1738  }
1739 
1740  // On 32 bit MSVC, `fmodf(f32)` is not defined - only `fmod(f64)`
1741  // is. We should promote the value to 64-bits to solve this.
1742  // This is what the CRT headers do - `fmodf` is an inline header
1743  // function casting to f64 and calling `fmod`.
1744  if (Subtarget.is32Bit() && (Subtarget.isTargetKnownWindowsMSVC() ||
1745  Subtarget.isTargetWindowsItanium()))
1746  for (ISD::NodeType Op :
1751 
1752  // We have target-specific dag combine patterns for the following nodes:
1792 
1794 
1795  MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1797  MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1799  MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1801 
1802  // TODO: These control memcmp expansion in CGP and could be raised higher, but
1803  // that needs to benchmarked and balanced with the potential use of vector
1804  // load/store types (PR33329, PR33914).
1805  MaxLoadsPerMemcmp = 2;
1807 
1808  // Set loop alignment to 2^ExperimentalPrefLoopAlignment bytes (default: 2^4).
1810 
1811  // An out-of-order CPU can speculatively execute past a predictable branch,
1812  // but a conditional move could be stalled by an expensive earlier operation.
1813  PredictableSelectIsExpensive = Subtarget.getSchedModel().isOutOfOrder();
1814  EnableExtLdPromotion = true;
1815  setPrefFunctionAlignment(4); // 2^4 bytes.
1816 
1818 }
1819 
1820 // This has so far only been implemented for 64-bit MachO.
1822  return Subtarget.isTargetMachO() && Subtarget.is64Bit();
1823 }
1824 
1826  // Currently only MSVC CRTs XOR the frame pointer into the stack guard value.
1827  return Subtarget.getTargetTriple().isOSMSVCRT();
1828 }
1829 
1831  const SDLoc &DL) const {
1832  EVT PtrTy = getPointerTy(DAG.getDataLayout());
1833  unsigned XorOp = Subtarget.is64Bit() ? X86::XOR64_FP : X86::XOR32_FP;
1834  MachineSDNode *Node = DAG.getMachineNode(XorOp, DL, PtrTy, Val);
1835  return SDValue(Node, 0);
1836 }
1837 
1840  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1841  return TypeSplitVector;
1842 
1844  VT.getVectorNumElements() != 1 &&
1845  VT.getVectorElementType() != MVT::i1)
1846  return TypeWidenVector;
1847 
1849 }
1850 
1852  CallingConv::ID CC,
1853  EVT VT) const {
1854  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1855  return MVT::v32i8;
1856  return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1857 }
1858 
1860  CallingConv::ID CC,
1861  EVT VT) const {
1862  if (VT == MVT::v32i1 && Subtarget.hasAVX512() && !Subtarget.hasBWI())
1863  return 1;
1864  return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1865 }
1866 
1869  EVT VT) const {
1870  if (!VT.isVector())
1871  return MVT::i8;
1872 
1873  if (Subtarget.hasAVX512()) {
1874  const unsigned NumElts = VT.getVectorNumElements();
1875 
1876  // Figure out what this type will be legalized to.
1877  EVT LegalVT = VT;
1878  while (getTypeAction(Context, LegalVT) != TypeLegal)
1879  LegalVT = getTypeToTransformTo(Context, LegalVT);
1880 
1881  // If we got a 512-bit vector then we'll definitely have a vXi1 compare.
1882  if (LegalVT.getSimpleVT().is512BitVector())
1883  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1884 
1885  if (LegalVT.getSimpleVT().isVector() && Subtarget.hasVLX()) {
1886  // If we legalized to less than a 512-bit vector, then we will use a vXi1
1887  // compare for vXi32/vXi64 for sure. If we have BWI we will also support
1888  // vXi16/vXi8.
1889  MVT EltVT = LegalVT.getSimpleVT().getVectorElementType();
1890  if (Subtarget.hasBWI() || EltVT.getSizeInBits() >= 32)
1891  return EVT::getVectorVT(Context, MVT::i1, NumElts);
1892  }
1893  }
1894 
1896 }
1897 
1898 /// Helper for getByValTypeAlignment to determine
1899 /// the desired ByVal argument alignment.
1900 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1901  if (MaxAlign == 16)
1902  return;
1903  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1904  if (VTy->getBitWidth() == 128)
1905  MaxAlign = 16;
1906  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1907  unsigned EltAlign = 0;
1908  getMaxByValAlign(ATy->getElementType(), EltAlign);
1909  if (EltAlign > MaxAlign)
1910  MaxAlign = EltAlign;
1911  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1912  for (auto *EltTy : STy->elements()) {
1913  unsigned EltAlign = 0;
1914  getMaxByValAlign(EltTy, EltAlign);
1915  if (EltAlign > MaxAlign)
1916  MaxAlign = EltAlign;
1917  if (MaxAlign == 16)
1918  break;
1919  }
1920  }
1921 }
1922 
1923 /// Return the desired alignment for ByVal aggregate
1924 /// function arguments in the caller parameter area. For X86, aggregates
1925 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1926 /// are at 4-byte boundaries.
1928  const DataLayout &DL) const {
1929  if (Subtarget.is64Bit()) {
1930  // Max of 8 and alignment of type.
1931  unsigned TyAlign = DL.getABITypeAlignment(Ty);
1932  if (TyAlign > 8)
1933  return TyAlign;
1934  return 8;
1935  }
1936 
1937  unsigned Align = 4;
1938  if (Subtarget.hasSSE1())
1939  getMaxByValAlign(Ty, Align);
1940  return Align;
1941 }
1942 
1943 /// Returns the target specific optimal type for load
1944 /// and store operations as a result of memset, memcpy, and memmove
1945 /// lowering. If DstAlign is zero that means it's safe to destination
1946 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1947 /// means there isn't a need to check it against alignment requirement,
1948 /// probably because the source does not need to be loaded. If 'IsMemset' is
1949 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1950 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1951 /// source is constant so it does not need to be loaded.
1952 /// It returns EVT::Other if the type should be determined using generic
1953 /// target-independent logic.
1954 EVT
1956  unsigned DstAlign, unsigned SrcAlign,
1957  bool IsMemset, bool ZeroMemset,
1958  bool MemcpyStrSrc,
1959  MachineFunction &MF) const {
1960  const Function &F = MF.getFunction();
1961  if (!F.hasFnAttribute(Attribute::NoImplicitFloat)) {
1962  if (Size >= 16 &&
1963  (!Subtarget.isUnalignedMem16Slow() ||
1964  ((DstAlign == 0 || DstAlign >= 16) &&
1965  (SrcAlign == 0 || SrcAlign >= 16)))) {
1966  // FIXME: Check if unaligned 32-byte accesses are slow.
1967  if (Size >= 32 && Subtarget.hasAVX()) {
1968  // Although this isn't a well-supported type for AVX1, we'll let
1969  // legalization and shuffle lowering produce the optimal codegen. If we
1970  // choose an optimal type with a vector element larger than a byte,
1971  // getMemsetStores() may create an intermediate splat (using an integer
1972  // multiply) before we splat as a vector.
1973  return MVT::v32i8;
1974  }
1975  if (Subtarget.hasSSE2())
1976  return MVT::v16i8;
1977  // TODO: Can SSE1 handle a byte vector?
1978  // If we have SSE1 registers we should be able to use them.
1979  if (Subtarget.hasSSE1() && (Subtarget.is64Bit() || Subtarget.hasX87()))
1980  return MVT::v4f32;
1981  } else if ((!IsMemset || ZeroMemset) && !MemcpyStrSrc && Size >= 8 &&
1982  !Subtarget.is64Bit() && Subtarget.hasSSE2()) {
1983  // Do not use f64 to lower memcpy if source is string constant. It's
1984  // better to use i32 to avoid the loads.
1985  // Also, do not use f64 to lower memset unless this is a memset of zeros.
1986  // The gymnastics of splatting a byte value into an XMM register and then
1987  // only using 8-byte stores (because this is a CPU with slow unaligned
1988  // 16-byte accesses) makes that a loser.
1989  return MVT::f64;
1990  }
1991  }
1992  // This is a compromise. If we reach here, unaligned accesses may be slow on
1993  // this target. However, creating smaller, aligned accesses could be even
1994  // slower and would certainly be a lot more code.
1995  if (Subtarget.is64Bit() && Size >= 8)
1996  return MVT::i64;
1997  return MVT::i32;
1998 }
1999 
2001  if (VT == MVT::f32)
2002  return X86ScalarSSEf32;
2003  else if (VT == MVT::f64)
2004  return X86ScalarSSEf64;
2005  return true;
2006 }
2007 
2008 bool
2010  unsigned,
2011  unsigned,
2012  bool *Fast) const {
2013  if (Fast) {
2014  switch (VT.getSizeInBits()) {
2015  default:
2016  // 8-byte and under are always assumed to be fast.
2017  *Fast = true;
2018  break;
2019  case 128:
2020  *Fast = !Subtarget.isUnalignedMem16Slow();
2021  break;
2022  case 256:
2023  *Fast = !Subtarget.isUnalignedMem32Slow();
2024  break;
2025  // TODO: What about AVX-512 (512-bit) accesses?
2026  }
2027  }
2028  // Misaligned accesses of any size are always allowed.
2029  return true;
2030 }
2031 
2032 /// Return the entry encoding for a jump table in the
2033 /// current function. The returned value is a member of the
2034 /// MachineJumpTableInfo::JTEntryKind enum.
2036  // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
2037  // symbol.
2038  if (isPositionIndependent() && Subtarget.isPICStyleGOT())
2040 
2041  // Otherwise, use the normal jump table encoding heuristics.
2043 }
2044 
2046  return Subtarget.useSoftFloat();
2047 }
2048 
2050  ArgListTy &Args) const {
2051 
2052  // Only relabel X86-32 for C / Stdcall CCs.
2053  if (Subtarget.is64Bit())
2054  return;
2055  if (CC != CallingConv::C && CC != CallingConv::X86_StdCall)
2056  return;
2057  unsigned ParamRegs = 0;
2058  if (auto *M = MF->getFunction().getParent())
2059  ParamRegs = M->getNumberRegisterParameters();
2060 
2061  // Mark the first N int arguments as having reg
2062  for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
2063  Type *T = Args[Idx].Ty;
2064  if (T->isIntOrPtrTy())
2065  if (MF->getDataLayout().getTypeAllocSize(T) <= 8) {
2066  unsigned numRegs = 1;
2067  if (MF->getDataLayout().getTypeAllocSize(T) > 4)
2068  numRegs = 2;
2069  if (ParamRegs < numRegs)
2070  return;
2071  ParamRegs -= numRegs;
2072  Args[Idx].IsInReg = true;
2073  }
2074  }
2075 }
2076 
2077 const MCExpr *
2079  const MachineBasicBlock *MBB,
2080  unsigned uid,MCContext &Ctx) const{
2081  assert(isPositionIndependent() && Subtarget.isPICStyleGOT());
2082  // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
2083  // entries.
2084  return MCSymbolRefExpr::create(MBB->getSymbol(),
2086 }
2087 
2088 /// Returns relocation base for the given PIC jumptable.
2090  SelectionDAG &DAG) const {
2091  if (!Subtarget.is64Bit())
2092  // This doesn't have SDLoc associated with it, but is not really the
2093  // same as a Register.
2094  return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
2095  getPointerTy(DAG.getDataLayout()));
2096  return Table;
2097 }
2098 
2099 /// This returns the relocation base for the given PIC jumptable,
2100 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
2103  MCContext &Ctx) const {
2104  // X86-64 uses RIP relative addressing based on the jump table label.
2105  if (Subtarget.isPICStyleRIPRel())
2106  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2107 
2108  // Otherwise, the reference is relative to the PIC base.
2109  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2110 }
2111 
2112 std::pair<const TargetRegisterClass *, uint8_t>
2114  MVT VT) const {
2115  const TargetRegisterClass *RRC = nullptr;
2116  uint8_t Cost = 1;
2117  switch (VT.SimpleTy) {
2118  default:
2120  case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
2121  RRC = Subtarget.is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
2122  break;
2123  case MVT::x86mmx:
2124  RRC = &X86::VR64RegClass;
2125  break;
2126  case MVT::f32: case MVT::f64:
2127  case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
2128  case MVT::v4f32: case MVT::v2f64:
2129  case MVT::v32i8: case MVT::v16i16: case MVT::v8i32: case MVT::v4i64:
2130  case MVT::v8f32: case MVT::v4f64:
2131  case MVT::v64i8: case MVT::v32i16: case MVT::v16i32: case MVT::v8i64:
2132  case MVT::v16f32: case MVT::v8f64:
2133  RRC = &X86::VR128XRegClass;
2134  break;
2135  }
2136  return std::make_pair(RRC, Cost);
2137 }
2138 
2139 unsigned X86TargetLowering::getAddressSpace() const {
2140  if (Subtarget.is64Bit())
2141  return (getTargetMachine().getCodeModel() == CodeModel::Kernel) ? 256 : 257;
2142  return 256;
2143 }
2144 
2145 static bool hasStackGuardSlotTLS(const Triple &TargetTriple) {
2146  return TargetTriple.isOSGlibc() || TargetTriple.isOSFuchsia() ||
2147  (TargetTriple.isAndroid() && !TargetTriple.isAndroidVersionLT(17));
2148 }
2149 
2151  unsigned Offset, unsigned AddressSpace) {
2154  Type::getInt8PtrTy(IRB.getContext())->getPointerTo(AddressSpace));
2155 }
2156 
2158  // glibc, bionic, and Fuchsia have a special slot for the stack guard in
2159  // tcbhead_t; use it instead of the usual global variable (see
2160  // sysdeps/{i386,x86_64}/nptl/tls.h)
2161  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple())) {
2162  if (Subtarget.isTargetFuchsia()) {
2163  // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
2164  return SegmentOffset(IRB, 0x10, getAddressSpace());
2165  } else {
2166  // %fs:0x28, unless we're using a Kernel code model, in which case
2167  // it's %gs:0x28. gs:0x14 on i386.
2168  unsigned Offset = (Subtarget.is64Bit()) ? 0x28 : 0x14;
2169  return SegmentOffset(IRB, Offset, getAddressSpace());
2170  }
2171  }
2172 
2173  return TargetLowering::getIRStackGuard(IRB);
2174 }
2175 
2177  // MSVC CRT provides functionalities for stack protection.
2178  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2180  // MSVC CRT has a global variable holding security cookie.
2181  M.getOrInsertGlobal("__security_cookie",
2183 
2184  // MSVC CRT has a function to validate security cookie.
2185  auto *SecurityCheckCookie = cast<Function>(
2186  M.getOrInsertFunction("__security_check_cookie",
2189  SecurityCheckCookie->setCallingConv(CallingConv::X86_FastCall);
2190  SecurityCheckCookie->addAttribute(1, Attribute::AttrKind::InReg);
2191  return;
2192  }
2193  // glibc, bionic, and Fuchsia have a special slot for the stack guard.
2194  if (hasStackGuardSlotTLS(Subtarget.getTargetTriple()))
2195  return;
2197 }
2198 
2200  // MSVC CRT has a global variable holding security cookie.
2201  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2203  return M.getGlobalVariable("__security_cookie");
2204  }
2206 }
2207 
2209  // MSVC CRT has a function to validate security cookie.
2210  if (Subtarget.getTargetTriple().isWindowsMSVCEnvironment() ||
2212  return M.getFunction("__security_check_cookie");
2213  }
2215 }
2216 
2218  if (Subtarget.getTargetTriple().isOSContiki())
2219  return getDefaultSafeStackPointerLocation(IRB, false);
2220 
2221  // Android provides a fixed TLS slot for the SafeStack pointer. See the
2222  // definition of TLS_SLOT_SAFESTACK in
2223  // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
2224  if (Subtarget.isTargetAndroid()) {
2225  // %fs:0x48, unless we're using a Kernel code model, in which case it's %gs:
2226  // %gs:0x24 on i386
2227  unsigned Offset = (Subtarget.is64Bit()) ? 0x48 : 0x24;
2228  return SegmentOffset(IRB, Offset, getAddressSpace());
2229  }
2230 
2231  // Fuchsia is similar.
2232  if (Subtarget.isTargetFuchsia()) {
2233  // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
2234  return SegmentOffset(IRB, 0x18, getAddressSpace());
2235  }
2236 
2238 }
2239 
2241  unsigned DestAS) const {
2242  assert(SrcAS != DestAS && "Expected different address spaces!");
2243 
2244  return SrcAS < 256 && DestAS < 256;
2245 }
2246 
2247 //===----------------------------------------------------------------------===//
2248 // Return Value Calling Convention Implementation
2249 //===----------------------------------------------------------------------===//
2250 
2251 #include "X86GenCallingConv.inc"
2252 
2253 bool X86TargetLowering::CanLowerReturn(
2254  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2255  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2257  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2258  return CCInfo.CheckReturn(Outs, RetCC_X86);
2259 }
2260 
2261 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2262  static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2263  return ScratchRegs;
2264 }
2265 
2266 /// Lowers masks values (v*i1) to the local register values
2267 /// \returns DAG node after lowering to register type
2268 static SDValue lowerMasksToReg(const SDValue &ValArg, const EVT &ValLoc,
2269  const SDLoc &Dl, SelectionDAG &DAG) {
2270  EVT ValVT = ValArg.getValueType();
2271 
2272  if (ValVT == MVT::v1i1)
2273  return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Dl, ValLoc, ValArg,
2274  DAG.getIntPtrConstant(0, Dl));
2275 
2276  if ((ValVT == MVT::v8i1 && (ValLoc == MVT::i8 || ValLoc == MVT::i32)) ||
2277  (ValVT == MVT::v16i1 && (ValLoc == MVT::i16 || ValLoc == MVT::i32))) {
2278  // Two stage lowering might be required
2279  // bitcast: v8i1 -> i8 / v16i1 -> i16
2280  // anyextend: i8 -> i32 / i16 -> i32
2281  EVT TempValLoc = ValVT == MVT::v8i1 ? MVT::i8 : MVT::i16;
2282  SDValue ValToCopy = DAG.getBitcast(TempValLoc, ValArg);
2283  if (ValLoc == MVT::i32)
2284  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValToCopy);
2285  return ValToCopy;
2286  }
2287 
2288  if ((ValVT == MVT::v32i1 && ValLoc == MVT::i32) ||
2289  (ValVT == MVT::v64i1 && ValLoc == MVT::i64)) {
2290  // One stage lowering is required
2291  // bitcast: v32i1 -> i32 / v64i1 -> i64
2292  return DAG.getBitcast(ValLoc, ValArg);
2293  }
2294 
2295  return DAG.getNode(ISD::ANY_EXTEND, Dl, ValLoc, ValArg);
2296 }
2297 
2298 /// Breaks v64i1 value into two registers and adds the new node to the DAG
2300  const SDLoc &Dl, SelectionDAG &DAG, SDValue Chain, SDValue &Arg,
2301  SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, CCValAssign &VA,
2302  CCValAssign &NextVA, const X86Subtarget &Subtarget) {
2303  assert(Subtarget.hasBWI() && "Expected AVX512BW target!");
2304  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2305  assert(Arg.getValueType() == MVT::i64 && "Expecting 64 bit value");
2306  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2307  "The value should reside in two registers");
2308 
2309  // Before splitting the value we cast it to i64
2310  Arg = DAG.getBitcast(MVT::i64, Arg);
2311 
2312  // Splitting the value into two i32 types
2313  SDValue Lo, Hi;
2314  Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2315  DAG.getConstant(0, Dl, MVT::i32));
2316  Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32, Arg,
2317  DAG.getConstant(1, Dl, MVT::i32));
2318 
2319  // Attach the two i32 types into corresponding registers
2320  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
2321  RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Hi));
2322 }
2323 
2324 SDValue
2325 X86TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2326  bool isVarArg,
2327  const SmallVectorImpl<ISD::OutputArg> &Outs,
2328  const SmallVectorImpl<SDValue> &OutVals,
2329  const SDLoc &dl, SelectionDAG &DAG) const {
2330  MachineFunction &MF = DAG.getMachineFunction();
2332 
2333  // In some cases we need to disable registers from the default CSR list.
2334  // For example, when they are used for argument passing.
2335  bool ShouldDisableCalleeSavedRegister =
2336  CallConv == CallingConv::X86_RegCall ||
2337  MF.getFunction().hasFnAttribute("no_caller_saved_registers");
2338 
2339  if (CallConv == CallingConv::X86_INTR && !Outs.empty())
2340  report_fatal_error("X86 interrupts may not return any value");
2341 
2343  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2344  CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2345 
2346  SDValue Flag;
2347  SmallVector<SDValue, 6> RetOps;
2348  RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2349  // Operand #1 = Bytes To Pop
2350  RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2351  MVT::i32));
2352 
2353  // Copy the result values into the output registers.
2354  for (unsigned I = 0, OutsIndex = 0, E = RVLocs.size(); I != E;
2355  ++I, ++OutsIndex) {
2356  CCValAssign &VA = RVLocs[I];
2357  assert(VA.isRegLoc() && "Can only return in registers!");
2358 
2359  // Add the register to the CalleeSaveDisableRegs list.
2360  if (ShouldDisableCalleeSavedRegister)
2362 
2363  SDValue ValToCopy = OutVals[OutsIndex];
2364  EVT ValVT = ValToCopy.getValueType();
2365 
2366  // Promote values to the appropriate types.
2367  if (VA.getLocInfo() == CCValAssign::SExt)
2368  ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2369  else if (VA.getLocInfo() == CCValAssign::ZExt)
2370  ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2371  else if (VA.getLocInfo() == CCValAssign::AExt) {
2372  if (ValVT.isVector() && ValVT.getVectorElementType() == MVT::i1)
2373  ValToCopy = lowerMasksToReg(ValToCopy, VA.getLocVT(), dl, DAG);
2374  else
2375  ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2376  }
2377  else if (VA.getLocInfo() == CCValAssign::BCvt)
2378  ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2379 
2381  "Unexpected FP-extend for return value.");
2382 
2383  // If this is x86-64, and we disabled SSE, we can't return FP values,
2384  // or SSE or MMX vectors.
2385  if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2386  VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2387  (Subtarget.is64Bit() && !Subtarget.hasSSE1())) {
2388  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2389  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2390  } else if (ValVT == MVT::f64 &&
2391  (Subtarget.is64Bit() && !Subtarget.hasSSE2())) {
2392  // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2393  // llvm-gcc has never done it right and no one has noticed, so this
2394  // should be OK for now.
2395  errorUnsupported(DAG, dl, "SSE2 register return with SSE2 disabled");
2396  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2397  }
2398 
2399  // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2400  // the RET instruction and handled by the FP Stackifier.
2401  if (VA.getLocReg() == X86::FP0 ||
2402  VA.getLocReg() == X86::FP1) {
2403  // If this is a copy from an xmm register to ST(0), use an FPExtend to
2404  // change the value to the FP stack register class.
2405  if (isScalarFPTypeInSSEReg(VA.getValVT()))
2406  ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2407  RetOps.push_back(ValToCopy);
2408  // Don't emit a copytoreg.
2409  continue;
2410  }
2411 
2412  // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2413  // which is returned in RAX / RDX.
2414  if (Subtarget.is64Bit()) {
2415  if (ValVT == MVT::x86mmx) {
2416  if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2417  ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2418  ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2419  ValToCopy);
2420  // If we don't have SSE2 available, convert to v4f32 so the generated
2421  // register is legal.
2422  if (!Subtarget.hasSSE2())
2423  ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2424  }
2425  }
2426  }
2427 
2429 
2430  if (VA.needsCustom()) {
2431  assert(VA.getValVT() == MVT::v64i1 &&
2432  "Currently the only custom case is when we split v64i1 to 2 regs");
2433 
2434  Passv64i1ArgInRegs(dl, DAG, Chain, ValToCopy, RegsToPass, VA, RVLocs[++I],
2435  Subtarget);
2436 
2437  assert(2 == RegsToPass.size() &&
2438  "Expecting two registers after Pass64BitArgInRegs");
2439 
2440  // Add the second register to the CalleeSaveDisableRegs list.
2441  if (ShouldDisableCalleeSavedRegister)
2442  MF.getRegInfo().disableCalleeSavedRegister(RVLocs[I].getLocReg());
2443  } else {
2444  RegsToPass.push_back(std::make_pair(VA.getLocReg(), ValToCopy));
2445  }
2446 
2447  // Add nodes to the DAG and add the values into the RetOps list
2448  for (auto &Reg : RegsToPass) {
2449  Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, Flag);
2450  Flag = Chain.getValue(1);
2451  RetOps.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
2452  }
2453  }
2454 
2455  // Swift calling convention does not require we copy the sret argument
2456  // into %rax/%eax for the return, and SRetReturnReg is not set for Swift.
2457 
2458  // All x86 ABIs require that for returning structs by value we copy
2459  // the sret argument into %rax/%eax (depending on ABI) for the return.
2460  // We saved the argument into a virtual register in the entry block,
2461  // so now we copy the value out and into %rax/%eax.
2462  //
2463  // Checking Function.hasStructRetAttr() here is insufficient because the IR
2464  // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2465  // false, then an sret argument may be implicitly inserted in the SelDAG. In
2466  // either case FuncInfo->setSRetReturnReg() will have been called.
2467  if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2468  // When we have both sret and another return value, we should use the
2469  // original Chain stored in RetOps[0], instead of the current Chain updated
2470  // in the above loop. If we only have sret, RetOps[0] equals to Chain.
2471 
2472  // For the case of sret and another return value, we have
2473  // Chain_0 at the function entry
2474  // Chain_1 = getCopyToReg(Chain_0) in the above loop
2475  // If we use Chain_1 in getCopyFromReg, we will have
2476  // Val = getCopyFromReg(Chain_1)
2477  // Chain_2 = getCopyToReg(Chain_1, Val) from below
2478 
2479  // getCopyToReg(Chain_0) will be glued together with
2480  // getCopyToReg(Chain_1, Val) into Unit A, getCopyFromReg(Chain_1) will be
2481  // in Unit B, and we will have cyclic dependency between Unit A and Unit B:
2482  // Data dependency from Unit B to Unit A due to usage of Val in
2483  // getCopyToReg(Chain_1, Val)
2484  // Chain dependency from Unit A to Unit B
2485 
2486  // So here, we use RetOps[0] (i.e Chain_0) for getCopyFromReg.
2487  SDValue Val = DAG.getCopyFromReg(RetOps[0], dl, SRetReg,
2488  getPointerTy(MF.getDataLayout()));
2489 
2490  unsigned RetValReg
2491  = (Subtarget.is64Bit() && !Subtarget.isTarget64BitILP32()) ?
2492  X86::RAX : X86::EAX;
2493  Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2494  Flag = Chain.getValue(1);
2495 
2496  // RAX/EAX now acts like a return value.
2497  RetOps.push_back(
2498  DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2499 
2500  // Add the returned register to the CalleeSaveDisableRegs list.
2501  if (ShouldDisableCalleeSavedRegister)
2502  MF.getRegInfo().disableCalleeSavedRegister(RetValReg);
2503  }
2504 
2505  const X86RegisterInfo *TRI = Subtarget.getRegisterInfo();
2506  const MCPhysReg *I =
2508  if (I) {
2509  for (; *I; ++I) {
2510  if (X86::GR64RegClass.contains(*I))
2511  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2512  else
2513  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2514  }
2515  }
2516 
2517  RetOps[0] = Chain; // Update chain.
2518 
2519  // Add the flag if we have it.
2520  if (Flag.getNode())
2521  RetOps.push_back(Flag);
2522 
2524  if (CallConv == CallingConv::X86_INTR)
2525  opcode = X86ISD::IRET;
2526  return DAG.getNode(opcode, dl, MVT::Other, RetOps);
2527 }
2528 
2529 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2530  if (N->getNumValues() != 1 || !N->hasNUsesOfValue(1, 0))
2531  return false;
2532 
2533  SDValue TCChain = Chain;
2534  SDNode *Copy = *N->use_begin();
2535  if (Copy->getOpcode() == ISD::CopyToReg) {
2536  // If the copy has a glue operand, we conservatively assume it isn't safe to
2537  // perform a tail call.
2538  if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2539  return false;
2540  TCChain = Copy->getOperand(0);
2541  } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2542  return false;
2543 
2544  bool HasRet = false;
2545  for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2546  UI != UE; ++UI) {
2547  if (UI->getOpcode() != X86ISD::RET_FLAG)
2548  return false;
2549  // If we are returning more than one value, we can definitely
2550  // not make a tail call see PR19530
2551  if (UI->getNumOperands() > 4)
2552  return false;
2553  if (UI->getNumOperands() == 4 &&
2554  UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2555  return false;
2556  HasRet = true;
2557  }
2558 
2559  if (!HasRet)
2560  return false;
2561 
2562  Chain = TCChain;
2563  return true;
2564 }
2565 
2566 EVT X86TargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
2567  ISD::NodeType ExtendKind) const {
2568  MVT ReturnMVT = MVT::i32;
2569 
2570  bool Darwin = Subtarget.getTargetTriple().isOSDarwin();
2571  if (VT == MVT::i1 || (!Darwin && (VT == MVT::i8 || VT == MVT::i16))) {
2572  // The ABI does not require i1, i8 or i16 to be extended.
2573  //
2574  // On Darwin, there is code in the wild relying on Clang's old behaviour of
2575  // always extending i8/i16 return values, so keep doing that for now.
2576  // (PR26665).
2577  ReturnMVT = MVT::i8;
2578  }
2579 
2580  EVT MinVT = getRegisterType(Context, ReturnMVT);
2581  return VT.bitsLT(MinVT) ? MinVT : VT;
2582 }
2583 
2584 /// Reads two 32 bit registers and creates a 64 bit mask value.
2585 /// \param VA The current 32 bit value that need to be assigned.
2586 /// \param NextVA The next 32 bit value that need to be assigned.
2587 /// \param Root The parent DAG node.
2588 /// \param [in,out] InFlag Represents SDvalue in the parent DAG node for
2589 /// glue purposes. In the case the DAG is already using
2590 /// physical register instead of virtual, we should glue
2591 /// our new SDValue to InFlag SDvalue.
2592 /// \return a new SDvalue of size 64bit.
2594  SDValue &Root, SelectionDAG &DAG,
2595  const SDLoc &Dl, const X86Subtarget &Subtarget,
2596  SDValue *InFlag = nullptr) {
2597  assert((Subtarget.hasBWI()) && "Expected AVX512BW target!");
2598  assert(Subtarget.is32Bit() && "Expecting 32 bit target");
2599  assert(VA.getValVT() == MVT::v64i1 &&
2600  "Expecting first location of 64 bit width type");
2601  assert(NextVA.getValVT() == VA.getValVT() &&
2602  "The locations should have the same type");
2603  assert(VA.isRegLoc() && NextVA.isRegLoc() &&
2604  "The values should reside in two registers");
2605 
2606  SDValue Lo, Hi;
2607  unsigned Reg;
2608  SDValue ArgValueLo, ArgValueHi;
2609 
2610  MachineFunction &MF = DAG.getMachineFunction();
2611  const TargetRegisterClass *RC = &X86::GR32RegClass;
2612 
2613  // Read a 32 bit value from the registers.
2614  if (nullptr == InFlag) {
2615  // When no physical register is present,
2616  // create an intermediate virtual register.
2617  Reg = MF.addLiveIn(VA.getLocReg(), RC);
2618  ArgValueLo = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2619  Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2620  ArgValueHi = DAG.getCopyFromReg(Root, Dl, Reg, MVT::i32);
2621  } else {
2622  // When a physical register is available read the value from it and glue
2623  // the reads together.
2624  ArgValueLo =
2625  DAG.getCopyFromReg(Root, Dl, VA.getLocReg(), MVT::i32, *InFlag);
2626  *InFlag = ArgValueLo.getValue(2);
2627  ArgValueHi =
2628  DAG.getCopyFromReg(Root, Dl, NextVA.getLocReg(), MVT::i32, *InFlag);
2629  *InFlag = ArgValueHi.getValue(2);
2630  }
2631 
2632  // Convert the i32 type into v32i1 type.
2633  Lo = DAG.getBitcast(MVT::v32i1, ArgValueLo);
2634 
2635  // Convert the i32 type into v32i1 type.
2636  Hi = DAG.getBitcast(MVT::v32i1, ArgValueHi);
2637 
2638  // Concatenate the two values together.
2639  return DAG.getNode(ISD::CONCAT_VECTORS, Dl, MVT::v64i1, Lo, Hi);
2640 }
2641 
2642 /// The function will lower a register of various sizes (8/16/32/64)
2643 /// to a mask value of the expected size (v8i1/v16i1/v32i1/v64i1)
2644 /// \returns a DAG node contains the operand after lowering to mask type.
2645 static SDValue lowerRegToMasks(const SDValue &ValArg, const EVT &ValVT,
2646  const EVT &ValLoc, const SDLoc &Dl,
2647  SelectionDAG &DAG) {
2648  SDValue ValReturned = ValArg;
2649 
2650  if (ValVT == MVT::v1i1)
2651  return DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v1i1, ValReturned);
2652 
2653  if (ValVT == MVT::v64i1) {
2654  // In 32 bit machine, this case is handled by getv64i1Argument
2655  assert(ValLoc == MVT::i64 && "Expecting only i64 locations");
2656  // In 64 bit machine, There is no need to truncate the value only bitcast
2657  } else {
2658  MVT maskLen;
2659  switch (ValVT.getSimpleVT().SimpleTy) {
2660  case MVT::v8i1:
2661  maskLen = MVT::i8;
2662  break;
2663  case MVT::v16i1:
2664  maskLen = MVT::i16;
2665  break;
2666  case MVT::v32i1:
2667  maskLen = MVT::i32;
2668  break;
2669  default:
2670  llvm_unreachable("Expecting a vector of i1 types");
2671  }
2672 
2673  ValReturned = DAG.getNode(ISD::TRUNCATE, Dl, maskLen, ValReturned);
2674  }
2675  return DAG.getBitcast(ValVT, ValReturned);
2676 }
2677 
2678 /// Lower the result values of a call into the
2679 /// appropriate copies out of appropriate physical registers.
2680 ///
2681 SDValue X86TargetLowering::LowerCallResult(
2682  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2683  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2684  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
2685  uint32_t *RegMask) const {
2686 
2687  const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2688  // Assign locations to each value returned by this call.
2690  bool Is64Bit = Subtarget.is64Bit();
2691  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2692  *DAG.getContext());
2693  CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2694 
2695  // Copy all of the result registers out of their specified physreg.
2696  for (unsigned I = 0, InsIndex = 0, E = RVLocs.size(); I != E;
2697  ++I, ++InsIndex) {
2698  CCValAssign &VA = RVLocs[I];
2699  EVT CopyVT = VA.getLocVT();
2700 
2701  // In some calling conventions we need to remove the used registers
2702  // from the register mask.
2703  if (RegMask) {
2704  for (MCSubRegIterator SubRegs(VA.getLocReg(), TRI, /*IncludeSelf=*/true);
2705  SubRegs.isValid(); ++SubRegs)
2706  RegMask[*SubRegs / 32] &= ~(1u << (*SubRegs % 32));
2707  }
2708 
2709  // If this is x86-64, and we disabled SSE, we can't return FP values
2710  if ((CopyVT == MVT::f32 || CopyVT == MVT::f64 || CopyVT == MVT::f128) &&
2711  ((Is64Bit || Ins[InsIndex].Flags.isInReg()) && !Subtarget.hasSSE1())) {
2712  errorUnsupported(DAG, dl, "SSE register return with SSE disabled");
2713  VA.convertToReg(X86::FP0); // Set reg to FP0, avoid hitting asserts.
2714  }
2715 
2716  // If we prefer to use the value in xmm registers, copy it out as f80 and
2717  // use a truncate to move it from fp stack reg to xmm reg.
2718  bool RoundAfterCopy = false;
2719  if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2721  if (!Subtarget.hasX87())
2722  report_fatal_error("X87 register return with X87 disabled");
2723  CopyVT = MVT::f80;
2724  RoundAfterCopy = (CopyVT != VA.getLocVT());
2725  }
2726 
2727  SDValue Val;
2728  if (VA.needsCustom()) {
2729  assert(VA.getValVT() == MVT::v64i1 &&
2730  "Currently the only custom case is when we split v64i1 to 2 regs");
2731  Val =
2732  getv64i1Argument(VA, RVLocs[++I], Chain, DAG, dl, Subtarget, &InFlag);
2733  } else {
2734  Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), CopyVT, InFlag)
2735  .getValue(1);
2736  Val = Chain.getValue(0);
2737  InFlag = Chain.getValue(2);
2738  }
2739 
2740  if (RoundAfterCopy)
2741  Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2742  // This truncation won't change the value.
2743  DAG.getIntPtrConstant(1, dl));
2744 
2745  if (VA.isExtInLoc() && (VA.getValVT().getScalarType() == MVT::i1)) {
2746  if (VA.getValVT().isVector() &&
2747  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
2748  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
2749  // promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
2750  Val = lowerRegToMasks(Val, VA.getValVT(), VA.getLocVT(), dl, DAG);
2751  } else
2752  Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2753  }
2754 
2755  InVals.push_back(Val);
2756  }
2757 
2758  return Chain;
2759 }
2760 
2761 //===----------------------------------------------------------------------===//
2762 // C & StdCall & Fast Calling Convention implementation
2763 //===----------------------------------------------------------------------===//
2764 // StdCall calling convention seems to be standard for many Windows' API
2765 // routines and around. It differs from C calling convention just a little:
2766 // callee should clean up the stack, not caller. Symbols should be also
2767 // decorated in some fancy way :) It doesn't support any vector arguments.
2768 // For info on fast calling convention see Fast Calling Convention (tail call)
2769 // implementation LowerX86_32FastCCCallTo.
2770 
2771 /// CallIsStructReturn - Determines whether a call uses struct return
2772 /// semantics.
2777 };
2778 static StructReturnType
2780  if (Outs.empty())
2781  return NotStructReturn;
2782 
2783  const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2784  if (!Flags.isSRet())
2785  return NotStructReturn;
2786  if (Flags.isInReg() || IsMCU)
2787  return RegStructReturn;
2788  return StackStructReturn;
2789 }
2790 
2791 /// Determines whether a function uses struct return semantics.
2792 static StructReturnType
2794  if (Ins.empty())
2795  return NotStructReturn;
2796 
2797  const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2798  if (!Flags.isSRet())
2799  return NotStructReturn;
2800  if (Flags.isInReg() || IsMCU)
2801  return RegStructReturn;
2802  return StackStructReturn;
2803 }
2804 
2805 /// Make a copy of an aggregate at address specified by "Src" to address
2806 /// "Dst" with size and alignment information specified by the specific
2807 /// parameter attribute. The copy will be passed as a byval function parameter.
2809  SDValue Chain, ISD::ArgFlagsTy Flags,
2810  SelectionDAG &DAG, const SDLoc &dl) {
2811  SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2812 
2813  return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2814  /*isVolatile*/false, /*AlwaysInline=*/true,
2815  /*isTailCall*/false,
2817 }
2818 
2819 /// Return true if the calling convention is one that we can guarantee TCO for.
2821  return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2823  CC == CallingConv::HHVM);
2824 }
2825 
2826 /// Return true if we might ever do TCO for calls with this calling convention.
2828  switch (CC) {
2829  // C calling conventions:
2830  case CallingConv::C:
2831  case CallingConv::Win64:
2833  // Callee pop conventions:
2838  return true;
2839  default:
2840  return canGuaranteeTCO(CC);
2841  }
2842 }
2843 
2844 /// Return true if the function is being made into a tailcall target by
2845 /// changing its ABI.
2846 static bool shouldGuaranteeTCO(CallingConv::ID CC, bool GuaranteedTailCallOpt) {
2847  return GuaranteedTailCallOpt && canGuaranteeTCO(CC);
2848 }
2849 
2850 bool X86TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2851  auto Attr =
2852  CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2853  if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2854  return false;
2855 
2856  ImmutableCallSite CS(CI);
2857  CallingConv::ID CalleeCC = CS.getCallingConv();
2858  if (!mayTailCallThisCC(CalleeCC))
2859  return false;
2860 
2861  return true;
2862 }
2863 
2864 SDValue
2865 X86TargetLowering::LowerMemArgument(SDValue Chain, CallingConv::ID CallConv,
2866  const SmallVectorImpl<ISD::InputArg> &Ins,
2867  const SDLoc &dl, SelectionDAG &DAG,
2868  const CCValAssign &VA,
2869  MachineFrameInfo &MFI, unsigned i) const {
2870  // Create the nodes corresponding to a load from this parameter slot.
2871  ISD::ArgFlagsTy Flags = Ins[i].Flags;
2872  bool AlwaysUseMutable = shouldGuaranteeTCO(
2873  CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2874  bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2875  EVT ValVT;
2876  MVT PtrVT = getPointerTy(DAG.getDataLayout());
2877 
2878  // If value is passed by pointer we have address passed instead of the value
2879  // itself. No need to extend if the mask value and location share the same
2880  // absolute size.
2881  bool ExtendedInMem =
2882  VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1 &&
2883  VA.getValVT().getSizeInBits() != VA.getLocVT().getSizeInBits();
2884 
2885  if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2886  ValVT = VA.getLocVT();
2887  else
2888  ValVT = VA.getValVT();
2889 
2890  // Calculate SP offset of interrupt parameter, re-arrange the slot normally
2891  // taken by a return address.
2892  int Offset = 0;
2893  if (CallConv == CallingConv::X86_INTR) {
2894  // X86 interrupts may take one or two arguments.
2895  // On the stack there will be no return address as in regular call.
2896  // Offset of last argument need to be set to -4/-8 bytes.
2897  // Where offset of the first argument out of two, should be set to 0 bytes.
2898  Offset = (Subtarget.is64Bit() ? 8 : 4) * ((i + 1) % Ins.size() - 1);
2899  if (Subtarget.is64Bit() && Ins.size() == 2) {
2900  // The stack pointer needs to be realigned for 64 bit handlers with error
2901  // code, so the argument offset changes by 8 bytes.
2902  Offset += 8;
2903  }
2904  }
2905 
2906  // FIXME: For now, all byval parameter objects are marked mutable. This can be
2907  // changed with more analysis.
2908  // In case of tail call optimization mark all arguments mutable. Since they
2909  // could be overwritten by lowering of arguments in case of a tail call.
2910  if (Flags.isByVal()) {
2911  unsigned Bytes = Flags.getByValSize();
2912  if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2913 
2914  // FIXME: For now, all byval parameter objects are marked as aliasing. This
2915  // can be improved with deeper analysis.
2916  int FI = MFI.CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable,
2917  /*isAliased=*/true);
2918  // Adjust SP offset of interrupt parameter.
2919  if (CallConv == CallingConv::X86_INTR) {
2920  MFI.setObjectOffset(FI, Offset);
2921  }
2922  return DAG.getFrameIndex(FI, PtrVT);
2923  }
2924 
2925  // This is an argument in memory. We might be able to perform copy elision.
2926  if (Flags.isCopyElisionCandidate()) {
2927  EVT ArgVT = Ins[i].ArgVT;
2928  SDValue PartAddr;
2929  if (Ins[i].PartOffset == 0) {
2930  // If this is a one-part value or the first part of a multi-part value,
2931  // create a stack object for the entire argument value type and return a
2932  // load from our portion of it. This assumes that if the first part of an
2933  // argument is in memory, the rest will also be in memory.
2934  int FI = MFI.CreateFixedObject(ArgVT.getStoreSize(), VA.getLocMemOffset(),
2935  /*Immutable=*/false);
2936  PartAddr = DAG.getFrameIndex(FI, PtrVT);
2937  return DAG.getLoad(
2938  ValVT, dl, Chain, PartAddr,
2940  } else {
2941  // This is not the first piece of an argument in memory. See if there is
2942  // already a fixed stack object including this offset. If so, assume it
2943  // was created by the PartOffset == 0 branch above and create a load from
2944  // the appropriate offset into it.
2945  int64_t PartBegin = VA.getLocMemOffset();
2946  int64_t PartEnd = PartBegin + ValVT.getSizeInBits() / 8;
2947  int FI = MFI.getObjectIndexBegin();
2948  for (; MFI.isFixedObjectIndex(FI); ++FI) {
2949  int64_t ObjBegin = MFI.getObjectOffset(FI);
2950  int64_t ObjEnd = ObjBegin + MFI.getObjectSize(FI);
2951  if (ObjBegin <= PartBegin && PartEnd <= ObjEnd)
2952  break;
2953  }
2954  if (MFI.isFixedObjectIndex(FI)) {
2955  SDValue Addr =
2956  DAG.getNode(ISD::ADD, dl, PtrVT, DAG.getFrameIndex(FI, PtrVT),
2957  DAG.getIntPtrConstant(Ins[i].PartOffset, dl));
2958  return DAG.getLoad(
2959  ValVT, dl, Chain, Addr,
2961  Ins[i].PartOffset));
2962  }
2963  }
2964  }
2965 
2966  int FI = MFI.CreateFixedObject(ValVT.getSizeInBits() / 8,
2967  VA.getLocMemOffset(), isImmutable);
2968 
2969  // Set SExt or ZExt flag.
2970  if (VA.getLocInfo() == CCValAssign::ZExt) {
2971  MFI.setObjectZExt(FI, true);
2972  } else if (VA.getLocInfo() == CCValAssign::SExt) {
2973  MFI.setObjectSExt(FI, true);
2974  }
2975 
2976  // Adjust SP offset of interrupt parameter.
2977  if (CallConv == CallingConv::X86_INTR) {
2978  MFI.setObjectOffset(FI, Offset);
2979  }
2980 
2981  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2982  SDValue Val = DAG.getLoad(
2983  ValVT, dl, Chain, FIN,
2985  return ExtendedInMem
2986  ? (VA.getValVT().isVector()
2987  ? DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VA.getValVT(), Val)
2988  : DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val))
2989  : Val;
2990 }
2991 
2992 // FIXME: Get this from tablegen.
2994  const X86Subtarget &Subtarget) {
2995  assert(Subtarget.is64Bit());
2996 
2997  if (Subtarget.isCallingConvWin64(CallConv)) {
2998  static const MCPhysReg GPR64ArgRegsWin64[] = {
2999  X86::RCX, X86::RDX, X86::R8, X86::R9
3000  };
3001  return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
3002  }
3003 
3004  static const MCPhysReg GPR64ArgRegs64Bit[] = {
3005  X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
3006  };
3007  return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
3008 }
3009 
3010 // FIXME: Get this from tablegen.
3012  CallingConv::ID CallConv,
3013  const X86Subtarget &Subtarget) {
3014  assert(Subtarget.is64Bit());
3015  if (Subtarget.isCallingConvWin64(CallConv)) {
3016  // The XMM registers which might contain var arg parameters are shadowed
3017  // in their paired GPR. So we only need to save the GPR to their home
3018  // slots.
3019  // TODO: __vectorcall will change this.
3020  return None;
3021  }
3022 
3023  const Function &F = MF.getFunction();
3024  bool NoImplicitFloatOps = F.hasFnAttribute(Attribute::NoImplicitFloat);
3025  bool isSoftFloat = Subtarget.useSoftFloat();
3026  assert(!(isSoftFloat && NoImplicitFloatOps) &&
3027  "SSE register cannot be used when SSE is disabled!");
3028  if (isSoftFloat || NoImplicitFloatOps || !Subtarget.hasSSE1())
3029  // Kernel mode asks for SSE to be disabled, so there are no XMM argument
3030  // registers.
3031  return None;
3032 
3033  static const MCPhysReg XMMArgRegs64Bit[] = {
3034  X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3035  X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3036  };
3037  return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
3038 }
3039 
3040 #ifndef NDEBUG
3042  return std::is_sorted(ArgLocs.begin(), ArgLocs.end(),
3043  [](const CCValAssign &A, const CCValAssign &B) -> bool {
3044  return A.getValNo() < B.getValNo();
3045  });
3046 }
3047 #endif
3048 
3049 SDValue X86TargetLowering::LowerFormalArguments(
3050  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3051  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3052  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3053  MachineFunction &MF = DAG.getMachineFunction();
3055  const TargetFrameLowering &TFI = *Subtarget.getFrameLowering();
3056 
3057  const Function &F = MF.getFunction();
3058  if (F.hasExternalLinkage() && Subtarget.isTargetCygMing() &&
3059  F.getName() == "main")
3060  FuncInfo->setForceFramePointer(true);
3061 
3062  MachineFrameInfo &MFI = MF.getFrameInfo();
3063  bool Is64Bit = Subtarget.is64Bit();
3064  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3065 
3066  assert(
3067  !(isVarArg && canGuaranteeTCO(CallConv)) &&
3068  "Var args not supported with calling conv' regcall, fastcc, ghc or hipe");
3069 
3070  if (CallConv == CallingConv::X86_INTR) {
3071  bool isLegal = Ins.size() == 1 ||
3072  (Ins.size() == 2 && ((Is64Bit && Ins[1].VT == MVT::i64) ||
3073  (!Is64Bit && Ins[1].VT == MVT::i32)));
3074  if (!isLegal)
3075  report_fatal_error("X86 interrupts may take one or two arguments");
3076  }
3077 
3078  // Assign locations to all of the incoming arguments.
3080  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3081 
3082  // Allocate shadow area for Win64.
3083  if (IsWin64)
3084  CCInfo.AllocateStack(32, 8);
3085 
3086  CCInfo.AnalyzeArguments(Ins, CC_X86);
3087 
3088  // In vectorcall calling convention a second pass is required for the HVA
3089  // types.
3090  if (CallingConv::X86_VectorCall == CallConv) {
3091  CCInfo.AnalyzeArgumentsSecondPass(Ins, CC_X86);
3092  }
3093 
3094  // The next loop assumes that the locations are in the same order of the
3095  // input arguments.
3096  assert(isSortedByValueNo(ArgLocs) &&
3097  "Argument Location list must be sorted before lowering");
3098 
3099  SDValue ArgValue;
3100  for (unsigned I = 0, InsIndex = 0, E = ArgLocs.size(); I != E;
3101  ++I, ++InsIndex) {
3102  assert(InsIndex < Ins.size() && "Invalid Ins index");
3103  CCValAssign &VA = ArgLocs[I];
3104 
3105  if (VA.isRegLoc()) {
3106  EVT RegVT = VA.getLocVT();
3107  if (VA.needsCustom()) {
3108  assert(
3109  VA.getValVT() == MVT::v64i1 &&
3110  "Currently the only custom case is when we split v64i1 to 2 regs");
3111 
3112  // v64i1 values, in regcall calling convention, that are
3113  // compiled to 32 bit arch, are split up into two registers.
3114  ArgValue =
3115  getv64i1Argument(VA, ArgLocs[++I], Chain, DAG, dl, Subtarget);
3116  } else {
3117  const TargetRegisterClass *RC;
3118  if (RegVT == MVT::i8)
3119  RC = &X86::GR8RegClass;
3120  else if (RegVT == MVT::i16)
3121  RC = &X86::GR16RegClass;
3122  else if (RegVT == MVT::i32)
3123  RC = &X86::GR32RegClass;
3124  else if (Is64Bit && RegVT == MVT::i64)
3125  RC = &X86::GR64RegClass;
3126  else if (RegVT == MVT::f32)
3127  RC = Subtarget.hasAVX512() ? &X86::FR32XRegClass : &X86::FR32RegClass;
3128  else if (RegVT == MVT::f64)
3129  RC = Subtarget.hasAVX512() ? &X86::FR64XRegClass : &X86::FR64RegClass;
3130  else if (RegVT == MVT::f80)
3131  RC = &X86::RFP80RegClass;
3132  else if (RegVT == MVT::f128)
3133  RC = &X86::VR128RegClass;
3134  else if (RegVT.is512BitVector())
3135  RC = &X86::VR512RegClass;
3136  else if (RegVT.is256BitVector())
3137  RC = Subtarget.hasVLX() ? &X86::VR256XRegClass : &X86::VR256RegClass;
3138  else if (RegVT.is128BitVector())
3139  RC = Subtarget.hasVLX() ? &X86::VR128XRegClass : &X86::VR128RegClass;
3140  else if (RegVT == MVT::x86mmx)
3141  RC = &X86::VR64RegClass;
3142  else if (RegVT == MVT::v1i1)
3143  RC = &X86::VK1RegClass;
3144  else if (RegVT == MVT::v8i1)
3145  RC = &X86::VK8RegClass;
3146  else if (RegVT == MVT::v16i1)
3147  RC = &X86::VK16RegClass;
3148  else if (RegVT == MVT::v32i1)
3149  RC = &X86::VK32RegClass;
3150  else if (RegVT == MVT::v64i1)
3151  RC = &X86::VK64RegClass;
3152  else
3153  llvm_unreachable("Unknown argument type!");
3154 
3155  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3156  ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3157  }
3158 
3159  // If this is an 8 or 16-bit value, it is really passed promoted to 32
3160  // bits. Insert an assert[sz]ext to capture this, then truncate to the
3161  // right size.
3162  if (VA.getLocInfo() == CCValAssign::SExt)
3163  ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3164  DAG.getValueType(VA.getValVT()));
3165  else if (VA.getLocInfo() == CCValAssign::ZExt)
3166  ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3167  DAG.getValueType(VA.getValVT()));
3168  else if (VA.getLocInfo() == CCValAssign::BCvt)
3169  ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
3170 
3171  if (VA.isExtInLoc()) {
3172  // Handle MMX values passed in XMM regs.
3173  if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
3174  ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
3175  else if (VA.getValVT().isVector() &&
3176  VA.getValVT().getScalarType() == MVT::i1 &&
3177  ((VA.getLocVT() == MVT::i64) || (VA.getLocVT() == MVT::i32) ||
3178  (VA.getLocVT() == MVT::i16) || (VA.getLocVT() == MVT::i8))) {
3179  // Promoting a mask type (v*i1) into a register of type i64/i32/i16/i8
3180  ArgValue = lowerRegToMasks(ArgValue, VA.getValVT(), RegVT, dl, DAG);
3181  } else
3182  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3183  }
3184  } else {
3185  assert(VA.isMemLoc());
3186  ArgValue =
3187  LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, InsIndex);
3188  }
3189 
3190  // If value is passed via pointer - do a load.
3191  if (VA.getLocInfo() == CCValAssign::Indirect && !Ins[I].Flags.isByVal())
3192  ArgValue =
3193  DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, MachinePointerInfo());
3194 
3195  InVals.push_back(ArgValue);
3196  }
3197 
3198  for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
3199  // Swift calling convention does not require we copy the sret argument
3200  // into %rax/%eax for the return. We don't set SRetReturnReg for Swift.
3201  if (CallConv == CallingConv::Swift)
3202  continue;
3203 
3204  // All x86 ABIs require that for returning structs by value we copy the
3205  // sret argument into %rax/%eax (depending on ABI) for the return. Save
3206  // the argument into a virtual register so that we can access it from the
3207  // return points.
3208  if (Ins[I].Flags.isSRet()) {
3209  unsigned Reg = FuncInfo->getSRetReturnReg();
3210  if (!Reg) {
3211  MVT PtrTy = getPointerTy(DAG.getDataLayout());
3212  Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
3213  FuncInfo->setSRetReturnReg(Reg);
3214  }
3215  SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[I]);
3216  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3217  break;
3218  }
3219  }
3220 
3221  unsigned StackSize = CCInfo.getNextStackOffset();
3222  // Align stack specially for tail calls.
3223  if (shouldGuaranteeTCO(CallConv,
3225  StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
3226 
3227  // If the function takes variable number of arguments, make a frame index for
3228  // the start of the first vararg value... for expansion of llvm.va_start. We
3229  // can skip this if there are no va_start calls.
3230  if (MFI.hasVAStart() &&
3231  (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
3232  CallConv != CallingConv::X86_ThisCall))) {
3233  FuncInfo->setVarArgsFrameIndex(MFI.CreateFixedObject(1, StackSize, true));
3234  }
3235 
3236  // Figure out if XMM registers are in use.
3237  assert(!(Subtarget.useSoftFloat() &&
3238  F.hasFnAttribute(Attribute::NoImplicitFloat)) &&
3239  "SSE register cannot be used when SSE is disabled!");
3240 
3241  // 64-bit calling conventions support varargs and register parameters, so we
3242  // have to do extra work to spill them in the prologue.
3243  if (Is64Bit && isVarArg && MFI.hasVAStart()) {
3244  // Find the first unallocated argument registers.
3245  ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
3246  ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
3247  unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
3248  unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
3249  assert(!(NumXMMRegs && !Subtarget.hasSSE1()) &&
3250  "SSE register cannot be used when SSE is disabled!");
3251 
3252  // Gather all the live in physical registers.
3253  SmallVector<SDValue, 6> LiveGPRs;
3254  SmallVector<SDValue, 8> LiveXMMRegs;
3255  SDValue ALVal;
3256  for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
3257  unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
3258  LiveGPRs.push_back(
3259  DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
3260  }
3261  if (!ArgXMMs.empty()) {
3262  unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3263  ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
3264  for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
3265  unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
3266  LiveXMMRegs.push_back(
3267  DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
3268  }
3269  }
3270 
3271  if (IsWin64) {
3272  // Get to the caller-allocated home save location. Add 8 to account
3273  // for the return address.
3274  int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
3275  FuncInfo->setRegSaveFrameIndex(
3276  MFI.CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
3277  // Fixup to set vararg frame on shadow area (4 x i64).
3278  if (NumIntRegs < 4)
3279  FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
3280  } else {
3281  // For X86-64, if there are vararg parameters that are passed via
3282  // registers, then we must store them to their spots on the stack so
3283  // they may be loaded by dereferencing the result of va_next.
3284  FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
3285  FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
3287  ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
3288  }
3289 
3290  // Store the integer parameter registers.
3291  SmallVector<SDValue, 8> MemOps;
3292  SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
3293  getPointerTy(DAG.getDataLayout()));
3294  unsigned Offset = FuncInfo->getVarArgsGPOffset();
3295  for (SDValue Val : LiveGPRs) {
3296  SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3297  RSFIN, DAG.getIntPtrConstant(Offset, dl));
3298  SDValue Store =
3299  DAG.getStore(Val.getValue(1), dl, Val, FIN,
3301  DAG.getMachineFunction(),
3302  FuncInfo->getRegSaveFrameIndex(), Offset));
3303  MemOps.push_back(Store);
3304  Offset += 8;
3305  }
3306 
3307  if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
3308  // Now store the XMM (fp + vector) parameter registers.
3309  SmallVector<SDValue, 12> SaveXMMOps;
3310  SaveXMMOps.push_back(Chain);
3311  SaveXMMOps.push_back(ALVal);
3312  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3313  FuncInfo->getRegSaveFrameIndex(), dl));
3314  SaveXMMOps.push_back(DAG.getIntPtrConstant(
3315  FuncInfo->getVarArgsFPOffset(), dl));
3316  SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
3317  LiveXMMRegs.end());
3319  MVT::Other, SaveXMMOps));
3320  }
3321 
3322  if (!MemOps.empty())
3323  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3324  }
3325 
3326  if (isVarArg && MFI.hasMustTailInVarArgFunc()) {
3327  // Find the largest legal vector type.
3328  MVT VecVT = MVT::Other;
3329  // FIXME: Only some x86_32 calling conventions support AVX512.
3330  if (Subtarget.hasAVX512() &&
3331  (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
3332  CallConv == CallingConv::Intel_OCL_BI)))
3333  VecVT = MVT::v16f32;
3334  else if (Subtarget.hasAVX())
3335  VecVT = MVT::v8f32;
3336  else if (Subtarget.hasSSE2())
3337  VecVT = MVT::v4f32;
3338 
3339  // We forward some GPRs and some vector types.
3340  SmallVector<MVT, 2> RegParmTypes;
3341  MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
3342  RegParmTypes.push_back(IntVT);
3343  if (VecVT != MVT::Other)
3344  RegParmTypes.push_back(VecVT);
3345 
3346  // Compute the set of forwarded registers. The rest are scratch.
3348  FuncInfo->getForwardedMustTailRegParms();
3349  CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
3350 
3351  // Conservatively forward AL on x86_64, since it might be used for varargs.
3352  if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
3353  unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
3354  Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
3355  }
3356 
3357  // Copy all forwards from physical to virtual registers.
3358  for (ForwardedRegister &F : Forwards) {
3359  // FIXME: Can we use a less constrained schedule?
3360  SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3361  F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
3362  Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
3363  }
3364  }
3365 
3366  // Some CCs need callee pop.
3367  if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3369  FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
3370  } else if (CallConv == CallingConv::X86_INTR && Ins.size() == 2) {
3371  // X86 interrupts must pop the error code (and the alignment padding) if
3372  // present.
3373  FuncInfo->setBytesToPopOnReturn(Is64Bit ? 16 : 4);
3374  } else {
3375  FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
3376  // If this is an sret function, the return should pop the hidden pointer.
3377  if (!Is64Bit && !canGuaranteeTCO(CallConv) &&
3378  !Subtarget.getTargetTriple().isOSMSVCRT() &&
3379  argsAreStructReturn(Ins, Subtarget.isTargetMCU()) == StackStructReturn)
3380  FuncInfo->setBytesToPopOnReturn(4);
3381  }
3382 
3383  if (!Is64Bit) {
3384  // RegSaveFrameIndex is X86-64 only.
3385  FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
3386  if (CallConv == CallingConv::X86_FastCall ||
3387  CallConv == CallingConv::X86_ThisCall)
3388  // fastcc functions can't have varargs.
3389  FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
3390  }
3391 
3392  FuncInfo->setArgumentStackSize(StackSize);
3393 
3394  if (WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo()) {
3396  if (Personality == EHPersonality::CoreCLR) {
3397  assert(Is64Bit);
3398  // TODO: Add a mechanism to frame lowering that will allow us to indicate
3399  // that we'd prefer this slot be allocated towards the bottom of the frame
3400  // (i.e. near the stack pointer after allocating the frame). Every
3401  // funclet needs a copy of this slot in its (mostly empty) frame, and the
3402  // offset from the bottom of this and each funclet's frame must be the
3403  // same, so the size of funclets' (mostly empty) frames is dictated by
3404  // how far this slot is from the bottom (since they allocate just enough
3405  // space to accommodate holding this slot at the correct offset).
3406  int PSPSymFI = MFI.CreateStackObject(8, 8, /*isSS=*/false);
3407  EHInfo->PSPSymFrameIdx = PSPSymFI;
3408  }
3409  }
3410 
3411  if (CallConv == CallingConv::X86_RegCall ||
3412  F.hasFnAttribute("no_caller_saved_registers")) {
3414  for (std::pair<unsigned, unsigned> Pair : MRI.liveins())
3415  MRI.disableCalleeSavedRegister(Pair.first);
3416  }
3417 
3418  return Chain;
3419 }
3420 
3421 SDValue X86TargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
3422  SDValue Arg, const SDLoc &dl,
3423  SelectionDAG &DAG,
3424  const CCValAssign &VA,
3425  ISD::ArgFlagsTy Flags) const {
3426  unsigned LocMemOffset = VA.getLocMemOffset();
3427  SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
3428  PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3429  StackPtr, PtrOff);
3430  if (Flags.isByVal())
3431  return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
3432 
3433  return DAG.getStore(
3434  Chain, dl, Arg, PtrOff,
3435  MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
3436 }
3437 
3438 /// Emit a load of return address if tail call
3439 /// optimization is performed and it is required.
3440 SDValue X86TargetLowering::EmitTailCallLoadRetAddr(
3441  SelectionDAG &DAG, SDValue &OutRetAddr, SDValue Chain, bool IsTailCall,
3442  bool Is64Bit, int FPDiff, const SDLoc &dl) const {
3443  // Adjust the Return address stack slot.
3444  EVT VT = getPointerTy(DAG.getDataLayout());
3445  OutRetAddr = getReturnAddressFrameIndex(DAG);
3446 
3447  // Load the "old" Return address.
3448  OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo());
3449  return SDValue(OutRetAddr.getNode(), 1);
3450 }
3451 
3452 /// Emit a store of the return address if tail call
3453 /// optimization is performed and it is required (FPDiff!=0).
3455  SDValue Chain, SDValue RetAddrFrIdx,
3456  EVT PtrVT, unsigned SlotSize,
3457  int FPDiff, const SDLoc &dl) {
3458  // Store the return address to the appropriate stack slot.
3459  if (!FPDiff) return Chain;
3460  // Calculate the new stack slot for the return address.
3461  int NewReturnAddrFI =
3462  MF.getFrameInfo().CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
3463  false);
3464  SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
3465  Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
3467  DAG.getMachineFunction(), NewReturnAddrFI));
3468  return Chain;
3469 }
3470 
3471 /// Returns a vector_shuffle mask for an movs{s|d}, movd
3472 /// operation of specified width.
3473 static SDValue getMOVL(SelectionDAG &DAG, const SDLoc &dl, MVT VT, SDValue V1,
3474  SDValue V2) {
3475  unsigned NumElems = VT.getVectorNumElements();
3477  Mask.push_back(NumElems);
3478  for (unsigned i = 1; i != NumElems; ++i)
3479  Mask.push_back(i);
3480  return DAG.getVectorShuffle(VT, dl, V1, V2, Mask);
3481 }
3482 
3483 SDValue
3484 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3485  SmallVectorImpl<SDValue> &InVals) const {
3486  SelectionDAG &DAG = CLI.DAG;
3487  SDLoc &dl = CLI.DL;
3489  SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3491  SDValue Chain = CLI.Chain;
3492  SDValue Callee = CLI.Callee;
3493  CallingConv::ID CallConv = CLI.CallConv;
3494  bool &isTailCall = CLI.IsTailCall;
3495  bool isVarArg = CLI.IsVarArg;
3496 
3497  MachineFunction &MF = DAG.getMachineFunction();
3498  bool Is64Bit = Subtarget.is64Bit();
3499  bool IsWin64 = Subtarget.isCallingConvWin64(CallConv);
3500  StructReturnType SR = callIsStructReturn(Outs, Subtarget.isTargetMCU());
3501  bool IsSibcall = false;
3503  auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
3504  const auto *CI = dyn_cast_or_null<CallInst>(CLI.CS.getInstruction());
3505  const Function *Fn = CI ? CI->getCalledFunction() : nullptr;
3506  bool HasNCSR = (CI && CI->hasFnAttr("no_caller_saved_registers")) ||
3507  (Fn && Fn->hasFnAttribute("no_caller_saved_registers"));
3508  const auto *II = dyn_cast_or_null<InvokeInst>(CLI.CS.getInstruction());
3509  bool HasNoCfCheck =
3510  (CI && CI->doesNoCfCheck()) || (II && II->doesNoCfCheck());
3511  const Module *M = MF.getMMI().getModule();
3512  Metadata *IsCFProtectionSupported = M->getModuleFlag("cf-protection-branch");
3513 
3514  if (CallConv == CallingConv::X86_INTR)
3515  report_fatal_error("X86 interrupts may not be called directly");
3516 
3517  if (Attr.getValueAsString() == "true")
3518  isTailCall = false;
3519 
3520  if (Subtarget.isPICStyleGOT() &&
3522  // If we are using a GOT, disable tail calls to external symbols with
3523  // default visibility. Tail calling such a symbol requires using a GOT
3524  // relocation, which forces early binding of the symbol. This breaks code
3525  // that require lazy function symbol resolution. Using musttail or
3526  // GuaranteedTailCallOpt will override this.
3528  if (!G || (!G->getGlobal()->hasLocalLinkage() &&
3530  isTailCall = false;
3531  }
3532 
3533  bool IsMustTail = CLI.CS && CLI.CS.isMustTailCall();
3534  if (IsMustTail) {
3535  // Force this to be a tail call. The verifier rules are enough to ensure
3536  // that we can lower this successfully without moving the return address
3537  // around.
3538  isTailCall = true;
3539  } else if (isTailCall) {
3540  // Check if it's really possible to do a tail call.
3541  isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
3542  isVarArg, SR != NotStructReturn,
3543  MF.getFunction().hasStructRetAttr(), CLI.RetTy,
3544  Outs, OutVals, Ins, DAG);
3545 
3546  // Sibcalls are automatically detected tailcalls which do not require
3547  // ABI changes.
3548  if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
3549  IsSibcall = true;
3550 
3551  if (isTailCall)
3552  ++NumTailCalls;
3553  }
3554 
3555  assert(!(isVarArg && canGuaranteeTCO(CallConv)) &&
3556  "Var args not supported with calling convention fastcc, ghc or hipe");
3557 
3558  // Analyze operands of the call, assigning locations to each operand.
3560  CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
3561 
3562  // Allocate shadow area for Win64.
3563  if (IsWin64)
3564  CCInfo.AllocateStack(32, 8);
3565 
3566  CCInfo.AnalyzeArguments(Outs, CC_X86);
3567 
3568  // In vectorcall calling convention a second pass is required for the HVA
3569  // types.
3570  if (CallingConv::X86_VectorCall == CallConv) {
3571  CCInfo.AnalyzeArgumentsSecondPass(Outs, CC_X86);
3572  }
3573 
3574  // Get a count of how many bytes are to be pushed on the stack.
3575  unsigned NumBytes = CCInfo.getAlignedCallFrameSize();
3576  if (IsSibcall)
3577  // This is a sibcall. The memory operands are available in caller's
3578  // own caller's stack.
3579  NumBytes = 0;
3580  else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
3581  canGuaranteeTCO(CallConv))
3582  NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
3583 
3584  int FPDiff = 0;
3585  if (isTailCall && !IsSibcall && !IsMustTail) {
3586  // Lower arguments at fp - stackoffset + fpdiff.
3587  unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
3588 
3589  FPDiff = NumBytesCallerPushed - NumBytes;
3590 
3591  // Set the delta of movement of the returnaddr stackslot.
3592  // But only set if delta is greater than previous delta.
3593  if (FPDiff < X86Info->getTCReturnAddrDelta())
3594  X86Info->setTCReturnAddrDelta(FPDiff);
3595  }
3596 
3597  unsigned NumBytesToPush = NumBytes;
3598  unsigned NumBytesToPop = NumBytes;
3599 
3600  // If we have an inalloca argument, all stack space has already been allocated
3601  // for us and be right at the top of the stack. We don't support multiple
3602  // arguments passed in memory when using inalloca.
3603  if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
3604  NumBytesToPush = 0;
3605  if (!ArgLocs.back().isMemLoc())
3606  report_fatal_error("cannot use inalloca attribute on a register "
3607  "parameter");
3608  if (ArgLocs.back().getLocMemOffset() != 0)
3609  report_fatal_error("any parameter with the inalloca attribute must be "
3610  "the only memory argument");
3611  }
3612 
3613  if (!IsSibcall)
3614  Chain = DAG.getCALLSEQ_START(Chain, NumBytesToPush,
3615  NumBytes - NumBytesToPush, dl);
3616 
3617  SDValue RetAddrFrIdx;
3618  // Load return address for tail calls.
3619  if (isTailCall && FPDiff)
3620  Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
3621  Is64Bit, FPDiff, dl);
3622 
3624  SmallVector<SDValue, 8> MemOpChains;
3625  SDValue StackPtr;
3626 
3627  // The next loop assumes that the locations are in the same order of the
3628  // input arguments.
3629  assert(isSortedByValueNo(ArgLocs) &&
3630  "Argument Location list must be sorted before lowering");
3631 
3632  // Walk the register/memloc assignments, inserting copies/loads. In the case
3633  // of tail call optimization arguments are handle later.
3634  const X86RegisterInfo *RegInfo = Subtarget.getRegisterInfo();
3635  for (unsigned I = 0, OutIndex = 0, E = ArgLocs.size(); I != E;
3636  ++I, ++OutIndex) {
3637  assert(OutIndex < Outs.size() && "Invalid Out index");
3638  // Skip inalloca arguments, they have already been written.
3639  ISD::ArgFlagsTy Flags = Outs[OutIndex].Flags;
3640  if (Flags.isInAlloca())
3641  continue;
3642 
3643  CCValAssign &VA = ArgLocs[I];
3644  EVT RegVT = VA.getLocVT();
3645  SDValue Arg = OutVals[OutIndex];
3646  bool isByVal = Flags.isByVal();
3647 
3648  // Promote the value if needed.
3649  switch (VA.getLocInfo()) {
3650  default: llvm_unreachable("Unknown loc info!");
3651  case CCValAssign::Full: break;
3652  case CCValAssign::SExt:
3653  Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3654  break;
3655  case CCValAssign::ZExt:
3656  Arg = DAG.<