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