LLVM  7.0.0svn
PPCISelLowering.cpp
Go to the documentation of this file.
1 //===-- PPCISelLowering.cpp - PPC 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 PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCExpr.h"
74 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/Format.h"
84 #include "llvm/Support/KnownBits.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
115 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
116 
117 STATISTIC(NumTailCalls, "Number of tail calls");
118 STATISTIC(NumSiblingCalls, "Number of sibling calls");
119 
120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
121 
122 // FIXME: Remove this once the bug has been fixed!
124 
126  const PPCSubtarget &STI)
127  : TargetLowering(TM), Subtarget(STI) {
128  // Use _setjmp/_longjmp instead of setjmp/longjmp.
131 
132  // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
133  // arguments are at least 4/8 bytes aligned.
134  bool isPPC64 = Subtarget.isPPC64();
135  setMinStackArgumentAlignment(isPPC64 ? 8:4);
136 
137  // Set up the register classes.
138  addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
139  if (!useSoftFloat()) {
140  if (hasSPE()) {
141  addRegisterClass(MVT::f32, &PPC::SPE4RCRegClass);
142  addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
143  } else {
144  addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
145  addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
146  }
147  }
148 
149  // Match BITREVERSE to customized fast code sequence in the td file.
152 
153  // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
155 
156  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
157  for (MVT VT : MVT::integer_valuetypes()) {
160  }
161 
163 
164  // PowerPC has pre-inc load and store's.
175  if (!Subtarget.hasSPE()) {
180  }
181 
182  // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
183  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
184  for (MVT VT : ScalarIntVTs) {
189  }
190 
191  if (Subtarget.useCRBits()) {
193 
194  if (isPPC64 || Subtarget.hasFPCVT()) {
197  isPPC64 ? MVT::i64 : MVT::i32);
200  isPPC64 ? MVT::i64 : MVT::i32);
201  } else {
204  }
205 
206  // PowerPC does not support direct load/store of condition registers.
209 
210  // FIXME: Remove this once the ANDI glue bug is fixed:
211  if (ANDIGlueBug)
213 
214  for (MVT VT : MVT::integer_valuetypes()) {
218  }
219 
220  addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
221  }
222 
223  // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
224  // PPC (the libcall is not available).
227 
228  // We do not currently implement these libm ops for PowerPC.
235 
236  // PowerPC has no SREM/UREM instructions unless we are on P9
237  // On P9 we may use a hardware instruction to compute the remainder.
238  // The instructions are not legalized directly because in the cases where the
239  // result of both the remainder and the division is required it is more
240  // efficient to compute the remainder from the result of the division rather
241  // than use the remainder instruction.
242  if (Subtarget.isISA3_0()) {
245  setOperationAction(ISD::SREM, MVT::i64, Custom);
246  setOperationAction(ISD::UREM, MVT::i64, Custom);
247  } else {
250  setOperationAction(ISD::SREM, MVT::i64, Expand);
251  setOperationAction(ISD::UREM, MVT::i64, Expand);
252  }
253 
254  if (Subtarget.hasP9Vector()) {
258  }
259 
260  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
269 
270  // We don't support sin/cos/sqrt/fmod/pow
281  if (Subtarget.hasSPE()) {
284  } else {
287  }
288 
290 
291  // If we're enabling GP optimizations, use hardware square root
292  if (!Subtarget.hasFSQRT() &&
293  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
294  Subtarget.hasFRE()))
296 
297  if (!Subtarget.hasFSQRT() &&
298  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
299  Subtarget.hasFRES()))
301 
302  if (Subtarget.hasFCPSGN()) {
305  } else {
308  }
309 
310  if (Subtarget.hasFPRND()) {
315 
320  }
321 
322  // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
323  // to speed up scalar BSWAP64.
324  // CTPOP or CTTZ were introduced in P8/P9 respectively
326  if (Subtarget.isISA3_0()) {
327  setOperationAction(ISD::BSWAP, MVT::i64 , Custom);
329  setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
330  } else {
331  setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
333  setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
334  }
335 
336  if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
338  setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
339  } else {
341  setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
342  }
343 
344  // PowerPC does not have ROTR
346  setOperationAction(ISD::ROTR, MVT::i64 , Expand);
347 
348  if (!Subtarget.useCRBits()) {
349  // PowerPC does not have Select
354  }
355 
356  // PowerPC wants to turn select_cc of FP into fsel when possible.
359 
360  // PowerPC wants to optimize integer setcc a bit
361  if (!Subtarget.useCRBits())
363 
364  // PowerPC does not have BRCOND which requires SetCC
365  if (!Subtarget.useCRBits())
367 
369 
370  if (Subtarget.hasSPE()) {
371  // SPE has built-in conversions
375  } else {
376  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
378 
379  // PowerPC does not have [U|S]INT_TO_FP
382  }
383 
384  if (Subtarget.hasDirectMove() && isPPC64) {
389  } else {
394  }
395 
396  // We cannot sextinreg(i1). Expand to shifts.
398 
399  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
400  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
401  // support continuation, user-level threading, and etc.. As a result, no
402  // other SjLj exception interfaces are implemented and please don't build
403  // your own exception handling based on them.
404  // LLVM/Clang supports zero-cost DWARF exception handling.
407 
408  // We want to legalize GlobalAddress and ConstantPool nodes into the
409  // appropriate instructions to materialize the address.
420 
421  // TRAP is legal.
423 
424  // TRAMPOLINE is custom lowered.
427 
428  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
430 
431  if (Subtarget.isSVR4ABI()) {
432  if (isPPC64) {
433  // VAARG always uses double-word chunks, so promote anything smaller.
435  AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
437  AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
443  } else {
444  // VAARG is custom lowered with the 32-bit SVR4 ABI.
447  }
448  } else
450 
451  if (Subtarget.isSVR4ABI() && !isPPC64)
452  // VACOPY is custom lowered with the 32-bit SVR4 ABI.
454  else
456 
457  // Use the default implementation.
467 
468  // We want to custom lower some of our intrinsics.
470 
471  // To handle counter-based loop conditions.
473 
478 
479  // Comparisons that require checking two conditions.
480  if (Subtarget.hasSPE()) {
485  }
498 
499  if (Subtarget.has64BitSupport()) {
500  // They also have instructions for converting between i64 and fp.
505  // This is just the low 32 bits of a (signed) fp->i64 conversion.
506  // We cannot do this with Promote because i64 is not a legal type.
508 
509  if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
511  } else {
512  // PowerPC does not have FP_TO_UINT on 32-bit implementations.
513  if (Subtarget.hasSPE())
515  else
517  }
518 
519  // With the instructions enabled under FPCVT, we can do everything.
520  if (Subtarget.hasFPCVT()) {
521  if (Subtarget.has64BitSupport()) {
526  }
527 
532  }
533 
534  if (Subtarget.use64BitRegs()) {
535  // 64-bit PowerPC implementations can support i64 types directly
536  addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
537  // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
539  // 64-bit PowerPC wants to expand i128 shifts itself.
543  } else {
544  // 32-bit PowerPC wants to expand i64 shifts itself.
548  }
549 
550  if (Subtarget.hasAltivec()) {
551  // First set operation action for all vector types to expand. Then we
552  // will selectively turn on ones that can be effectively codegen'd.
553  for (MVT VT : MVT::vector_valuetypes()) {
554  // add/sub are legal for all supported vector VT's.
557 
558  // Vector instructions introduced in P8
559  if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
562  }
563  else {
566  }
567 
568  // Vector instructions introduced in P9
569  if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
571  else
573 
574  // We promote all shuffles to v16i8.
577 
578  // We promote all non-typed operations to v4i32.
593 
594  // No other operations are legal.
633 
634  for (MVT InnerVT : MVT::vector_valuetypes()) {
635  setTruncStoreAction(VT, InnerVT, Expand);
636  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
637  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
638  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
639  }
640  }
641 
642  // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
643  // with merges, splats, etc.
645 
651  Subtarget.useCRBits() ? Legal : Expand);
661 
662  addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
663  addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
664  addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
665  addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
666 
669 
670  if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
673  }
674 
675  if (Subtarget.hasP8Altivec())
677  else
679 
682 
685 
690 
691  // Altivec does not contain unordered floating-point compare instructions
696 
697  if (Subtarget.hasVSX()) {
700  if (Subtarget.hasP8Vector()) {
703  }
704  if (Subtarget.hasDirectMove() && isPPC64) {
713  }
715 
721 
723 
726 
729 
735 
736  // Share the Altivec comparison restrictions.
741 
744 
746 
747  if (Subtarget.hasP8Vector())
748  addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
749 
750  addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
751 
752  addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
753  addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
754  addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
755 
756  if (Subtarget.hasP8Altivec()) {
760 
761  // 128 bit shifts can be accomplished via 3 instructions for SHL and
762  // SRL, but not for SRA because of the instructions available:
763  // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
764  // doing
768 
770  }
771  else {
775 
777 
778  // VSX v2i64 only supports non-arithmetic operations.
781  }
782 
787 
789 
794 
795  // Vector operation legalization checks the result type of
796  // SIGN_EXTEND_INREG, overall legalization checks the inner type.
801 
806 
807  if (Subtarget.hasDirectMove())
810 
811  addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
812  }
813 
814  if (Subtarget.hasP8Altivec()) {
815  addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
816  addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
817  }
818 
819  if (Subtarget.hasP9Vector()) {
822 
823  // 128 bit shifts can be accomplished via 3 instructions for SHL and
824  // SRL, but not for SRA because of the instructions available:
825  // VS{RL} and VS{RL}O.
829 
830  if (EnableQuadPrecision) {
831  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
837  // No extending loads to f128 on PPC.
838  for (MVT FPT : MVT::fp_valuetypes())
847 
854 
861  // No implementation for these ops for PowerPC.
867  }
868 
869  }
870 
871  if (Subtarget.hasP9Altivec()) {
874  }
875  }
876 
877  if (Subtarget.hasQPX()) {
882 
885 
888 
891 
892  if (!Subtarget.useCRBits())
895 
903 
906 
910 
921 
924 
927 
928  addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
929 
934 
937 
940 
941  if (!Subtarget.useCRBits())
944 
952 
955 
966 
969 
972 
973  addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
974 
978 
979  if (!Subtarget.useCRBits())
982 
985 
993 
996 
997  addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
998 
1003 
1008 
1011 
1012  // These need to set FE_INEXACT, and so cannot be vectorized here.
1015 
1016  if (TM.Options.UnsafeFPMath) {
1019 
1022  } else {
1025 
1028  }
1029  }
1030 
1031  if (Subtarget.has64BitSupport())
1033 
1034  setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1035 
1036  if (!isPPC64) {
1039  }
1040 
1042 
1043  if (Subtarget.hasAltivec()) {
1044  // Altivec instructions set fields to all zeros or all ones.
1046  }
1047 
1048  if (!isPPC64) {
1049  // These libcalls are not available in 32-bit.
1050  setLibcallName(RTLIB::SHL_I128, nullptr);
1051  setLibcallName(RTLIB::SRL_I128, nullptr);
1052  setLibcallName(RTLIB::SRA_I128, nullptr);
1053  }
1054 
1055  setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1056 
1057  // We have target-specific dag combine patterns for the following nodes:
1063  if (Subtarget.hasFPCVT())
1068  if (Subtarget.useCRBits())
1074 
1078 
1079  if (Subtarget.useCRBits()) {
1083  }
1084 
1085  // Use reciprocal estimates.
1086  if (TM.Options.UnsafeFPMath) {
1089  }
1090 
1091  // Darwin long double math library functions have $LDBL128 appended.
1092  if (Subtarget.isDarwin()) {
1093  setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1094  setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1095  setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1096  setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1097  setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1098  setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1099  setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1100  setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1101  setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1102  setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1103  }
1104 
1105  if (EnableQuadPrecision) {
1106  setLibcallName(RTLIB::LOG_F128, "logf128");
1107  setLibcallName(RTLIB::LOG2_F128, "log2f128");
1108  setLibcallName(RTLIB::LOG10_F128, "log10f128");
1109  setLibcallName(RTLIB::EXP_F128, "expf128");
1110  setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1111  setLibcallName(RTLIB::SIN_F128, "sinf128");
1112  setLibcallName(RTLIB::COS_F128, "cosf128");
1113  setLibcallName(RTLIB::POW_F128, "powf128");
1114  setLibcallName(RTLIB::FMIN_F128, "fminf128");
1115  setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1116  setLibcallName(RTLIB::POWI_F128, "__powikf2");
1117  setLibcallName(RTLIB::REM_F128, "fmodf128");
1118  }
1119 
1120  // With 32 condition bits, we don't need to sink (and duplicate) compares
1121  // aggressively in CodeGenPrep.
1122  if (Subtarget.useCRBits()) {
1125  }
1126 
1128  if (Subtarget.isDarwin())
1130 
1131  switch (Subtarget.getDarwinDirective()) {
1132  default: break;
1133  case PPC::DIR_970:
1134  case PPC::DIR_A2:
1135  case PPC::DIR_E500:
1136  case PPC::DIR_E500mc:
1137  case PPC::DIR_E5500:
1138  case PPC::DIR_PWR4:
1139  case PPC::DIR_PWR5:
1140  case PPC::DIR_PWR5X:
1141  case PPC::DIR_PWR6:
1142  case PPC::DIR_PWR6X:
1143  case PPC::DIR_PWR7:
1144  case PPC::DIR_PWR8:
1145  case PPC::DIR_PWR9:
1148  break;
1149  }
1150 
1151  if (Subtarget.enableMachineScheduler())
1153  else
1155 
1157 
1158  // The Freescale cores do better with aggressive inlining of memcpy and
1159  // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1160  if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1161  Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1162  MaxStoresPerMemset = 32;
1164  MaxStoresPerMemcpy = 32;
1166  MaxStoresPerMemmove = 32;
1168  } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1169  // The A2 also benefits from (very) aggressive inlining of memcpy and
1170  // friends. The overhead of a the function call, even when warm, can be
1171  // over one hundred cycles.
1172  MaxStoresPerMemset = 128;
1173  MaxStoresPerMemcpy = 128;
1174  MaxStoresPerMemmove = 128;
1175  MaxLoadsPerMemcmp = 128;
1176  } else {
1177  MaxLoadsPerMemcmp = 8;
1179  }
1180 }
1181 
1182 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1183 /// the desired ByVal argument alignment.
1184 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1185  unsigned MaxMaxAlign) {
1186  if (MaxAlign == MaxMaxAlign)
1187  return;
1188  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1189  if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1190  MaxAlign = 32;
1191  else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1192  MaxAlign = 16;
1193  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1194  unsigned EltAlign = 0;
1195  getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1196  if (EltAlign > MaxAlign)
1197  MaxAlign = EltAlign;
1198  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1199  for (auto *EltTy : STy->elements()) {
1200  unsigned EltAlign = 0;
1201  getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1202  if (EltAlign > MaxAlign)
1203  MaxAlign = EltAlign;
1204  if (MaxAlign == MaxMaxAlign)
1205  break;
1206  }
1207  }
1208 }
1209 
1210 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1211 /// function arguments in the caller parameter area.
1213  const DataLayout &DL) const {
1214  // Darwin passes everything on 4 byte boundary.
1215  if (Subtarget.isDarwin())
1216  return 4;
1217 
1218  // 16byte and wider vectors are passed on 16byte boundary.
1219  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1220  unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1221  if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1222  getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1223  return Align;
1224 }
1225 
1227  EVT VT) const {
1228  if (Subtarget.hasSPE() && VT == MVT::f64)
1229  return 2;
1230  return PPCTargetLowering::getNumRegisters(Context, VT);
1231 }
1232 
1234  EVT VT) const {
1235  if (Subtarget.hasSPE() && VT == MVT::f64)
1236  return MVT::i32;
1237  return PPCTargetLowering::getRegisterType(Context, VT);
1238 }
1239 
1241  return Subtarget.useSoftFloat();
1242 }
1243 
1245  return Subtarget.hasSPE();
1246 }
1247 
1248 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1249  switch ((PPCISD::NodeType)Opcode) {
1250  case PPCISD::FIRST_NUMBER: break;
1251  case PPCISD::FSEL: return "PPCISD::FSEL";
1252  case PPCISD::FCFID: return "PPCISD::FCFID";
1253  case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1254  case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1255  case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1256  case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1257  case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1258  case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1259  case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1261  return "PPCISD::FP_TO_UINT_IN_VSR,";
1263  return "PPCISD::FP_TO_SINT_IN_VSR";
1264  case PPCISD::FRE: return "PPCISD::FRE";
1265  case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1266  case PPCISD::STFIWX: return "PPCISD::STFIWX";
1267  case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
1268  case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
1269  case PPCISD::VPERM: return "PPCISD::VPERM";
1270  case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1271  case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1272  case PPCISD::XXREVERSE: return "PPCISD::XXREVERSE";
1273  case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1274  case PPCISD::VECSHL: return "PPCISD::VECSHL";
1275  case PPCISD::CMPB: return "PPCISD::CMPB";
1276  case PPCISD::Hi: return "PPCISD::Hi";
1277  case PPCISD::Lo: return "PPCISD::Lo";
1278  case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1279  case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1280  case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1281  case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1282  case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1283  case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1284  case PPCISD::SRL: return "PPCISD::SRL";
1285  case PPCISD::SRA: return "PPCISD::SRA";
1286  case PPCISD::SHL: return "PPCISD::SHL";
1287  case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1288  case PPCISD::CALL: return "PPCISD::CALL";
1289  case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1290  case PPCISD::MTCTR: return "PPCISD::MTCTR";
1291  case PPCISD::BCTRL: return "PPCISD::BCTRL";
1292  case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1293  case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1294  case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1295  case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1296  case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1297  case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1298  case PPCISD::MFVSR: return "PPCISD::MFVSR";
1299  case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1300  case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1301  case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1302  case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1303  case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT";
1304  case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT";
1305  case PPCISD::VCMP: return "PPCISD::VCMP";
1306  case PPCISD::VCMPo: return "PPCISD::VCMPo";
1307  case PPCISD::LBRX: return "PPCISD::LBRX";
1308  case PPCISD::STBRX: return "PPCISD::STBRX";
1309  case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1310  case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1311  case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1312  case PPCISD::STXSIX: return "PPCISD::STXSIX";
1313  case PPCISD::VEXTS: return "PPCISD::VEXTS";
1314  case PPCISD::SExtVElems: return "PPCISD::SExtVElems";
1315  case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1316  case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1318  return "PPCISD::ST_VSR_SCAL_INT";
1319  case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1320  case PPCISD::BDNZ: return "PPCISD::BDNZ";
1321  case PPCISD::BDZ: return "PPCISD::BDZ";
1322  case PPCISD::MFFS: return "PPCISD::MFFS";
1323  case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1324  case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1325  case PPCISD::CR6SET: return "PPCISD::CR6SET";
1326  case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1327  case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1328  case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1329  case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1330  case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1331  case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1332  case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1333  case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1334  case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1335  case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1336  case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1337  case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1338  case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1339  case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1340  case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1341  case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1342  case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1343  case PPCISD::SC: return "PPCISD::SC";
1344  case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1345  case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1346  case PPCISD::RFEBB: return "PPCISD::RFEBB";
1347  case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1348  case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1349  case PPCISD::QVFPERM: return "PPCISD::QVFPERM";
1350  case PPCISD::QVGPCI: return "PPCISD::QVGPCI";
1351  case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI";
1352  case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI";
1353  case PPCISD::QBFLT: return "PPCISD::QBFLT";
1354  case PPCISD::QVLFSb: return "PPCISD::QVLFSb";
1355  case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1356  }
1357  return nullptr;
1358 }
1359 
1361  EVT VT) const {
1362  if (!VT.isVector())
1363  return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1364 
1365  if (Subtarget.hasQPX())
1367 
1369 }
1370 
1372  assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1373  return true;
1374 }
1375 
1376 //===----------------------------------------------------------------------===//
1377 // Node matching predicates, for use by the tblgen matching code.
1378 //===----------------------------------------------------------------------===//
1379 
1380 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1382  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1383  return CFP->getValueAPF().isZero();
1384  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1385  // Maybe this has already been legalized into the constant pool?
1386  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1387  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1388  return CFP->getValueAPF().isZero();
1389  }
1390  return false;
1391 }
1392 
1393 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1394 /// true if Op is undef or if it matches the specified value.
1395 static bool isConstantOrUndef(int Op, int Val) {
1396  return Op < 0 || Op == Val;
1397 }
1398 
1399 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1400 /// VPKUHUM instruction.
1401 /// The ShuffleKind distinguishes between big-endian operations with
1402 /// two different inputs (0), either-endian operations with two identical
1403 /// inputs (1), and little-endian operations with two different inputs (2).
1404 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1406  SelectionDAG &DAG) {
1407  bool IsLE = DAG.getDataLayout().isLittleEndian();
1408  if (ShuffleKind == 0) {
1409  if (IsLE)
1410  return false;
1411  for (unsigned i = 0; i != 16; ++i)
1412  if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1413  return false;
1414  } else if (ShuffleKind == 2) {
1415  if (!IsLE)
1416  return false;
1417  for (unsigned i = 0; i != 16; ++i)
1418  if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1419  return false;
1420  } else if (ShuffleKind == 1) {
1421  unsigned j = IsLE ? 0 : 1;
1422  for (unsigned i = 0; i != 8; ++i)
1423  if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1424  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1425  return false;
1426  }
1427  return true;
1428 }
1429 
1430 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1431 /// VPKUWUM instruction.
1432 /// The ShuffleKind distinguishes between big-endian operations with
1433 /// two different inputs (0), either-endian operations with two identical
1434 /// inputs (1), and little-endian operations with two different inputs (2).
1435 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1437  SelectionDAG &DAG) {
1438  bool IsLE = DAG.getDataLayout().isLittleEndian();
1439  if (ShuffleKind == 0) {
1440  if (IsLE)
1441  return false;
1442  for (unsigned i = 0; i != 16; i += 2)
1443  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1444  !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1445  return false;
1446  } else if (ShuffleKind == 2) {
1447  if (!IsLE)
1448  return false;
1449  for (unsigned i = 0; i != 16; i += 2)
1450  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1451  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1452  return false;
1453  } else if (ShuffleKind == 1) {
1454  unsigned j = IsLE ? 0 : 2;
1455  for (unsigned i = 0; i != 8; i += 2)
1456  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1457  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1458  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1459  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1460  return false;
1461  }
1462  return true;
1463 }
1464 
1465 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1466 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1467 /// current subtarget.
1468 ///
1469 /// The ShuffleKind distinguishes between big-endian operations with
1470 /// two different inputs (0), either-endian operations with two identical
1471 /// inputs (1), and little-endian operations with two different inputs (2).
1472 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1474  SelectionDAG &DAG) {
1475  const PPCSubtarget& Subtarget =
1476  static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1477  if (!Subtarget.hasP8Vector())
1478  return false;
1479 
1480  bool IsLE = DAG.getDataLayout().isLittleEndian();
1481  if (ShuffleKind == 0) {
1482  if (IsLE)
1483  return false;
1484  for (unsigned i = 0; i != 16; i += 4)
1485  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1486  !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1487  !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1488  !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1489  return false;
1490  } else if (ShuffleKind == 2) {
1491  if (!IsLE)
1492  return false;
1493  for (unsigned i = 0; i != 16; i += 4)
1494  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1495  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1496  !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1497  !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1498  return false;
1499  } else if (ShuffleKind == 1) {
1500  unsigned j = IsLE ? 0 : 4;
1501  for (unsigned i = 0; i != 8; i += 4)
1502  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1503  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1504  !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1505  !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1506  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1507  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1508  !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1509  !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1510  return false;
1511  }
1512  return true;
1513 }
1514 
1515 /// isVMerge - Common function, used to match vmrg* shuffles.
1516 ///
1517 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1518  unsigned LHSStart, unsigned RHSStart) {
1519  if (N->getValueType(0) != MVT::v16i8)
1520  return false;
1521  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1522  "Unsupported merge size!");
1523 
1524  for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1525  for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1526  if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1527  LHSStart+j+i*UnitSize) ||
1528  !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1529  RHSStart+j+i*UnitSize))
1530  return false;
1531  }
1532  return true;
1533 }
1534 
1535 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1536 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1537 /// The ShuffleKind distinguishes between big-endian merges with two
1538 /// different inputs (0), either-endian merges with two identical inputs (1),
1539 /// and little-endian merges with two different inputs (2). For the latter,
1540 /// the input operands are swapped (see PPCInstrAltivec.td).
1542  unsigned ShuffleKind, SelectionDAG &DAG) {
1543  if (DAG.getDataLayout().isLittleEndian()) {
1544  if (ShuffleKind == 1) // unary
1545  return isVMerge(N, UnitSize, 0, 0);
1546  else if (ShuffleKind == 2) // swapped
1547  return isVMerge(N, UnitSize, 0, 16);
1548  else
1549  return false;
1550  } else {
1551  if (ShuffleKind == 1) // unary
1552  return isVMerge(N, UnitSize, 8, 8);
1553  else if (ShuffleKind == 0) // normal
1554  return isVMerge(N, UnitSize, 8, 24);
1555  else
1556  return false;
1557  }
1558 }
1559 
1560 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1561 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1562 /// The ShuffleKind distinguishes between big-endian merges with two
1563 /// different inputs (0), either-endian merges with two identical inputs (1),
1564 /// and little-endian merges with two different inputs (2). For the latter,
1565 /// the input operands are swapped (see PPCInstrAltivec.td).
1567  unsigned ShuffleKind, SelectionDAG &DAG) {
1568  if (DAG.getDataLayout().isLittleEndian()) {
1569  if (ShuffleKind == 1) // unary
1570  return isVMerge(N, UnitSize, 8, 8);
1571  else if (ShuffleKind == 2) // swapped
1572  return isVMerge(N, UnitSize, 8, 24);
1573  else
1574  return false;
1575  } else {
1576  if (ShuffleKind == 1) // unary
1577  return isVMerge(N, UnitSize, 0, 0);
1578  else if (ShuffleKind == 0) // normal
1579  return isVMerge(N, UnitSize, 0, 16);
1580  else
1581  return false;
1582  }
1583 }
1584 
1585 /**
1586  * Common function used to match vmrgew and vmrgow shuffles
1587  *
1588  * The indexOffset determines whether to look for even or odd words in
1589  * the shuffle mask. This is based on the of the endianness of the target
1590  * machine.
1591  * - Little Endian:
1592  * - Use offset of 0 to check for odd elements
1593  * - Use offset of 4 to check for even elements
1594  * - Big Endian:
1595  * - Use offset of 0 to check for even elements
1596  * - Use offset of 4 to check for odd elements
1597  * A detailed description of the vector element ordering for little endian and
1598  * big endian can be found at
1599  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1600  * Targeting your applications - what little endian and big endian IBM XL C/C++
1601  * compiler differences mean to you
1602  *
1603  * The mask to the shuffle vector instruction specifies the indices of the
1604  * elements from the two input vectors to place in the result. The elements are
1605  * numbered in array-access order, starting with the first vector. These vectors
1606  * are always of type v16i8, thus each vector will contain 16 elements of size
1607  * 8. More info on the shuffle vector can be found in the
1608  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1609  * Language Reference.
1610  *
1611  * The RHSStartValue indicates whether the same input vectors are used (unary)
1612  * or two different input vectors are used, based on the following:
1613  * - If the instruction uses the same vector for both inputs, the range of the
1614  * indices will be 0 to 15. In this case, the RHSStart value passed should
1615  * be 0.
1616  * - If the instruction has two different vectors then the range of the
1617  * indices will be 0 to 31. In this case, the RHSStart value passed should
1618  * be 16 (indices 0-15 specify elements in the first vector while indices 16
1619  * to 31 specify elements in the second vector).
1620  *
1621  * \param[in] N The shuffle vector SD Node to analyze
1622  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1623  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1624  * vector to the shuffle_vector instruction
1625  * \return true iff this shuffle vector represents an even or odd word merge
1626  */
1627 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1628  unsigned RHSStartValue) {
1629  if (N->getValueType(0) != MVT::v16i8)
1630  return false;
1631 
1632  for (unsigned i = 0; i < 2; ++i)
1633  for (unsigned j = 0; j < 4; ++j)
1634  if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1635  i*RHSStartValue+j+IndexOffset) ||
1636  !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1637  i*RHSStartValue+j+IndexOffset+8))
1638  return false;
1639  return true;
1640 }
1641 
1642 /**
1643  * Determine if the specified shuffle mask is suitable for the vmrgew or
1644  * vmrgow instructions.
1645  *
1646  * \param[in] N The shuffle vector SD Node to analyze
1647  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1648  * \param[in] ShuffleKind Identify the type of merge:
1649  * - 0 = big-endian merge with two different inputs;
1650  * - 1 = either-endian merge with two identical inputs;
1651  * - 2 = little-endian merge with two different inputs (inputs are swapped for
1652  * little-endian merges).
1653  * \param[in] DAG The current SelectionDAG
1654  * \return true iff this shuffle mask
1655  */
1657  unsigned ShuffleKind, SelectionDAG &DAG) {
1658  if (DAG.getDataLayout().isLittleEndian()) {
1659  unsigned indexOffset = CheckEven ? 4 : 0;
1660  if (ShuffleKind == 1) // Unary
1661  return isVMerge(N, indexOffset, 0);
1662  else if (ShuffleKind == 2) // swapped
1663  return isVMerge(N, indexOffset, 16);
1664  else
1665  return false;
1666  }
1667  else {
1668  unsigned indexOffset = CheckEven ? 0 : 4;
1669  if (ShuffleKind == 1) // Unary
1670  return isVMerge(N, indexOffset, 0);
1671  else if (ShuffleKind == 0) // Normal
1672  return isVMerge(N, indexOffset, 16);
1673  else
1674  return false;
1675  }
1676  return false;
1677 }
1678 
1679 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1680 /// amount, otherwise return -1.
1681 /// The ShuffleKind distinguishes between big-endian operations with two
1682 /// different inputs (0), either-endian operations with two identical inputs
1683 /// (1), and little-endian operations with two different inputs (2). For the
1684 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1685 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1686  SelectionDAG &DAG) {
1687  if (N->getValueType(0) != MVT::v16i8)
1688  return -1;
1689 
1690  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1691 
1692  // Find the first non-undef value in the shuffle mask.
1693  unsigned i;
1694  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1695  /*search*/;
1696 
1697  if (i == 16) return -1; // all undef.
1698 
1699  // Otherwise, check to see if the rest of the elements are consecutively
1700  // numbered from this value.
1701  unsigned ShiftAmt = SVOp->getMaskElt(i);
1702  if (ShiftAmt < i) return -1;
1703 
1704  ShiftAmt -= i;
1705  bool isLE = DAG.getDataLayout().isLittleEndian();
1706 
1707  if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1708  // Check the rest of the elements to see if they are consecutive.
1709  for (++i; i != 16; ++i)
1710  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1711  return -1;
1712  } else if (ShuffleKind == 1) {
1713  // Check the rest of the elements to see if they are consecutive.
1714  for (++i; i != 16; ++i)
1715  if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1716  return -1;
1717  } else
1718  return -1;
1719 
1720  if (isLE)
1721  ShiftAmt = 16 - ShiftAmt;
1722 
1723  return ShiftAmt;
1724 }
1725 
1726 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1727 /// specifies a splat of a single element that is suitable for input to
1728 /// VSPLTB/VSPLTH/VSPLTW.
1730  assert(N->getValueType(0) == MVT::v16i8 &&
1731  (EltSize == 1 || EltSize == 2 || EltSize == 4));
1732 
1733  // The consecutive indices need to specify an element, not part of two
1734  // different elements. So abandon ship early if this isn't the case.
1735  if (N->getMaskElt(0) % EltSize != 0)
1736  return false;
1737 
1738  // This is a splat operation if each element of the permute is the same, and
1739  // if the value doesn't reference the second vector.
1740  unsigned ElementBase = N->getMaskElt(0);
1741 
1742  // FIXME: Handle UNDEF elements too!
1743  if (ElementBase >= 16)
1744  return false;
1745 
1746  // Check that the indices are consecutive, in the case of a multi-byte element
1747  // splatted with a v16i8 mask.
1748  for (unsigned i = 1; i != EltSize; ++i)
1749  if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1750  return false;
1751 
1752  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1753  if (N->getMaskElt(i) < 0) continue;
1754  for (unsigned j = 0; j != EltSize; ++j)
1755  if (N->getMaskElt(i+j) != N->getMaskElt(j))
1756  return false;
1757  }
1758  return true;
1759 }
1760 
1761 /// Check that the mask is shuffling N byte elements. Within each N byte
1762 /// element of the mask, the indices could be either in increasing or
1763 /// decreasing order as long as they are consecutive.
1764 /// \param[in] N the shuffle vector SD Node to analyze
1765 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1766 /// Word/DoubleWord/QuadWord).
1767 /// \param[in] StepLen the delta indices number among the N byte element, if
1768 /// the mask is in increasing/decreasing order then it is 1/-1.
1769 /// \return true iff the mask is shuffling N byte elements.
1770 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1771  int StepLen) {
1772  assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1773  "Unexpected element width.");
1774  assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1775 
1776  unsigned NumOfElem = 16 / Width;
1777  unsigned MaskVal[16]; // Width is never greater than 16
1778  for (unsigned i = 0; i < NumOfElem; ++i) {
1779  MaskVal[0] = N->getMaskElt(i * Width);
1780  if ((StepLen == 1) && (MaskVal[0] % Width)) {
1781  return false;
1782  } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1783  return false;
1784  }
1785 
1786  for (unsigned int j = 1; j < Width; ++j) {
1787  MaskVal[j] = N->getMaskElt(i * Width + j);
1788  if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1789  return false;
1790  }
1791  }
1792  }
1793 
1794  return true;
1795 }
1796 
1797 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1798  unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1799  if (!isNByteElemShuffleMask(N, 4, 1))
1800  return false;
1801 
1802  // Now we look at mask elements 0,4,8,12
1803  unsigned M0 = N->getMaskElt(0) / 4;
1804  unsigned M1 = N->getMaskElt(4) / 4;
1805  unsigned M2 = N->getMaskElt(8) / 4;
1806  unsigned M3 = N->getMaskElt(12) / 4;
1807  unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1808  unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1809 
1810  // Below, let H and L be arbitrary elements of the shuffle mask
1811  // where H is in the range [4,7] and L is in the range [0,3].
1812  // H, 1, 2, 3 or L, 5, 6, 7
1813  if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1814  (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1815  ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1816  InsertAtByte = IsLE ? 12 : 0;
1817  Swap = M0 < 4;
1818  return true;
1819  }
1820  // 0, H, 2, 3 or 4, L, 6, 7
1821  if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1822  (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1823  ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1824  InsertAtByte = IsLE ? 8 : 4;
1825  Swap = M1 < 4;
1826  return true;
1827  }
1828  // 0, 1, H, 3 or 4, 5, L, 7
1829  if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1830  (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1831  ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1832  InsertAtByte = IsLE ? 4 : 8;
1833  Swap = M2 < 4;
1834  return true;
1835  }
1836  // 0, 1, 2, H or 4, 5, 6, L
1837  if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1838  (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1839  ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1840  InsertAtByte = IsLE ? 0 : 12;
1841  Swap = M3 < 4;
1842  return true;
1843  }
1844 
1845  // If both vector operands for the shuffle are the same vector, the mask will
1846  // contain only elements from the first one and the second one will be undef.
1847  if (N->getOperand(1).isUndef()) {
1848  ShiftElts = 0;
1849  Swap = true;
1850  unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1851  if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1852  InsertAtByte = IsLE ? 12 : 0;
1853  return true;
1854  }
1855  if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1856  InsertAtByte = IsLE ? 8 : 4;
1857  return true;
1858  }
1859  if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1860  InsertAtByte = IsLE ? 4 : 8;
1861  return true;
1862  }
1863  if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1864  InsertAtByte = IsLE ? 0 : 12;
1865  return true;
1866  }
1867  }
1868 
1869  return false;
1870 }
1871 
1873  bool &Swap, bool IsLE) {
1874  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1875  // Ensure each byte index of the word is consecutive.
1876  if (!isNByteElemShuffleMask(N, 4, 1))
1877  return false;
1878 
1879  // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1880  unsigned M0 = N->getMaskElt(0) / 4;
1881  unsigned M1 = N->getMaskElt(4) / 4;
1882  unsigned M2 = N->getMaskElt(8) / 4;
1883  unsigned M3 = N->getMaskElt(12) / 4;
1884 
1885  // If both vector operands for the shuffle are the same vector, the mask will
1886  // contain only elements from the first one and the second one will be undef.
1887  if (N->getOperand(1).isUndef()) {
1888  assert(M0 < 4 && "Indexing into an undef vector?");
1889  if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1890  return false;
1891 
1892  ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1893  Swap = false;
1894  return true;
1895  }
1896 
1897  // Ensure each word index of the ShuffleVector Mask is consecutive.
1898  if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1899  return false;
1900 
1901  if (IsLE) {
1902  if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1903  // Input vectors don't need to be swapped if the leading element
1904  // of the result is one of the 3 left elements of the second vector
1905  // (or if there is no shift to be done at all).
1906  Swap = false;
1907  ShiftElts = (8 - M0) % 8;
1908  } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1909  // Input vectors need to be swapped if the leading element
1910  // of the result is one of the 3 left elements of the first vector
1911  // (or if we're shifting by 4 - thereby simply swapping the vectors).
1912  Swap = true;
1913  ShiftElts = (4 - M0) % 4;
1914  }
1915 
1916  return true;
1917  } else { // BE
1918  if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1919  // Input vectors don't need to be swapped if the leading element
1920  // of the result is one of the 4 elements of the first vector.
1921  Swap = false;
1922  ShiftElts = M0;
1923  } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1924  // Input vectors need to be swapped if the leading element
1925  // of the result is one of the 4 elements of the right vector.
1926  Swap = true;
1927  ShiftElts = M0 - 4;
1928  }
1929 
1930  return true;
1931  }
1932 }
1933 
1935  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1936 
1937  if (!isNByteElemShuffleMask(N, Width, -1))
1938  return false;
1939 
1940  for (int i = 0; i < 16; i += Width)
1941  if (N->getMaskElt(i) != i + Width - 1)
1942  return false;
1943 
1944  return true;
1945 }
1946 
1948  return isXXBRShuffleMaskHelper(N, 2);
1949 }
1950 
1952  return isXXBRShuffleMaskHelper(N, 4);
1953 }
1954 
1956  return isXXBRShuffleMaskHelper(N, 8);
1957 }
1958 
1960  return isXXBRShuffleMaskHelper(N, 16);
1961 }
1962 
1963 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1964 /// if the inputs to the instruction should be swapped and set \p DM to the
1965 /// value for the immediate.
1966 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1967 /// AND element 0 of the result comes from the first input (LE) or second input
1968 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1969 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1970 /// mask.
1972  bool &Swap, bool IsLE) {
1973  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1974 
1975  // Ensure each byte index of the double word is consecutive.
1976  if (!isNByteElemShuffleMask(N, 8, 1))
1977  return false;
1978 
1979  unsigned M0 = N->getMaskElt(0) / 8;
1980  unsigned M1 = N->getMaskElt(8) / 8;
1981  assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1982 
1983  // If both vector operands for the shuffle are the same vector, the mask will
1984  // contain only elements from the first one and the second one will be undef.
1985  if (N->getOperand(1).isUndef()) {
1986  if ((M0 | M1) < 2) {
1987  DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1988  Swap = false;
1989  return true;
1990  } else
1991  return false;
1992  }
1993 
1994  if (IsLE) {
1995  if (M0 > 1 && M1 < 2) {
1996  Swap = false;
1997  } else if (M0 < 2 && M1 > 1) {
1998  M0 = (M0 + 2) % 4;
1999  M1 = (M1 + 2) % 4;
2000  Swap = true;
2001  } else
2002  return false;
2003 
2004  // Note: if control flow comes here that means Swap is already set above
2005  DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2006  return true;
2007  } else { // BE
2008  if (M0 < 2 && M1 > 1) {
2009  Swap = false;
2010  } else if (M0 > 1 && M1 < 2) {
2011  M0 = (M0 + 2) % 4;
2012  M1 = (M1 + 2) % 4;
2013  Swap = true;
2014  } else
2015  return false;
2016 
2017  // Note: if control flow comes here that means Swap is already set above
2018  DM = (M0 << 1) + (M1 & 1);
2019  return true;
2020  }
2021 }
2022 
2023 
2024 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
2025 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
2026 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
2027  SelectionDAG &DAG) {
2028  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2029  assert(isSplatShuffleMask(SVOp, EltSize));
2030  if (DAG.getDataLayout().isLittleEndian())
2031  return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2032  else
2033  return SVOp->getMaskElt(0) / EltSize;
2034 }
2035 
2036 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2037 /// by using a vspltis[bhw] instruction of the specified element size, return
2038 /// the constant being splatted. The ByteSize field indicates the number of
2039 /// bytes of each element [124] -> [bhw].
2040 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2041  SDValue OpVal(nullptr, 0);
2042 
2043  // If ByteSize of the splat is bigger than the element size of the
2044  // build_vector, then we have a case where we are checking for a splat where
2045  // multiple elements of the buildvector are folded together into a single
2046  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2047  unsigned EltSize = 16/N->getNumOperands();
2048  if (EltSize < ByteSize) {
2049  unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2050  SDValue UniquedVals[4];
2051  assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2052 
2053  // See if all of the elements in the buildvector agree across.
2054  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2055  if (N->getOperand(i).isUndef()) continue;
2056  // If the element isn't a constant, bail fully out.
2057  if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2058 
2059  if (!UniquedVals[i&(Multiple-1)].getNode())
2060  UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2061  else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2062  return SDValue(); // no match.
2063  }
2064 
2065  // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2066  // either constant or undef values that are identical for each chunk. See
2067  // if these chunks can form into a larger vspltis*.
2068 
2069  // Check to see if all of the leading entries are either 0 or -1. If
2070  // neither, then this won't fit into the immediate field.
2071  bool LeadingZero = true;
2072  bool LeadingOnes = true;
2073  for (unsigned i = 0; i != Multiple-1; ++i) {
2074  if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2075 
2076  LeadingZero &= isNullConstant(UniquedVals[i]);
2077  LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2078  }
2079  // Finally, check the least significant entry.
2080  if (LeadingZero) {
2081  if (!UniquedVals[Multiple-1].getNode())
2082  return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2083  int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2084  if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2085  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2086  }
2087  if (LeadingOnes) {
2088  if (!UniquedVals[Multiple-1].getNode())
2089  return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2090  int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2091  if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2092  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2093  }
2094 
2095  return SDValue();
2096  }
2097 
2098  // Check to see if this buildvec has a single non-undef value in its elements.
2099  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2100  if (N->getOperand(i).isUndef()) continue;
2101  if (!OpVal.getNode())
2102  OpVal = N->getOperand(i);
2103  else if (OpVal != N->getOperand(i))
2104  return SDValue();
2105  }
2106 
2107  if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2108 
2109  unsigned ValSizeInBytes = EltSize;
2110  uint64_t Value = 0;
2111  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2112  Value = CN->getZExtValue();
2113  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2114  assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2115  Value = FloatToBits(CN->getValueAPF().convertToFloat());
2116  }
2117 
2118  // If the splat value is larger than the element value, then we can never do
2119  // this splat. The only case that we could fit the replicated bits into our
2120  // immediate field for would be zero, and we prefer to use vxor for it.
2121  if (ValSizeInBytes < ByteSize) return SDValue();
2122 
2123  // If the element value is larger than the splat value, check if it consists
2124  // of a repeated bit pattern of size ByteSize.
2125  if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2126  return SDValue();
2127 
2128  // Properly sign extend the value.
2129  int MaskVal = SignExtend32(Value, ByteSize * 8);
2130 
2131  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2132  if (MaskVal == 0) return SDValue();
2133 
2134  // Finally, if this value fits in a 5 bit sext field, return it
2135  if (SignExtend32<5>(MaskVal) == MaskVal)
2136  return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2137  return SDValue();
2138 }
2139 
2140 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2141 /// amount, otherwise return -1.
2143  EVT VT = N->getValueType(0);
2144  if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2145  return -1;
2146 
2147  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2148 
2149  // Find the first non-undef value in the shuffle mask.
2150  unsigned i;
2151  for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2152  /*search*/;
2153 
2154  if (i == 4) return -1; // all undef.
2155 
2156  // Otherwise, check to see if the rest of the elements are consecutively
2157  // numbered from this value.
2158  unsigned ShiftAmt = SVOp->getMaskElt(i);
2159  if (ShiftAmt < i) return -1;
2160  ShiftAmt -= i;
2161 
2162  // Check the rest of the elements to see if they are consecutive.
2163  for (++i; i != 4; ++i)
2164  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2165  return -1;
2166 
2167  return ShiftAmt;
2168 }
2169 
2170 //===----------------------------------------------------------------------===//
2171 // Addressing Mode Selection
2172 //===----------------------------------------------------------------------===//
2173 
2174 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2175 /// or 64-bit immediate, and if the value can be accurately represented as a
2176 /// sign extension from a 16-bit value. If so, this returns true and the
2177 /// immediate.
2178 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2179  if (!isa<ConstantSDNode>(N))
2180  return false;
2181 
2182  Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2183  if (N->getValueType(0) == MVT::i32)
2184  return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2185  else
2186  return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2187 }
2188 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2189  return isIntS16Immediate(Op.getNode(), Imm);
2190 }
2191 
2192 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2193 /// can be represented as an indexed [r+r] operation. Returns false if it
2194 /// can be more efficiently represented with [r+imm].
2196  SDValue &Index,
2197  SelectionDAG &DAG) const {
2198  int16_t imm = 0;
2199  if (N.getOpcode() == ISD::ADD) {
2200  if (isIntS16Immediate(N.getOperand(1), imm))
2201  return false; // r+i
2202  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2203  return false; // r+i
2204 
2205  Base = N.getOperand(0);
2206  Index = N.getOperand(1);
2207  return true;
2208  } else if (N.getOpcode() == ISD::OR) {
2209  if (isIntS16Immediate(N.getOperand(1), imm))
2210  return false; // r+i can fold it if we can.
2211 
2212  // If this is an or of disjoint bitfields, we can codegen this as an add
2213  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2214  // disjoint.
2215  KnownBits LHSKnown, RHSKnown;
2216  DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2217 
2218  if (LHSKnown.Zero.getBoolValue()) {
2219  DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2220  // If all of the bits are known zero on the LHS or RHS, the add won't
2221  // carry.
2222  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2223  Base = N.getOperand(0);
2224  Index = N.getOperand(1);
2225  return true;
2226  }
2227  }
2228  }
2229 
2230  return false;
2231 }
2232 
2233 // If we happen to be doing an i64 load or store into a stack slot that has
2234 // less than a 4-byte alignment, then the frame-index elimination may need to
2235 // use an indexed load or store instruction (because the offset may not be a
2236 // multiple of 4). The extra register needed to hold the offset comes from the
2237 // register scavenger, and it is possible that the scavenger will need to use
2238 // an emergency spill slot. As a result, we need to make sure that a spill slot
2239 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2240 // stack slot.
2241 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2242  // FIXME: This does not handle the LWA case.
2243  if (VT != MVT::i64)
2244  return;
2245 
2246  // NOTE: We'll exclude negative FIs here, which come from argument
2247  // lowering, because there are no known test cases triggering this problem
2248  // using packed structures (or similar). We can remove this exclusion if
2249  // we find such a test case. The reason why this is so test-case driven is
2250  // because this entire 'fixup' is only to prevent crashes (from the
2251  // register scavenger) on not-really-valid inputs. For example, if we have:
2252  // %a = alloca i1
2253  // %b = bitcast i1* %a to i64*
2254  // store i64* a, i64 b
2255  // then the store should really be marked as 'align 1', but is not. If it
2256  // were marked as 'align 1' then the indexed form would have been
2257  // instruction-selected initially, and the problem this 'fixup' is preventing
2258  // won't happen regardless.
2259  if (FrameIdx < 0)
2260  return;
2261 
2262  MachineFunction &MF = DAG.getMachineFunction();
2263  MachineFrameInfo &MFI = MF.getFrameInfo();
2264 
2265  unsigned Align = MFI.getObjectAlignment(FrameIdx);
2266  if (Align >= 4)
2267  return;
2268 
2269  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2270  FuncInfo->setHasNonRISpills();
2271 }
2272 
2273 /// Returns true if the address N can be represented by a base register plus
2274 /// a signed 16-bit displacement [r+imm], and if it is not better
2275 /// represented as reg+reg. If \p Alignment is non-zero, only accept
2276 /// displacements that are multiples of that value.
2278  SDValue &Base,
2279  SelectionDAG &DAG,
2280  unsigned Alignment) const {
2281  // FIXME dl should come from parent load or store, not from address
2282  SDLoc dl(N);
2283  // If this can be more profitably realized as r+r, fail.
2284  if (SelectAddressRegReg(N, Disp, Base, DAG))
2285  return false;
2286 
2287  if (N.getOpcode() == ISD::ADD) {
2288  int16_t imm = 0;
2289  if (isIntS16Immediate(N.getOperand(1), imm) &&
2290  (!Alignment || (imm % Alignment) == 0)) {
2291  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2292  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2293  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2294  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2295  } else {
2296  Base = N.getOperand(0);
2297  }
2298  return true; // [r+i]
2299  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2300  // Match LOAD (ADD (X, Lo(G))).
2301  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2302  && "Cannot handle constant offsets yet!");
2303  Disp = N.getOperand(1).getOperand(0); // The global address.
2304  assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2305  Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2306  Disp.getOpcode() == ISD::TargetConstantPool ||
2307  Disp.getOpcode() == ISD::TargetJumpTable);
2308  Base = N.getOperand(0);
2309  return true; // [&g+r]
2310  }
2311  } else if (N.getOpcode() == ISD::OR) {
2312  int16_t imm = 0;
2313  if (isIntS16Immediate(N.getOperand(1), imm) &&
2314  (!Alignment || (imm % Alignment) == 0)) {
2315  // If this is an or of disjoint bitfields, we can codegen this as an add
2316  // (for better address arithmetic) if the LHS and RHS of the OR are
2317  // provably disjoint.
2318  KnownBits LHSKnown;
2319  DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2320 
2321  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2322  // If all of the bits are known zero on the LHS or RHS, the add won't
2323  // carry.
2324  if (FrameIndexSDNode *FI =
2325  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2326  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2327  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2328  } else {
2329  Base = N.getOperand(0);
2330  }
2331  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2332  return true;
2333  }
2334  }
2335  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2336  // Loading from a constant address.
2337 
2338  // If this address fits entirely in a 16-bit sext immediate field, codegen
2339  // this as "d, 0"
2340  int16_t Imm;
2341  if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2342  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2343  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2344  CN->getValueType(0));
2345  return true;
2346  }
2347 
2348  // Handle 32-bit sext immediates with LIS + addr mode.
2349  if ((CN->getValueType(0) == MVT::i32 ||
2350  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2351  (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2352  int Addr = (int)CN->getZExtValue();
2353 
2354  // Otherwise, break this down into an LIS + disp.
2355  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2356 
2357  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2358  MVT::i32);
2359  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2360  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2361  return true;
2362  }
2363  }
2364 
2365  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2366  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2367  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2368  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2369  } else
2370  Base = N;
2371  return true; // [r+0]
2372 }
2373 
2374 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2375 /// represented as an indexed [r+r] operation.
2377  SDValue &Index,
2378  SelectionDAG &DAG) const {
2379  // Check to see if we can easily represent this as an [r+r] address. This
2380  // will fail if it thinks that the address is more profitably represented as
2381  // reg+imm, e.g. where imm = 0.
2382  if (SelectAddressRegReg(N, Base, Index, DAG))
2383  return true;
2384 
2385  // If the address is the result of an add, we will utilize the fact that the
2386  // address calculation includes an implicit add. However, we can reduce
2387  // register pressure if we do not materialize a constant just for use as the
2388  // index register. We only get rid of the add if it is not an add of a
2389  // value and a 16-bit signed constant and both have a single use.
2390  int16_t imm = 0;
2391  if (N.getOpcode() == ISD::ADD &&
2392  (!isIntS16Immediate(N.getOperand(1), imm) ||
2393  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2394  Base = N.getOperand(0);
2395  Index = N.getOperand(1);
2396  return true;
2397  }
2398 
2399  // Otherwise, do it the hard way, using R0 as the base register.
2400  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2401  N.getValueType());
2402  Index = N;
2403  return true;
2404 }
2405 
2406 /// getPreIndexedAddressParts - returns true by value, base pointer and
2407 /// offset pointer and addressing mode by reference if the node's address
2408 /// can be legally represented as pre-indexed load / store address.
2410  SDValue &Offset,
2411  ISD::MemIndexedMode &AM,
2412  SelectionDAG &DAG) const {
2413  if (DisablePPCPreinc) return false;
2414 
2415  bool isLoad = true;
2416  SDValue Ptr;
2417  EVT VT;
2418  unsigned Alignment;
2419  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2420  Ptr = LD->getBasePtr();
2421  VT = LD->getMemoryVT();
2422  Alignment = LD->getAlignment();
2423  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2424  Ptr = ST->getBasePtr();
2425  VT = ST->getMemoryVT();
2426  Alignment = ST->getAlignment();
2427  isLoad = false;
2428  } else
2429  return false;
2430 
2431  // PowerPC doesn't have preinc load/store instructions for vectors (except
2432  // for QPX, which does have preinc r+r forms).
2433  if (VT.isVector()) {
2434  if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2435  return false;
2436  } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2437  AM = ISD::PRE_INC;
2438  return true;
2439  }
2440  }
2441 
2442  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2443  // Common code will reject creating a pre-inc form if the base pointer
2444  // is a frame index, or if N is a store and the base pointer is either
2445  // the same as or a predecessor of the value being stored. Check for
2446  // those situations here, and try with swapped Base/Offset instead.
2447  bool Swap = false;
2448 
2449  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2450  Swap = true;
2451  else if (!isLoad) {
2452  SDValue Val = cast<StoreSDNode>(N)->getValue();
2453  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2454  Swap = true;
2455  }
2456 
2457  if (Swap)
2458  std::swap(Base, Offset);
2459 
2460  AM = ISD::PRE_INC;
2461  return true;
2462  }
2463 
2464  // LDU/STU can only handle immediates that are a multiple of 4.
2465  if (VT != MVT::i64) {
2466  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2467  return false;
2468  } else {
2469  // LDU/STU need an address with at least 4-byte alignment.
2470  if (Alignment < 4)
2471  return false;
2472 
2473  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2474  return false;
2475  }
2476 
2477  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2478  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2479  // sext i32 to i64 when addr mode is r+i.
2480  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2481  LD->getExtensionType() == ISD::SEXTLOAD &&
2482  isa<ConstantSDNode>(Offset))
2483  return false;
2484  }
2485 
2486  AM = ISD::PRE_INC;
2487  return true;
2488 }
2489 
2490 //===----------------------------------------------------------------------===//
2491 // LowerOperation implementation
2492 //===----------------------------------------------------------------------===//
2493 
2494 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2495 /// and LoOpFlags to the target MO flags.
2496 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2497  unsigned &HiOpFlags, unsigned &LoOpFlags,
2498  const GlobalValue *GV = nullptr) {
2499  HiOpFlags = PPCII::MO_HA;
2500  LoOpFlags = PPCII::MO_LO;
2501 
2502  // Don't use the pic base if not in PIC relocation model.
2503  if (IsPIC) {
2504  HiOpFlags |= PPCII::MO_PIC_FLAG;
2505  LoOpFlags |= PPCII::MO_PIC_FLAG;
2506  }
2507 
2508  // If this is a reference to a global value that requires a non-lazy-ptr, make
2509  // sure that instruction lowering adds it.
2510  if (GV && Subtarget.hasLazyResolverStub(GV)) {
2511  HiOpFlags |= PPCII::MO_NLP_FLAG;
2512  LoOpFlags |= PPCII::MO_NLP_FLAG;
2513 
2514  if (GV->hasHiddenVisibility()) {
2515  HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2516  LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2517  }
2518  }
2519 }
2520 
2521 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2522  SelectionDAG &DAG) {
2523  SDLoc DL(HiPart);
2524  EVT PtrVT = HiPart.getValueType();
2525  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2526 
2527  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2528  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2529 
2530  // With PIC, the first instruction is actually "GR+hi(&G)".
2531  if (isPIC)
2532  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2533  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2534 
2535  // Generate non-pic code that has direct accesses to the constant pool.
2536  // The address of the global is just (hi(&g)+lo(&g)).
2537  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2538 }
2539 
2541  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2542  FuncInfo->setUsesTOCBasePtr();
2543 }
2544 
2545 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2547 }
2548 
2549 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2550  SDValue GA) {
2551  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2552  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2553  DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2554 
2555  SDValue Ops[] = { GA, Reg };
2556  return DAG.getMemIntrinsicNode(
2557  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2560 }
2561 
2562 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2563  SelectionDAG &DAG) const {
2564  EVT PtrVT = Op.getValueType();
2565  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2566  const Constant *C = CP->getConstVal();
2567 
2568  // 64-bit SVR4 ABI code is always position-independent.
2569  // The actual address of the GlobalValue is stored in the TOC.
2570  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2571  setUsesTOCBasePtr(DAG);
2572  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2573  return getTOCEntry(DAG, SDLoc(CP), true, GA);
2574  }
2575 
2576  unsigned MOHiFlag, MOLoFlag;
2577  bool IsPIC = isPositionIndependent();
2578  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2579 
2580  if (IsPIC && Subtarget.isSVR4ABI()) {
2581  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2583  return getTOCEntry(DAG, SDLoc(CP), false, GA);
2584  }
2585 
2586  SDValue CPIHi =
2587  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2588  SDValue CPILo =
2589  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2590  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2591 }
2592 
2593 // For 64-bit PowerPC, prefer the more compact relative encodings.
2594 // This trades 32 bits per jump table entry for one or two instructions
2595 // on the jump site.
2597  if (isJumpTableRelative())
2599 
2601 }
2602 
2604  if (Subtarget.isPPC64())
2605  return true;
2607 }
2608 
2610  SelectionDAG &DAG) const {
2611  if (!Subtarget.isPPC64())
2612  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2613 
2614  switch (getTargetMachine().getCodeModel()) {
2615  case CodeModel::Small:
2616  case CodeModel::Medium:
2617  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2618  default:
2619  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2620  getPointerTy(DAG.getDataLayout()));
2621  }
2622 }
2623 
2624 const MCExpr *
2626  unsigned JTI,
2627  MCContext &Ctx) const {
2628  if (!Subtarget.isPPC64())
2629  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2630 
2631  switch (getTargetMachine().getCodeModel()) {
2632  case CodeModel::Small:
2633  case CodeModel::Medium:
2634  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2635  default:
2636  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2637  }
2638 }
2639 
2640 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2641  EVT PtrVT = Op.getValueType();
2642  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2643 
2644  // 64-bit SVR4 ABI code is always position-independent.
2645  // The actual address of the GlobalValue is stored in the TOC.
2646  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2647  setUsesTOCBasePtr(DAG);
2648  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2649  return getTOCEntry(DAG, SDLoc(JT), true, GA);
2650  }
2651 
2652  unsigned MOHiFlag, MOLoFlag;
2653  bool IsPIC = isPositionIndependent();
2654  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2655 
2656  if (IsPIC && Subtarget.isSVR4ABI()) {
2657  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2659  return getTOCEntry(DAG, SDLoc(GA), false, GA);
2660  }
2661 
2662  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2663  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2664  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2665 }
2666 
2667 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2668  SelectionDAG &DAG) const {
2669  EVT PtrVT = Op.getValueType();
2670  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2671  const BlockAddress *BA = BASDN->getBlockAddress();
2672 
2673  // 64-bit SVR4 ABI code is always position-independent.
2674  // The actual BlockAddress is stored in the TOC.
2675  if (Subtarget.isSVR4ABI() && isPositionIndependent()) {
2676  if (Subtarget.isPPC64())
2677  setUsesTOCBasePtr(DAG);
2678  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2679  return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2680  }
2681 
2682  unsigned MOHiFlag, MOLoFlag;
2683  bool IsPIC = isPositionIndependent();
2684  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2685  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2686  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2687  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2688 }
2689 
2690 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2691  SelectionDAG &DAG) const {
2692  // FIXME: TLS addresses currently use medium model code sequences,
2693  // which is the most useful form. Eventually support for small and
2694  // large models could be added if users need it, at the cost of
2695  // additional complexity.
2696  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2697  if (DAG.getTarget().useEmulatedTLS())
2698  return LowerToTLSEmulatedModel(GA, DAG);
2699 
2700  SDLoc dl(GA);
2701  const GlobalValue *GV = GA->getGlobal();
2702  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2703  bool is64bit = Subtarget.isPPC64();
2704  const Module *M = DAG.getMachineFunction().getFunction().getParent();
2705  PICLevel::Level picLevel = M->getPICLevel();
2706 
2708 
2709  if (Model == TLSModel::LocalExec) {
2710  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2712  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2714  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2715  : DAG.getRegister(PPC::R2, MVT::i32);
2716 
2717  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2718  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2719  }
2720 
2721  if (Model == TLSModel::InitialExec) {
2722  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2723  SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2724  PPCII::MO_TLS);
2725  SDValue GOTPtr;
2726  if (is64bit) {
2727  setUsesTOCBasePtr(DAG);
2728  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2729  GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2730  PtrVT, GOTReg, TGA);
2731  } else
2732  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2733  SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2734  PtrVT, TGA, GOTPtr);
2735  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2736  }
2737 
2738  if (Model == TLSModel::GeneralDynamic) {
2739  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2740  SDValue GOTPtr;
2741  if (is64bit) {
2742  setUsesTOCBasePtr(DAG);
2743  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2744  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2745  GOTReg, TGA);
2746  } else {
2747  if (picLevel == PICLevel::SmallPIC)
2748  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2749  else
2750  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2751  }
2752  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2753  GOTPtr, TGA, TGA);
2754  }
2755 
2756  if (Model == TLSModel::LocalDynamic) {
2757  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2758  SDValue GOTPtr;
2759  if (is64bit) {
2760  setUsesTOCBasePtr(DAG);
2761  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2762  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2763  GOTReg, TGA);
2764  } else {
2765  if (picLevel == PICLevel::SmallPIC)
2766  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2767  else
2768  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2769  }
2770  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2771  PtrVT, GOTPtr, TGA, TGA);
2772  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2773  PtrVT, TLSAddr, TGA);
2774  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2775  }
2776 
2777  llvm_unreachable("Unknown TLS model!");
2778 }
2779 
2780 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2781  SelectionDAG &DAG) const {
2782  EVT PtrVT = Op.getValueType();
2783  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2784  SDLoc DL(GSDN);
2785  const GlobalValue *GV = GSDN->getGlobal();
2786 
2787  // 64-bit SVR4 ABI code is always position-independent.
2788  // The actual address of the GlobalValue is stored in the TOC.
2789  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2790  setUsesTOCBasePtr(DAG);
2791  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2792  return getTOCEntry(DAG, DL, true, GA);
2793  }
2794 
2795  unsigned MOHiFlag, MOLoFlag;
2796  bool IsPIC = isPositionIndependent();
2797  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2798 
2799  if (IsPIC && Subtarget.isSVR4ABI()) {
2800  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2801  GSDN->getOffset(),
2803  return getTOCEntry(DAG, DL, false, GA);
2804  }
2805 
2806  SDValue GAHi =
2807  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2808  SDValue GALo =
2809  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2810 
2811  SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2812 
2813  // If the global reference is actually to a non-lazy-pointer, we have to do an
2814  // extra load to get the address of the global.
2815  if (MOHiFlag & PPCII::MO_NLP_FLAG)
2816  Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2817  return Ptr;
2818 }
2819 
2820 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2821  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2822  SDLoc dl(Op);
2823 
2824  if (Op.getValueType() == MVT::v2i64) {
2825  // When the operands themselves are v2i64 values, we need to do something
2826  // special because VSX has no underlying comparison operations for these.
2827  if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2828  // Equality can be handled by casting to the legal type for Altivec
2829  // comparisons, everything else needs to be expanded.
2830  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2831  return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2832  DAG.getSetCC(dl, MVT::v4i32,
2833  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2834  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2835  CC));
2836  }
2837 
2838  return SDValue();
2839  }
2840 
2841  // We handle most of these in the usual way.
2842  return Op;
2843  }
2844 
2845  // If we're comparing for equality to zero, expose the fact that this is
2846  // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2847  // fold the new nodes.
2848  if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2849  return V;
2850 
2851  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2852  // Leave comparisons against 0 and -1 alone for now, since they're usually
2853  // optimized. FIXME: revisit this when we can custom lower all setcc
2854  // optimizations.
2855  if (C->isAllOnesValue() || C->isNullValue())
2856  return SDValue();
2857  }
2858 
2859  // If we have an integer seteq/setne, turn it into a compare against zero
2860  // by xor'ing the rhs with the lhs, which is faster than setting a
2861  // condition register, reading it back out, and masking the correct bit. The
2862  // normal approach here uses sub to do this instead of xor. Using xor exposes
2863  // the result to other bit-twiddling opportunities.
2864  EVT LHSVT = Op.getOperand(0).getValueType();
2865  if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2866  EVT VT = Op.getValueType();
2867  SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2868  Op.getOperand(1));
2869  return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2870  }
2871  return SDValue();
2872 }
2873 
2874 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2875  SDNode *Node = Op.getNode();
2876  EVT VT = Node->getValueType(0);
2877  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2878  SDValue InChain = Node->getOperand(0);
2879  SDValue VAListPtr = Node->getOperand(1);
2880  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2881  SDLoc dl(Node);
2882 
2883  assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2884 
2885  // gpr_index
2886  SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2887  VAListPtr, MachinePointerInfo(SV), MVT::i8);
2888  InChain = GprIndex.getValue(1);
2889 
2890  if (VT == MVT::i64) {
2891  // Check if GprIndex is even
2892  SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2893  DAG.getConstant(1, dl, MVT::i32));
2894  SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2895  DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2896  SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2897  DAG.getConstant(1, dl, MVT::i32));
2898  // Align GprIndex to be even if it isn't
2899  GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2900  GprIndex);
2901  }
2902 
2903  // fpr index is 1 byte after gpr
2904  SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2905  DAG.getConstant(1, dl, MVT::i32));
2906 
2907  // fpr
2908  SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2909  FprPtr, MachinePointerInfo(SV), MVT::i8);
2910  InChain = FprIndex.getValue(1);
2911 
2912  SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2913  DAG.getConstant(8, dl, MVT::i32));
2914 
2915  SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2916  DAG.getConstant(4, dl, MVT::i32));
2917 
2918  // areas
2919  SDValue OverflowArea =
2920  DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2921  InChain = OverflowArea.getValue(1);
2922 
2923  SDValue RegSaveArea =
2924  DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2925  InChain = RegSaveArea.getValue(1);
2926 
2927  // select overflow_area if index > 8
2928  SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2929  DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2930 
2931  // adjustment constant gpr_index * 4/8
2932  SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2933  VT.isInteger() ? GprIndex : FprIndex,
2934  DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2935  MVT::i32));
2936 
2937  // OurReg = RegSaveArea + RegConstant
2938  SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2939  RegConstant);
2940 
2941  // Floating types are 32 bytes into RegSaveArea
2942  if (VT.isFloatingPoint())
2943  OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2944  DAG.getConstant(32, dl, MVT::i32));
2945 
2946  // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2947  SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2948  VT.isInteger() ? GprIndex : FprIndex,
2949  DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2950  MVT::i32));
2951 
2952  InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2953  VT.isInteger() ? VAListPtr : FprPtr,
2955 
2956  // determine if we should load from reg_save_area or overflow_area
2957  SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2958 
2959  // increase overflow_area by 4/8 if gpr/fpr > 8
2960  SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2961  DAG.getConstant(VT.isInteger() ? 4 : 8,
2962  dl, MVT::i32));
2963 
2964  OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2965  OverflowAreaPlusN);
2966 
2967  InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2969 
2970  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2971 }
2972 
2973 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2974  assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2975 
2976  // We have to copy the entire va_list struct:
2977  // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2978  return DAG.getMemcpy(Op.getOperand(0), Op,
2979  Op.getOperand(1), Op.getOperand(2),
2980  DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2982 }
2983 
2984 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2985  SelectionDAG &DAG) const {
2986  return Op.getOperand(0);
2987 }
2988 
2989 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2990  SelectionDAG &DAG) const {
2991  SDValue Chain = Op.getOperand(0);
2992  SDValue Trmp = Op.getOperand(1); // trampoline
2993  SDValue FPtr = Op.getOperand(2); // nested function
2994  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2995  SDLoc dl(Op);
2996 
2997  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2998  bool isPPC64 = (PtrVT == MVT::i64);
2999  Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3000 
3003 
3004  Entry.Ty = IntPtrTy;
3005  Entry.Node = Trmp; Args.push_back(Entry);
3006 
3007  // TrampSize == (isPPC64 ? 48 : 40);
3008  Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3009  isPPC64 ? MVT::i64 : MVT::i32);
3010  Args.push_back(Entry);
3011 
3012  Entry.Node = FPtr; Args.push_back(Entry);
3013  Entry.Node = Nest; Args.push_back(Entry);
3014 
3015  // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3017  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3019  DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3020 
3021  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3022  return CallResult.second;
3023 }
3024 
3025 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3026  MachineFunction &MF = DAG.getMachineFunction();
3027  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3028  EVT PtrVT = getPointerTy(MF.getDataLayout());
3029 
3030  SDLoc dl(Op);
3031 
3032  if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3033  // vastart just stores the address of the VarArgsFrameIndex slot into the
3034  // memory location argument.
3035  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3036  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3037  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3038  MachinePointerInfo(SV));
3039  }
3040 
3041  // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3042  // We suppose the given va_list is already allocated.
3043  //
3044  // typedef struct {
3045  // char gpr; /* index into the array of 8 GPRs
3046  // * stored in the register save area
3047  // * gpr=0 corresponds to r3,
3048  // * gpr=1 to r4, etc.
3049  // */
3050  // char fpr; /* index into the array of 8 FPRs
3051  // * stored in the register save area
3052  // * fpr=0 corresponds to f1,
3053  // * fpr=1 to f2, etc.
3054  // */
3055  // char *overflow_arg_area;
3056  // /* location on stack that holds
3057  // * the next overflow argument
3058  // */
3059  // char *reg_save_area;
3060  // /* where r3:r10 and f1:f8 (if saved)
3061  // * are stored
3062  // */
3063  // } va_list[1];
3064 
3065  SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3066  SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3067  SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3068  PtrVT);
3069  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3070  PtrVT);
3071 
3072  uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3073  SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3074 
3075  uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3076  SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3077 
3078  uint64_t FPROffset = 1;
3079  SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3080 
3081  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3082 
3083  // Store first byte : number of int regs
3084  SDValue firstStore =
3085  DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3087  uint64_t nextOffset = FPROffset;
3088  SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3089  ConstFPROffset);
3090 
3091  // Store second byte : number of float regs
3092  SDValue secondStore =
3093  DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3094  MachinePointerInfo(SV, nextOffset), MVT::i8);
3095  nextOffset += StackOffset;
3096  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3097 
3098  // Store second word : arguments given on stack
3099  SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3100  MachinePointerInfo(SV, nextOffset));
3101  nextOffset += FrameOffset;
3102  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3103 
3104  // Store third word : arguments given in registers
3105  return DAG.getStore(thirdStore, dl, FR, nextPtr,
3106  MachinePointerInfo(SV, nextOffset));
3107 }
3108 
3109 #include "PPCGenCallingConv.inc"
3110 
3111 // Function whose sole purpose is to kill compiler warnings
3112 // stemming from unused functions included from PPCGenCallingConv.inc.
3113 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3114  return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3115 }
3116 
3117 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3118  CCValAssign::LocInfo &LocInfo,
3119  ISD::ArgFlagsTy &ArgFlags,
3120  CCState &State) {
3121  return true;
3122 }
3123 
3124 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3125  MVT &LocVT,
3126  CCValAssign::LocInfo &LocInfo,
3127  ISD::ArgFlagsTy &ArgFlags,
3128  CCState &State) {
3129  static const MCPhysReg ArgRegs[] = {
3130  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3131  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3132  };
3133  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3134 
3135  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3136 
3137  // Skip one register if the first unallocated register has an even register
3138  // number and there are still argument registers available which have not been
3139  // allocated yet. RegNum is actually an index into ArgRegs, which means we
3140  // need to skip a register if RegNum is odd.
3141  if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3142  State.AllocateReg(ArgRegs[RegNum]);
3143  }
3144 
3145  // Always return false here, as this function only makes sure that the first
3146  // unallocated register has an odd register number and does not actually
3147  // allocate a register for the current argument.
3148  return false;
3149 }
3150 
3151 bool
3153  MVT &LocVT,
3154  CCValAssign::LocInfo &LocInfo,
3155  ISD::ArgFlagsTy &ArgFlags,
3156  CCState &State) {
3157  static const MCPhysReg ArgRegs[] = {
3158  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3159  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3160  };
3161  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3162 
3163  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3164  int RegsLeft = NumArgRegs - RegNum;
3165 
3166  // Skip if there is not enough registers left for long double type (4 gpr regs
3167  // in soft float mode) and put long double argument on the stack.
3168  if (RegNum != NumArgRegs && RegsLeft < 4) {
3169  for (int i = 0; i < RegsLeft; i++) {
3170  State.AllocateReg(ArgRegs[RegNum + i]);
3171  }
3172  }
3173 
3174  return false;
3175 }
3176 
3177 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3178  MVT &LocVT,
3179  CCValAssign::LocInfo &LocInfo,
3180  ISD::ArgFlagsTy &ArgFlags,
3181  CCState &State) {
3182  static const MCPhysReg ArgRegs[] = {
3183  PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3184  PPC::F8
3185  };
3186 
3187  const unsigned NumArgRegs = array_lengthof(ArgRegs);
3188 
3189  unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3190 
3191  // If there is only one Floating-point register left we need to put both f64
3192  // values of a split ppc_fp128 value on the stack.
3193  if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3194  State.AllocateReg(ArgRegs[RegNum]);
3195  }
3196 
3197  // Always return false here, as this function only makes sure that the two f64
3198  // values a ppc_fp128 value is split into are both passed in registers or both
3199  // passed on the stack and does not actually allocate a register for the
3200  // current argument.
3201  return false;
3202 }
3203 
3204 /// FPR - The set of FP registers that should be allocated for arguments,
3205 /// on Darwin.
3206 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3207  PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3208  PPC::F11, PPC::F12, PPC::F13};
3209 
3210 /// QFPR - The set of QPX registers that should be allocated for arguments.
3211 static const MCPhysReg QFPR[] = {
3212  PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3213  PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3214 
3215 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3216 /// the stack.
3217 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3218  unsigned PtrByteSize) {
3219  unsigned ArgSize = ArgVT.getStoreSize();
3220  if (Flags.isByVal())
3221  ArgSize = Flags.getByValSize();
3222 
3223  // Round up to multiples of the pointer size, except for array members,
3224  // which are always packed.
3225  if (!Flags.isInConsecutiveRegs())
3226  ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3227 
3228  return ArgSize;
3229 }
3230 
3231 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3232 /// on the stack.
3233 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3234  ISD::ArgFlagsTy Flags,
3235  unsigned PtrByteSize) {
3236  unsigned Align = PtrByteSize;
3237 
3238  // Altivec parameters are padded to a 16 byte boundary.
3239  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3240  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3241  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3242  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3243  Align = 16;
3244  // QPX vector types stored in double-precision are padded to a 32 byte
3245  // boundary.
3246  else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3247  Align = 32;
3248 
3249  // ByVal parameters are aligned as requested.
3250  if (Flags.isByVal()) {
3251  unsigned BVAlign = Flags.getByValAlign();
3252  if (BVAlign > PtrByteSize) {
3253  if (BVAlign % PtrByteSize != 0)
3255  "ByVal alignment is not a multiple of the pointer size");
3256 
3257  Align = BVAlign;
3258  }
3259  }
3260 
3261  // Array members are always packed to their original alignment.
3262  if (Flags.isInConsecutiveRegs()) {
3263  // If the array member was split into multiple registers, the first
3264  // needs to be aligned to the size of the full type. (Except for
3265  // ppcf128, which is only aligned as its f64 components.)
3266  if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3267  Align = OrigVT.getStoreSize();
3268  else
3269  Align = ArgVT.getStoreSize();
3270  }
3271 
3272  return Align;
3273 }
3274 
3275 /// CalculateStackSlotUsed - Return whether this argument will use its
3276 /// stack slot (instead of being passed in registers). ArgOffset,
3277 /// AvailableFPRs, and AvailableVRs must hold the current argument
3278 /// position, and will be updated to account for this argument.
3279 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3280  ISD::ArgFlagsTy Flags,
3281  unsigned PtrByteSize,
3282  unsigned LinkageSize,
3283  unsigned ParamAreaSize,
3284  unsigned &ArgOffset,
3285  unsigned &AvailableFPRs,
3286  unsigned &AvailableVRs, bool HasQPX) {
3287  bool UseMemory = false;
3288 
3289  // Respect alignment of argument on the stack.
3290  unsigned Align =
3291  CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3292  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3293  // If there's no space left in the argument save area, we must
3294  // use memory (this check also catches zero-sized arguments).
3295  if (ArgOffset >= LinkageSize + ParamAreaSize)
3296  UseMemory = true;
3297 
3298  // Allocate argument on the stack.
3299  ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3300  if (Flags.isInConsecutiveRegsLast())
3301  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3302  // If we overran the argument save area, we must use memory
3303  // (this check catches arguments passed partially in memory)
3304  if (ArgOffset > LinkageSize + ParamAreaSize)
3305  UseMemory = true;
3306 
3307  // However, if the argument is actually passed in an FPR or a VR,
3308  // we don't use memory after all.
3309  if (!Flags.isByVal()) {
3310  if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3311  // QPX registers overlap with the scalar FP registers.
3312  (HasQPX && (ArgVT == MVT::v4f32 ||
3313  ArgVT == MVT::v4f64 ||
3314  ArgVT == MVT::v4i1)))
3315  if (AvailableFPRs > 0) {
3316  --AvailableFPRs;
3317  return false;
3318  }
3319  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3320  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3321  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3322  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3323  if (AvailableVRs > 0) {
3324  --AvailableVRs;
3325  return false;
3326  }
3327  }
3328 
3329  return UseMemory;
3330 }
3331 
3332 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3333 /// ensure minimum alignment required for target.
3335  unsigned NumBytes) {
3336  unsigned TargetAlign = Lowering->getStackAlignment();
3337  unsigned AlignMask = TargetAlign - 1;
3338  NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3339  return NumBytes;
3340 }
3341 
3342 SDValue PPCTargetLowering::LowerFormalArguments(
3343  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3344  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3345  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3346  if (Subtarget.isSVR4ABI()) {
3347  if (Subtarget.isPPC64())
3348  return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3349  dl, DAG, InVals);
3350  else
3351  return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3352  dl, DAG, InVals);
3353  } else {
3354  return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3355  dl, DAG, InVals);
3356  }
3357 }
3358 
3359 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3360  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3361  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3362  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3363 
3364  // 32-bit SVR4 ABI Stack Frame Layout:
3365  // +-----------------------------------+
3366  // +--> | Back chain |
3367  // | +-----------------------------------+
3368  // | | Floating-point register save area |
3369  // | +-----------------------------------+
3370  // | | General register save area |
3371  // | +-----------------------------------+
3372  // | | CR save word |
3373  // | +-----------------------------------+
3374  // | | VRSAVE save word |
3375  // | +-----------------------------------+
3376  // | | Alignment padding |
3377  // | +-----------------------------------+
3378  // | | Vector register save area |
3379  // | +-----------------------------------+
3380  // | | Local variable space |
3381  // | +-----------------------------------+
3382  // | | Parameter list area |
3383  // | +-----------------------------------+
3384  // | | LR save word |
3385  // | +-----------------------------------+
3386  // SP--> +--- | Back chain |
3387  // +-----------------------------------+
3388  //
3389  // Specifications:
3390  // System V Application Binary Interface PowerPC Processor Supplement
3391  // AltiVec Technology Programming Interface Manual
3392 
3393  MachineFunction &MF = DAG.getMachineFunction();
3394  MachineFrameInfo &MFI = MF.getFrameInfo();
3395  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3396 
3397  EVT PtrVT = getPointerTy(MF.getDataLayout());
3398  // Potential tail calls could cause overwriting of argument stack slots.
3399  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3400  (CallConv == CallingConv::Fast));
3401  unsigned PtrByteSize = 4;
3402 
3403  // Assign locations to all of the incoming arguments.
3405  PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3406  *DAG.getContext());
3407 
3408  // Reserve space for the linkage area on the stack.
3409  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3410  CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3411  if (useSoftFloat() || hasSPE())
3412  CCInfo.PreAnalyzeFormalArguments(Ins);
3413 
3414  CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3415  CCInfo.clearWasPPCF128();
3416 
3417  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3418  CCValAssign &VA = ArgLocs[i];
3419 
3420  // Arguments stored in registers.
3421  if (VA.isRegLoc()) {
3422  const TargetRegisterClass *RC;
3423  EVT ValVT = VA.getValVT();
3424 
3425  switch (ValVT.getSimpleVT().SimpleTy) {
3426  default:
3427  llvm_unreachable("ValVT not supported by formal arguments Lowering");
3428  case MVT::i1:
3429  case MVT::i32:
3430  RC = &PPC::GPRCRegClass;
3431  break;
3432  case MVT::f32:
3433  if (Subtarget.hasP8Vector())
3434  RC = &PPC::VSSRCRegClass;
3435  else if (Subtarget.hasSPE())
3436  RC = &PPC::SPE4RCRegClass;
3437  else
3438  RC = &PPC::F4RCRegClass;
3439  break;
3440  case MVT::f64:
3441  if (Subtarget.hasVSX())
3442  RC = &PPC::VSFRCRegClass;
3443  else if (Subtarget.hasSPE())
3444  RC = &PPC::SPERCRegClass;
3445  else
3446  RC = &PPC::F8RCRegClass;
3447  break;
3448  case MVT::v16i8:
3449  case MVT::v8i16:
3450  case MVT::v4i32:
3451  RC = &PPC::VRRCRegClass;
3452  break;
3453  case MVT::v4f32:
3454  RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3455  break;
3456  case MVT::v2f64:
3457  case MVT::v2i64:
3458  RC = &PPC::VRRCRegClass;
3459  break;
3460  case MVT::v4f64:
3461  RC = &PPC::QFRCRegClass;
3462  break;
3463  case MVT::v4i1:
3464  RC = &PPC::QBRCRegClass;
3465  break;
3466  }
3467 
3468  // Transform the arguments stored in physical registers into virtual ones.
3469  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3470  SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3471  ValVT == MVT::i1 ? MVT::i32 : ValVT);
3472 
3473  if (ValVT == MVT::i1)
3474  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3475 
3476  InVals.push_back(ArgValue);
3477  } else {
3478  // Argument stored in memory.
3479  assert(VA.isMemLoc());
3480 
3481  unsigned ArgSize = VA.getLocVT().getStoreSize();
3482  int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3483  isImmutable);
3484 
3485  // Create load nodes to retrieve arguments from the stack.
3486  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3487  InVals.push_back(
3488  DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3489  }
3490  }
3491 
3492  // Assign locations to all of the incoming aggregate by value arguments.
3493  // Aggregates passed by value are stored in the local variable space of the
3494  // caller's stack frame, right above the parameter list area.
3495  SmallVector<CCValAssign, 16> ByValArgLocs;
3496  CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3497  ByValArgLocs, *DAG.getContext());
3498 
3499  // Reserve stack space for the allocations in CCInfo.
3500  CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3501 
3502  CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3503 
3504  // Area that is at least reserved in the caller of this function.
3505  unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3506  MinReservedArea = std::max(MinReservedArea, LinkageSize);
3507 
3508  // Set the size that is at least reserved in caller of this function. Tail
3509  // call optimized function's reserved stack space needs to be aligned so that
3510  // taking the difference between two stack areas will result in an aligned
3511  // stack.
3512  MinReservedArea =
3513  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3514  FuncInfo->setMinReservedArea(MinReservedArea);
3515 
3516  SmallVector<SDValue, 8> MemOps;
3517 
3518  // If the function takes variable number of arguments, make a frame index for
3519  // the start of the first vararg value... for expansion of llvm.va_start.
3520  if (isVarArg) {
3521  static const MCPhysReg GPArgRegs[] = {
3522  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3523  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3524  };
3525  const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3526 
3527  static const MCPhysReg FPArgRegs[] = {
3528  PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3529  PPC::F8
3530  };
3531  unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3532 
3533  if (useSoftFloat() || hasSPE())
3534  NumFPArgRegs = 0;
3535 
3536  FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3537  FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3538 
3539  // Make room for NumGPArgRegs and NumFPArgRegs.
3540  int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3541  NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3542 
3543  FuncInfo->setVarArgsStackOffset(
3544  MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3545  CCInfo.getNextStackOffset(), true));
3546 
3547  FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3548  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3549 
3550  // The fixed integer arguments of a variadic function are stored to the
3551  // VarArgsFrameIndex on the stack so that they may be loaded by
3552  // dereferencing the result of va_next.
3553  for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3554  // Get an existing live-in vreg, or add a new one.
3555  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3556  if (!VReg)
3557  VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3558 
3559  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3560  SDValue Store =
3561  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3562  MemOps.push_back(Store);
3563  // Increment the address by four for the next argument to store
3564  SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3565  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3566  }
3567 
3568  // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3569  // is set.
3570  // The double arguments are stored to the VarArgsFrameIndex
3571  // on the stack.
3572  for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3573  // Get an existing live-in vreg, or add a new one.
3574  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3575  if (!VReg)
3576  VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3577 
3578  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3579  SDValue Store =
3580  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3581  MemOps.push_back(Store);
3582  // Increment the address by eight for the next argument to store
3583  SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3584  PtrVT);
3585  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3586  }
3587  }
3588 
3589  if (!MemOps.empty())
3590  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3591 
3592  return Chain;
3593 }
3594 
3595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3596 // value to MVT::i64 and then truncate to the correct register size.
3597 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3598  EVT ObjectVT, SelectionDAG &DAG,
3599  SDValue ArgVal,
3600  const SDLoc &dl) const {
3601  if (Flags.isSExt())
3602  ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3603  DAG.getValueType(ObjectVT));
3604  else if (Flags.isZExt())
3605  ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3606  DAG.getValueType(ObjectVT));
3607 
3608  return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3609 }
3610 
3611 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3612  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3613  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3614  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3615  // TODO: add description of PPC stack frame format, or at least some docs.
3616  //
3617  bool isELFv2ABI = Subtarget.isELFv2ABI();
3618  bool isLittleEndian = Subtarget.isLittleEndian();
3619  MachineFunction &MF = DAG.getMachineFunction();
3620  MachineFrameInfo &MFI = MF.getFrameInfo();
3621  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3622 
3623  assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3624  "fastcc not supported on varargs functions");
3625 
3626  EVT PtrVT = getPointerTy(MF.getDataLayout());
3627  // Potential tail calls could cause overwriting of argument stack slots.
3628  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3629  (CallConv == CallingConv::Fast));
3630  unsigned PtrByteSize = 8;
3631  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3632 
3633  static const MCPhysReg GPR[] = {
3634  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3635  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3636  };
3637  static const MCPhysReg VR[] = {
3638  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3639  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3640  };
3641 
3642  const unsigned Num_GPR_Regs = array_lengthof(GPR);
3643  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3644  const unsigned Num_VR_Regs = array_lengthof(VR);
3645  const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3646 
3647  // Do a first pass over the arguments to determine whether the ABI
3648  // guarantees that our caller has allocated the parameter save area
3649  // on its stack frame. In the ELFv1 ABI, this is always the case;
3650  // in the ELFv2 ABI, it is true if this is a vararg function or if
3651  // any parameter is located in a stack slot.
3652 
3653  bool HasParameterArea = !isELFv2ABI || isVarArg;
3654  unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3655  unsigned NumBytes = LinkageSize;
3656  unsigned AvailableFPRs = Num_FPR_Regs;
3657  unsigned AvailableVRs = Num_VR_Regs;
3658  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3659  if (Ins[i].Flags.isNest())
3660  continue;
3661 
3662  if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3663  PtrByteSize, LinkageSize, ParamAreaSize,
3664  NumBytes, AvailableFPRs, AvailableVRs,
3665  Subtarget.hasQPX()))
3666  HasParameterArea = true;
3667  }
3668 
3669  // Add DAG nodes to load the arguments or copy them out of registers. On
3670  // entry to a function on PPC, the arguments start after the linkage area,
3671  // although the first ones are often in registers.
3672 
3673  unsigned ArgOffset = LinkageSize;
3674  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3675  unsigned &QFPR_idx = FPR_idx;
3676  SmallVector<SDValue, 8> MemOps;
3678  unsigned CurArgIdx = 0;
3679  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3680  SDValue ArgVal;
3681  bool needsLoad = false;
3682  EVT ObjectVT = Ins[ArgNo].VT;
3683  EVT OrigVT = Ins[ArgNo].ArgVT;
3684  unsigned ObjSize = ObjectVT.getStoreSize();
3685  unsigned ArgSize = ObjSize;
3686  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3687  if (Ins[ArgNo].isOrigArg()) {
3688  std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3689  CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3690  }
3691  // We re-align the argument offset for each argument, except when using the
3692  // fast calling convention, when we need to make sure we do that only when
3693  // we'll actually use a stack slot.
3694  unsigned CurArgOffset, Align;
3695  auto ComputeArgOffset = [&]() {
3696  /* Respect alignment of argument on the stack. */
3697  Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3698  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3699  CurArgOffset = ArgOffset;
3700  };
3701 
3702  if (CallConv != CallingConv::Fast) {
3703  ComputeArgOffset();
3704 
3705  /* Compute GPR index associated with argument offset. */
3706  GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3707  GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3708  }
3709 
3710  // FIXME the codegen can be much improved in some cases.
3711  // We do not have to keep everything in memory.
3712  if (Flags.isByVal()) {
3713  assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3714 
3715  if (CallConv == CallingConv::Fast)
3716  ComputeArgOffset();
3717 
3718  // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3719  ObjSize = Flags.getByValSize();
3720  ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3721  // Empty aggregate parameters do not take up registers. Examples:
3722  // struct { } a;
3723  // union { } b;
3724  // int c[0];
3725  // etc. However, we have to provide a place-holder in InVals, so
3726  // pretend we have an 8-byte item at the current address for that
3727  // purpose.
3728  if (!ObjSize) {
3729  int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3730  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3731  InVals.push_back(FIN);
3732  continue;
3733  }
3734 
3735  // Create a stack object covering all stack doublewords occupied
3736  // by the argument. If the argument is (fully or partially) on
3737  // the stack, or if the argument is fully in registers but the
3738  // caller has allocated the parameter save anyway, we can refer
3739  // directly to the caller's stack frame. Otherwise, create a
3740  // local copy in our own frame.
3741  int FI;
3742  if (HasParameterArea ||
3743  ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3744  FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3745  else
3746  FI = MFI.CreateStackObject(ArgSize, Align, false);
3747  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3748 
3749  // Handle aggregates smaller than 8 bytes.
3750  if (ObjSize < PtrByteSize) {
3751  // The value of the object is its address, which differs from the
3752  // address of the enclosing doubleword on big-endian systems.
3753  SDValue Arg = FIN;
3754  if (!isLittleEndian) {
3755  SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3756  Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3757  }
3758  InVals.push_back(Arg);
3759 
3760  if (GPR_idx != Num_GPR_Regs) {
3761  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3762  FuncInfo->addLiveInAttr(VReg, Flags);
3763  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3764  SDValue Store;
3765 
3766  if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3767  EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3768  (ObjSize == 2 ? MVT::i16 : MVT::i32));
3769  Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3770  MachinePointerInfo(&*FuncArg), ObjType);
3771  } else {
3772  // For sizes that don't fit a truncating store (3, 5, 6, 7),
3773  // store the whole register as-is to the parameter save area
3774  // slot.
3775  Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3776  MachinePointerInfo(&*FuncArg));
3777  }
3778 
3779  MemOps.push_back(Store);
3780  }
3781  // Whether we copied from a register or not, advance the offset
3782  // into the parameter save area by a full doubleword.
3783  ArgOffset += PtrByteSize;
3784  continue;
3785  }
3786 
3787  // The value of the object is its address, which is the address of
3788  // its first stack doubleword.
3789  InVals.push_back(FIN);
3790 
3791  // Store whatever pieces of the object are in registers to memory.
3792  for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3793  if (GPR_idx == Num_GPR_Regs)
3794  break;
3795 
3796  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3797  FuncInfo->addLiveInAttr(VReg, Flags);
3798  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3799  SDValue Addr = FIN;
3800  if (j) {
3801  SDValue Off = DAG.getConstant(j, dl, PtrVT);
3802  Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3803  }
3804  SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3805  MachinePointerInfo(&*FuncArg, j));
3806  MemOps.push_back(Store);
3807  ++GPR_idx;
3808  }
3809  ArgOffset += ArgSize;
3810  continue;
3811  }
3812 
3813  switch (ObjectVT.getSimpleVT().SimpleTy) {
3814  default: llvm_unreachable("Unhandled argument type!");
3815  case MVT::i1:
3816  case MVT::i32:
3817  case MVT::i64:
3818  if (Flags.isNest()) {
3819  // The 'nest' parameter, if any, is passed in R11.
3820  unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3821  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3822 
3823  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3824  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3825 
3826  break;
3827  }
3828 
3829  // These can be scalar arguments or elements of an integer array type
3830  // passed directly. Clang may use those instead of "byval" aggregate
3831  // types to avoid forcing arguments to memory unnecessarily.
3832  if (GPR_idx != Num_GPR_Regs) {
3833  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3834  FuncInfo->addLiveInAttr(VReg, Flags);
3835  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3836 
3837  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3838  // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3839  // value to MVT::i64 and then truncate to the correct register size.
3840  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3841  } else {
3842  if (CallConv == CallingConv::Fast)
3843  ComputeArgOffset();
3844 
3845  needsLoad = true;
3846  ArgSize = PtrByteSize;
3847  }
3848  if (CallConv != CallingConv::Fast || needsLoad)
3849  ArgOffset += 8;
3850  break;
3851 
3852  case MVT::f32:
3853  case MVT::f64:
3854  // These can be scalar arguments or elements of a float array type
3855  // passed directly. The latter are used to implement ELFv2 homogenous
3856  // float aggregates.
3857  if (FPR_idx != Num_FPR_Regs) {
3858  unsigned VReg;
3859 
3860  if (ObjectVT == MVT::f32)
3861  VReg = MF.addLiveIn(FPR[FPR_idx],
3862  Subtarget.hasP8Vector()
3863  ? &PPC::VSSRCRegClass
3864  : &PPC::F4RCRegClass);
3865  else
3866  VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3867  ? &PPC::VSFRCRegClass
3868  : &PPC::F8RCRegClass);
3869 
3870  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3871  ++FPR_idx;
3872  } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3873  // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3874  // once we support fp <-> gpr moves.
3875 
3876  // This can only ever happen in the presence of f32 array types,
3877  // since otherwise we never run out of FPRs before running out
3878  // of GPRs.
3879  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3880  FuncInfo->addLiveInAttr(VReg, Flags);
3881  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3882 
3883  if (ObjectVT == MVT::f32) {
3884  if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3885  ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3886  DAG.getConstant(32, dl, MVT::i32));
3887  ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3888  }
3889 
3890  ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3891  } else {
3892  if (CallConv == CallingConv::Fast)
3893  ComputeArgOffset();
3894 
3895  needsLoad = true;
3896  }
3897 
3898  // When passing an array of floats, the array occupies consecutive
3899  // space in the argument area; only round up to the next doubleword
3900  // at the end of the array. Otherwise, each float takes 8 bytes.
3901  if (CallConv != CallingConv::Fast || needsLoad) {
3902  ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3903  ArgOffset += ArgSize;
3904  if (Flags.isInConsecutiveRegsLast())
3905  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3906  }
3907  break;
3908  case MVT::v4f32:
3909  case MVT::v4i32:
3910  case MVT::v8i16:
3911  case MVT::v16i8:
3912  case MVT::v2f64:
3913  case MVT::v2i64:
3914  case MVT::v1i128:
3915  case MVT::f128:
3916  if (!Subtarget.hasQPX()) {
3917  // These can be scalar arguments or elements of a vector array type
3918  // passed directly. The latter are used to implement ELFv2 homogenous
3919  // vector aggregates.
3920  if (VR_idx != Num_VR_Regs) {
3921  unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3922  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3923  ++VR_idx;
3924  } else {
3925  if (CallConv == CallingConv::Fast)
3926  ComputeArgOffset();
3927  needsLoad = true;
3928  }
3929  if (CallConv != CallingConv::Fast || needsLoad)
3930  ArgOffset += 16;
3931  break;
3932  } // not QPX
3933 
3934  assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3935  "Invalid QPX parameter type");
3936  /* fall through */
3937 
3938  case MVT::v4f64:
3939  case MVT::v4i1:
3940  // QPX vectors are treated like their scalar floating-point subregisters
3941  // (except that they're larger).
3942  unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3943  if (QFPR_idx != Num_QFPR_Regs) {
3944  const TargetRegisterClass *RC;
3945  switch (ObjectVT.getSimpleVT().SimpleTy) {
3946  case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3947  case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3948  default: RC = &PPC::QBRCRegClass; break;
3949  }
3950 
3951  unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3952  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3953  ++QFPR_idx;
3954  } else {
3955  if (CallConv == CallingConv::Fast)
3956  ComputeArgOffset();
3957  needsLoad = true;
3958  }
3959  if (CallConv != CallingConv::Fast || needsLoad)
3960  ArgOffset += Sz;
3961  break;
3962  }
3963 
3964  // We need to load the argument to a virtual register if we determined
3965  // above that we ran out of physical registers of the appropriate type.
3966  if (needsLoad) {
3967  if (ObjSize < ArgSize && !isLittleEndian)
3968  CurArgOffset += ArgSize - ObjSize;
3969  int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3970  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3971  ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3972  }
3973 
3974  InVals.push_back(ArgVal);
3975  }
3976 
3977  // Area that is at least reserved in the caller of this function.
3978  unsigned MinReservedArea;
3979  if (HasParameterArea)
3980  MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3981  else
3982  MinReservedArea = LinkageSize;
3983 
3984  // Set the size that is at least reserved in caller of this function. Tail
3985  // call optimized functions' reserved stack space needs to be aligned so that
3986  // taking the difference between two stack areas will result in an aligned
3987  // stack.
3988  MinReservedArea =
3989  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3990  FuncInfo->setMinReservedArea(MinReservedArea);
3991 
3992  // If the function takes variable number of arguments, make a frame index for
3993  // the start of the first vararg value... for expansion of llvm.va_start.
3994  if (isVarArg) {
3995  int Depth = ArgOffset;
3996 
3997  FuncInfo->setVarArgsFrameIndex(
3998  MFI.CreateFixedObject(PtrByteSize, Depth, true));
3999  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4000 
4001  // If this function is vararg, store any remaining integer argument regs
4002  // to their spots on the stack so that they may be loaded by dereferencing
4003  // the result of va_next.
4004  for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4005  GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4006  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4007  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4008  SDValue Store =
4009  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4010  MemOps.push_back(Store);
4011  // Increment the address by four for the next argument to store
4012  SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4013  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4014  }
4015  }
4016 
4017  if (!MemOps.empty())
4018  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4019 
4020  return Chain;
4021 }
4022 
4023 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4024  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4025  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4026  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4027  // TODO: add description of PPC stack frame format, or at least some docs.
4028  //
4029  MachineFunction &MF = DAG.getMachineFunction();
4030  MachineFrameInfo &MFI = MF.getFrameInfo();
4031  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4032 
4033  EVT PtrVT = getPointerTy(MF.getDataLayout());
4034  bool isPPC64 = PtrVT == MVT::i64;
4035  // Potential tail calls could cause overwriting of argument stack slots.
4036  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4037  (CallConv == CallingConv::Fast));
4038  unsigned PtrByteSize = isPPC64 ? 8 : 4;
4039  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4040  unsigned ArgOffset = LinkageSize;
4041  // Area that is at least reserved in caller of this function.
4042  unsigned MinReservedArea = ArgOffset;
4043 
4044  static const MCPhysReg GPR_32[] = { // 32-bit registers.
4045  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4046  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4047  };
4048  static const MCPhysReg GPR_64[] = { // 64-bit registers.
4049  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4050  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4051  };
4052  static const MCPhysReg VR[] = {
4053  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4054  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4055  };
4056 
4057  const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4058  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4059  const unsigned Num_VR_Regs = array_lengthof( VR);
4060 
4061  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4062 
4063  const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4064 
4065  // In 32-bit non-varargs functions, the stack space for vectors is after the
4066  // stack space for non-vectors. We do not use this space unless we have
4067  // too many vectors to fit in registers, something that only occurs in
4068  // constructed examples:), but we have to walk the arglist to figure
4069  // that out...for the pathological case, compute VecArgOffset as the
4070  // start of the vector parameter area. Computing VecArgOffset is the
4071  // entire point of the following loop.
4072  unsigned VecArgOffset = ArgOffset;
4073  if (!isVarArg && !isPPC64) {
4074  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4075  ++ArgNo) {
4076  EVT ObjectVT = Ins[ArgNo].VT;
4077  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4078 
4079  if (Flags.isByVal()) {
4080  // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4081  unsigned ObjSize = Flags.getByValSize();
4082  unsigned ArgSize =
4083  ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4084  VecArgOffset += ArgSize;
4085  continue;
4086  }
4087 
4088  switch(ObjectVT.getSimpleVT().SimpleTy) {
4089  default: llvm_unreachable("Unhandled argument type!");
4090  case MVT::i1:
4091  case MVT::i32:
4092  case MVT::f32:
4093  VecArgOffset += 4;
4094  break;
4095  case MVT::i64: // PPC64
4096  case MVT::f64:
4097  // FIXME: We are guaranteed to be !isPPC64 at this point.
4098  // Does MVT::i64 apply?
4099  VecArgOffset += 8;
4100  break;
4101  case MVT::v4f32:
4102  case MVT::v4i32:
4103  case MVT::v8i16:
4104  case MVT::v16i8:
4105  // Nothing to do, we're only looking at Nonvector args here.
4106  break;
4107  }
4108  }
4109  }
4110  // We've found where the vector parameter area in memory is. Skip the
4111  // first 12 parameters; these don't use that memory.
4112  VecArgOffset = ((VecArgOffset+15)/16)*16;
4113  VecArgOffset += 12*16;
4114 
4115  // Add DAG nodes to load the arguments or copy them out of registers. On
4116  // entry to a function on PPC, the arguments start after the linkage area,
4117  // although the first ones are often in registers.
4118 
4119  SmallVector<SDValue, 8> MemOps;
4120  unsigned nAltivecParamsAtEnd = 0;
4122  unsigned CurArgIdx = 0;
4123  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4124  SDValue ArgVal;
4125  bool needsLoad = false;
4126  EVT ObjectVT = Ins[ArgNo].VT;
4127  unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4128  unsigned ArgSize = ObjSize;
4129  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4130  if (Ins[ArgNo].isOrigArg()) {
4131  std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4132  CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4133  }
4134  unsigned CurArgOffset = ArgOffset;
4135 
4136  // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4137  if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4138  ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4139  if (isVarArg || isPPC64) {
4140  MinReservedArea = ((MinReservedArea+15)/16)*16;
4141  MinReservedArea += CalculateStackSlotSize(ObjectVT,
4142  Flags,
4143  PtrByteSize);
4144  } else nAltivecParamsAtEnd++;
4145  } else
4146  // Calculate min reserved area.
4147  MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4148  Flags,
4149  PtrByteSize);
4150 
4151  // FIXME the codegen can be much improved in some cases.
4152  // We do not have to keep everything in memory.
4153  if (Flags.isByVal()) {
4154  assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4155 
4156  // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4157  ObjSize = Flags.getByValSize();
4158  ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4159  // Objects of size 1 and 2 are right justified, everything else is
4160  // left justified. This means the memory address is adjusted forwards.
4161  if (ObjSize==1 || ObjSize==2) {
4162  CurArgOffset = CurArgOffset + (4 - ObjSize);
4163  }
4164  // The value of the object is its address.
4165  int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4166  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4167  InVals.push_back(FIN);
4168  if (ObjSize==1 || ObjSize==2) {
4169  if (GPR_idx != Num_GPR_Regs) {
4170