LLVM  8.0.0svn
AArch64ISelLowering.cpp
Go to the documentation of this file.
1 //===-- AArch64ISelLowering.cpp - AArch64 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 implements the AArch64TargetLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AArch64ISelLowering.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/Intrinsics.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Use.h"
63 #include "llvm/IR/Value.h"
64 #include "llvm/MC/MCRegisterInfo.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/KnownBits.h"
77 #include <algorithm>
78 #include <bitset>
79 #include <cassert>
80 #include <cctype>
81 #include <cstdint>
82 #include <cstdlib>
83 #include <iterator>
84 #include <limits>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "aarch64-lower"
92 
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
96 
97 static cl::opt<bool>
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99  cl::desc("Allow AArch64 SLI/SRI formation"),
100  cl::init(false));
101 
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
106  "aarch64-elf-ldtls-generation", cl::Hidden,
107  cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
108  cl::init(false));
109 
110 static cl::opt<bool>
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112  cl::desc("Enable AArch64 logical imm instruction "
113  "optimization"),
114  cl::init(true));
115 
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
118 
120  const AArch64Subtarget &STI)
121  : TargetLowering(TM), Subtarget(&STI) {
122  // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123  // we have to make something up. Arbitrarily, choose ZeroOrOne.
125  // When comparing vectors the result sets the different elements in the
126  // vector to all-one or all-zero.
128 
129  // Set up the register classes.
130  addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131  addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
132 
133  if (Subtarget->hasFPARMv8()) {
134  addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135  addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136  addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137  addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
138  }
139 
140  if (Subtarget->hasNEON()) {
141  addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142  addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143  // Someone set us up the NEON.
144  addDRTypeForNEON(MVT::v2f32);
145  addDRTypeForNEON(MVT::v8i8);
146  addDRTypeForNEON(MVT::v4i16);
147  addDRTypeForNEON(MVT::v2i32);
148  addDRTypeForNEON(MVT::v1i64);
149  addDRTypeForNEON(MVT::v1f64);
150  addDRTypeForNEON(MVT::v4f16);
151 
152  addQRTypeForNEON(MVT::v4f32);
153  addQRTypeForNEON(MVT::v2f64);
154  addQRTypeForNEON(MVT::v16i8);
155  addQRTypeForNEON(MVT::v8i16);
156  addQRTypeForNEON(MVT::v4i32);
157  addQRTypeForNEON(MVT::v2i64);
158  addQRTypeForNEON(MVT::v8f16);
159  }
160 
161  // Compute derived properties from the register classes
163 
164  // Provide all sorts of operation actions
192 
196 
200 
202 
203  // Custom lowering hooks are needed for XOR
204  // to fold it into CSINC/CSINV.
207 
208  // Virtually no operation on f128 is legal, but LLVM can't expand them when
209  // there's a valid register class, so we need custom operations in most cases.
231 
232  // Lowering for many of the conversions is actually specified by the non-f128
233  // type. The LowerXXX function will be trivial when f128 isn't involved.
248 
249  // Variable arguments.
254 
255  // Variable-sized objects.
258 
259  if (Subtarget->isTargetWindows())
261  else
263 
264  // Constant pool entries
266 
267  // BlockAddress
269 
270  // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
279 
280  // AArch64 lacks both left-rotate and popcount instructions.
283  for (MVT VT : MVT::vector_valuetypes()) {
286  }
287 
288  // AArch64 doesn't have {U|S}MUL_LOHI.
291 
294 
297  for (MVT VT : MVT::vector_valuetypes()) {
300  }
307 
308  // Custom lower Add/Sub/Mul with overflow.
321 
330  if (Subtarget->hasFullFP16())
332  else
334 
366 
367  if (!Subtarget->hasFullFP16()) {
390 
391  // promote v4f16 to v4f32 when that is known to be safe.
404 
420 
441  }
442 
443  // AArch64 has implementations of a lot of rounding-like FP operations.
444  for (MVT Ty : {MVT::f32, MVT::f64}) {
455  }
456 
457  if (Subtarget->hasFullFP16()) {
468  }
469 
471 
473 
479 
480  // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
481  // This requires the Performance Monitors extension.
482  if (Subtarget->hasPerfMon())
484 
485  if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
486  getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
487  // Issue __sincos_stret if available.
490  } else {
493  }
494 
495  // Make floating-point constants legal for the large code model, so they don't
496  // become loads from the constant pool.
497  if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
500  }
501 
502  // AArch64 does not have floating-point extending loads, i1 sign-extending
503  // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
504  for (MVT VT : MVT::fp_valuetypes()) {
509  }
510  for (MVT VT : MVT::integer_valuetypes())
512 
520 
523 
524  // Indexed loads and stores are supported.
525  for (unsigned im = (unsigned)ISD::PRE_INC;
541  }
542 
543  // Trap.
545 
546  // We combine OR nodes for bitfield operations.
548 
549  // Vector add and sub nodes may conceal a high-half opportunity.
550  // Also, try to fold ADD into CSINC/CSINV..
557 
561 
563 
570  if (Subtarget->supportsAddressTopByteIgnored())
572 
574 
577 
581 
583 
584  // In case of strict alignment, avoid an excessive number of byte wide stores.
588 
593 
595 
597 
599 
600  EnableExtLdPromotion = true;
601 
602  // Set required alignment.
604  // Set preferred alignments.
607 
608  // Only change the limit for entries in a jump table if specified by
609  // the subtarget, but not at the command line.
610  unsigned MaxJT = STI.getMaximumJumpTableSize();
611  if (MaxJT && getMaximumJumpTableSize() == 0)
613 
614  setHasExtractBitsInsn(true);
615 
617 
618  if (Subtarget->hasNEON()) {
619  // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
620  // silliness like this:
646 
652 
654 
655  // AArch64 doesn't have a direct vector ->f32 conversion instructions for
656  // elements smaller than i32, so promote the input to i32 first.
661  // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
662  // -> v8f16 conversions.
667  // Similarly, there is no direct i32 -> f64 vector conversion instruction.
672  // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
673  // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
676 
679 
688 
689  // AArch64 doesn't have MUL.2d:
691  // Custom handling for some quad-vector types to detect MULL.
695 
696  // Vector reductions
697  for (MVT VT : MVT::integer_valuetypes()) {
703  }
704  for (MVT VT : MVT::fp_valuetypes()) {
707  }
708 
711  // Likewise, narrowing and extending vector loads/stores aren't handled
712  // directly.
713  for (MVT VT : MVT::vector_valuetypes()) {
715 
716  if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
719  } else {
722  }
725 
727 
728  for (MVT InnerVT : MVT::vector_valuetypes()) {
729  setTruncStoreAction(VT, InnerVT, Expand);
730  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
731  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
732  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
733  }
734  }
735 
736  // AArch64 has implementations of a lot of rounding-like FP operations.
737  for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
744  }
745 
747  }
748 
750 }
751 
752 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
753  assert(VT.isVector() && "VT should be a vector type");
754 
755  if (VT.isFloatingPoint()) {
757  setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
758  setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
759  }
760 
761  // Mark vector float intrinsics as expand.
762  if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
771 
772  // But we do support custom-lowering for FCOPYSIGN.
774  }
775 
788 
792  for (MVT InnerVT : MVT::all_valuetypes())
793  setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
794 
795  // CNT supports only B element sizes.
796  if (VT != MVT::v8i8 && VT != MVT::v16i8)
798 
804 
807 
808  if (!VT.isFloatingPoint())
810 
811  // [SU][MIN|MAX] are available for all NEON types apart from i64.
812  if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
813  for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
814  setOperationAction(Opcode, VT, Legal);
815 
816  // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
817  if (VT.isFloatingPoint() &&
818  (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
819  for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
821  setOperationAction(Opcode, VT, Legal);
822 
823  if (Subtarget->isLittleEndian()) {
824  for (unsigned im = (unsigned)ISD::PRE_INC;
828  }
829  }
830 }
831 
832 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
833  addRegisterClass(VT, &AArch64::FPR64RegClass);
834  addTypeForNEON(VT, MVT::v2i32);
835 }
836 
837 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
838  addRegisterClass(VT, &AArch64::FPR128RegClass);
839  addTypeForNEON(VT, MVT::v4i32);
840 }
841 
843  EVT VT) const {
844  if (!VT.isVector())
845  return MVT::i32;
847 }
848 
849 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
850  const APInt &Demanded,
852  unsigned NewOpc) {
853  uint64_t OldImm = Imm, NewImm, Enc;
854  uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
855 
856  // Return if the immediate is already all zeros, all ones, a bimm32 or a
857  // bimm64.
858  if (Imm == 0 || Imm == Mask ||
859  AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
860  return false;
861 
862  unsigned EltSize = Size;
863  uint64_t DemandedBits = Demanded.getZExtValue();
864 
865  // Clear bits that are not demanded.
866  Imm &= DemandedBits;
867 
868  while (true) {
869  // The goal here is to set the non-demanded bits in a way that minimizes
870  // the number of switching between 0 and 1. In order to achieve this goal,
871  // we set the non-demanded bits to the value of the preceding demanded bits.
872  // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
873  // non-demanded bit), we copy bit0 (1) to the least significant 'x',
874  // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
875  // The final result is 0b11000011.
876  uint64_t NonDemandedBits = ~DemandedBits;
877  uint64_t InvertedImm = ~Imm & DemandedBits;
878  uint64_t RotatedImm =
879  ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
880  NonDemandedBits;
881  uint64_t Sum = RotatedImm + NonDemandedBits;
882  bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
883  uint64_t Ones = (Sum + Carry) & NonDemandedBits;
884  NewImm = (Imm | Ones) & Mask;
885 
886  // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
887  // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
888  // we halve the element size and continue the search.
889  if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
890  break;
891 
892  // We cannot shrink the element size any further if it is 2-bits.
893  if (EltSize == 2)
894  return false;
895 
896  EltSize /= 2;
897  Mask >>= EltSize;
898  uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
899 
900  // Return if there is mismatch in any of the demanded bits of Imm and Hi.
901  if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
902  return false;
903 
904  // Merge the upper and lower halves of Imm and DemandedBits.
905  Imm |= Hi;
906  DemandedBits |= DemandedBitsHi;
907  }
908 
909  ++NumOptimizedImms;
910 
911  // Replicate the element across the register width.
912  while (EltSize < Size) {
913  NewImm |= NewImm << EltSize;
914  EltSize *= 2;
915  }
916 
917  (void)OldImm;
918  assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
919  "demanded bits should never be altered");
920  assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
921 
922  // Create the new constant immediate node.
923  EVT VT = Op.getValueType();
924  SDLoc DL(Op);
925  SDValue New;
926 
927  // If the new constant immediate is all-zeros or all-ones, let the target
928  // independent DAG combine optimize this node.
929  if (NewImm == 0 || NewImm == OrigMask) {
930  New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
931  TLO.DAG.getConstant(NewImm, DL, VT));
932  // Otherwise, create a machine node so that target independent DAG combine
933  // doesn't undo this optimization.
934  } else {
935  Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
936  SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
937  New = SDValue(
938  TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
939  }
940 
941  return TLO.CombineTo(Op, New);
942 }
943 
945  SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
946  // Delay this optimization to as late as possible.
947  if (!TLO.LegalOps)
948  return false;
949 
951  return false;
952 
953  EVT VT = Op.getValueType();
954  if (VT.isVector())
955  return false;
956 
957  unsigned Size = VT.getSizeInBits();
958  assert((Size == 32 || Size == 64) &&
959  "i32 or i64 is expected after legalization.");
960 
961  // Exit early if we demand all bits.
962  if (Demanded.countPopulation() == Size)
963  return false;
964 
965  unsigned NewOpc;
966  switch (Op.getOpcode()) {
967  default:
968  return false;
969  case ISD::AND:
970  NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
971  break;
972  case ISD::OR:
973  NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
974  break;
975  case ISD::XOR:
976  NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
977  break;
978  }
980  if (!C)
981  return false;
982  uint64_t Imm = C->getZExtValue();
983  return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
984 }
985 
986 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
987 /// Mask are known to be either zero or one and return them Known.
989  const SDValue Op, KnownBits &Known,
990  const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
991  switch (Op.getOpcode()) {
992  default:
993  break;
994  case AArch64ISD::CSEL: {
995  KnownBits Known2;
996  DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
997  DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
998  Known.Zero &= Known2.Zero;
999  Known.One &= Known2.One;
1000  break;
1001  }
1002  case ISD::INTRINSIC_W_CHAIN: {
1003  ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
1004  Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
1005  switch (IntID) {
1006  default: return;
1007  case Intrinsic::aarch64_ldaxr:
1008  case Intrinsic::aarch64_ldxr: {
1009  unsigned BitWidth = Known.getBitWidth();
1010  EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
1011  unsigned MemBits = VT.getScalarSizeInBits();
1012  Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
1013  return;
1014  }
1015  }
1016  break;
1017  }
1019  case ISD::INTRINSIC_VOID: {
1020  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1021  switch (IntNo) {
1022  default:
1023  break;
1024  case Intrinsic::aarch64_neon_umaxv:
1025  case Intrinsic::aarch64_neon_uminv: {
1026  // Figure out the datatype of the vector operand. The UMINV instruction
1027  // will zero extend the result, so we can mark as known zero all the
1028  // bits larger than the element datatype. 32-bit or larget doesn't need
1029  // this as those are legal types and will be handled by isel directly.
1030  MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1031  unsigned BitWidth = Known.getBitWidth();
1032  if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1033  assert(BitWidth >= 8 && "Unexpected width!");
1034  APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1035  Known.Zero |= Mask;
1036  } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1037  assert(BitWidth >= 16 && "Unexpected width!");
1038  APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1039  Known.Zero |= Mask;
1040  }
1041  break;
1042  } break;
1043  }
1044  }
1045  }
1046 }
1047 
1049  EVT) const {
1050  return MVT::i64;
1051 }
1052 
1054  unsigned AddrSpace,
1055  unsigned Align,
1056  bool *Fast) const {
1057  if (Subtarget->requiresStrictAlign())
1058  return false;
1059 
1060  if (Fast) {
1061  // Some CPUs are fine with unaligned stores except for 128-bit ones.
1062  *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1063  // See comments in performSTORECombine() for more details about
1064  // these conditions.
1065 
1066  // Code that uses clang vector extensions can mark that it
1067  // wants unaligned accesses to be treated as fast by
1068  // underspecifying alignment to be 1 or 2.
1069  Align <= 2 ||
1070 
1071  // Disregard v2i64. Memcpy lowering produces those and splitting
1072  // them regresses performance on micro-benchmarks and olden/bh.
1073  VT == MVT::v2i64;
1074  }
1075  return true;
1076 }
1077 
1078 FastISel *
1080  const TargetLibraryInfo *libInfo) const {
1081  return AArch64::createFastISel(funcInfo, libInfo);
1082 }
1083 
1084 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1085  switch ((AArch64ISD::NodeType)Opcode) {
1086  case AArch64ISD::FIRST_NUMBER: break;
1087  case AArch64ISD::CALL: return "AArch64ISD::CALL";
1088  case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1089  case AArch64ISD::ADR: return "AArch64ISD::ADR";
1090  case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1091  case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1092  case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1093  case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1094  case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1095  case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1096  case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1097  case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1098  case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1099  case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1100  case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1101  case AArch64ISD::ADC: return "AArch64ISD::ADC";
1102  case AArch64ISD::SBC: return "AArch64ISD::SBC";
1103  case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1104  case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1105  case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1106  case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1107  case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1108  case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1109  case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1110  case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1111  case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1112  case AArch64ISD::DUP: return "AArch64ISD::DUP";
1113  case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1114  case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1115  case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1116  case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1117  case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1118  case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1119  case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1120  case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1121  case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1122  case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1123  case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1124  case AArch64ISD::BICi: return "AArch64ISD::BICi";
1125  case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1126  case AArch64ISD::BSL: return "AArch64ISD::BSL";
1127  case AArch64ISD::NEG: return "AArch64ISD::NEG";
1128  case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1129  case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1130  case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1131  case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1132  case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1133  case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1134  case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1135  case AArch64ISD::REV16: return "AArch64ISD::REV16";
1136  case AArch64ISD::REV32: return "AArch64ISD::REV32";
1137  case AArch64ISD::REV64: return "AArch64ISD::REV64";
1138  case AArch64ISD::EXT: return "AArch64ISD::EXT";
1139  case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1140  case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1141  case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1142  case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1143  case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1144  case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1145  case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1146  case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1147  case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1148  case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1149  case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1150  case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1151  case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1152  case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1153  case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1154  case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1155  case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1156  case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1157  case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1158  case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1159  case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1160  case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1161  case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1162  case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1163  case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1164  case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1165  case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1166  case AArch64ISD::NOT: return "AArch64ISD::NOT";
1167  case AArch64ISD::BIT: return "AArch64ISD::BIT";
1168  case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1169  case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1170  case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1171  case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1172  case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1173  case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1174  case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1175  case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1176  case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1177  case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1178  case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1179  case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1180  case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1181  case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1182  case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1183  case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1184  case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1185  case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1186  case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1187  case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1188  case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1189  case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1190  case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1191  case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1192  case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1193  case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1194  case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1195  case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1196  case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1197  case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1198  case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1199  case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1200  case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1201  case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1202  case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1203  case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1204  case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1205  case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1206  case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1207  case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1208  case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1209  case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1210  case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1211  case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1212  }
1213  return nullptr;
1214 }
1215 
1218  MachineBasicBlock *MBB) const {
1219  // We materialise the F128CSEL pseudo-instruction as some control flow and a
1220  // phi node:
1221 
1222  // OrigBB:
1223  // [... previous instrs leading to comparison ...]
1224  // b.ne TrueBB
1225  // b EndBB
1226  // TrueBB:
1227  // ; Fallthrough
1228  // EndBB:
1229  // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1230 
1231  MachineFunction *MF = MBB->getParent();
1232  const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1233  const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1234  DebugLoc DL = MI.getDebugLoc();
1235  MachineFunction::iterator It = ++MBB->getIterator();
1236 
1237  unsigned DestReg = MI.getOperand(0).getReg();
1238  unsigned IfTrueReg = MI.getOperand(1).getReg();
1239  unsigned IfFalseReg = MI.getOperand(2).getReg();
1240  unsigned CondCode = MI.getOperand(3).getImm();
1241  bool NZCVKilled = MI.getOperand(4).isKill();
1242 
1243  MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244  MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245  MF->insert(It, TrueBB);
1246  MF->insert(It, EndBB);
1247 
1248  // Transfer rest of current basic-block to EndBB
1249  EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1250  MBB->end());
1251  EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1252 
1253  BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1254  BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1255  MBB->addSuccessor(TrueBB);
1256  MBB->addSuccessor(EndBB);
1257 
1258  // TrueBB falls through to the end.
1259  TrueBB->addSuccessor(EndBB);
1260 
1261  if (!NZCVKilled) {
1262  TrueBB->addLiveIn(AArch64::NZCV);
1263  EndBB->addLiveIn(AArch64::NZCV);
1264  }
1265 
1266  BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1267  .addReg(IfTrueReg)
1268  .addMBB(TrueBB)
1269  .addReg(IfFalseReg)
1270  .addMBB(MBB);
1271 
1272  MI.eraseFromParent();
1273  return EndBB;
1274 }
1275 
1277  MachineInstr &MI, MachineBasicBlock *BB) const {
1278  switch (MI.getOpcode()) {
1279  default:
1280 #ifndef NDEBUG
1281  MI.dump();
1282 #endif
1283  llvm_unreachable("Unexpected instruction for custom inserter!");
1284 
1285  case AArch64::F128CSEL:
1286  return EmitF128CSEL(MI, BB);
1287 
1288  case TargetOpcode::STACKMAP:
1289  case TargetOpcode::PATCHPOINT:
1290  return emitPatchPoint(MI, BB);
1291  }
1292 }
1293 
1294 //===----------------------------------------------------------------------===//
1295 // AArch64 Lowering private implementation.
1296 //===----------------------------------------------------------------------===//
1297 
1298 //===----------------------------------------------------------------------===//
1299 // Lowering Code
1300 //===----------------------------------------------------------------------===//
1301 
1302 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1303 /// CC
1305  switch (CC) {
1306  default:
1307  llvm_unreachable("Unknown condition code!");
1308  case ISD::SETNE:
1309  return AArch64CC::NE;
1310  case ISD::SETEQ:
1311  return AArch64CC::EQ;
1312  case ISD::SETGT:
1313  return AArch64CC::GT;
1314  case ISD::SETGE:
1315  return AArch64CC::GE;
1316  case ISD::SETLT:
1317  return AArch64CC::LT;
1318  case ISD::SETLE:
1319  return AArch64CC::LE;
1320  case ISD::SETUGT:
1321  return AArch64CC::HI;
1322  case ISD::SETUGE:
1323  return AArch64CC::HS;
1324  case ISD::SETULT:
1325  return AArch64CC::LO;
1326  case ISD::SETULE:
1327  return AArch64CC::LS;
1328  }
1329 }
1330 
1331 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1334  AArch64CC::CondCode &CondCode2) {
1335  CondCode2 = AArch64CC::AL;
1336  switch (CC) {
1337  default:
1338  llvm_unreachable("Unknown FP condition!");
1339  case ISD::SETEQ:
1340  case ISD::SETOEQ:
1341  CondCode = AArch64CC::EQ;
1342  break;
1343  case ISD::SETGT:
1344  case ISD::SETOGT:
1345  CondCode = AArch64CC::GT;
1346  break;
1347  case ISD::SETGE:
1348  case ISD::SETOGE:
1349  CondCode = AArch64CC::GE;
1350  break;
1351  case ISD::SETOLT:
1352  CondCode = AArch64CC::MI;
1353  break;
1354  case ISD::SETOLE:
1355  CondCode = AArch64CC::LS;
1356  break;
1357  case ISD::SETONE:
1358  CondCode = AArch64CC::MI;
1359  CondCode2 = AArch64CC::GT;
1360  break;
1361  case ISD::SETO:
1362  CondCode = AArch64CC::VC;
1363  break;
1364  case ISD::SETUO:
1365  CondCode = AArch64CC::VS;
1366  break;
1367  case ISD::SETUEQ:
1368  CondCode = AArch64CC::EQ;
1369  CondCode2 = AArch64CC::VS;
1370  break;
1371  case ISD::SETUGT:
1372  CondCode = AArch64CC::HI;
1373  break;
1374  case ISD::SETUGE:
1375  CondCode = AArch64CC::PL;
1376  break;
1377  case ISD::SETLT:
1378  case ISD::SETULT:
1379  CondCode = AArch64CC::LT;
1380  break;
1381  case ISD::SETLE:
1382  case ISD::SETULE:
1383  CondCode = AArch64CC::LE;
1384  break;
1385  case ISD::SETNE:
1386  case ISD::SETUNE:
1387  CondCode = AArch64CC::NE;
1388  break;
1389  }
1390 }
1391 
1392 /// Convert a DAG fp condition code to an AArch64 CC.
1393 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1394 /// should be AND'ed instead of OR'ed.
1397  AArch64CC::CondCode &CondCode2) {
1398  CondCode2 = AArch64CC::AL;
1399  switch (CC) {
1400  default:
1401  changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1402  assert(CondCode2 == AArch64CC::AL);
1403  break;
1404  case ISD::SETONE:
1405  // (a one b)
1406  // == ((a olt b) || (a ogt b))
1407  // == ((a ord b) && (a une b))
1408  CondCode = AArch64CC::VC;
1409  CondCode2 = AArch64CC::NE;
1410  break;
1411  case ISD::SETUEQ:
1412  // (a ueq b)
1413  // == ((a uno b) || (a oeq b))
1414  // == ((a ule b) && (a uge b))
1415  CondCode = AArch64CC::PL;
1416  CondCode2 = AArch64CC::LE;
1417  break;
1418  }
1419 }
1420 
1421 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1422 /// CC usable with the vector instructions. Fewer operations are available
1423 /// without a real NZCV register, so we have to use less efficient combinations
1424 /// to get the same effect.
1427  AArch64CC::CondCode &CondCode2,
1428  bool &Invert) {
1429  Invert = false;
1430  switch (CC) {
1431  default:
1432  // Mostly the scalar mappings work fine.
1433  changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1434  break;
1435  case ISD::SETUO:
1436  Invert = true;
1438  case ISD::SETO:
1439  CondCode = AArch64CC::MI;
1440  CondCode2 = AArch64CC::GE;
1441  break;
1442  case ISD::SETUEQ:
1443  case ISD::SETULT:
1444  case ISD::SETULE:
1445  case ISD::SETUGT:
1446  case ISD::SETUGE:
1447  // All of the compare-mask comparisons are ordered, but we can switch
1448  // between the two by a double inversion. E.g. ULE == !OGT.
1449  Invert = true;
1450  changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1451  break;
1452  }
1453 }
1454 
1455 static bool isLegalArithImmed(uint64_t C) {
1456  // Matches AArch64DAGToDAGISel::SelectArithImmed().
1457  bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1458  LLVM_DEBUG(dbgs() << "Is imm " << C
1459  << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1460  return IsLegal;
1461 }
1462 
1463 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1464 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1465 // can be set differently by this operation. It comes down to whether
1466 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1467 // everything is fine. If not then the optimization is wrong. Thus general
1468 // comparisons are only valid if op2 != 0.
1469 //
1470 // So, finally, the only LLVM-native comparisons that don't mention C and V
1471 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1472 // the absence of information about op2.
1473 static bool isCMN(SDValue Op, ISD::CondCode CC) {
1474  return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
1475  (CC == ISD::SETEQ || CC == ISD::SETNE);
1476 }
1477 
1479  const SDLoc &dl, SelectionDAG &DAG) {
1480  EVT VT = LHS.getValueType();
1481  const bool FullFP16 =
1482  static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1483 
1484  if (VT.isFloatingPoint()) {
1485  assert(VT != MVT::f128);
1486  if (VT == MVT::f16 && !FullFP16) {
1487  LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1488  RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1489  VT = MVT::f32;
1490  }
1491  return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1492  }
1493 
1494  // The CMP instruction is just an alias for SUBS, and representing it as
1495  // SUBS means that it's possible to get CSE with subtract operations.
1496  // A later phase can perform the optimization of setting the destination
1497  // register to WZR/XZR if it ends up being unused.
1498  unsigned Opcode = AArch64ISD::SUBS;
1499 
1500  if (isCMN(RHS, CC)) {
1501  // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1502  Opcode = AArch64ISD::ADDS;
1503  RHS = RHS.getOperand(1);
1504  } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1505  !isUnsignedIntSetCC(CC)) {
1506  // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1507  // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1508  // of the signed comparisons.
1509  Opcode = AArch64ISD::ANDS;
1510  RHS = LHS.getOperand(1);
1511  LHS = LHS.getOperand(0);
1512  }
1513 
1514  return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1515  .getValue(1);
1516 }
1517 
1518 /// \defgroup AArch64CCMP CMP;CCMP matching
1519 ///
1520 /// These functions deal with the formation of CMP;CCMP;... sequences.
1521 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1522 /// a comparison. They set the NZCV flags to a predefined value if their
1523 /// predicate is false. This allows to express arbitrary conjunctions, for
1524 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1525 /// expressed as:
1526 /// cmp A
1527 /// ccmp B, inv(CB), CA
1528 /// check for CB flags
1529 ///
1530 /// In general we can create code for arbitrary "... (and (and A B) C)"
1531 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1532 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1533 /// negation operations:
1534 /// We can negate the results of a single comparison by inverting the flags
1535 /// used when the predicate fails and inverting the flags tested in the next
1536 /// instruction; We can also negate the results of the whole previous
1537 /// conditional compare sequence by inverting the flags tested in the next
1538 /// instruction. However there is no way to negate the result of a partial
1539 /// sequence.
1540 ///
1541 /// Therefore on encountering an "or" expression we can negate the subtree on
1542 /// one side and have to be able to push the negate to the leafs of the subtree
1543 /// on the other side (see also the comments in code). As complete example:
1544 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1545 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1546 /// is transformed to
1547 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1548 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1549 /// and implemented as:
1550 /// cmp C
1551 /// ccmp D, inv(CD), CC
1552 /// ccmp A, CA, inv(CD)
1553 /// ccmp B, CB, inv(CA)
1554 /// check for CB flags
1555 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1556 /// by conditional compare sequences.
1557 /// @{
1558 
1559 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1561  ISD::CondCode CC, SDValue CCOp,
1563  AArch64CC::CondCode OutCC,
1564  const SDLoc &DL, SelectionDAG &DAG) {
1565  unsigned Opcode = 0;
1566  const bool FullFP16 =
1567  static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1568 
1569  if (LHS.getValueType().isFloatingPoint()) {
1570  assert(LHS.getValueType() != MVT::f128);
1571  if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1572  LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1573  RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1574  }
1575  Opcode = AArch64ISD::FCCMP;
1576  } else if (RHS.getOpcode() == ISD::SUB) {
1577  SDValue SubOp0 = RHS.getOperand(0);
1578  if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1579  // See emitComparison() on why we can only do this for SETEQ and SETNE.
1580  Opcode = AArch64ISD::CCMN;
1581  RHS = RHS.getOperand(1);
1582  }
1583  }
1584  if (Opcode == 0)
1585  Opcode = AArch64ISD::CCMP;
1586 
1587  SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1589  unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1590  SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1591  return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1592 }
1593 
1594 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1595 /// CanPushNegate is set to true if we can push a negate operation through
1596 /// the tree in a was that we are left with AND operations and negate operations
1597 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1598 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1599 /// brought into such a form.
1600 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1601  unsigned Depth = 0) {
1602  if (!Val.hasOneUse())
1603  return false;
1604  unsigned Opcode = Val->getOpcode();
1605  if (Opcode == ISD::SETCC) {
1606  if (Val->getOperand(0).getValueType() == MVT::f128)
1607  return false;
1608  CanNegate = true;
1609  return true;
1610  }
1611  // Protect against exponential runtime and stack overflow.
1612  if (Depth > 6)
1613  return false;
1614  if (Opcode == ISD::AND || Opcode == ISD::OR) {
1615  SDValue O0 = Val->getOperand(0);
1616  SDValue O1 = Val->getOperand(1);
1617  bool CanNegateL;
1618  if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1619  return false;
1620  bool CanNegateR;
1621  if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1622  return false;
1623 
1624  if (Opcode == ISD::OR) {
1625  // For an OR expression we need to be able to negate at least one side or
1626  // we cannot do the transformation at all.
1627  if (!CanNegateL && !CanNegateR)
1628  return false;
1629  // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1630  // can negate the x and y subtrees.
1631  CanNegate = CanNegateL && CanNegateR;
1632  } else {
1633  // If the operands are OR expressions then we finally need to negate their
1634  // outputs, we can only do that for the operand with emitted last by
1635  // negating OutCC, not for both operands.
1636  bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1637  bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1638  if (NeedsNegOutL && NeedsNegOutR)
1639  return false;
1640  // We cannot negate an AND operation (it would become an OR),
1641  CanNegate = false;
1642  }
1643  return true;
1644  }
1645  return false;
1646 }
1647 
1648 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1649 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1650 /// Tries to transform the given i1 producing node @p Val to a series compare
1651 /// and conditional compare operations. @returns an NZCV flags producing node
1652 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1653 /// transformation was not possible.
1654 /// On recursive invocations @p PushNegate may be set to true to have negation
1655 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1656 /// for the comparisons in the current subtree; @p Depth limits the search
1657 /// depth to avoid stack overflow.
1659  AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1661  // We're at a tree leaf, produce a conditional comparison operation.
1662  unsigned Opcode = Val->getOpcode();
1663  if (Opcode == ISD::SETCC) {
1664  SDValue LHS = Val->getOperand(0);
1665  SDValue RHS = Val->getOperand(1);
1666  ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1667  bool isInteger = LHS.getValueType().isInteger();
1668  if (Negate)
1669  CC = getSetCCInverse(CC, isInteger);
1670  SDLoc DL(Val);
1671  // Determine OutCC and handle FP special case.
1672  if (isInteger) {
1673  OutCC = changeIntCCToAArch64CC(CC);
1674  } else {
1676  AArch64CC::CondCode ExtraCC;
1677  changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1678  // Some floating point conditions can't be tested with a single condition
1679  // code. Construct an additional comparison in this case.
1680  if (ExtraCC != AArch64CC::AL) {
1681  SDValue ExtraCmp;
1682  if (!CCOp.getNode())
1683  ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1684  else
1685  ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1686  ExtraCC, DL, DAG);
1687  CCOp = ExtraCmp;
1688  Predicate = ExtraCC;
1689  }
1690  }
1691 
1692  // Produce a normal comparison if we are first in the chain
1693  if (!CCOp)
1694  return emitComparison(LHS, RHS, CC, DL, DAG);
1695  // Otherwise produce a ccmp.
1696  return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1697  DAG);
1698  }
1699  assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1700  "Valid conjunction/disjunction tree");
1701 
1702  // Check if both sides can be transformed.
1703  SDValue LHS = Val->getOperand(0);
1704  SDValue RHS = Val->getOperand(1);
1705 
1706  // In case of an OR we need to negate our operands and the result.
1707  // (A v B) <=> not(not(A) ^ not(B))
1708  bool NegateOpsAndResult = Opcode == ISD::OR;
1709  // We can negate the results of all previous operations by inverting the
1710  // predicate flags giving us a free negation for one side. The other side
1711  // must be negatable by itself.
1712  if (NegateOpsAndResult) {
1713  // See which side we can negate.
1714  bool CanNegateL;
1715  bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1716  assert(isValidL && "Valid conjunction/disjunction tree");
1717  (void)isValidL;
1718 
1719 #ifndef NDEBUG
1720  bool CanNegateR;
1721  bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1722  assert(isValidR && "Valid conjunction/disjunction tree");
1723  assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1724 #endif
1725 
1726  // Order the side which we cannot negate to RHS so we can emit it first.
1727  if (!CanNegateL)
1728  std::swap(LHS, RHS);
1729  } else {
1730  bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1731  assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1732  "Valid conjunction/disjunction tree");
1733  // Order the side where we need to negate the output flags to RHS so it
1734  // gets emitted first.
1735  if (NeedsNegOutL)
1736  std::swap(LHS, RHS);
1737  }
1738 
1739  // Emit RHS. If we want to negate the tree we only need to push a negate
1740  // through if we are already in a PushNegate case, otherwise we can negate
1741  // the "flags to test" afterwards.
1742  AArch64CC::CondCode RHSCC;
1743  SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1744  CCOp, Predicate);
1745  if (NegateOpsAndResult && !Negate)
1746  RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1747  // Emit LHS. We may need to negate it.
1748  SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1749  NegateOpsAndResult, CmpR,
1750  RHSCC);
1751  // If we transformed an OR to and AND then we have to negate the result
1752  // (or absorb the Negate parameter).
1753  if (NegateOpsAndResult && !Negate)
1754  OutCC = AArch64CC::getInvertedCondCode(OutCC);
1755  return CmpL;
1756 }
1757 
1758 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1759 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1760 /// \see emitConjunctionDisjunctionTreeRec().
1762  AArch64CC::CondCode &OutCC) {
1763  bool CanNegate;
1764  if (!isConjunctionDisjunctionTree(Val, CanNegate))
1765  return SDValue();
1766 
1767  return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1768  AArch64CC::AL);
1769 }
1770 
1771 /// @}
1772 
1773 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1774 /// extension operations.
1776  auto isSupportedExtend = [&](SDValue V) {
1777  if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
1778  return true;
1779 
1780  if (V.getOpcode() == ISD::AND)
1781  if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
1782  uint64_t Mask = MaskCst->getZExtValue();
1783  return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
1784  }
1785 
1786  return false;
1787  };
1788 
1789  if (!Op.hasOneUse())
1790  return 0;
1791 
1792  if (isSupportedExtend(Op))
1793  return 1;
1794 
1795  unsigned Opc = Op.getOpcode();
1796  if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
1797  if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1798  uint64_t Shift = ShiftCst->getZExtValue();
1799  if (isSupportedExtend(Op.getOperand(0)))
1800  return (Shift <= 4) ? 2 : 1;
1801  EVT VT = Op.getValueType();
1802  if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
1803  return 1;
1804  }
1805 
1806  return 0;
1807 }
1808 
1810  SDValue &AArch64cc, SelectionDAG &DAG,
1811  const SDLoc &dl) {
1812  if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1813  EVT VT = RHS.getValueType();
1814  uint64_t C = RHSC->getZExtValue();
1815  if (!isLegalArithImmed(C)) {
1816  // Constant does not fit, try adjusting it by one?
1817  switch (CC) {
1818  default:
1819  break;
1820  case ISD::SETLT:
1821  case ISD::SETGE:
1822  if ((VT == MVT::i32 && C != 0x80000000 &&
1823  isLegalArithImmed((uint32_t)(C - 1))) ||
1824  (VT == MVT::i64 && C != 0x80000000ULL &&
1825  isLegalArithImmed(C - 1ULL))) {
1826  CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1827  C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1828  RHS = DAG.getConstant(C, dl, VT);
1829  }
1830  break;
1831  case ISD::SETULT:
1832  case ISD::SETUGE:
1833  if ((VT == MVT::i32 && C != 0 &&
1834  isLegalArithImmed((uint32_t)(C - 1))) ||
1835  (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1836  CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1837  C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1838  RHS = DAG.getConstant(C, dl, VT);
1839  }
1840  break;
1841  case ISD::SETLE:
1842  case ISD::SETGT:
1843  if ((VT == MVT::i32 && C != INT32_MAX &&
1844  isLegalArithImmed((uint32_t)(C + 1))) ||
1845  (VT == MVT::i64 && C != INT64_MAX &&
1846  isLegalArithImmed(C + 1ULL))) {
1847  CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1848  C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1849  RHS = DAG.getConstant(C, dl, VT);
1850  }
1851  break;
1852  case ISD::SETULE:
1853  case ISD::SETUGT:
1854  if ((VT == MVT::i32 && C != UINT32_MAX &&
1855  isLegalArithImmed((uint32_t)(C + 1))) ||
1856  (VT == MVT::i64 && C != UINT64_MAX &&
1857  isLegalArithImmed(C + 1ULL))) {
1858  CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1859  C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1860  RHS = DAG.getConstant(C, dl, VT);
1861  }
1862  break;
1863  }
1864  }
1865  }
1866 
1867  // Comparisons are canonicalized so that the RHS operand is simpler than the
1868  // LHS one, the extreme case being when RHS is an immediate. However, AArch64
1869  // can fold some shift+extend operations on the RHS operand, so swap the
1870  // operands if that can be done.
1871  //
1872  // For example:
1873  // lsl w13, w11, #1
1874  // cmp w13, w12
1875  // can be turned into:
1876  // cmp w12, w11, lsl #1
1877  if (!isa<ConstantSDNode>(RHS) ||
1878  !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
1879  SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
1880 
1882  std::swap(LHS, RHS);
1884  }
1885  }
1886 
1887  SDValue Cmp;
1888  AArch64CC::CondCode AArch64CC;
1889  if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1890  const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1891 
1892  // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1893  // For the i8 operand, the largest immediate is 255, so this can be easily
1894  // encoded in the compare instruction. For the i16 operand, however, the
1895  // largest immediate cannot be encoded in the compare.
1896  // Therefore, use a sign extending load and cmn to avoid materializing the
1897  // -1 constant. For example,
1898  // movz w1, #65535
1899  // ldrh w0, [x0, #0]
1900  // cmp w0, w1
1901  // >
1902  // ldrsh w0, [x0, #0]
1903  // cmn w0, #1
1904  // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1905  // if and only if (sext LHS) == (sext RHS). The checks are in place to
1906  // ensure both the LHS and RHS are truly zero extended and to make sure the
1907  // transformation is profitable.
1908  if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1909  cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1910  cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1911  LHS.getNode()->hasNUsesOfValue(1, 0)) {
1912  int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1913  if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1914  SDValue SExt =
1915  DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1916  DAG.getValueType(MVT::i16));
1917  Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1918  RHS.getValueType()),
1919  CC, dl, DAG);
1920  AArch64CC = changeIntCCToAArch64CC(CC);
1921  }
1922  }
1923 
1924  if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1925  if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1926  if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1927  AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1928  }
1929  }
1930  }
1931 
1932  if (!Cmp) {
1933  Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1934  AArch64CC = changeIntCCToAArch64CC(CC);
1935  }
1936  AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1937  return Cmp;
1938 }
1939 
1940 static std::pair<SDValue, SDValue>
1942  assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1943  "Unsupported value type");
1944  SDValue Value, Overflow;
1945  SDLoc DL(Op);
1946  SDValue LHS = Op.getOperand(0);
1947  SDValue RHS = Op.getOperand(1);
1948  unsigned Opc = 0;
1949  switch (Op.getOpcode()) {
1950  default:
1951  llvm_unreachable("Unknown overflow instruction!");
1952  case ISD::SADDO:
1953  Opc = AArch64ISD::ADDS;
1954  CC = AArch64CC::VS;
1955  break;
1956  case ISD::UADDO:
1957  Opc = AArch64ISD::ADDS;
1958  CC = AArch64CC::HS;
1959  break;
1960  case ISD::SSUBO:
1961  Opc = AArch64ISD::SUBS;
1962  CC = AArch64CC::VS;
1963  break;
1964  case ISD::USUBO:
1965  Opc = AArch64ISD::SUBS;
1966  CC = AArch64CC::LO;
1967  break;
1968  // Multiply needs a little bit extra work.
1969  case ISD::SMULO:
1970  case ISD::UMULO: {
1971  CC = AArch64CC::NE;
1972  bool IsSigned = Op.getOpcode() == ISD::SMULO;
1973  if (Op.getValueType() == MVT::i32) {
1974  unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1975  // For a 32 bit multiply with overflow check we want the instruction
1976  // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1977  // need to generate the following pattern:
1978  // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1979  LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1980  RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1981  SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1982  SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1983  DAG.getConstant(0, DL, MVT::i64));
1984  // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1985  // operation. We need to clear out the upper 32 bits, because we used a
1986  // widening multiply that wrote all 64 bits. In the end this should be a
1987  // noop.
1988  Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1989  if (IsSigned) {
1990  // The signed overflow check requires more than just a simple check for
1991  // any bit set in the upper 32 bits of the result. These bits could be
1992  // just the sign bits of a negative number. To perform the overflow
1993  // check we have to arithmetic shift right the 32nd bit of the result by
1994  // 31 bits. Then we compare the result to the upper 32 bits.
1995  SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1996  DAG.getConstant(32, DL, MVT::i64));
1997  UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1998  SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1999  DAG.getConstant(31, DL, MVT::i64));
2000  // It is important that LowerBits is last, otherwise the arithmetic
2001  // shift will not be folded into the compare (SUBS).
2002  SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
2003  Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2004  .getValue(1);
2005  } else {
2006  // The overflow check for unsigned multiply is easy. We only need to
2007  // check if any of the upper 32 bits are set. This can be done with a
2008  // CMP (shifted register). For that we need to generate the following
2009  // pattern:
2010  // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2011  SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
2012  DAG.getConstant(32, DL, MVT::i64));
2013  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2014  Overflow =
2015  DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2016  DAG.getConstant(0, DL, MVT::i64),
2017  UpperBits).getValue(1);
2018  }
2019  break;
2020  }
2021  assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
2022  // For the 64 bit multiply
2023  Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
2024  if (IsSigned) {
2025  SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
2026  SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
2027  DAG.getConstant(63, DL, MVT::i64));
2028  // It is important that LowerBits is last, otherwise the arithmetic
2029  // shift will not be folded into the compare (SUBS).
2030  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2031  Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
2032  .getValue(1);
2033  } else {
2034  SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
2035  SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
2036  Overflow =
2037  DAG.getNode(AArch64ISD::SUBS, DL, VTs,
2038  DAG.getConstant(0, DL, MVT::i64),
2039  UpperBits).getValue(1);
2040  }
2041  break;
2042  }
2043  } // switch (...)
2044 
2045  if (Opc) {
2046  SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
2047 
2048  // Emit the AArch64 operation with overflow check.
2049  Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
2050  Overflow = Value.getValue(1);
2051  }
2052  return std::make_pair(Value, Overflow);
2053 }
2054 
2055 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
2056  RTLIB::Libcall Call) const {
2057  SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2058  return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
2059 }
2060 
2061 // Returns true if the given Op is the overflow flag result of an overflow
2062 // intrinsic operation.
2063 static bool isOverflowIntrOpRes(SDValue Op) {
2064  unsigned Opc = Op.getOpcode();
2065  return (Op.getResNo() == 1 &&
2066  (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2067  Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2068 }
2069 
2071  SDValue Sel = Op.getOperand(0);
2072  SDValue Other = Op.getOperand(1);
2073  SDLoc dl(Sel);
2074 
2075  // If the operand is an overflow checking operation, invert the condition
2076  // code and kill the Not operation. I.e., transform:
2077  // (xor (overflow_op_bool, 1))
2078  // -->
2079  // (csel 1, 0, invert(cc), overflow_op_bool)
2080  // ... which later gets transformed to just a cset instruction with an
2081  // inverted condition code, rather than a cset + eor sequence.
2082  if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
2083  // Only lower legal XALUO ops.
2084  if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2085  return SDValue();
2086 
2087  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2088  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2090  SDValue Value, Overflow;
2091  std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2092  SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2093  return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2094  CCVal, Overflow);
2095  }
2096  // If neither operand is a SELECT_CC, give up.
2097  if (Sel.getOpcode() != ISD::SELECT_CC)
2098  std::swap(Sel, Other);
2099  if (Sel.getOpcode() != ISD::SELECT_CC)
2100  return Op;
2101 
2102  // The folding we want to perform is:
2103  // (xor x, (select_cc a, b, cc, 0, -1) )
2104  // -->
2105  // (csel x, (xor x, -1), cc ...)
2106  //
2107  // The latter will get matched to a CSINV instruction.
2108 
2109  ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2110  SDValue LHS = Sel.getOperand(0);
2111  SDValue RHS = Sel.getOperand(1);
2112  SDValue TVal = Sel.getOperand(2);
2113  SDValue FVal = Sel.getOperand(3);
2114 
2115  // FIXME: This could be generalized to non-integer comparisons.
2116  if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2117  return Op;
2118 
2119  ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2120  ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2121 
2122  // The values aren't constants, this isn't the pattern we're looking for.
2123  if (!CFVal || !CTVal)
2124  return Op;
2125 
2126  // We can commute the SELECT_CC by inverting the condition. This
2127  // might be needed to make this fit into a CSINV pattern.
2128  if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2129  std::swap(TVal, FVal);
2130  std::swap(CTVal, CFVal);
2131  CC = ISD::getSetCCInverse(CC, true);
2132  }
2133 
2134  // If the constants line up, perform the transform!
2135  if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2136  SDValue CCVal;
2137  SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2138 
2139  FVal = Other;
2140  TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2141  DAG.getConstant(-1ULL, dl, Other.getValueType()));
2142 
2143  return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2144  CCVal, Cmp);
2145  }
2146 
2147  return Op;
2148 }
2149 
2151  EVT VT = Op.getValueType();
2152 
2153  // Let legalize expand this if it isn't a legal type yet.
2154  if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2155  return SDValue();
2156 
2157  SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2158 
2159  unsigned Opc;
2160  bool ExtraOp = false;
2161  switch (Op.getOpcode()) {
2162  default:
2163  llvm_unreachable("Invalid code");
2164  case ISD::ADDC:
2165  Opc = AArch64ISD::ADDS;
2166  break;
2167  case ISD::SUBC:
2168  Opc = AArch64ISD::SUBS;
2169  break;
2170  case ISD::ADDE:
2171  Opc = AArch64ISD::ADCS;
2172  ExtraOp = true;
2173  break;
2174  case ISD::SUBE:
2175  Opc = AArch64ISD::SBCS;
2176  ExtraOp = true;
2177  break;
2178  }
2179 
2180  if (!ExtraOp)
2181  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2182  return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2183  Op.getOperand(2));
2184 }
2185 
2187  // Let legalize expand this if it isn't a legal type yet.
2189  return SDValue();
2190 
2191  SDLoc dl(Op);
2193  // The actual operation that sets the overflow or carry flag.
2194  SDValue Value, Overflow;
2195  std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2196 
2197  // We use 0 and 1 as false and true values.
2198  SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2199  SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2200 
2201  // We use an inverted condition, because the conditional select is inverted
2202  // too. This will allow it to be selected to a single instruction:
2203  // CSINC Wd, WZR, WZR, invert(cond).
2204  SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2205  Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2206  CCVal, Overflow);
2207 
2208  SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2209  return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2210 }
2211 
2212 // Prefetch operands are:
2213 // 1: Address to prefetch
2214 // 2: bool isWrite
2215 // 3: int locality (0 = no locality ... 3 = extreme locality)
2216 // 4: bool isDataCache
2218  SDLoc DL(Op);
2219  unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2220  unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2221  unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2222 
2223  bool IsStream = !Locality;
2224  // When the locality number is set
2225  if (Locality) {
2226  // The front-end should have filtered out the out-of-range values
2227  assert(Locality <= 3 && "Prefetch locality out-of-range");
2228  // The locality degree is the opposite of the cache speed.
2229  // Put the number the other way around.
2230  // The encoding starts at 0 for level 1
2231  Locality = 3 - Locality;
2232  }
2233 
2234  // built the mask value encoding the expected behavior.
2235  unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2236  (!IsData << 3) | // IsDataCache bit
2237  (Locality << 1) | // Cache level bits
2238  (unsigned)IsStream; // Stream bit
2239  return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2240  DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2241 }
2242 
2243 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2244  SelectionDAG &DAG) const {
2245  assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2246 
2247  RTLIB::Libcall LC;
2249 
2250  return LowerF128Call(Op, DAG, LC);
2251 }
2252 
2253 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2254  SelectionDAG &DAG) const {
2255  if (Op.getOperand(0).getValueType() != MVT::f128) {
2256  // It's legal except when f128 is involved
2257  return Op;
2258  }
2259 
2260  RTLIB::Libcall LC;
2262 
2263  // FP_ROUND node has a second operand indicating whether it is known to be
2264  // precise. That doesn't take part in the LibCall so we can't directly use
2265  // LowerF128Call.
2266  SDValue SrcVal = Op.getOperand(0);
2267  return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2268  SDLoc(Op)).first;
2269 }
2270 
2272  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2273  // Any additional optimization in this function should be recorded
2274  // in the cost tables.
2275  EVT InVT = Op.getOperand(0).getValueType();
2276  EVT VT = Op.getValueType();
2277  unsigned NumElts = InVT.getVectorNumElements();
2278 
2279  // f16 vectors are promoted to f32 before a conversion.
2280  if (InVT.getVectorElementType() == MVT::f16) {
2281  MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2282  SDLoc dl(Op);
2283  return DAG.getNode(
2284  Op.getOpcode(), dl, Op.getValueType(),
2285  DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2286  }
2287 
2288  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2289  SDLoc dl(Op);
2290  SDValue Cv =
2291  DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2292  Op.getOperand(0));
2293  return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2294  }
2295 
2296  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2297  SDLoc dl(Op);
2298  MVT ExtVT =
2300  VT.getVectorNumElements());
2301  SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2302  return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2303  }
2304 
2305  // Type changing conversions are illegal.
2306  return Op;
2307 }
2308 
2309 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2310  SelectionDAG &DAG) const {
2311  if (Op.getOperand(0).getValueType().isVector())
2312  return LowerVectorFP_TO_INT(Op, DAG);
2313 
2314  // f16 conversions are promoted to f32 when full fp16 is not supported.
2315  if (Op.getOperand(0).getValueType() == MVT::f16 &&
2316  !Subtarget->hasFullFP16()) {
2317  SDLoc dl(Op);
2318  return DAG.getNode(
2319  Op.getOpcode(), dl, Op.getValueType(),
2320  DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2321  }
2322 
2323  if (Op.getOperand(0).getValueType() != MVT::f128) {
2324  // It's legal except when f128 is involved
2325  return Op;
2326  }
2327 
2328  RTLIB::Libcall LC;
2329  if (Op.getOpcode() == ISD::FP_TO_SINT)
2331  else
2333 
2334  SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2335  return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2336 }
2337 
2339  // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2340  // Any additional optimization in this function should be recorded
2341  // in the cost tables.
2342  EVT VT = Op.getValueType();
2343  SDLoc dl(Op);
2344  SDValue In = Op.getOperand(0);
2345  EVT InVT = In.getValueType();
2346 
2347  if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2348  MVT CastVT =
2350  InVT.getVectorNumElements());
2351  In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2352  return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2353  }
2354 
2355  if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2356  unsigned CastOpc =
2358  EVT CastVT = VT.changeVectorElementTypeToInteger();
2359  In = DAG.getNode(CastOpc, dl, CastVT, In);
2360  return DAG.getNode(Op.getOpcode(), dl, VT, In);
2361  }
2362 
2363  return Op;
2364 }
2365 
2366 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2367  SelectionDAG &DAG) const {
2368  if (Op.getValueType().isVector())
2369  return LowerVectorINT_TO_FP(Op, DAG);
2370 
2371  // f16 conversions are promoted to f32 when full fp16 is not supported.
2372  if (Op.getValueType() == MVT::f16 &&
2373  !Subtarget->hasFullFP16()) {
2374  SDLoc dl(Op);
2375  return DAG.getNode(
2376  ISD::FP_ROUND, dl, MVT::f16,
2377  DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2378  DAG.getIntPtrConstant(0, dl));
2379  }
2380 
2381  // i128 conversions are libcalls.
2382  if (Op.getOperand(0).getValueType() == MVT::i128)
2383  return SDValue();
2384 
2385  // Other conversions are legal, unless it's to the completely software-based
2386  // fp128.
2387  if (Op.getValueType() != MVT::f128)
2388  return Op;
2389 
2390  RTLIB::Libcall LC;
2391  if (Op.getOpcode() == ISD::SINT_TO_FP)
2393  else
2395 
2396  return LowerF128Call(Op, DAG, LC);
2397 }
2398 
2399 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2400  SelectionDAG &DAG) const {
2401  // For iOS, we want to call an alternative entry point: __sincos_stret,
2402  // which returns the values in two S / D registers.
2403  SDLoc dl(Op);
2404  SDValue Arg = Op.getOperand(0);
2405  EVT ArgVT = Arg.getValueType();
2406  Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2407 
2408  ArgListTy Args;
2409  ArgListEntry Entry;
2410 
2411  Entry.Node = Arg;
2412  Entry.Ty = ArgTy;
2413  Entry.IsSExt = false;
2414  Entry.IsZExt = false;
2415  Args.push_back(Entry);
2416 
2417  RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2418  : RTLIB::SINCOS_STRET_F32;
2419  const char *LibcallName = getLibcallName(LC);
2420  SDValue Callee =
2421  DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2422 
2423  StructType *RetTy = StructType::get(ArgTy, ArgTy);
2425  CLI.setDebugLoc(dl)
2426  .setChain(DAG.getEntryNode())
2427  .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2428 
2429  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2430  return CallResult.first;
2431 }
2432 
2434  if (Op.getValueType() != MVT::f16)
2435  return SDValue();
2436 
2437  assert(Op.getOperand(0).getValueType() == MVT::i16);
2438  SDLoc DL(Op);
2439 
2440  Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2441  Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2442  return SDValue(
2443  DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2444  DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2445  0);
2446 }
2447 
2448 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2449  if (OrigVT.getSizeInBits() >= 64)
2450  return OrigVT;
2451 
2452  assert(OrigVT.isSimple() && "Expecting a simple value type");
2453 
2454  MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2455  switch (OrigSimpleTy) {
2456  default: llvm_unreachable("Unexpected Vector Type");
2457  case MVT::v2i8:
2458  case MVT::v2i16:
2459  return MVT::v2i32;
2460  case MVT::v4i8:
2461  return MVT::v4i16;
2462  }
2463 }
2464 
2466  const EVT &OrigTy,
2467  const EVT &ExtTy,
2468  unsigned ExtOpcode) {
2469  // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2470  // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2471  // 64-bits we need to insert a new extension so that it will be 64-bits.
2472  assert(ExtTy.is128BitVector() && "Unexpected extension size");
2473  if (OrigTy.getSizeInBits() >= 64)
2474  return N;
2475 
2476  // Must extend size to at least 64 bits to be used as an operand for VMULL.
2477  EVT NewVT = getExtensionTo64Bits(OrigTy);
2478 
2479  return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2480 }
2481 
2483  bool isSigned) {
2484  EVT VT = N->getValueType(0);
2485 
2486  if (N->getOpcode() != ISD::BUILD_VECTOR)
2487  return false;
2488 
2489  for (const SDValue &Elt : N->op_values()) {
2490  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2491  unsigned EltSize = VT.getScalarSizeInBits();
2492  unsigned HalfSize = EltSize / 2;
2493  if (isSigned) {
2494  if (!isIntN(HalfSize, C->getSExtValue()))
2495  return false;
2496  } else {
2497  if (!isUIntN(HalfSize, C->getZExtValue()))
2498  return false;
2499  }
2500  continue;
2501  }
2502  return false;
2503  }
2504 
2505  return true;
2506 }
2507 
2509  if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2511  N->getOperand(0)->getValueType(0),
2512  N->getValueType(0),
2513  N->getOpcode());
2514 
2515  assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2516  EVT VT = N->getValueType(0);
2517  SDLoc dl(N);
2518  unsigned EltSize = VT.getScalarSizeInBits() / 2;
2519  unsigned NumElts = VT.getVectorNumElements();
2520  MVT TruncVT = MVT::getIntegerVT(EltSize);
2522  for (unsigned i = 0; i != NumElts; ++i) {
2523  ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2524  const APInt &CInt = C->getAPIntValue();
2525  // Element types smaller than 32 bits are not legal, so use i32 elements.
2526  // The values are implicitly truncated so sext vs. zext doesn't matter.
2527  Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2528  }
2529  return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2530 }
2531 
2532 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2533  return N->getOpcode() == ISD::SIGN_EXTEND ||
2534  isExtendedBUILD_VECTOR(N, DAG, true);
2535 }
2536 
2537 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2538  return N->getOpcode() == ISD::ZERO_EXTEND ||
2539  isExtendedBUILD_VECTOR(N, DAG, false);
2540 }
2541 
2542 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2543  unsigned Opcode = N->getOpcode();
2544  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2545  SDNode *N0 = N->getOperand(0).getNode();
2546  SDNode *N1 = N->getOperand(1).getNode();
2547  return N0->hasOneUse() && N1->hasOneUse() &&
2548  isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2549  }
2550  return false;
2551 }
2552 
2553 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2554  unsigned Opcode = N->getOpcode();
2555  if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2556  SDNode *N0 = N->getOperand(0).getNode();
2557  SDNode *N1 = N->getOperand(1).getNode();
2558  return N0->hasOneUse() && N1->hasOneUse() &&
2559  isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2560  }
2561  return false;
2562 }
2563 
2564 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
2565  SelectionDAG &DAG) const {
2566  // The rounding mode is in bits 23:22 of the FPSCR.
2567  // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2568  // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2569  // so that the shift + and get folded into a bitfield extract.
2570  SDLoc dl(Op);
2571 
2572  SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64,
2573  DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl,
2574  MVT::i64));
2575  SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
2576  SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
2577  DAG.getConstant(1U << 22, dl, MVT::i32));
2578  SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
2579  DAG.getConstant(22, dl, MVT::i32));
2580  return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
2581  DAG.getConstant(3, dl, MVT::i32));
2582 }
2583 
2585  // Multiplications are only custom-lowered for 128-bit vectors so that
2586  // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2587  EVT VT = Op.getValueType();
2588  assert(VT.is128BitVector() && VT.isInteger() &&
2589  "unexpected type for custom-lowering ISD::MUL");
2590  SDNode *N0 = Op.getOperand(0).getNode();
2591  SDNode *N1 = Op.getOperand(1).getNode();
2592  unsigned NewOpc = 0;
2593  bool isMLA = false;
2594  bool isN0SExt = isSignExtended(N0, DAG);
2595  bool isN1SExt = isSignExtended(N1, DAG);
2596  if (isN0SExt && isN1SExt)
2597  NewOpc = AArch64ISD::SMULL;
2598  else {
2599  bool isN0ZExt = isZeroExtended(N0, DAG);
2600  bool isN1ZExt = isZeroExtended(N1, DAG);
2601  if (isN0ZExt && isN1ZExt)
2602  NewOpc = AArch64ISD::UMULL;
2603  else if (isN1SExt || isN1ZExt) {
2604  // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2605  // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2606  if (isN1SExt && isAddSubSExt(N0, DAG)) {
2607  NewOpc = AArch64ISD::SMULL;
2608  isMLA = true;
2609  } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2610  NewOpc = AArch64ISD::UMULL;
2611  isMLA = true;
2612  } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2613  std::swap(N0, N1);
2614  NewOpc = AArch64ISD::UMULL;
2615  isMLA = true;
2616  }
2617  }
2618 
2619  if (!NewOpc) {
2620  if (VT == MVT::v2i64)
2621  // Fall through to expand this. It is not legal.
2622  return SDValue();
2623  else
2624  // Other vector multiplications are legal.
2625  return Op;
2626  }
2627  }
2628 
2629  // Legalize to a S/UMULL instruction
2630  SDLoc DL(Op);
2631  SDValue Op0;
2632  SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2633  if (!isMLA) {
2634  Op0 = skipExtensionForVectorMULL(N0, DAG);
2635  assert(Op0.getValueType().is64BitVector() &&
2636  Op1.getValueType().is64BitVector() &&
2637  "unexpected types for extended operands to VMULL");
2638  return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2639  }
2640  // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2641  // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2642  // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2643  SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2644  SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2645  EVT Op1VT = Op1.getValueType();
2646  return DAG.getNode(N0->getOpcode(), DL, VT,
2647  DAG.getNode(NewOpc, DL, VT,
2648  DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2649  DAG.getNode(NewOpc, DL, VT,
2650  DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2651 }
2652 
2653 // Lower vector multiply high (ISD::MULHS and ISD::MULHU).
2655  // Multiplications are only custom-lowered for 128-bit vectors so that
2656  // {S,U}MULL{2} can be detected. Otherwise v2i64 multiplications are not
2657  // legal.
2658  EVT VT = Op.getValueType();
2659  assert(VT.is128BitVector() && VT.isInteger() &&
2660  "unexpected type for custom-lowering ISD::MULH{U,S}");
2661 
2662  SDValue V0 = Op.getOperand(0);
2663  SDValue V1 = Op.getOperand(1);
2664 
2665  SDLoc DL(Op);
2666 
2667  EVT ExtractVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
2668 
2669  // We turn (V0 mulhs/mulhu V1) to:
2670  //
2671  // (uzp2 (smull (extract_subvector (ExtractVT V128:V0, (i64 0)),
2672  // (extract_subvector (ExtractVT V128:V1, (i64 0))))),
2673  // (smull (extract_subvector (ExtractVT V128:V0, (i64 VMull2Idx)),
2674  // (extract_subvector (ExtractVT V128:V2, (i64 VMull2Idx))))))
2675  //
2676  // Where ExtractVT is a subvector with half number of elements, and
2677  // VMullIdx2 is the index of the middle element (the high part).
2678  //
2679  // The vector hight part extract and multiply will be matched against
2680  // {S,U}MULL{v16i8_v8i16,v8i16_v4i32,v4i32_v2i64} which in turn will
2681  // issue a {s}mull2 instruction.
2682  //
2683  // This basically multiply the lower subvector with '{s,u}mull', the high
2684  // subvector with '{s,u}mull2', and shuffle both results high part in
2685  // resulting vector.
2686  unsigned Mull2VectorIdx = VT.getVectorNumElements () / 2;
2687  SDValue VMullIdx = DAG.getConstant(0, DL, MVT::i64);
2688  SDValue VMull2Idx = DAG.getConstant(Mull2VectorIdx, DL, MVT::i64);
2689 
2690  SDValue VMullV0 =
2691  DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMullIdx);
2692  SDValue VMullV1 =
2693  DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMullIdx);
2694 
2695  SDValue VMull2V0 =
2696  DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V0, VMull2Idx);
2697  SDValue VMull2V1 =
2698  DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtractVT, V1, VMull2Idx);
2699 
2700  unsigned MullOpc = Op.getOpcode() == ISD::MULHS ? AArch64ISD::SMULL
2702 
2703  EVT MullVT = ExtractVT.widenIntegerVectorElementType(*DAG.getContext());
2704  SDValue Mull = DAG.getNode(MullOpc, DL, MullVT, VMullV0, VMullV1);
2705  SDValue Mull2 = DAG.getNode(MullOpc, DL, MullVT, VMull2V0, VMull2V1);
2706 
2707  Mull = DAG.getNode(ISD::BITCAST, DL, VT, Mull);
2708  Mull2 = DAG.getNode(ISD::BITCAST, DL, VT, Mull2);
2709 
2710  return DAG.getNode(AArch64ISD::UZP2, DL, VT, Mull, Mull2);
2711 }
2712 
2713 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2714  SelectionDAG &DAG) const {
2715  unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2716  SDLoc dl(Op);
2717  switch (IntNo) {
2718  default: return SDValue(); // Don't custom lower most intrinsics.
2719  case Intrinsic::thread_pointer: {
2720  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721  return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2722  }
2723  case Intrinsic::aarch64_neon_abs:
2724  return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2725  Op.getOperand(1));
2726  case Intrinsic::aarch64_neon_smax:
2727  return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2728  Op.getOperand(1), Op.getOperand(2));
2729  case Intrinsic::aarch64_neon_umax:
2730  return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2731  Op.getOperand(1), Op.getOperand(2));
2732  case Intrinsic::aarch64_neon_smin:
2733  return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2734  Op.getOperand(1), Op.getOperand(2));
2735  case Intrinsic::aarch64_neon_umin:
2736  return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2737  Op.getOperand(1), Op.getOperand(2));
2738  }
2739 }
2740 
2741 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2743  EVT VT, EVT MemVT,
2744  SelectionDAG &DAG) {
2745  assert(VT.isVector() && "VT should be a vector type");
2746  assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
2747 
2748  SDValue Value = ST->getValue();
2749 
2750  // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2751  // the word lane which represent the v4i8 subvector. It optimizes the store
2752  // to:
2753  //
2754  // xtn v0.8b, v0.8h
2755  // str s0, [x0]
2756 
2757  SDValue Undef = DAG.getUNDEF(MVT::i16);
2758  SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
2759  {Undef, Undef, Undef, Undef});
2760 
2761  SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
2762  Value, UndefVec);
2763  SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
2764 
2765  Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
2766  SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
2767  Trunc, DAG.getConstant(0, DL, MVT::i64));
2768 
2769  return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
2770  ST->getBasePtr(), ST->getMemOperand());
2771 }
2772 
2773 // Custom lowering for any store, vector or scalar and/or default or with
2774 // a truncate operations. Currently only custom lower truncate operation
2775 // from vector v4i16 to v4i8.
2776 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
2777  SelectionDAG &DAG) const {
2778  SDLoc Dl(Op);
2779  StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
2780  assert (StoreNode && "Can only custom lower store nodes");
2781 
2782  SDValue Value = StoreNode->getValue();
2783 
2784  EVT VT = Value.getValueType();
2785  EVT MemVT = StoreNode->getMemoryVT();
2786 
2787  assert (VT.isVector() && "Can only custom lower vector store types");
2788 
2789  unsigned AS = StoreNode->getAddressSpace();
2790  unsigned Align = StoreNode->getAlignment();
2791  if (Align < MemVT.getStoreSize() &&
2792  !allowsMisalignedMemoryAccesses(MemVT, AS, Align, nullptr)) {
2793  return scalarizeVectorStore(StoreNode, DAG);
2794  }
2795 
2796  if (StoreNode->isTruncatingStore()) {
2797  return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
2798  }
2799 
2800  return SDValue();
2801 }
2802 
2804  SelectionDAG &DAG) const {
2805  LLVM_DEBUG(dbgs() << "Custom lowering: ");
2806  LLVM_DEBUG(Op.dump());
2807 
2808  switch (Op.getOpcode()) {
2809  default:
2810  llvm_unreachable("unimplemented operand");
2811  return SDValue();
2812  case ISD::BITCAST:
2813  return LowerBITCAST(Op, DAG);
2814  case ISD::GlobalAddress:
2815  return LowerGlobalAddress(Op, DAG);
2816  case ISD::GlobalTLSAddress:
2817  return LowerGlobalTLSAddress(Op, DAG);
2818  case ISD::SETCC:
2819  return LowerSETCC(Op, DAG);
2820  case ISD::BR_CC:
2821  return LowerBR_CC(Op, DAG);
2822  case ISD::SELECT:
2823  return LowerSELECT(Op, DAG);
2824  case ISD::SELECT_CC:
2825  return LowerSELECT_CC(Op, DAG);
2826  case ISD::JumpTable:
2827  return LowerJumpTable(Op, DAG);
2828  case ISD::ConstantPool:
2829  return LowerConstantPool(Op, DAG);
2830  case ISD::BlockAddress:
2831  return LowerBlockAddress(Op, DAG);
2832  case ISD::VASTART:
2833  return LowerVASTART(Op, DAG);
2834  case ISD::VACOPY:
2835  return LowerVACOPY(Op, DAG);
2836  case ISD::VAARG:
2837  return LowerVAARG(Op, DAG);
2838  case ISD::ADDC:
2839  case ISD::ADDE:
2840  case ISD::SUBC:
2841  case ISD::SUBE:
2842  return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2843  case ISD::SADDO:
2844  case ISD::UADDO:
2845  case ISD::SSUBO:
2846  case ISD::USUBO:
2847  case ISD::SMULO:
2848  case ISD::UMULO:
2849  return LowerXALUO(Op, DAG);
2850  case ISD::FADD:
2851  return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2852  case ISD::FSUB:
2853  return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2854  case ISD::FMUL:
2855  return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2856  case ISD::FDIV:
2857  return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2858  case ISD::FP_ROUND:
2859  return LowerFP_ROUND(Op, DAG);
2860  case ISD::FP_EXTEND:
2861  return LowerFP_EXTEND(Op, DAG);
2862  case ISD::FRAMEADDR:
2863  return LowerFRAMEADDR(Op, DAG);
2864  case ISD::RETURNADDR:
2865  return LowerRETURNADDR(Op, DAG);
2867  return LowerINSERT_VECTOR_ELT(Op, DAG);
2869  return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2870  case ISD::BUILD_VECTOR:
2871  return LowerBUILD_VECTOR(Op, DAG);
2872  case ISD::VECTOR_SHUFFLE:
2873  return LowerVECTOR_SHUFFLE(Op, DAG);
2875  return LowerEXTRACT_SUBVECTOR(Op, DAG);
2876  case ISD::SRA:
2877  case ISD::SRL:
2878  case ISD::SHL:
2879  return LowerVectorSRA_SRL_SHL(Op, DAG);
2880  case ISD::SHL_PARTS:
2881  return LowerShiftLeftParts(Op, DAG);
2882  case ISD::SRL_PARTS:
2883  case ISD::SRA_PARTS:
2884  return LowerShiftRightParts(Op, DAG);
2885  case ISD::CTPOP:
2886  return LowerCTPOP(Op, DAG);
2887  case ISD::FCOPYSIGN:
2888  return LowerFCOPYSIGN(Op, DAG);
2889  case ISD::AND:
2890  return LowerVectorAND(Op, DAG);
2891  case ISD::OR:
2892  return LowerVectorOR(Op, DAG);
2893  case ISD::XOR:
2894  return LowerXOR(Op, DAG);
2895  case ISD::PREFETCH:
2896  return LowerPREFETCH(Op, DAG);
2897  case ISD::SINT_TO_FP:
2898  case ISD::UINT_TO_FP:
2899  return LowerINT_TO_FP(Op, DAG);
2900  case ISD::FP_TO_SINT:
2901  case ISD::FP_TO_UINT:
2902  return LowerFP_TO_INT(Op, DAG);
2903  case ISD::FSINCOS:
2904  return LowerFSINCOS(Op, DAG);
2905  case ISD::FLT_ROUNDS_:
2906  return LowerFLT_ROUNDS_(Op, DAG);
2907  case ISD::MUL:
2908  return LowerMUL(Op, DAG);
2909  case ISD::MULHS:
2910  case ISD::MULHU:
2911  return LowerMULH(Op, DAG);
2913  return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2914  case ISD::STORE:
2915  return LowerSTORE(Op, DAG);
2916  case ISD::VECREDUCE_ADD:
2917  case ISD::VECREDUCE_SMAX:
2918  case ISD::VECREDUCE_SMIN:
2919  case ISD::VECREDUCE_UMAX:
2920  case ISD::VECREDUCE_UMIN:
2921  case ISD::VECREDUCE_FMAX:
2922  case ISD::VECREDUCE_FMIN:
2923  return LowerVECREDUCE(Op, DAG);
2924  case ISD::ATOMIC_LOAD_SUB:
2925  return LowerATOMIC_LOAD_SUB(Op, DAG);
2926  case ISD::ATOMIC_LOAD_AND:
2927  return LowerATOMIC_LOAD_AND(Op, DAG);
2929  return LowerDYNAMIC_STACKALLOC(Op, DAG);
2930  }
2931 }
2932 
2933 //===----------------------------------------------------------------------===//
2934 // Calling Convention Implementation
2935 //===----------------------------------------------------------------------===//
2936 
2937 #include "AArch64GenCallingConv.inc"
2938 
2939 /// Selects the correct CCAssignFn for a given CallingConvention value.
2941  bool IsVarArg) const {
2942  switch (CC) {
2943  default:
2944  report_fatal_error("Unsupported calling convention.");
2946  return CC_AArch64_WebKit_JS;
2947  case CallingConv::GHC:
2948  return CC_AArch64_GHC;
2949  case CallingConv::C:
2950  case CallingConv::Fast:
2953  case CallingConv::Swift:
2954  if (Subtarget->isTargetWindows() && IsVarArg)
2955  return CC_AArch64_Win64_VarArg;
2956  if (!Subtarget->isTargetDarwin())
2957  return CC_AArch64_AAPCS;
2958  return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2959  case CallingConv::Win64:
2960  return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2962  return CC_AArch64_AAPCS;
2963  }
2964 }
2965 
2966 CCAssignFn *
2968  return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2969  : RetCC_AArch64_AAPCS;
2970 }
2971 
2972 SDValue AArch64TargetLowering::LowerFormalArguments(
2973  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2974  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2975  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2976  MachineFunction &MF = DAG.getMachineFunction();
2977  MachineFrameInfo &MFI = MF.getFrameInfo();
2978  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2979 
2980  // Assign locations to all of the incoming arguments.
2982  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2983  *DAG.getContext());
2984 
2985  // At this point, Ins[].VT may already be promoted to i32. To correctly
2986  // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2987  // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2988  // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2989  // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2990  // LocVT.
2991  unsigned NumArgs = Ins.size();
2993  unsigned CurArgIdx = 0;
2994  for (unsigned i = 0; i != NumArgs; ++i) {
2995  MVT ValVT = Ins[i].VT;
2996  if (Ins[i].isOrigArg()) {
2997  std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2998  CurArgIdx = Ins[i].getOrigArgIndex();
2999 
3000  // Get type of the original argument.
3001  EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
3002  /*AllowUnknown*/ true);
3003  MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
3004  // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3005  if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3006  ValVT = MVT::i8;
3007  else if (ActualMVT == MVT::i16)
3008  ValVT = MVT::i16;
3009  }
3010  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3011  bool Res =
3012  AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
3013  assert(!Res && "Call operand has unhandled type");
3014  (void)Res;
3015  }
3016  assert(ArgLocs.size() == Ins.size());
3017  SmallVector<SDValue, 16> ArgValues;
3018  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3019  CCValAssign &VA = ArgLocs[i];
3020 
3021  if (Ins[i].Flags.isByVal()) {
3022  // Byval is used for HFAs in the PCS, but the system should work in a
3023  // non-compliant manner for larger structs.
3024  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3025  int Size = Ins[i].Flags.getByValSize();
3026  unsigned NumRegs = (Size + 7) / 8;
3027 
3028  // FIXME: This works on big-endian for composite byvals, which are the common
3029  // case. It should also work for fundamental types too.
3030  unsigned FrameIdx =
3031  MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
3032  SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
3033  InVals.push_back(FrameIdxN);
3034 
3035  continue;
3036  }
3037 
3038  if (VA.isRegLoc()) {
3039  // Arguments stored in registers.
3040  EVT RegVT = VA.getLocVT();
3041 
3042  SDValue ArgValue;
3043  const TargetRegisterClass *RC;
3044 
3045  if (RegVT == MVT::i32)
3046  RC = &AArch64::GPR32RegClass;
3047  else if (RegVT == MVT::i64)
3048  RC = &AArch64::GPR64RegClass;
3049  else if (RegVT == MVT::f16)
3050  RC = &AArch64::FPR16RegClass;
3051  else if (RegVT == MVT::f32)
3052  RC = &AArch64::FPR32RegClass;
3053  else if (RegVT == MVT::f64 || RegVT.is64BitVector())
3054  RC = &AArch64::FPR64RegClass;
3055  else if (RegVT == MVT::f128 || RegVT.is128BitVector())
3056  RC = &AArch64::FPR128RegClass;
3057  else
3058  llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3059 
3060  // Transform the arguments in physical registers into virtual ones.
3061  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3062  ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3063 
3064  // If this is an 8, 16 or 32-bit value, it is really passed promoted
3065  // to 64 bits. Insert an assert[sz]ext to capture this, then
3066  // truncate to the right size.
3067  switch (VA.getLocInfo()) {
3068  default:
3069  llvm_unreachable("Unknown loc info!");
3070  case CCValAssign::Full:
3071  break;
3072  case CCValAssign::BCvt:
3073  ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
3074  break;
3075  case CCValAssign::AExt:
3076  case CCValAssign::SExt:
3077  case CCValAssign::ZExt:
3078  // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3079  // nodes after our lowering.
3080  assert(RegVT == Ins[i].VT && "incorrect register location selected");
3081  break;
3082  }
3083 
3084  InVals.push_back(ArgValue);
3085 
3086  } else { // VA.isRegLoc()
3087  assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
3088  unsigned ArgOffset = VA.getLocMemOffset();
3089  unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
3090 
3091  uint32_t BEAlign = 0;
3092  if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
3093  !Ins[i].Flags.isInConsecutiveRegs())
3094  BEAlign = 8 - ArgSize;
3095 
3096  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
3097 
3098  // Create load nodes to retrieve arguments from the stack.
3099  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3100  SDValue ArgValue;
3101 
3102  // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3104  MVT MemVT = VA.getValVT();
3105 
3106  switch (VA.getLocInfo()) {
3107  default:
3108  break;
3109  case CCValAssign::BCvt:
3110  MemVT = VA.getLocVT();
3111  break;
3112  case CCValAssign::SExt:
3113  ExtType = ISD::SEXTLOAD;
3114  break;
3115  case CCValAssign::ZExt:
3116  ExtType = ISD::ZEXTLOAD;
3117  break;
3118  case CCValAssign::AExt:
3119  ExtType = ISD::EXTLOAD;
3120  break;
3121  }
3122 
3123  ArgValue = DAG.getExtLoad(
3124  ExtType, DL, VA.getLocVT(), Chain, FIN,
3126  MemVT);
3127 
3128  InVals.push_back(ArgValue);
3129  }
3130  }
3131 
3132  // varargs
3134  if (isVarArg) {
3135  if (!Subtarget->isTargetDarwin() || IsWin64) {
3136  // The AAPCS variadic function ABI is identical to the non-variadic
3137  // one. As a result there may be more arguments in registers and we should
3138  // save them for future reference.
3139  // Win64 variadic functions also pass arguments in registers, but all float
3140  // arguments are passed in integer registers.
3141  saveVarArgRegisters(CCInfo, DAG, DL, Chain);
3142  }
3143 
3144  // This will point to the next argument passed via stack.
3145  unsigned StackOffset = CCInfo.getNextStackOffset();
3146  // We currently pass all varargs at 8-byte alignment.
3147  StackOffset = ((StackOffset + 7) & ~7);
3148  FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
3149  }
3150 
3151  unsigned StackArgSize = CCInfo.getNextStackOffset();
3152  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3153  if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
3154  // This is a non-standard ABI so by fiat I say we're allowed to make full
3155  // use of the stack area to be popped, which must be aligned to 16 bytes in
3156  // any case:
3157  StackArgSize = alignTo(StackArgSize, 16);
3158 
3159  // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3160  // a multiple of 16.
3161  FuncInfo->setArgumentStackToRestore(StackArgSize);
3162 
3163  // This realignment carries over to the available bytes below. Our own
3164  // callers will guarantee the space is free by giving an aligned value to
3165  // CALLSEQ_START.
3166  }
3167  // Even if we're not expected to free up the space, it's useful to know how
3168  // much is there while considering tail calls (because we can reuse it).
3169  FuncInfo->setBytesInStackArgArea(StackArgSize);
3170 
3171  if (Subtarget->hasCustomCallingConv())
3172  Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
3173 
3174  return Chain;
3175 }
3176 
3177 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
3178  SelectionDAG &DAG,
3179  const SDLoc &DL,
3180  SDValue &Chain) const {
3181  MachineFunction &MF = DAG.getMachineFunction();
3182  MachineFrameInfo &MFI = MF.getFrameInfo();
3184  auto PtrVT = getPointerTy(DAG.getDataLayout());
3185  bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
3186 
3187  SmallVector<SDValue, 8> MemOps;
3188 
3189  static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
3190  AArch64::X3, AArch64::X4, AArch64::X5,
3191  AArch64::X6, AArch64::X7 };
3192  static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
3193  unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
3194 
3195  unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
3196  int GPRIdx = 0;
3197  if (GPRSaveSize != 0) {
3198  if (IsWin64) {
3199  GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
3200  if (GPRSaveSize & 15)
3201  // The extra size here, if triggered, will always be 8.
3202  MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
3203  } else
3204  GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
3205 
3206  SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
3207 
3208  for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
3209  unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
3210  SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
3211  SDValue Store = DAG.getStore(
3212  Val.getValue(1), DL, Val, FIN,
3213  IsWin64
3215  GPRIdx,
3216  (i - FirstVariadicGPR) * 8)
3218  MemOps.push_back(Store);
3219  FIN =
3220  DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
3221  }
3222  }
3223  FuncInfo->setVarArgsGPRIndex(GPRIdx);
3224  FuncInfo->setVarArgsGPRSize(GPRSaveSize);
3225 
3226  if (Subtarget->hasFPARMv8() && !IsWin64) {
3227  static const MCPhysReg FPRArgRegs[] = {
3228  AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
3229  AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
3230  static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
3231  unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
3232 
3233  unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
3234  int FPRIdx = 0;
3235  if (FPRSaveSize != 0) {
3236  FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
3237 
3238  SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
3239 
3240  for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
3241  unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
3242  SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
3243 
3244  SDValue Store = DAG.getStore(
3245  Val.getValue(1), DL, Val, FIN,
3247  MemOps.push_back(Store);
3248  FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3249  DAG.getConstant(16, DL, PtrVT));
3250  }
3251  }
3252  FuncInfo->setVarArgsFPRIndex(FPRIdx);
3253  FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3254  }
3255 
3256  if (!MemOps.empty()) {
3257  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3258  }
3259 }
3260 
3261 /// LowerCallResult - Lower the result values of a call into the
3262 /// appropriate copies out of appropriate physical registers.
3263 SDValue AArch64TargetLowering::LowerCallResult(
3264  SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3265  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3266  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3267  SDValue ThisVal) const {
3268  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3269  ? RetCC_AArch64_WebKit_JS
3270  : RetCC_AArch64_AAPCS;
3271  // Assign locations to each value returned by this call.
3273  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3274  *DAG.getContext());
3275  CCInfo.AnalyzeCallResult(Ins, RetCC);
3276 
3277  // Copy all of the result registers out of their specified physreg.
3278  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3279  CCValAssign VA = RVLocs[i];
3280 
3281  // Pass 'this' value directly from the argument to return value, to avoid
3282  // reg unit interference
3283  if (i == 0 && isThisReturn) {
3284  assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3285  "unexpected return calling convention register assignment");
3286  InVals.push_back(ThisVal);
3287  continue;
3288  }
3289 
3290  SDValue Val =
3291  DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3292  Chain = Val.getValue(1);
3293  InFlag = Val.getValue(2);
3294 
3295  switch (VA.getLocInfo()) {
3296  default:
3297  llvm_unreachable("Unknown loc info!");
3298  case CCValAssign::Full:
3299  break;
3300  case CCValAssign::BCvt:
3301  Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3302  break;
3303  }
3304 
3305  InVals.push_back(Val);
3306  }
3307 
3308  return Chain;
3309 }
3310 
3311 /// Return true if the calling convention is one that we can guarantee TCO for.
3313  return CC == CallingConv::Fast;
3314 }
3315 
3316 /// Return true if we might ever do TCO for calls with this calling convention.
3318  switch (CC) {
3319  case CallingConv::C:
3321  case CallingConv::Swift:
3322  return true;
3323  default:
3324  return canGuaranteeTCO(CC);
3325  }
3326 }
3327 
3328 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3329  SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3330  const SmallVectorImpl<ISD::OutputArg> &Outs,
3331  const SmallVectorImpl<SDValue> &OutVals,
3332  const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3333  if (!mayTailCallThisCC(CalleeCC))
3334  return false;
3335 
3336  MachineFunction &MF = DAG.getMachineFunction();
3337  const Function &CallerF = MF.getFunction();
3338  CallingConv::ID CallerCC = CallerF.getCallingConv();
3339  bool CCMatch = CallerCC == CalleeCC;
3340 
3341  // Byval parameters hand the function a pointer directly into the stack area
3342  // we want to reuse during a tail call. Working around this *is* possible (see
3343  // X86) but less efficient and uglier in LowerCall.
3344  for (Function::const_arg_iterator i = CallerF.arg_begin(),
3345  e = CallerF.arg_end();
3346  i != e; ++i)
3347  if (i->hasByValAttr())
3348  return false;
3349 
3351  return canGuaranteeTCO(CalleeCC) && CCMatch;
3352 
3353  // Externally-defined functions with weak linkage should not be
3354  // tail-called on AArch64 when the OS does not support dynamic
3355  // pre-emption of symbols, as the AAELF spec requires normal calls
3356  // to undefined weak functions to be replaced with a NOP or jump to the
3357  // next instruction. The behaviour of branch instructions in this
3358  // situation (as used for tail calls) is implementation-defined, so we
3359  // cannot rely on the linker replacing the tail call with a return.
3360  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3361  const GlobalValue *GV = G->getGlobal();
3362  const Triple &TT = getTargetMachine().getTargetTriple();
3363  if (GV->hasExternalWeakLinkage() &&
3364  (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3365  return false;
3366  }
3367 
3368  // Now we search for cases where we can use a tail call without changing the
3369  // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3370  // concept.
3371 
3372  // I want anyone implementing a new calling convention to think long and hard
3373  // about this assert.
3374  assert((!isVarArg || CalleeCC == CallingConv::C) &&
3375  "Unexpected variadic calling convention");
3376 
3377  LLVMContext &C = *DAG.getContext();
3378  if (isVarArg && !Outs.empty()) {
3379  // At least two cases here: if caller is fastcc then we can't have any
3380  // memory arguments (we'd be expected to clean up the stack afterwards). If
3381  // caller is C then we could potentially use its argument area.
3382 
3383  // FIXME: for now we take the most conservative of these in both cases:
3384  // disallow all variadic memory operands.
3386  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3387 
3388  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3389  for (const CCValAssign &ArgLoc : ArgLocs)
3390  if (!ArgLoc.isRegLoc())
3391  return false;
3392  }
3393 
3394  // Check that the call results are passed in the same way.
3395  if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3396  CCAssignFnForCall(CalleeCC, isVarArg),
3397  CCAssignFnForCall(CallerCC, isVarArg)))
3398  return false;
3399  // The callee has to preserve all registers the caller needs to preserve.
3400  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3401  const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3402  if (!CCMatch) {
3403  const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3404  if (Subtarget->hasCustomCallingConv()) {
3405  TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
3406  TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
3407  }
3408  if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3409  return false;
3410  }
3411 
3412  // Nothing more to check if the callee is taking no arguments
3413  if (Outs.empty())
3414  return true;
3415 
3417  CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3418 
3419  CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3420 
3421  const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3422 
3423  // If the stack arguments for this call do not fit into our own save area then
3424  // the call cannot be made tail.
3425  if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3426  return false;
3427 
3428  const MachineRegisterInfo &MRI = MF.getRegInfo();
3429  if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3430  return false;
3431 
3432  return true;
3433 }
3434 
3435 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3436  SelectionDAG &DAG,
3437  MachineFrameInfo &MFI,
3438  int ClobberedFI) const {
3439  SmallVector<SDValue, 8> ArgChains;
3440  int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3441  int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3442 
3443  // Include the original chain at the beginning of the list. When this is
3444  // used by target LowerCall hooks, this helps legalize find the
3445  // CALLSEQ_BEGIN node.
3446  ArgChains.push_back(Chain);
3447 
3448  // Add a chain value for each stack argument corresponding
3449  for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3450  UE = DAG.getEntryNode().getNode()->use_end();
3451  U != UE; ++U)
3452  if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3453  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3454  if (FI->getIndex() < 0) {
3455  int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3456  int64_t InLastByte = InFirstByte;
3457  InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3458 
3459  if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3460  (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3461  ArgChains.push_back(SDValue(L, 1));
3462  }
3463 
3464  // Build a tokenfactor for all the chains.
3465  return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3466 }
3467 
3468 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3469  bool TailCallOpt) const {
3470  return CallCC == CallingConv::Fast && TailCallOpt;
3471 }
3472 
3473 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3474 /// and add input and output parameter nodes.
3475 SDValue
3476 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3477  SmallVectorImpl<SDValue> &InVals) const {
3478  SelectionDAG &DAG = CLI.DAG;
3479  SDLoc &DL = CLI.DL;
3480  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3481  SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3482  SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3483  SDValue Chain = CLI.Chain;
3484  SDValue Callee = CLI.Callee;
3485  bool &IsTailCall = CLI.IsTailCall;
3486  CallingConv::ID CallConv = CLI.CallConv;
3487  bool IsVarArg = CLI.IsVarArg;
3488 
3489  MachineFunction &MF = DAG.getMachineFunction();
3490  bool IsThisReturn = false;
3491 
3493  bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3494  bool IsSibCall = false;
3495 
3496  if (IsTailCall) {
3497  // Check if it's really possible to do a tail call.
3498  IsTailCall = isEligibleForTailCallOptimization(
3499  Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3500  if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3501  report_fatal_error("failed to perform tail call elimination on a call "
3502  "site marked musttail");
3503 
3504  // A sibling call is one where we're under the usual C ABI and not planning
3505  // to change that but can still do a tail call:
3506  if (!TailCallOpt && IsTailCall)
3507  IsSibCall = true;
3508 
3509  if (IsTailCall)
3510  ++NumTailCalls;
3511  }
3512 
3513  // Analyze operands of the call, assigning locations to each operand.
3515  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3516  *DAG.getContext());
3517 
3518  if (IsVarArg) {
3519  // Handle fixed and variable vector arguments differently.
3520  // Variable vector arguments always go into memory.
3521  unsigned NumArgs = Outs.size();
3522 
3523  for (unsigned i = 0; i != NumArgs; ++i) {
3524  MVT ArgVT = Outs[i].VT;
3525  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3526  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3527  /*IsVarArg=*/ !Outs[i].IsFixed);
3528  bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3529  assert(!Res && "Call operand has unhandled type");
3530  (void)Res;
3531  }
3532  } else {
3533  // At this point, Outs[].VT may already be promoted to i32. To correctly
3534  // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3535  // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3536  // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3537  // we use a special version of AnalyzeCallOperands to pass in ValVT and
3538  // LocVT.
3539  unsigned NumArgs = Outs.size();
3540  for (unsigned i = 0; i != NumArgs; ++i) {
3541  MVT ValVT = Outs[i].VT;
3542  // Get type of the original argument.
3543  EVT ActualVT = getValueType(DAG.getDataLayout(),
3544  CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3545  /*AllowUnknown*/ true);
3546  MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3547  ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3548  // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3549  if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3550  ValVT = MVT::i8;
3551  else if (ActualMVT == MVT::i16)
3552  ValVT = MVT::i16;
3553 
3554  CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3555  bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3556  assert(!Res && "Call operand has unhandled type");
3557  (void)Res;
3558  }
3559  }
3560 
3561  // Get a count of how many bytes are to be pushed on the stack.
3562  unsigned NumBytes = CCInfo.getNextStackOffset();
3563 
3564  if (IsSibCall) {
3565  // Since we're not changing the ABI to make this a tail call, the memory
3566  // operands are already available in the caller's incoming argument space.
3567  NumBytes = 0;
3568  }
3569 
3570  // FPDiff is the byte offset of the call's argument area from the callee's.
3571  // Stores to callee stack arguments will be placed in FixedStackSlots offset
3572  // by this amount for a tail call. In a sibling call it must be 0 because the
3573  // caller will deallocate the entire stack and the callee still expects its
3574  // arguments to begin at SP+0. Completely unused for non-tail calls.
3575  int FPDiff = 0;
3576 
3577  if (IsTailCall && !IsSibCall) {
3578  unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3579 
3580  // Since callee will pop argument stack as a tail call, we must keep the
3581  // popped size 16-byte aligned.
3582  NumBytes = alignTo(NumBytes, 16);
3583 
3584  // FPDiff will be negative if this tail call requires more space than we
3585  // would automatically have in our incoming argument space. Positive if we
3586  // can actually shrink the stack.
3587  FPDiff = NumReusableBytes - NumBytes;
3588 
3589  // The stack pointer must be 16-byte aligned at all times it's used for a
3590  // memory operation, which in practice means at *all* times and in
3591  // particular across call boundaries. Therefore our own arguments started at
3592  // a 16-byte aligned SP and the delta applied for the tail call should
3593  // satisfy the same constraint.
3594  assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3595  }
3596 
3597  // Adjust the stack pointer for the new arguments...
3598  // These operations are automatically eliminated by the prolog/epilog pass
3599  if (!IsSibCall)
3600  Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3601 
3602  SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3603  getPointerTy(DAG.getDataLayout()));
3604 
3606  SmallVector<SDValue, 8> MemOpChains;
3607  auto PtrVT = getPointerTy(DAG.getDataLayout());
3608 
3609  // Walk the register/memloc assignments, inserting copies/loads.
3610  for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3611  ++i, ++realArgIdx) {
3612  CCValAssign &VA = ArgLocs[i];
3613  SDValue Arg = OutVals[realArgIdx];
3614  ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3615 
3616  // Promote the value if needed.
3617  switch (VA.getLocInfo()) {
3618  default:
3619  llvm_unreachable("Unknown loc info!");
3620  case CCValAssign::Full:
3621  break;
3622  case CCValAssign::SExt:
3623  Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3624  break;
3625  case CCValAssign::ZExt:
3626  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3627  break;
3628  case CCValAssign::AExt:
3629  if (Outs[realArgIdx].ArgVT == MVT::i1) {
3630  // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3631  Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3632  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3633  }
3634  Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3635  break;
3636  case CCValAssign::BCvt:
3637  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3638  break;
3639  case CCValAssign::FPExt:
3640  Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3641  break;
3642  }
3643 
3644  if (VA.isRegLoc()) {
3645  if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3646  Outs[0].VT == MVT::i64) {
3647  assert(VA.getLocVT() == MVT::i64 &&
3648  "unexpected calling convention register assignment");
3649  assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3650  "unexpected use of 'returned'");
3651  IsThisReturn = true;
3652  }
3653  RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3654  } else {
3655  assert(VA.isMemLoc());
3656 
3657  SDValue DstAddr;
3658  MachinePointerInfo DstInfo;
3659 
3660  // FIXME: This works on big-endian for composite byvals, which are the
3661  // common case. It should also work for fundamental types too.
3662  uint32_t BEAlign = 0;
3663  unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3664  : VA.getValVT().getSizeInBits();
3665  OpSize = (OpSize + 7) / 8;
3666  if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3667  !Flags.isInConsecutiveRegs()) {
3668  if (OpSize < 8)
3669  BEAlign = 8 - OpSize;
3670  }
3671  unsigned LocMemOffset = VA.getLocMemOffset();
3672  int32_t Offset = LocMemOffset + BEAlign;
3673  SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3674  PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3675 
3676  if (IsTailCall) {
3677  Offset = Offset + FPDiff;
3678  int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3679 
3680  DstAddr = DAG.getFrameIndex(FI, PtrVT);
3681  DstInfo =
3683 
3684  // Make sure any stack arguments overlapping with where we're storing
3685  // are loaded before this eventual operation. Otherwise they'll be
3686  // clobbered.
3687  Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3688  } else {
3689  SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3690 
3691  DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3693  LocMemOffset);
3694  }
3695 
3696  if (Outs[i].Flags.isByVal()) {
3697  SDValue SizeNode =
3698  DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3699  SDValue Cpy = DAG.getMemcpy(
3700  Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3701  /*isVol = */ false, /*AlwaysInline = */ false,
3702  /*isTailCall = */ false,
3703  DstInfo, MachinePointerInfo());
3704 
3705  MemOpChains.push_back(Cpy);
3706  } else {
3707  // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3708  // promoted to a legal register type i32, we should truncate Arg back to
3709  // i1/i8/i16.
3710  if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3711  VA.getValVT() == MVT::i16)
3712  Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3713 
3714  SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3715  MemOpChains.push_back(Store);
3716  }
3717  }
3718  }
3719 
3720  if (!MemOpChains.empty())
3721  Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3722 
3723  // Build a sequence of copy-to-reg nodes chained together with token chain
3724  // and flag operands which copy the outgoing args into the appropriate regs.
3725  SDValue InFlag;
3726  for (auto &RegToPass : RegsToPass) {
3727  Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3728  RegToPass.second, InFlag);
3729  InFlag = Chain.getValue(1);
3730  }
3731 
3732  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3733  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3734  // node so that legalize doesn't hack it.
3735  if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3736  auto GV = G->getGlobal();
3737  if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3739  Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3740  Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3741  } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3742  assert(Subtarget->isTargetWindows() &&
3743  "Windows is the only supported COFF target");
3744  Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3745  } else {
3746  const GlobalValue *GV = G->getGlobal();
3747  Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3748  }
3749  } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3750  if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3751  Subtarget->isTargetMachO()) {
3752  const char *Sym = S->getSymbol();
3753  Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3754  Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3755  } else {
3756  const char *Sym = S->getSymbol();
3757  Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3758  }
3759  }
3760 
3761  // We don't usually want to end the call-sequence here because we would tidy
3762  // the frame up *after* the call, however in the ABI-changing tail-call case
3763  // we've carefully laid out the parameters so that when sp is reset they'll be
3764  // in the correct location.
3765  if (IsTailCall && !IsSibCall) {
3766  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3767  DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3768  InFlag = Chain.getValue(1);
3769  }
3770 
3771  std::vector<SDValue> Ops;
3772  Ops.push_back(Chain);
3773  Ops.push_back(Callee);
3774 
3775  if (IsTailCall) {
3776  // Each tail call may have to adjust the stack by a different amount, so
3777  // this information must travel along with the operation for eventual
3778  // consumption by emitEpilogue.
3779  Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3780  }
3781 
3782  // Add argument registers to the end of the list so that they are known live
3783  // into the call.
3784  for (auto &RegToPass : RegsToPass)
3785  Ops.push_back(DAG.getRegister(RegToPass.first,
3786  RegToPass.second.getValueType()));
3787 
3788  // Add a register mask operand representing the call-preserved registers.
3789  const uint32_t *Mask;
3790  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3791  if (IsThisReturn) {
3792  // For 'this' returns, use the X0-preserving mask if applicable
3793  Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3794  if (!Mask) {
3795  IsThisReturn = false;
3796  Mask = TRI->getCallPreservedMask(MF, CallConv);
3797  }
3798  } else
3799  Mask = TRI->getCallPreservedMask(MF, CallConv);
3800 
3801  if (Subtarget->hasCustomCallingConv())
3802  TRI->UpdateCustomCallPreservedMask(MF, &Mask);
3803 
3804  if (TRI->isAnyArgRegReserved(MF))
3805  TRI->emitReservedArgRegCallError(MF);
3806 
3807  assert(Mask && "Missing call preserved mask for calling convention");
3808  Ops.push_back(DAG.getRegisterMask(Mask));
3809 
3810  if (InFlag.getNode())
3811  Ops.push_back(InFlag);
3812 
3813  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3814 
3815  // If we're doing a tall call, use a TC_RETURN here rather than an
3816  // actual call instruction.
3817  if (IsTailCall) {
3819  return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3820  }
3821 
3822  // Returns a chain and a flag for retval copy to use.
3823  Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3824  InFlag = Chain.getValue(1);
3825 
3826  uint64_t CalleePopBytes =
3827  DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3828 
3829  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3830  DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3831  InFlag, DL);
3832  if (!Ins.empty())
3833  InFlag = Chain.getValue(1);
3834 
3835  // Handle result values, copying them out of physregs into vregs that we
3836  // return.
3837  return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3838  InVals, IsThisReturn,
3839  IsThisReturn ? OutVals[0] : SDValue());
3840 }
3841 
3842 bool AArch64TargetLowering::CanLowerReturn(
3843  CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3844  const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3845  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3846  ? RetCC_AArch64_WebKit_JS
3847  : RetCC_AArch64_AAPCS;
3849  CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3850  return CCInfo.CheckReturn(Outs, RetCC);
3851 }
3852 
3853 SDValue
3854 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3855  bool isVarArg,
3856  const SmallVectorImpl<ISD::OutputArg> &Outs,
3857  const SmallVectorImpl<SDValue> &OutVals,
3858  const SDLoc &DL, SelectionDAG &DAG) const {
3859  CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3860  ? RetCC_AArch64_WebKit_JS
3861  : RetCC_AArch64_AAPCS;
3863  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3864  *DAG.getContext());
3865  CCInfo.AnalyzeReturn(Outs, RetCC);
3866 
3867  // Copy the result values into the output registers.
3868  SDValue Flag;
3869  SmallVector<SDValue, 4> RetOps(1, Chain);
3870  for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3871  ++i, ++realRVLocIdx) {
3872  CCValAssign &VA = RVLocs[i];
3873  assert(VA.isRegLoc() && "Can only return in registers!");
3874  SDValue Arg = OutVals[realRVLocIdx];
3875 
3876  switch (VA.getLocInfo()) {
3877  default:
3878  llvm_unreachable("Unknown loc info!");
3879  case CCValAssign::Full:
3880  if (Outs[i].ArgVT == MVT::i1) {
3881  // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3882  // value. This is strictly redundant on Darwin (which uses "zeroext
3883  // i1"), but will be optimised out before ISel.
3884  Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3885  Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3886  }
3887  break;
3888  case CCValAssign::BCvt:
3889  Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3890  break;
3891  }
3892 
3893  Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3894  Flag = Chain.getValue(1);
3895  RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3896  }
3897  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3898  const MCPhysReg *I =
3900  if (I) {
3901  for (; *I; ++I) {
3902  if (AArch64::GPR64RegClass.contains(*I))
3903  RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3904  else if (AArch64::FPR64RegClass.contains(*I))
3905  RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3906  else
3907  llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3908  }
3909  }
3910 
3911  RetOps[0] = Chain; // Update chain.
3912 
3913  // Add the flag if we have it.
3914  if (Flag.getNode())
3915  RetOps.push_back(Flag);
3916 
3917  return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3918 }
3919 
3920 //===----------------------------------------------------------------------===//
3921 // Other Lowering Code
3922 //===----------------------------------------------------------------------===//
3923 
3924 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3925  SelectionDAG &DAG,
3926  unsigned Flag) const {
3927  return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
3928  N->getOffset(), Flag);
3929 }
3930 
3931 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3932  SelectionDAG &DAG,
3933  unsigned Flag) const {
3934  return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3935 }
3936 
3937 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3938  SelectionDAG &DAG,
3939  unsigned Flag) const {
3940  return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3941  N->getOffset(), Flag);
3942 }
3943 
3944 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3945  SelectionDAG &DAG,
3946  unsigned Flag) const {
3947  return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3948 }
3949 
3950 // (loadGOT sym)
3951 template <class NodeTy>
3952 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3953  unsigned Flags) const {
3954  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3955  SDLoc DL(N);
3956  EVT Ty = getPointerTy(DAG.getDataLayout());
3957  SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
3958  // FIXME: Once remat is capable of dealing with instructions with register
3959  // operands, expand this into two nodes instead of using a wrapper node.
3960  return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3961 }
3962 
3963 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3964 template <class NodeTy>
3965 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3966  unsigned Flags) const {
3967  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3968  SDLoc DL(N);
3969  EVT Ty = getPointerTy(DAG.getDataLayout());
3970  const unsigned char MO_NC = AArch64II::MO_NC;
3971  return DAG.getNode(
3972  AArch64ISD::WrapperLarge, DL, Ty,
3973  getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3974  getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3975  getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3976  getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
3977 }
3978 
3979 // (addlow (adrp %hi(sym)) %lo(sym))
3980 template <class NodeTy>
3981 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3982  unsigned Flags) const {
3983  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3984  SDLoc DL(N);
3985  EVT Ty = getPointerTy(DAG.getDataLayout());
3986  SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
3987  SDValue Lo = getTargetNode(N, Ty, DAG,
3989  SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3990  return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3991 }
3992 
3993 // (adr sym)
3994 template <class NodeTy>
3995 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
3996  unsigned Flags) const {
3997  LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
3998  SDLoc DL(N);
3999  EVT Ty = getPointerTy(DAG.getDataLayout());
4000  SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
4001  return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
4002 }
4003 
4004 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
4005  SelectionDAG &DAG) const {
4006  GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
4007  const GlobalValue *GV = GN->getGlobal();
4008  unsigned char OpFlags =
4009  Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4010 
4011  if (OpFlags != AArch64II::MO_NO_FLAG)
4012  assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
4013  "unexpected offset in global node");
4014 
4015  // This also catches the large code model case for Darwin, and tiny code
4016  // model with got relocations.
4017  if ((OpFlags & AArch64II::MO_GOT) != 0) {
4018  return getGOT(GN, DAG, OpFlags);
4019  }
4020 
4021  SDValue Result;
4022  if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4023  Result = getAddrLarge(GN, DAG, OpFlags);
4024  } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
4025  Result = getAddrTiny(GN, DAG, OpFlags);
4026  } else {
4027  Result = getAddr(GN, DAG, OpFlags);
4028  }
4029  EVT PtrVT = getPointerTy(DAG.getDataLayout());
4030  SDLoc DL(GN);
4032  Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
4034  return Result;
4035 }
4036 
4037 /// Convert a TLS address reference into the correct sequence of loads
4038 /// and calls to compute the variable's address (for Darwin, currently) and
4039 /// return an SDValue containing the final node.
4040 
4041 /// Darwin only has one TLS scheme which must be capable of dealing with the
4042 /// fully general situation, in the worst case. This means:
4043 /// + "extern __thread" declaration.
4044 /// + Defined in a possibly unknown dynamic library.
4045 ///
4046 /// The general system is that each __thread variable has a [3 x i64] descriptor
4047 /// which contains information used by the runtime to calculate the address. The
4048 /// only part of this the compiler needs to know about is the first xword, which
4049 /// contains a function pointer that must be called with the address of the
4050 /// entire descriptor in "x0".
4051 ///
4052 /// Since this descriptor may be in a different unit, in general even the
4053 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4054 /// is:
4055 /// adrp x0, _var@TLVPPAGE
4056 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4057 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4058 /// ; the function pointer
4059 /// blr x1 ; Uses descriptor address in x0
4060 /// ; Address of _var is now in x0.
4061 ///
4062 /// If the address of _var's descriptor *is* known to the linker, then it can
4063 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4064 /// a slight efficiency gain.
4065 SDValue
4066 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
4067  SelectionDAG &DAG) const {
4068  assert(Subtarget->isTargetDarwin() &&
4069  "This function expects a Darwin target");
4070 
4071  SDLoc DL(Op);
4072  MVT PtrVT = getPointerTy(DAG.getDataLayout());
4073  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4074 
4075  SDValue TLVPAddr =
4076  DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
4077  SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
4078 
4079  // The first entry in the descriptor is a function pointer that we must call
4080  // to obtain the address of the variable.
4081  SDValue Chain = DAG.getEntryNode();
4082  SDValue FuncTLVGet = DAG.getLoad(
4083  MVT::i64, DL, Chain, DescAddr,
4085  /* Alignment = */ 8,
4088  Chain = FuncTLVGet.getValue(1);
4089 
4091  MFI.setAdjustsStack(true);
4092 
4093  // TLS calls preserve all registers except those that absolutely must be
4094  // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4095  // silly).
4096  const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
4097  const uint32_t *Mask = TRI->getTLSCallPreservedMask();