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