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