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 as [r+imm]. If \p EncodingAlignment is
2223 /// non-zero and N can be represented by a base register plus a signed 16-bit
2224 /// displacement, make a more precise judgement by checking (displacement % \p
2225 /// EncodingAlignment).
2227  SDValue &Index, SelectionDAG &DAG,
2228  unsigned EncodingAlignment) const {
2229  int16_t imm = 0;
2230  if (N.getOpcode() == ISD::ADD) {
2231  if (isIntS16Immediate(N.getOperand(1), imm) &&
2232  (!EncodingAlignment || !(imm % EncodingAlignment)))
2233  return false; // r+i
2234  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2235  return false; // r+i
2236 
2237  Base = N.getOperand(0);
2238  Index = N.getOperand(1);
2239  return true;
2240  } else if (N.getOpcode() == ISD::OR) {
2241  if (isIntS16Immediate(N.getOperand(1), imm) &&
2242  (!EncodingAlignment || !(imm % EncodingAlignment)))
2243  return false; // r+i can fold it if we can.
2244 
2245  // If this is an or of disjoint bitfields, we can codegen this as an add
2246  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2247  // disjoint.
2248  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2249 
2250  if (LHSKnown.Zero.getBoolValue()) {
2251  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2252  // If all of the bits are known zero on the LHS or RHS, the add won't
2253  // carry.
2254  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2255  Base = N.getOperand(0);
2256  Index = N.getOperand(1);
2257  return true;
2258  }
2259  }
2260  }
2261 
2262  return false;
2263 }
2264 
2265 // If we happen to be doing an i64 load or store into a stack slot that has
2266 // less than a 4-byte alignment, then the frame-index elimination may need to
2267 // use an indexed load or store instruction (because the offset may not be a
2268 // multiple of 4). The extra register needed to hold the offset comes from the
2269 // register scavenger, and it is possible that the scavenger will need to use
2270 // an emergency spill slot. As a result, we need to make sure that a spill slot
2271 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2272 // stack slot.
2273 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2274  // FIXME: This does not handle the LWA case.
2275  if (VT != MVT::i64)
2276  return;
2277 
2278  // NOTE: We'll exclude negative FIs here, which come from argument
2279  // lowering, because there are no known test cases triggering this problem
2280  // using packed structures (or similar). We can remove this exclusion if
2281  // we find such a test case. The reason why this is so test-case driven is
2282  // because this entire 'fixup' is only to prevent crashes (from the
2283  // register scavenger) on not-really-valid inputs. For example, if we have:
2284  // %a = alloca i1
2285  // %b = bitcast i1* %a to i64*
2286  // store i64* a, i64 b
2287  // then the store should really be marked as 'align 1', but is not. If it
2288  // were marked as 'align 1' then the indexed form would have been
2289  // instruction-selected initially, and the problem this 'fixup' is preventing
2290  // won't happen regardless.
2291  if (FrameIdx < 0)
2292  return;
2293 
2294  MachineFunction &MF = DAG.getMachineFunction();
2295  MachineFrameInfo &MFI = MF.getFrameInfo();
2296 
2297  unsigned Align = MFI.getObjectAlignment(FrameIdx);
2298  if (Align >= 4)
2299  return;
2300 
2301  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2302  FuncInfo->setHasNonRISpills();
2303 }
2304 
2305 /// Returns true if the address N can be represented by a base register plus
2306 /// a signed 16-bit displacement [r+imm], and if it is not better
2307 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2308 /// displacements that are multiples of that value.
2310  SDValue &Base,
2311  SelectionDAG &DAG,
2312  unsigned EncodingAlignment) const {
2313  // FIXME dl should come from parent load or store, not from address
2314  SDLoc dl(N);
2315  // If this can be more profitably realized as r+r, fail.
2316  if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2317  return false;
2318 
2319  if (N.getOpcode() == ISD::ADD) {
2320  int16_t imm = 0;
2321  if (isIntS16Immediate(N.getOperand(1), imm) &&
2322  (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2323  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2324  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2325  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2326  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2327  } else {
2328  Base = N.getOperand(0);
2329  }
2330  return true; // [r+i]
2331  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2332  // Match LOAD (ADD (X, Lo(G))).
2333  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2334  && "Cannot handle constant offsets yet!");
2335  Disp = N.getOperand(1).getOperand(0); // The global address.
2336  assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2337  Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2338  Disp.getOpcode() == ISD::TargetConstantPool ||
2339  Disp.getOpcode() == ISD::TargetJumpTable);
2340  Base = N.getOperand(0);
2341  return true; // [&g+r]
2342  }
2343  } else if (N.getOpcode() == ISD::OR) {
2344  int16_t imm = 0;
2345  if (isIntS16Immediate(N.getOperand(1), imm) &&
2346  (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2347  // If this is an or of disjoint bitfields, we can codegen this as an add
2348  // (for better address arithmetic) if the LHS and RHS of the OR are
2349  // provably disjoint.
2350  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2351 
2352  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2353  // If all of the bits are known zero on the LHS or RHS, the add won't
2354  // carry.
2355  if (FrameIndexSDNode *FI =
2356  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2357  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2358  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2359  } else {
2360  Base = N.getOperand(0);
2361  }
2362  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2363  return true;
2364  }
2365  }
2366  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2367  // Loading from a constant address.
2368 
2369  // If this address fits entirely in a 16-bit sext immediate field, codegen
2370  // this as "d, 0"
2371  int16_t Imm;
2372  if (isIntS16Immediate(CN, Imm) &&
2373  (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2374  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2375  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2376  CN->getValueType(0));
2377  return true;
2378  }
2379 
2380  // Handle 32-bit sext immediates with LIS + addr mode.
2381  if ((CN->getValueType(0) == MVT::i32 ||
2382  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2383  (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2384  int Addr = (int)CN->getZExtValue();
2385 
2386  // Otherwise, break this down into an LIS + disp.
2387  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2388 
2389  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2390  MVT::i32);
2391  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2392  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2393  return true;
2394  }
2395  }
2396 
2397  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2398  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2399  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2400  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2401  } else
2402  Base = N;
2403  return true; // [r+0]
2404 }
2405 
2406 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2407 /// represented as an indexed [r+r] operation.
2409  SDValue &Index,
2410  SelectionDAG &DAG) const {
2411  // Check to see if we can easily represent this as an [r+r] address. This
2412  // will fail if it thinks that the address is more profitably represented as
2413  // reg+imm, e.g. where imm = 0.
2414  if (SelectAddressRegReg(N, Base, Index, DAG))
2415  return true;
2416 
2417  // If the address is the result of an add, we will utilize the fact that the
2418  // address calculation includes an implicit add. However, we can reduce
2419  // register pressure if we do not materialize a constant just for use as the
2420  // index register. We only get rid of the add if it is not an add of a
2421  // value and a 16-bit signed constant and both have a single use.
2422  int16_t imm = 0;
2423  if (N.getOpcode() == ISD::ADD &&
2424  (!isIntS16Immediate(N.getOperand(1), imm) ||
2425  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2426  Base = N.getOperand(0);
2427  Index = N.getOperand(1);
2428  return true;
2429  }
2430 
2431  // Otherwise, do it the hard way, using R0 as the base register.
2432  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2433  N.getValueType());
2434  Index = N;
2435  return true;
2436 }
2437 
2438 /// Returns true if we should use a direct load into vector instruction
2439 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2441 
2442  // If there are any other uses other than scalar to vector, then we should
2443  // keep it as a scalar load -> direct move pattern to prevent multiple
2444  // loads.
2446  if (!LD)
2447  return false;
2448 
2449  EVT MemVT = LD->getMemoryVT();
2450  if (!MemVT.isSimple())
2451  return false;
2452  switch(MemVT.getSimpleVT().SimpleTy) {
2453  case MVT::i64:
2454  break;
2455  case MVT::i32:
2456  if (!ST.hasP8Vector())
2457  return false;
2458  break;
2459  case MVT::i16:
2460  case MVT::i8:
2461  if (!ST.hasP9Vector())
2462  return false;
2463  break;
2464  default:
2465  return false;
2466  }
2467 
2468  SDValue LoadedVal(N, 0);
2469  if (!LoadedVal.hasOneUse())
2470  return false;
2471 
2472  for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2473  UI != UE; ++UI)
2474  if (UI.getUse().get().getResNo() == 0 &&
2475  UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2476  return false;
2477 
2478  return true;
2479 }
2480 
2481 /// getPreIndexedAddressParts - returns true by value, base pointer and
2482 /// offset pointer and addressing mode by reference if the node's address
2483 /// can be legally represented as pre-indexed load / store address.
2485  SDValue &Offset,
2486  ISD::MemIndexedMode &AM,
2487  SelectionDAG &DAG) const {
2488  if (DisablePPCPreinc) return false;
2489 
2490  bool isLoad = true;
2491  SDValue Ptr;
2492  EVT VT;
2493  unsigned Alignment;
2494  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2495  Ptr = LD->getBasePtr();
2496  VT = LD->getMemoryVT();
2497  Alignment = LD->getAlignment();
2498  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2499  Ptr = ST->getBasePtr();
2500  VT = ST->getMemoryVT();
2501  Alignment = ST->getAlignment();
2502  isLoad = false;
2503  } else
2504  return false;
2505 
2506  // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2507  // instructions because we can fold these into a more efficient instruction
2508  // instead, (such as LXSD).
2509  if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2510  return false;
2511  }
2512 
2513  // PowerPC doesn't have preinc load/store instructions for vectors (except
2514  // for QPX, which does have preinc r+r forms).
2515  if (VT.isVector()) {
2516  if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2517  return false;
2518  } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2519  AM = ISD::PRE_INC;
2520  return true;
2521  }
2522  }
2523 
2524  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2525  // Common code will reject creating a pre-inc form if the base pointer
2526  // is a frame index, or if N is a store and the base pointer is either
2527  // the same as or a predecessor of the value being stored. Check for
2528  // those situations here, and try with swapped Base/Offset instead.
2529  bool Swap = false;
2530 
2531  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2532  Swap = true;
2533  else if (!isLoad) {
2534  SDValue Val = cast<StoreSDNode>(N)->getValue();
2535  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2536  Swap = true;
2537  }
2538 
2539  if (Swap)
2540  std::swap(Base, Offset);
2541 
2542  AM = ISD::PRE_INC;
2543  return true;
2544  }
2545 
2546  // LDU/STU can only handle immediates that are a multiple of 4.
2547  if (VT != MVT::i64) {
2548  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2549  return false;
2550  } else {
2551  // LDU/STU need an address with at least 4-byte alignment.
2552  if (Alignment < 4)
2553  return false;
2554 
2555  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2556  return false;
2557  }
2558 
2559  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2560  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
2561  // sext i32 to i64 when addr mode is r+i.
2562  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2563  LD->getExtensionType() == ISD::SEXTLOAD &&
2564  isa<ConstantSDNode>(Offset))
2565  return false;
2566  }
2567 
2568  AM = ISD::PRE_INC;
2569  return true;
2570 }
2571 
2572 //===----------------------------------------------------------------------===//
2573 // LowerOperation implementation
2574 //===----------------------------------------------------------------------===//
2575 
2576 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2577 /// and LoOpFlags to the target MO flags.
2578 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2579  unsigned &HiOpFlags, unsigned &LoOpFlags,
2580  const GlobalValue *GV = nullptr) {
2581  HiOpFlags = PPCII::MO_HA;
2582  LoOpFlags = PPCII::MO_LO;
2583 
2584  // Don't use the pic base if not in PIC relocation model.
2585  if (IsPIC) {
2586  HiOpFlags |= PPCII::MO_PIC_FLAG;
2587  LoOpFlags |= PPCII::MO_PIC_FLAG;
2588  }
2589 
2590  // If this is a reference to a global value that requires a non-lazy-ptr, make
2591  // sure that instruction lowering adds it.
2592  if (GV && Subtarget.hasLazyResolverStub(GV)) {
2593  HiOpFlags |= PPCII::MO_NLP_FLAG;
2594  LoOpFlags |= PPCII::MO_NLP_FLAG;
2595 
2596  if (GV->hasHiddenVisibility()) {
2597  HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2598  LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2599  }
2600  }
2601 }
2602 
2603 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2604  SelectionDAG &DAG) {
2605  SDLoc DL(HiPart);
2606  EVT PtrVT = HiPart.getValueType();
2607  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2608 
2609  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2610  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2611 
2612  // With PIC, the first instruction is actually "GR+hi(&G)".
2613  if (isPIC)
2614  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2615  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2616 
2617  // Generate non-pic code that has direct accesses to the constant pool.
2618  // The address of the global is just (hi(&g)+lo(&g)).
2619  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2620 }
2621 
2623  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2624  FuncInfo->setUsesTOCBasePtr();
2625 }
2626 
2627 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2629 }
2630 
2631 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2632  SDValue GA) {
2633  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2634  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2635  DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2636 
2637  SDValue Ops[] = { GA, Reg };
2638  return DAG.getMemIntrinsicNode(
2639  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2642 }
2643 
2644 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2645  SelectionDAG &DAG) const {
2646  EVT PtrVT = Op.getValueType();
2647  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2648  const Constant *C = CP->getConstVal();
2649 
2650  // 64-bit SVR4 ABI code is always position-independent.
2651  // The actual address of the GlobalValue is stored in the TOC.
2652  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2653  setUsesTOCBasePtr(DAG);
2654  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2655  return getTOCEntry(DAG, SDLoc(CP), true, GA);
2656  }
2657 
2658  unsigned MOHiFlag, MOLoFlag;
2659  bool IsPIC = isPositionIndependent();
2660  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2661 
2662  if (IsPIC && Subtarget.isSVR4ABI()) {
2663  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2665  return getTOCEntry(DAG, SDLoc(CP), false, GA);
2666  }
2667 
2668  SDValue CPIHi =
2669  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2670  SDValue CPILo =
2671  DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2672  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2673 }
2674 
2675 // For 64-bit PowerPC, prefer the more compact relative encodings.
2676 // This trades 32 bits per jump table entry for one or two instructions
2677 // on the jump site.
2679  if (isJumpTableRelative())
2681 
2683 }
2684 
2686  if (Subtarget.isPPC64())
2687  return true;
2689 }
2690 
2692  SelectionDAG &DAG) const {
2693  if (!Subtarget.isPPC64())
2694  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2695 
2696  switch (getTargetMachine().getCodeModel()) {
2697  case CodeModel::Small:
2698  case CodeModel::Medium:
2699  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2700  default:
2701  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2702  getPointerTy(DAG.getDataLayout()));
2703  }
2704 }
2705 
2706 const MCExpr *
2708  unsigned JTI,
2709  MCContext &Ctx) const {
2710  if (!Subtarget.isPPC64())
2711  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2712 
2713  switch (getTargetMachine().getCodeModel()) {
2714  case CodeModel::Small:
2715  case CodeModel::Medium:
2716  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2717  default:
2718  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2719  }
2720 }
2721 
2722 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2723  EVT PtrVT = Op.getValueType();
2724  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2725 
2726  // 64-bit SVR4 ABI code is always position-independent.
2727  // The actual address of the GlobalValue is stored in the TOC.
2728  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2729  setUsesTOCBasePtr(DAG);
2730  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2731  return getTOCEntry(DAG, SDLoc(JT), true, GA);
2732  }
2733 
2734  unsigned MOHiFlag, MOLoFlag;
2735  bool IsPIC = isPositionIndependent();
2736  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2737 
2738  if (IsPIC && Subtarget.isSVR4ABI()) {
2739  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2741  return getTOCEntry(DAG, SDLoc(GA), false, GA);
2742  }
2743 
2744  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2745  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2746  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2747 }
2748 
2749 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2750  SelectionDAG &DAG) const {
2751  EVT PtrVT = Op.getValueType();
2752  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2753  const BlockAddress *BA = BASDN->getBlockAddress();
2754 
2755  // 64-bit SVR4 ABI code is always position-independent.
2756  // The actual BlockAddress is stored in the TOC.
2757  if (Subtarget.isSVR4ABI() &&
2758  (Subtarget.isPPC64() || isPositionIndependent())) {
2759  if (Subtarget.isPPC64())
2760  setUsesTOCBasePtr(DAG);
2761  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2762  return getTOCEntry(DAG, SDLoc(BASDN), Subtarget.isPPC64(), GA);
2763  }
2764 
2765  unsigned MOHiFlag, MOLoFlag;
2766  bool IsPIC = isPositionIndependent();
2767  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2768  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2769  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2770  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2771 }
2772 
2773 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2774  SelectionDAG &DAG) const {
2775  // FIXME: TLS addresses currently use medium model code sequences,
2776  // which is the most useful form. Eventually support for small and
2777  // large models could be added if users need it, at the cost of
2778  // additional complexity.
2779  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2780  if (DAG.getTarget().useEmulatedTLS())
2781  return LowerToTLSEmulatedModel(GA, DAG);
2782 
2783  SDLoc dl(GA);
2784  const GlobalValue *GV = GA->getGlobal();
2785  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2786  bool is64bit = Subtarget.isPPC64();
2787  const Module *M = DAG.getMachineFunction().getFunction().getParent();
2788  PICLevel::Level picLevel = M->getPICLevel();
2789 
2790  const TargetMachine &TM = getTargetMachine();
2792 
2793  if (Model == TLSModel::LocalExec) {
2794  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2796  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2798  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2799  : DAG.getRegister(PPC::R2, MVT::i32);
2800 
2801  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2802  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2803  }
2804 
2805  if (Model == TLSModel::InitialExec) {
2806  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2807  SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2808  PPCII::MO_TLS);
2809  SDValue GOTPtr;
2810  if (is64bit) {
2811  setUsesTOCBasePtr(DAG);
2812  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2813  GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2814  PtrVT, GOTReg, TGA);
2815  } else {
2816  if (!TM.isPositionIndependent())
2817  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2818  else if (picLevel == PICLevel::SmallPIC)
2819  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2820  else
2821  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2822  }
2823  SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2824  PtrVT, TGA, GOTPtr);
2825  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2826  }
2827 
2828  if (Model == TLSModel::GeneralDynamic) {
2829  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2830  SDValue GOTPtr;
2831  if (is64bit) {
2832  setUsesTOCBasePtr(DAG);
2833  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2834  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2835  GOTReg, TGA);
2836  } else {
2837  if (picLevel == PICLevel::SmallPIC)
2838  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2839  else
2840  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2841  }
2842  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2843  GOTPtr, TGA, TGA);
2844  }
2845 
2846  if (Model == TLSModel::LocalDynamic) {
2847  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2848  SDValue GOTPtr;
2849  if (is64bit) {
2850  setUsesTOCBasePtr(DAG);
2851  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2852  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2853  GOTReg, TGA);
2854  } else {
2855  if (picLevel == PICLevel::SmallPIC)
2856  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2857  else
2858  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2859  }
2860  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2861  PtrVT, GOTPtr, TGA, TGA);
2862  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2863  PtrVT, TLSAddr, TGA);
2864  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2865  }
2866 
2867  llvm_unreachable("Unknown TLS model!");
2868 }
2869 
2870 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2871  SelectionDAG &DAG) const {
2872  EVT PtrVT = Op.getValueType();
2873  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2874  SDLoc DL(GSDN);
2875  const GlobalValue *GV = GSDN->getGlobal();
2876 
2877  // 64-bit SVR4 ABI code is always position-independent.
2878  // The actual address of the GlobalValue is stored in the TOC.
2879  if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2880  setUsesTOCBasePtr(DAG);
2881  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2882  return getTOCEntry(DAG, DL, true, GA);
2883  }
2884 
2885  unsigned MOHiFlag, MOLoFlag;
2886  bool IsPIC = isPositionIndependent();
2887  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2888 
2889  if (IsPIC && Subtarget.isSVR4ABI()) {
2890  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2891  GSDN->getOffset(),
2893  return getTOCEntry(DAG, DL, false, GA);
2894  }
2895 
2896  SDValue GAHi =
2897  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2898  SDValue GALo =
2899  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2900 
2901  SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2902 
2903  // If the global reference is actually to a non-lazy-pointer, we have to do an
2904  // extra load to get the address of the global.
2905  if (MOHiFlag & PPCII::MO_NLP_FLAG)
2906  Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2907  return Ptr;
2908 }
2909 
2910 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2911  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2912  SDLoc dl(Op);
2913 
2914  if (Op.getValueType() == MVT::v2i64) {
2915  // When the operands themselves are v2i64 values, we need to do something
2916  // special because VSX has no underlying comparison operations for these.
2917  if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2918  // Equality can be handled by casting to the legal type for Altivec
2919  // comparisons, everything else needs to be expanded.
2920  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2921  return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2922  DAG.getSetCC(dl, MVT::v4i32,
2923  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2924  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2925  CC));
2926  }
2927 
2928  return SDValue();
2929  }
2930 
2931  // We handle most of these in the usual way.
2932  return Op;
2933  }
2934 
2935  // If we're comparing for equality to zero, expose the fact that this is
2936  // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2937  // fold the new nodes.
2938  if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2939  return V;
2940 
2941  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2942  // Leave comparisons against 0 and -1 alone for now, since they're usually
2943  // optimized. FIXME: revisit this when we can custom lower all setcc
2944  // optimizations.
2945  if (C->isAllOnesValue() || C->isNullValue())
2946  return SDValue();
2947  }
2948 
2949  // If we have an integer seteq/setne, turn it into a compare against zero
2950  // by xor'ing the rhs with the lhs, which is faster than setting a
2951  // condition register, reading it back out, and masking the correct bit. The
2952  // normal approach here uses sub to do this instead of xor. Using xor exposes
2953  // the result to other bit-twiddling opportunities.
2954  EVT LHSVT = Op.getOperand(0).getValueType();
2955  if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2956  EVT VT = Op.getValueType();
2957  SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2958  Op.getOperand(1));
2959  return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2960  }
2961  return SDValue();
2962 }
2963 
2964 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2965  SDNode *Node = Op.getNode();
2966  EVT VT = Node->getValueType(0);
2967  EVT PtrVT = getPointerTy(DAG.getDataLayout());
2968  SDValue InChain = Node->getOperand(0);
2969  SDValue VAListPtr = Node->getOperand(1);
2970  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2971  SDLoc dl(Node);
2972 
2973  assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2974 
2975  // gpr_index
2976  SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2977  VAListPtr, MachinePointerInfo(SV), MVT::i8);
2978  InChain = GprIndex.getValue(1);
2979 
2980  if (VT == MVT::i64) {
2981  // Check if GprIndex is even
2982  SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2983  DAG.getConstant(1, dl, MVT::i32));
2984  SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2985  DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2986  SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2987  DAG.getConstant(1, dl, MVT::i32));
2988  // Align GprIndex to be even if it isn't
2989  GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2990  GprIndex);
2991  }
2992 
2993  // fpr index is 1 byte after gpr
2994  SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2995  DAG.getConstant(1, dl, MVT::i32));
2996 
2997  // fpr
2998  SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2999  FprPtr, MachinePointerInfo(SV), MVT::i8);
3000  InChain = FprIndex.getValue(1);
3001 
3002  SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3003  DAG.getConstant(8, dl, MVT::i32));
3004 
3005  SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3006  DAG.getConstant(4, dl, MVT::i32));
3007 
3008  // areas
3009  SDValue OverflowArea =
3010  DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3011  InChain = OverflowArea.getValue(1);
3012 
3013  SDValue RegSaveArea =
3014  DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3015  InChain = RegSaveArea.getValue(1);
3016 
3017  // select overflow_area if index > 8
3018  SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3019  DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3020 
3021  // adjustment constant gpr_index * 4/8
3022  SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3023  VT.isInteger() ? GprIndex : FprIndex,
3024  DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3025  MVT::i32));
3026 
3027  // OurReg = RegSaveArea + RegConstant
3028  SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3029  RegConstant);
3030 
3031  // Floating types are 32 bytes into RegSaveArea
3032  if (VT.isFloatingPoint())
3033  OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3034  DAG.getConstant(32, dl, MVT::i32));
3035 
3036  // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3037  SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3038  VT.isInteger() ? GprIndex : FprIndex,
3039  DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3040  MVT::i32));
3041 
3042  InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3043  VT.isInteger() ? VAListPtr : FprPtr,
3045 
3046  // determine if we should load from reg_save_area or overflow_area
3047  SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3048 
3049  // increase overflow_area by 4/8 if gpr/fpr > 8
3050  SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3051  DAG.getConstant(VT.isInteger() ? 4 : 8,
3052  dl, MVT::i32));
3053 
3054  OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3055  OverflowAreaPlusN);
3056 
3057  InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3059 
3060  return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3061 }
3062 
3063 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3064  assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3065 
3066  // We have to copy the entire va_list struct:
3067  // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3068  return DAG.getMemcpy(Op.getOperand(0), Op,
3069  Op.getOperand(1), Op.getOperand(2),
3070  DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3072 }
3073 
3074 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3075  SelectionDAG &DAG) const {
3076  return Op.getOperand(0);
3077 }
3078 
3079 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3080  SelectionDAG &DAG) const {
3081  SDValue Chain = Op.getOperand(0);
3082  SDValue Trmp = Op.getOperand(1); // trampoline
3083  SDValue FPtr = Op.getOperand(2); // nested function
3084  SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3085  SDLoc dl(Op);
3086 
3087  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3088  bool isPPC64 = (PtrVT == MVT::i64);
3089  Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3090 
3093 
3094  Entry.Ty = IntPtrTy;
3095  Entry.Node = Trmp; Args.push_back(Entry);
3096 
3097  // TrampSize == (isPPC64 ? 48 : 40);
3098  Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3099  isPPC64 ? MVT::i64 : MVT::i32);
3100  Args.push_back(Entry);
3101 
3102  Entry.Node = FPtr; Args.push_back(Entry);
3103  Entry.Node = Nest; Args.push_back(Entry);
3104 
3105  // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3107  CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3109  DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3110 
3111  std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3112  return CallResult.second;
3113 }
3114 
3115 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3116  MachineFunction &MF = DAG.getMachineFunction();
3117  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3118  EVT PtrVT = getPointerTy(MF.getDataLayout());
3119 
3120  SDLoc dl(Op);
3121 
3122  if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3123  // vastart just stores the address of the VarArgsFrameIndex slot into the
3124  // memory location argument.
3125  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3126  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3127  return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3128  MachinePointerInfo(SV));
3129  }
3130 
3131  // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3132  // We suppose the given va_list is already allocated.
3133  //
3134  // typedef struct {
3135  // char gpr; /* index into the array of 8 GPRs
3136  // * stored in the register save area
3137  // * gpr=0 corresponds to r3,
3138  // * gpr=1 to r4, etc.
3139  // */
3140  // char fpr; /* index into the array of 8 FPRs
3141  // * stored in the register save area
3142  // * fpr=0 corresponds to f1,
3143  // * fpr=1 to f2, etc.
3144  // */
3145  // char *overflow_arg_area;
3146  // /* location on stack that holds
3147  // * the next overflow argument
3148  // */
3149  // char *reg_save_area;
3150  // /* where r3:r10 and f1:f8 (if saved)
3151  // * are stored
3152  // */
3153  // } va_list[1];
3154 
3155  SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3156  SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3157  SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3158  PtrVT);
3159  SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3160  PtrVT);
3161 
3162  uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3163  SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3164 
3165  uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3166  SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3167 
3168  uint64_t FPROffset = 1;
3169  SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3170 
3171  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3172 
3173  // Store first byte : number of int regs
3174  SDValue firstStore =
3175  DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3177  uint64_t nextOffset = FPROffset;
3178  SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3179  ConstFPROffset);
3180 
3181  // Store second byte : number of float regs
3182  SDValue secondStore =
3183  DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3184  MachinePointerInfo(SV, nextOffset), MVT::i8);
3185  nextOffset += StackOffset;
3186  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3187 
3188  // Store second word : arguments given on stack
3189  SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3190  MachinePointerInfo(SV, nextOffset));
3191  nextOffset += FrameOffset;
3192  nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3193 
3194  // Store third word : arguments given in registers
3195  return DAG.getStore(thirdStore, dl, FR, nextPtr,
3196  MachinePointerInfo(SV, nextOffset));
3197 }
3198 
3199 /// FPR - The set of FP registers that should be allocated for arguments,
3200 /// on Darwin.
3201 static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
3202  PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
3203  PPC::F11, PPC::F12, PPC::F13};
3204 
3205 /// QFPR - The set of QPX registers that should be allocated for arguments.
3206 static const MCPhysReg QFPR[] = {
3207  PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7,
3208  PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3209 
3210 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3211 /// the stack.
3212 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3213  unsigned PtrByteSize) {
3214  unsigned ArgSize = ArgVT.getStoreSize();
3215  if (Flags.isByVal())
3216  ArgSize = Flags.getByValSize();
3217 
3218  // Round up to multiples of the pointer size, except for array members,
3219  // which are always packed.
3220  if (!Flags.isInConsecutiveRegs())
3221  ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3222 
3223  return ArgSize;
3224 }
3225 
3226 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3227 /// on the stack.
3228 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3229  ISD::ArgFlagsTy Flags,
3230  unsigned PtrByteSize) {
3231  unsigned Align = PtrByteSize;
3232 
3233  // Altivec parameters are padded to a 16 byte boundary.
3234  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3235  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3236  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3237  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3238  Align = 16;
3239  // QPX vector types stored in double-precision are padded to a 32 byte
3240  // boundary.
3241  else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3242  Align = 32;
3243 
3244  // ByVal parameters are aligned as requested.
3245  if (Flags.isByVal()) {
3246  unsigned BVAlign = Flags.getByValAlign();
3247  if (BVAlign > PtrByteSize) {
3248  if (BVAlign % PtrByteSize != 0)
3250  "ByVal alignment is not a multiple of the pointer size");
3251 
3252  Align = BVAlign;
3253  }
3254  }
3255 
3256  // Array members are always packed to their original alignment.
3257  if (Flags.isInConsecutiveRegs()) {
3258  // If the array member was split into multiple registers, the first
3259  // needs to be aligned to the size of the full type. (Except for
3260  // ppcf128, which is only aligned as its f64 components.)
3261  if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3262  Align = OrigVT.getStoreSize();
3263  else
3264  Align = ArgVT.getStoreSize();
3265  }
3266 
3267  return Align;
3268 }
3269 
3270 /// CalculateStackSlotUsed - Return whether this argument will use its
3271 /// stack slot (instead of being passed in registers). ArgOffset,
3272 /// AvailableFPRs, and AvailableVRs must hold the current argument
3273 /// position, and will be updated to account for this argument.
3274 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3275  ISD::ArgFlagsTy Flags,
3276  unsigned PtrByteSize,
3277  unsigned LinkageSize,
3278  unsigned ParamAreaSize,
3279  unsigned &ArgOffset,
3280  unsigned &AvailableFPRs,
3281  unsigned &AvailableVRs, bool HasQPX) {
3282  bool UseMemory = false;
3283 
3284  // Respect alignment of argument on the stack.
3285  unsigned Align =
3286  CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3287  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3288  // If there's no space left in the argument save area, we must
3289  // use memory (this check also catches zero-sized arguments).
3290  if (ArgOffset >= LinkageSize + ParamAreaSize)
3291  UseMemory = true;
3292 
3293  // Allocate argument on the stack.
3294  ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3295  if (Flags.isInConsecutiveRegsLast())
3296  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3297  // If we overran the argument save area, we must use memory
3298  // (this check catches arguments passed partially in memory)
3299  if (ArgOffset > LinkageSize + ParamAreaSize)
3300  UseMemory = true;
3301 
3302  // However, if the argument is actually passed in an FPR or a VR,
3303  // we don't use memory after all.
3304  if (!Flags.isByVal()) {
3305  if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3306  // QPX registers overlap with the scalar FP registers.
3307  (HasQPX && (ArgVT == MVT::v4f32 ||
3308  ArgVT == MVT::v4f64 ||
3309  ArgVT == MVT::v4i1)))
3310  if (AvailableFPRs > 0) {
3311  --AvailableFPRs;
3312  return false;
3313  }
3314  if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3315  ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3316  ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3317  ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3318  if (AvailableVRs > 0) {
3319  --AvailableVRs;
3320  return false;
3321  }
3322  }
3323 
3324  return UseMemory;
3325 }
3326 
3327 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3328 /// ensure minimum alignment required for target.
3330  unsigned NumBytes) {
3331  unsigned TargetAlign = Lowering->getStackAlignment();
3332  unsigned AlignMask = TargetAlign - 1;
3333  NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3334  return NumBytes;
3335 }
3336 
3337 SDValue PPCTargetLowering::LowerFormalArguments(
3338  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3339  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3340  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3341  if (Subtarget.isSVR4ABI()) {
3342  if (Subtarget.isPPC64())
3343  return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3344  dl, DAG, InVals);
3345  else
3346  return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3347  dl, DAG, InVals);
3348  } else {
3349  return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3350  dl, DAG, InVals);
3351  }
3352 }
3353 
3354 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3355  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3356  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3357  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3358 
3359  // 32-bit SVR4 ABI Stack Frame Layout:
3360  // +-----------------------------------+
3361  // +--> | Back chain |
3362  // | +-----------------------------------+
3363  // | | Floating-point register save area |
3364  // | +-----------------------------------+
3365  // | | General register save area |
3366  // | +-----------------------------------+
3367  // | | CR save word |
3368  // | +-----------------------------------+
3369  // | | VRSAVE save word |
3370  // | +-----------------------------------+
3371  // | | Alignment padding |
3372  // | +-----------------------------------+
3373  // | | Vector register save area |
3374  // | +-----------------------------------+
3375  // | | Local variable space |
3376  // | +-----------------------------------+
3377  // | | Parameter list area |
3378  // | +-----------------------------------+
3379  // | | LR save word |
3380  // | +-----------------------------------+
3381  // SP--> +--- | Back chain |
3382  // +-----------------------------------+
3383  //
3384  // Specifications:
3385  // System V Application Binary Interface PowerPC Processor Supplement
3386  // AltiVec Technology Programming Interface Manual
3387 
3388  MachineFunction &MF = DAG.getMachineFunction();
3389  MachineFrameInfo &MFI = MF.getFrameInfo();
3390  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3391 
3392  EVT PtrVT = getPointerTy(MF.getDataLayout());
3393  // Potential tail calls could cause overwriting of argument stack slots.
3394  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3395  (CallConv == CallingConv::Fast));
3396  unsigned PtrByteSize = 4;
3397 
3398  // Assign locations to all of the incoming arguments.
3400  PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3401  *DAG.getContext());
3402 
3403  // Reserve space for the linkage area on the stack.
3404  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3405  CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3406  if (useSoftFloat() || hasSPE())
3407  CCInfo.PreAnalyzeFormalArguments(Ins);
3408 
3409  CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3410  CCInfo.clearWasPPCF128();
3411 
3412  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3413  CCValAssign &VA = ArgLocs[i];
3414 
3415  // Arguments stored in registers.
3416  if (VA.isRegLoc()) {
3417  const TargetRegisterClass *RC;
3418  EVT ValVT = VA.getValVT();
3419 
3420  switch (ValVT.getSimpleVT().SimpleTy) {
3421  default:
3422  llvm_unreachable("ValVT not supported by formal arguments Lowering");
3423  case MVT::i1:
3424  case MVT::i32:
3425  RC = &PPC::GPRCRegClass;
3426  break;
3427  case MVT::f32:
3428  if (Subtarget.hasP8Vector())
3429  RC = &PPC::VSSRCRegClass;
3430  else if (Subtarget.hasSPE())
3431  RC = &PPC::SPE4RCRegClass;
3432  else
3433  RC = &PPC::F4RCRegClass;
3434  break;
3435  case MVT::f64:
3436  if (Subtarget.hasVSX())
3437  RC = &PPC::VSFRCRegClass;
3438  else if (Subtarget.hasSPE())
3439  RC = &PPC::SPERCRegClass;
3440  else
3441  RC = &PPC::F8RCRegClass;
3442  break;
3443  case MVT::v16i8:
3444  case MVT::v8i16:
3445  case MVT::v4i32:
3446  RC = &PPC::VRRCRegClass;
3447  break;
3448  case MVT::v4f32:
3449  RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3450  break;
3451  case MVT::v2f64:
3452  case MVT::v2i64:
3453  RC = &PPC::VRRCRegClass;
3454  break;
3455  case MVT::v4f64:
3456  RC = &PPC::QFRCRegClass;
3457  break;
3458  case MVT::v4i1:
3459  RC = &PPC::QBRCRegClass;
3460  break;
3461  }
3462 
3463  // Transform the arguments stored in physical registers into virtual ones.
3464  unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3465  SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3466  ValVT == MVT::i1 ? MVT::i32 : ValVT);
3467 
3468  if (ValVT == MVT::i1)
3469  ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3470 
3471  InVals.push_back(ArgValue);
3472  } else {
3473  // Argument stored in memory.
3474  assert(VA.isMemLoc());
3475 
3476  // Get the extended size of the argument type in stack
3477  unsigned ArgSize = VA.getLocVT().getStoreSize();
3478  // Get the actual size of the argument type
3479  unsigned ObjSize = VA.getValVT().getStoreSize();
3480  unsigned ArgOffset = VA.getLocMemOffset();
3481  // Stack objects in PPC32 are right justified.
3482  ArgOffset += ArgSize - ObjSize;
3483  int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3484 
3485  // Create load nodes to retrieve arguments from the stack.
3486  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3487  InVals.push_back(
3488  DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3489  }
3490  }
3491 
3492  // Assign locations to all of the incoming aggregate by value arguments.
3493  // Aggregates passed by value are stored in the local variable space of the
3494  // caller's stack frame, right above the parameter list area.
3495  SmallVector<CCValAssign, 16> ByValArgLocs;
3496  CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3497  ByValArgLocs, *DAG.getContext());
3498 
3499  // Reserve stack space for the allocations in CCInfo.
3500  CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3501 
3502  CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3503 
3504  // Area that is at least reserved in the caller of this function.
3505  unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3506  MinReservedArea = std::max(MinReservedArea, LinkageSize);
3507 
3508  // Set the size that is at least reserved in caller of this function. Tail
3509  // call optimized function's reserved stack space needs to be aligned so that
3510  // taking the difference between two stack areas will result in an aligned
3511  // stack.
3512  MinReservedArea =
3513  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3514  FuncInfo->setMinReservedArea(MinReservedArea);
3515 
3516  SmallVector<SDValue, 8> MemOps;
3517 
3518  // If the function takes variable number of arguments, make a frame index for
3519  // the start of the first vararg value... for expansion of llvm.va_start.
3520  if (isVarArg) {
3521  static const MCPhysReg GPArgRegs[] = {
3522  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3523  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3524  };
3525  const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3526 
3527  static const MCPhysReg FPArgRegs[] = {
3528  PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3529  PPC::F8
3530  };
3531  unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3532 
3533  if (useSoftFloat() || hasSPE())
3534  NumFPArgRegs = 0;
3535 
3536  FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3537  FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3538 
3539  // Make room for NumGPArgRegs and NumFPArgRegs.
3540  int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3541  NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3542 
3543  FuncInfo->setVarArgsStackOffset(
3544  MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3545  CCInfo.getNextStackOffset(), true));
3546 
3547  FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3548  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3549 
3550  // The fixed integer arguments of a variadic function are stored to the
3551  // VarArgsFrameIndex on the stack so that they may be loaded by
3552  // dereferencing the result of va_next.
3553  for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3554  // Get an existing live-in vreg, or add a new one.
3555  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3556  if (!VReg)
3557  VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3558 
3559  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3560  SDValue Store =
3561  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3562  MemOps.push_back(Store);
3563  // Increment the address by four for the next argument to store
3564  SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3565  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3566  }
3567 
3568  // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3569  // is set.
3570  // The double arguments are stored to the VarArgsFrameIndex
3571  // on the stack.
3572  for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3573  // Get an existing live-in vreg, or add a new one.
3574  unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3575  if (!VReg)
3576  VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3577 
3578  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3579  SDValue Store =
3580  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3581  MemOps.push_back(Store);
3582  // Increment the address by eight for the next argument to store
3583  SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3584  PtrVT);
3585  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3586  }
3587  }
3588 
3589  if (!MemOps.empty())
3590  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3591 
3592  return Chain;
3593 }
3594 
3595 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3596 // value to MVT::i64 and then truncate to the correct register size.
3597 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3598  EVT ObjectVT, SelectionDAG &DAG,
3599  SDValue ArgVal,
3600  const SDLoc &dl) const {
3601  if (Flags.isSExt())
3602  ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3603  DAG.getValueType(ObjectVT));
3604  else if (Flags.isZExt())
3605  ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3606  DAG.getValueType(ObjectVT));
3607 
3608  return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3609 }
3610 
3611 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3612  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3613  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3614  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3615  // TODO: add description of PPC stack frame format, or at least some docs.
3616  //
3617  bool isELFv2ABI = Subtarget.isELFv2ABI();
3618  bool isLittleEndian = Subtarget.isLittleEndian();
3619  MachineFunction &MF = DAG.getMachineFunction();
3620  MachineFrameInfo &MFI = MF.getFrameInfo();
3621  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3622 
3623  assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3624  "fastcc not supported on varargs functions");
3625 
3626  EVT PtrVT = getPointerTy(MF.getDataLayout());
3627  // Potential tail calls could cause overwriting of argument stack slots.
3628  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3629  (CallConv == CallingConv::Fast));
3630  unsigned PtrByteSize = 8;
3631  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3632 
3633  static const MCPhysReg GPR[] = {
3634  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3635  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3636  };
3637  static const MCPhysReg VR[] = {
3638  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3639  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3640  };
3641 
3642  const unsigned Num_GPR_Regs = array_lengthof(GPR);
3643  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3644  const unsigned Num_VR_Regs = array_lengthof(VR);
3645  const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3646 
3647  // Do a first pass over the arguments to determine whether the ABI
3648  // guarantees that our caller has allocated the parameter save area
3649  // on its stack frame. In the ELFv1 ABI, this is always the case;
3650  // in the ELFv2 ABI, it is true if this is a vararg function or if
3651  // any parameter is located in a stack slot.
3652 
3653  bool HasParameterArea = !isELFv2ABI || isVarArg;
3654  unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3655  unsigned NumBytes = LinkageSize;
3656  unsigned AvailableFPRs = Num_FPR_Regs;
3657  unsigned AvailableVRs = Num_VR_Regs;
3658  for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3659  if (Ins[i].Flags.isNest())
3660  continue;
3661 
3662  if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3663  PtrByteSize, LinkageSize, ParamAreaSize,
3664  NumBytes, AvailableFPRs, AvailableVRs,
3665  Subtarget.hasQPX()))
3666  HasParameterArea = true;
3667  }
3668 
3669  // Add DAG nodes to load the arguments or copy them out of registers. On
3670  // entry to a function on PPC, the arguments start after the linkage area,
3671  // although the first ones are often in registers.
3672 
3673  unsigned ArgOffset = LinkageSize;
3674  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3675  unsigned &QFPR_idx = FPR_idx;
3676  SmallVector<SDValue, 8> MemOps;
3678  unsigned CurArgIdx = 0;
3679  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3680  SDValue ArgVal;
3681  bool needsLoad = false;
3682  EVT ObjectVT = Ins[ArgNo].VT;
3683  EVT OrigVT = Ins[ArgNo].ArgVT;
3684  unsigned ObjSize = ObjectVT.getStoreSize();
3685  unsigned ArgSize = ObjSize;
3686  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3687  if (Ins[ArgNo].isOrigArg()) {
3688  std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3689  CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3690  }
3691  // We re-align the argument offset for each argument, except when using the
3692  // fast calling convention, when we need to make sure we do that only when
3693  // we'll actually use a stack slot.
3694  unsigned CurArgOffset, Align;
3695  auto ComputeArgOffset = [&]() {
3696  /* Respect alignment of argument on the stack. */
3697  Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3698  ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3699  CurArgOffset = ArgOffset;
3700  };
3701 
3702  if (CallConv != CallingConv::Fast) {
3703  ComputeArgOffset();
3704 
3705  /* Compute GPR index associated with argument offset. */
3706  GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3707  GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3708  }
3709 
3710  // FIXME the codegen can be much improved in some cases.
3711  // We do not have to keep everything in memory.
3712  if (Flags.isByVal()) {
3713  assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3714 
3715  if (CallConv == CallingConv::Fast)
3716  ComputeArgOffset();
3717 
3718  // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3719  ObjSize = Flags.getByValSize();
3720  ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3721  // Empty aggregate parameters do not take up registers. Examples:
3722  // struct { } a;
3723  // union { } b;
3724  // int c[0];
3725  // etc. However, we have to provide a place-holder in InVals, so
3726  // pretend we have an 8-byte item at the current address for that
3727  // purpose.
3728  if (!ObjSize) {
3729  int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3730  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3731  InVals.push_back(FIN);
3732  continue;
3733  }
3734 
3735  // Create a stack object covering all stack doublewords occupied
3736  // by the argument. If the argument is (fully or partially) on
3737  // the stack, or if the argument is fully in registers but the
3738  // caller has allocated the parameter save anyway, we can refer
3739  // directly to the caller's stack frame. Otherwise, create a
3740  // local copy in our own frame.
3741  int FI;
3742  if (HasParameterArea ||
3743  ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3744  FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3745  else
3746  FI = MFI.CreateStackObject(ArgSize, Align, false);
3747  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3748 
3749  // Handle aggregates smaller than 8 bytes.
3750  if (ObjSize < PtrByteSize) {
3751  // The value of the object is its address, which differs from the
3752  // address of the enclosing doubleword on big-endian systems.
3753  SDValue Arg = FIN;
3754  if (!isLittleEndian) {
3755  SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3756  Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3757  }
3758  InVals.push_back(Arg);
3759 
3760  if (GPR_idx != Num_GPR_Regs) {
3761  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3762  FuncInfo->addLiveInAttr(VReg, Flags);
3763  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3764  SDValue Store;
3765 
3766  if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3767  EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3768  (ObjSize == 2 ? MVT::i16 : MVT::i32));
3769  Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3770  MachinePointerInfo(&*FuncArg), ObjType);
3771  } else {
3772  // For sizes that don't fit a truncating store (3, 5, 6, 7),
3773  // store the whole register as-is to the parameter save area
3774  // slot.
3775  Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3776  MachinePointerInfo(&*FuncArg));
3777  }
3778 
3779  MemOps.push_back(Store);
3780  }
3781  // Whether we copied from a register or not, advance the offset
3782  // into the parameter save area by a full doubleword.
3783  ArgOffset += PtrByteSize;
3784  continue;
3785  }
3786 
3787  // The value of the object is its address, which is the address of
3788  // its first stack doubleword.
3789  InVals.push_back(FIN);
3790 
3791  // Store whatever pieces of the object are in registers to memory.
3792  for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3793  if (GPR_idx == Num_GPR_Regs)
3794  break;
3795 
3796  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3797  FuncInfo->addLiveInAttr(VReg, Flags);
3798  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3799  SDValue Addr = FIN;
3800  if (j) {
3801  SDValue Off = DAG.getConstant(j, dl, PtrVT);
3802  Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3803  }
3804  SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3805  MachinePointerInfo(&*FuncArg, j));
3806  MemOps.push_back(Store);
3807  ++GPR_idx;
3808  }
3809  ArgOffset += ArgSize;
3810  continue;
3811  }
3812 
3813  switch (ObjectVT.getSimpleVT().SimpleTy) {
3814  default: llvm_unreachable("Unhandled argument type!");
3815  case MVT::i1:
3816  case MVT::i32:
3817  case MVT::i64:
3818  if (Flags.isNest()) {
3819  // The 'nest' parameter, if any, is passed in R11.
3820  unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3821  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3822 
3823  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3824  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3825 
3826  break;
3827  }
3828 
3829  // These can be scalar arguments or elements of an integer array type
3830  // passed directly. Clang may use those instead of "byval" aggregate
3831  // types to avoid forcing arguments to memory unnecessarily.
3832  if (GPR_idx != Num_GPR_Regs) {
3833  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3834  FuncInfo->addLiveInAttr(VReg, Flags);
3835  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3836 
3837  if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3838  // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3839  // value to MVT::i64 and then truncate to the correct register size.
3840  ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3841  } else {
3842  if (CallConv == CallingConv::Fast)
3843  ComputeArgOffset();
3844 
3845  needsLoad = true;
3846  ArgSize = PtrByteSize;
3847  }
3848  if (CallConv != CallingConv::Fast || needsLoad)
3849  ArgOffset += 8;
3850  break;
3851 
3852  case MVT::f32:
3853  case MVT::f64:
3854  // These can be scalar arguments or elements of a float array type
3855  // passed directly. The latter are used to implement ELFv2 homogenous
3856  // float aggregates.
3857  if (FPR_idx != Num_FPR_Regs) {
3858  unsigned VReg;
3859 
3860  if (ObjectVT == MVT::f32)
3861  VReg = MF.addLiveIn(FPR[FPR_idx],
3862  Subtarget.hasP8Vector()
3863  ? &PPC::VSSRCRegClass
3864  : &PPC::F4RCRegClass);
3865  else
3866  VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3867  ? &PPC::VSFRCRegClass
3868  : &PPC::F8RCRegClass);
3869 
3870  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3871  ++FPR_idx;
3872  } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3873  // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3874  // once we support fp <-> gpr moves.
3875 
3876  // This can only ever happen in the presence of f32 array types,
3877  // since otherwise we never run out of FPRs before running out
3878  // of GPRs.
3879  unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3880  FuncInfo->addLiveInAttr(VReg, Flags);
3881  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3882 
3883  if (ObjectVT == MVT::f32) {
3884  if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3885  ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3886  DAG.getConstant(32, dl, MVT::i32));
3887  ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3888  }
3889 
3890  ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3891  } else {
3892  if (CallConv == CallingConv::Fast)
3893  ComputeArgOffset();
3894 
3895  needsLoad = true;
3896  }
3897 
3898  // When passing an array of floats, the array occupies consecutive
3899  // space in the argument area; only round up to the next doubleword
3900  // at the end of the array. Otherwise, each float takes 8 bytes.
3901  if (CallConv != CallingConv::Fast || needsLoad) {
3902  ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3903  ArgOffset += ArgSize;
3904  if (Flags.isInConsecutiveRegsLast())
3905  ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3906  }
3907  break;
3908  case MVT::v4f32:
3909  case MVT::v4i32:
3910  case MVT::v8i16:
3911  case MVT::v16i8:
3912  case MVT::v2f64:
3913  case MVT::v2i64:
3914  case MVT::v1i128:
3915  case MVT::f128:
3916  if (!Subtarget.hasQPX()) {
3917  // These can be scalar arguments or elements of a vector array type
3918  // passed directly. The latter are used to implement ELFv2 homogenous
3919  // vector aggregates.
3920  if (VR_idx != Num_VR_Regs) {
3921  unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3922  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3923  ++VR_idx;
3924  } else {
3925  if (CallConv == CallingConv::Fast)
3926  ComputeArgOffset();
3927  needsLoad = true;
3928  }
3929  if (CallConv != CallingConv::Fast || needsLoad)
3930  ArgOffset += 16;
3931  break;
3932  } // not QPX
3933 
3934  assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3935  "Invalid QPX parameter type");
3937 
3938  case MVT::v4f64:
3939  case MVT::v4i1:
3940  // QPX vectors are treated like their scalar floating-point subregisters
3941  // (except that they're larger).
3942  unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3943  if (QFPR_idx != Num_QFPR_Regs) {
3944  const TargetRegisterClass *RC;
3945  switch (ObjectVT.getSimpleVT().SimpleTy) {
3946  case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3947  case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3948  default: RC = &PPC::QBRCRegClass; break;
3949  }
3950 
3951  unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3952  ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3953  ++QFPR_idx;
3954  } else {
3955  if (CallConv == CallingConv::Fast)
3956  ComputeArgOffset();
3957  needsLoad = true;
3958  }
3959  if (CallConv != CallingConv::Fast || needsLoad)
3960  ArgOffset += Sz;
3961  break;
3962  }
3963 
3964  // We need to load the argument to a virtual register if we determined
3965  // above that we ran out of physical registers of the appropriate type.
3966  if (needsLoad) {
3967  if (ObjSize < ArgSize && !isLittleEndian)
3968  CurArgOffset += ArgSize - ObjSize;
3969  int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3970  SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3971  ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3972  }
3973 
3974  InVals.push_back(ArgVal);
3975  }
3976 
3977  // Area that is at least reserved in the caller of this function.
3978  unsigned MinReservedArea;
3979  if (HasParameterArea)
3980  MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3981  else
3982  MinReservedArea = LinkageSize;
3983 
3984  // Set the size that is at least reserved in caller of this function. Tail
3985  // call optimized functions' reserved stack space needs to be aligned so that
3986  // taking the difference between two stack areas will result in an aligned
3987  // stack.
3988  MinReservedArea =
3989  EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3990  FuncInfo->setMinReservedArea(MinReservedArea);
3991 
3992  // If the function takes variable number of arguments, make a frame index for
3993  // the start of the first vararg value... for expansion of llvm.va_start.
3994  if (isVarArg) {
3995  int Depth = ArgOffset;
3996 
3997  FuncInfo->setVarArgsFrameIndex(
3998  MFI.CreateFixedObject(PtrByteSize, Depth, true));
3999  SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4000 
4001  // If this function is vararg, store any remaining integer argument regs
4002  // to their spots on the stack so that they may be loaded by dereferencing
4003  // the result of va_next.
4004  for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4005  GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4006  unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4007  SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4008  SDValue Store =
4009  DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4010  MemOps.push_back(Store);
4011  // Increment the address by four for the next argument to store
4012  SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4013  FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4014  }
4015  }
4016 
4017  if (!MemOps.empty())
4018  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4019 
4020  return Chain;
4021 }
4022 
4023 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4024  SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4025  const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4026  SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4027  // TODO: add description of PPC stack frame format, or at least some docs.
4028  //
4029  MachineFunction &MF = DAG.getMachineFunction();
4030  MachineFrameInfo &MFI = MF.getFrameInfo();
4031  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4032 
4033  EVT PtrVT = getPointerTy(MF.getDataLayout());
4034  bool isPPC64 = PtrVT == MVT::i64;
4035  // Potential tail calls could cause overwriting of argument stack slots.
4036  bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4037  (CallConv == CallingConv::Fast));
4038  unsigned PtrByteSize = isPPC64 ? 8 : 4;
4039  unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4040  unsigned ArgOffset = LinkageSize;
4041  // Area that is at least reserved in caller of this function.
4042  unsigned MinReservedArea = ArgOffset;
4043 
4044  static const MCPhysReg GPR_32[] = { // 32-bit registers.
4045  PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4046  PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4047  };
4048  static const MCPhysReg GPR_64[] = { // 64-bit registers.
4049  PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4050  PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4051  };
4052  static const MCPhysReg VR[] = {
4053  PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4054  PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4055  };
4056 
4057  const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4058  const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4059  const unsigned Num_VR_Regs = array_lengthof( VR);
4060 
4061  unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4062 
4063  const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4064 
4065  // In 32-bit non-varargs functions, the stack space for vectors is after the
4066  // stack space for non-vectors. We do not use this space unless we have
4067  // too many vectors to fit in registers, something that only occurs in
4068  // constructed examples:), but we have to walk the arglist to figure
4069  // that out...for the pathological case, compute VecArgOffset as the
4070  // start of the vector parameter area. Computing VecArgOffset is the
4071  // entire point of the following loop.
4072  unsigned VecArgOffset = ArgOffset;
4073  if (!isVarArg && !isPPC64) {
4074  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4075  ++ArgNo) {
4076  EVT ObjectVT = Ins[ArgNo].VT;
4077  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4078 
4079  if (Flags.isByVal()) {
4080  // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4081  unsigned ObjSize = Flags.getByValSize();
4082  unsigned ArgSize =
4083  ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4084  VecArgOffset += ArgSize;
4085  continue;
4086  }
4087 
4088  switch(ObjectVT.getSimpleVT().SimpleTy) {
4089  default: llvm_unreachable("Unhandled argument type!");
4090  case MVT::i1:
4091  case MVT::i32:
4092  case MVT::f32:
4093  VecArgOffset += 4;
4094  break;
4095  case MVT::i64: // PPC64
4096  case MVT::f64:
4097  // FIXME: We are guaranteed to be !isPPC64 at this point.
4098  // Does MVT::i64 apply?
4099  VecArgOffset += 8;
4100  break;
4101  case MVT::v4f32:
4102  case MVT::v4i32:
4103  case MVT::v8i16:
4104  case MVT::v16i8:
4105  // Nothing to do, we're only looking at Nonvector args here.
4106  break;
4107  }
4108  }
4109  }
4110  // We've found where the vector parameter area in memory is. Skip the
4111  // first 12 parameters; these don't use that memory.
4112  VecArgOffset = ((VecArgOffset+15)/16)*16;
4113  VecArgOffset += 12*16;
4114 
4115  // Add DAG nodes to load the arguments or copy them out of registers. On
4116  // entry to a function on PPC, the arguments start after the linkage area,
4117  // although the first ones are often in registers.
4118 
4119  SmallVector<SDValue, 8> MemOps;
4120  unsigned nAltivecParamsAtEnd = 0;
4122  unsigned CurArgIdx = 0;
4123  for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4124  SDValue ArgVal;
4125  bool needsLoad = false;
4126  EVT ObjectVT = Ins[ArgNo].VT;
4127  unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4128  unsigned ArgSize = ObjSize;
4129  ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4130  if (Ins[ArgNo].isOrigArg()) {
4131  std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4132  CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4133  }
4134  unsigned CurArgOffset = ArgOffset;
4135 
4136  // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4137  if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4138  ObjectVT==