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