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