LLVM  14.0.0git
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"
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/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
125  "ppc-quadword-atomics",
126  cl::desc("enable quadword lock-free atomic operations"), cl::init(false),
127  cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
139 
140 // FIXME: Remove this once the bug has been fixed!
142 
144  const PPCSubtarget &STI)
145  : TargetLowering(TM), Subtarget(STI) {
146  // Initialize map that relates the PPC addressing modes to the computed flags
147  // of a load/store instruction. The map is used to determine the optimal
148  // addressing mode when selecting load and stores.
149  initializeAddrModeMap();
150  // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
151  // arguments are at least 4/8 bytes aligned.
152  bool isPPC64 = Subtarget.isPPC64();
153  setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
154 
155  // Set up the register classes.
156  addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
157  if (!useSoftFloat()) {
158  if (hasSPE()) {
159  addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
160  // EFPU2 APU only supports f32
161  if (!Subtarget.hasEFPU2())
162  addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
163  } else {
164  addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
165  addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
166  }
167  }
168 
169  // Match BITREVERSE to customized fast code sequence in the td file.
172 
173  // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
175 
176  // Custom lower inline assembly to check for special registers.
179 
180  // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
181  for (MVT VT : MVT::integer_valuetypes()) {
184  }
185 
186  if (Subtarget.isISA3_0()) {
191  } else {
192  // No extending loads from f16 or HW conversions back and forth.
201  }
202 
204 
205  // PowerPC has pre-inc load and store's.
216  if (!Subtarget.hasSPE()) {
221  }
222 
223  // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
224  const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
225  for (MVT VT : ScalarIntVTs) {
230  }
231 
232  if (Subtarget.useCRBits()) {
234 
235  if (isPPC64 || Subtarget.hasFPCVT()) {
238  isPPC64 ? MVT::i64 : MVT::i32);
241  isPPC64 ? MVT::i64 : MVT::i32);
242 
245  isPPC64 ? MVT::i64 : MVT::i32);
248  isPPC64 ? MVT::i64 : MVT::i32);
249 
252  isPPC64 ? MVT::i64 : MVT::i32);
255  isPPC64 ? MVT::i64 : MVT::i32);
256 
259  isPPC64 ? MVT::i64 : MVT::i32);
262  isPPC64 ? MVT::i64 : MVT::i32);
263  } else {
268  }
269 
270  // PowerPC does not support direct load/store of condition registers.
273 
274  // FIXME: Remove this once the ANDI glue bug is fixed:
275  if (ANDIGlueBug)
277 
278  for (MVT VT : MVT::integer_valuetypes()) {
282  }
283 
284  addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
285  }
286 
287  // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
288  // PPC (the libcall is not available).
293 
294  // We do not currently implement these libm ops for PowerPC.
301 
302  // PowerPC has no SREM/UREM instructions unless we are on P9
303  // On P9 we may use a hardware instruction to compute the remainder.
304  // When the result of both the remainder and the division is required it is
305  // more efficient to compute the remainder from the result of the division
306  // rather than use the remainder instruction. The instructions are legalized
307  // directly because the DivRemPairsPass performs the transformation at the IR
308  // level.
309  if (Subtarget.isISA3_0()) {
314  } else {
319  }
320 
321  // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
330 
331  // Handle constrained floating-point operations of scalar.
332  // TODO: Handle SPE specific operation.
338 
343 
344  if (!Subtarget.hasSPE()) {
347  }
348 
349  if (Subtarget.hasVSX()) {
352  }
353 
354  if (Subtarget.hasFSQRT()) {
357  }
358 
359  if (Subtarget.hasFPRND()) {
364 
369  }
370 
371  // We don't support sin/cos/sqrt/fmod/pow
382  if (Subtarget.hasSPE()) {
385  } else {
388  }
389 
390  if (Subtarget.hasSPE())
392 
394 
395  // If we're enabling GP optimizations, use hardware square root
396  if (!Subtarget.hasFSQRT() &&
397  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
398  Subtarget.hasFRE()))
400 
401  if (!Subtarget.hasFSQRT() &&
402  !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
403  Subtarget.hasFRES()))
405 
406  if (Subtarget.hasFCPSGN()) {
409  } else {
412  }
413 
414  if (Subtarget.hasFPRND()) {
419 
424  }
425 
426  // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
427  // to speed up scalar BSWAP64.
428  // CTPOP or CTTZ were introduced in P8/P9 respectively
430  if (Subtarget.hasP9Vector() && Subtarget.isPPC64())
432  else
434  if (Subtarget.isISA3_0()) {
437  } else {
440  }
441 
442  if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
445  } else {
448  }
449 
450  // PowerPC does not have ROTR
453 
454  if (!Subtarget.useCRBits()) {
455  // PowerPC does not have Select
460  }
461 
462  // PowerPC wants to turn select_cc of FP into fsel when possible.
465 
466  // PowerPC wants to optimize integer setcc a bit
467  if (!Subtarget.useCRBits())
469 
470  if (Subtarget.hasFPU()) {
474 
478  }
479 
480  // PowerPC does not have BRCOND which requires SetCC
481  if (!Subtarget.useCRBits())
483 
485 
486  if (Subtarget.hasSPE()) {
487  // SPE has built-in conversions
494 
495  // SPE supports signaling compare of f32/f64.
498  } else {
499  // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
502 
503  // PowerPC does not have [U|S]INT_TO_FP
508  }
509 
510  if (Subtarget.hasDirectMove() && isPPC64) {
515  if (TM.Options.UnsafeFPMath) {
524  }
525  } else {
530  }
531 
532  // We cannot sextinreg(i1). Expand to shifts.
534 
535  // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
536  // SjLj exception handling but a light-weight setjmp/longjmp replacement to
537  // support continuation, user-level threading, and etc.. As a result, no
538  // other SjLj exception interfaces are implemented and please don't build
539  // your own exception handling based on them.
540  // LLVM/Clang supports zero-cost DWARF exception handling.
543 
544  // We want to legalize GlobalAddress and ConstantPool nodes into the
545  // appropriate instructions to materialize the address.
556 
557  // TRAP is legal.
559 
560  // TRAMPOLINE is custom lowered.
563 
564  // VASTART needs to be custom lowered to use the VarArgsFrameIndex
566 
567  if (Subtarget.is64BitELFABI()) {
568  // VAARG always uses double-word chunks, so promote anything smaller.
578  } else if (Subtarget.is32BitELFABI()) {
579  // VAARG is custom lowered with the 32-bit SVR4 ABI.
582  } else
584 
585  // VACOPY is custom lowered with the 32-bit SVR4 ABI.
586  if (Subtarget.is32BitELFABI())
588  else
590 
591  // Use the default implementation.
601 
602  // We want to custom lower some of our intrinsics.
604 
605  // To handle counter-based loop conditions.
607 
612 
613  // Comparisons that require checking two conditions.
614  if (Subtarget.hasSPE()) {
619  }
632 
635 
636  if (Subtarget.has64BitSupport()) {
637  // They also have instructions for converting between i64 and fp.
646  // This is just the low 32 bits of a (signed) fp->i64 conversion.
647  // We cannot do this with Promote because i64 is not a legal type.
650 
651  if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
654  }
655  } else {
656  // PowerPC does not have FP_TO_UINT on 32-bit implementations.
657  if (Subtarget.hasSPE()) {
660  } else {
663  }
664  }
665 
666  // With the instructions enabled under FPCVT, we can do everything.
667  if (Subtarget.hasFPCVT()) {
668  if (Subtarget.has64BitSupport()) {
677  }
678 
687  }
688 
689  if (Subtarget.use64BitRegs()) {
690  // 64-bit PowerPC implementations can support i64 types directly
691  addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
692  // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
694  // 64-bit PowerPC wants to expand i128 shifts itself.
698  } else {
699  // 32-bit PowerPC wants to expand i64 shifts itself.
703  }
704 
705  // PowerPC has better expansions for funnel shifts than the generic
706  // TargetLowering::expandFunnelShift.
707  if (Subtarget.has64BitSupport()) {
710  }
713 
714  if (Subtarget.hasVSX()) {
719  }
720 
721  if (Subtarget.hasAltivec()) {
722  for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
727  }
728  // First set operation action for all vector types to expand. Then we
729  // will selectively turn on ones that can be effectively codegen'd.
730  for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
731  // add/sub are legal for all supported vector VT's.
734 
735  // For v2i64, these are only valid with P8Vector. This is corrected after
736  // the loop.
737  if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
742  }
743  else {
748  }
749 
750  if (Subtarget.hasVSX()) {
753  }
754 
755  // Vector instructions introduced in P8
756  if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
759  }
760  else {
763  }
764 
765  // Vector instructions introduced in P9
766  if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
768  else
770 
771  // We promote all shuffles to v16i8.
774 
775  // We promote all non-typed operations to v4i32.
791 
792  // No other operations are legal.
830 
831  for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
832  setTruncStoreAction(VT, InnerVT, Expand);
833  setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
834  setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
835  setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
836  }
837  }
839  if (!Subtarget.hasP8Vector()) {
844  }
845 
846  // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
847  // with merges, splats, etc.
849 
850  // Vector truncates to sub-word integer that fit in an Altivec/VSX register
851  // are cheap, so handle them before they get expanded to scalar.
857 
863  Subtarget.useCRBits() ? Legal : Expand);
877 
878  // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
880  // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
881  if (Subtarget.hasAltivec())
882  for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
884  // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
885  if (Subtarget.hasP8Altivec())
887 
888  addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
889  addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
890  addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
891  addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
892 
895 
896  if (Subtarget.hasVSX()) {
900  }
901 
902  if (Subtarget.hasP8Altivec())
904  else
906 
907  if (Subtarget.isISA3_1()) {
926  }
927 
930 
933 
938 
939  // Altivec does not contain unordered floating-point compare instructions
944 
945  if (Subtarget.hasVSX()) {
948  if (Subtarget.hasP8Vector()) {
951  }
952  if (Subtarget.hasDirectMove() && isPPC64) {
961  }
963 
964  // The nearbyint variants are not allowed to raise the inexact exception
965  // so we can only code-gen them with unsafe math.
966  if (TM.Options.UnsafeFPMath) {
969  }
970 
979 
985 
988 
991 
992  // Share the Altivec comparison restrictions.
997 
1000 
1002 
1003  if (Subtarget.hasP8Vector())
1004  addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1005 
1006  addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1007 
1008  addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1009  addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1010  addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1011 
1012  if (Subtarget.hasP8Altivec()) {
1016 
1017  // 128 bit shifts can be accomplished via 3 instructions for SHL and
1018  // SRL, but not for SRA because of the instructions available:
1019  // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1020  // doing
1024 
1026  }
1027  else {
1031 
1033 
1034  // VSX v2i64 only supports non-arithmetic operations.
1037  }
1038 
1039  if (Subtarget.isISA3_1())
1041  else
1043 
1048 
1050 
1059 
1060  // Custom handling for partial vectors of integers converted to
1061  // floating point. We already have optimal handling for v2i32 through
1062  // the DAG combine, so those aren't necessary.
1079 
1086 
1089 
1090  // Handle constrained floating-point operations of vector.
1091  // The predictor is `hasVSX` because altivec instruction has
1092  // no exception but VSX vector instruction has.
1106 
1120 
1121  addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1122  addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1123 
1124  for (MVT FPT : MVT::fp_valuetypes())
1126 
1127  // Expand the SELECT to SELECT_CC
1129 
1132 
1133  // No implementation for these ops for PowerPC.
1139  }
1140 
1141  if (Subtarget.hasP8Altivec()) {
1142  addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1143  addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1144  }
1145 
1146  if (Subtarget.hasP9Vector()) {
1149 
1150  // 128 bit shifts can be accomplished via 3 instructions for SHL and
1151  // SRL, but not for SRA because of the instructions available:
1152  // VS{RL} and VS{RL}O.
1156 
1162 
1170 
1177 
1181 
1182  // Handle constrained floating-point operations of fp128
1203  } else if (Subtarget.hasVSX()) {
1206 
1209 
1210  // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1211  // fp_to_uint and int_to_fp.
1214 
1222 
1223  // Expand the fp_extend if the target type is fp128.
1226 
1227  // Expand the fp_round if the source type is fp128.
1228  for (MVT VT : {MVT::f32, MVT::f64}) {
1231  }
1232 
1237 
1238  // Lower following f128 select_cc pattern:
1239  // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1241 
1242  // We need to handle f128 SELECT_CC with integer result type.
1245  }
1246 
1247  if (Subtarget.hasP9Altivec()) {
1250 
1258  }
1259 
1260  if (Subtarget.isISA3_1())
1262  }
1263 
1264  if (Subtarget.pairedVectorMemops()) {
1265  addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1268  }
1269  if (Subtarget.hasMMA()) {
1270  addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1274  }
1275 
1276  if (Subtarget.has64BitSupport())
1278 
1279  if (Subtarget.isISA3_1())
1281 
1283 
1284  if (!isPPC64) {
1287  }
1288 
1289  if (EnableQuadwordAtomics && Subtarget.hasQuadwordAtomics()) {
1294  }
1295 
1297 
1298  if (Subtarget.hasAltivec()) {
1299  // Altivec instructions set fields to all zeros or all ones.
1301  }
1302 
1303  if (!isPPC64) {
1304  // These libcalls are not available in 32-bit.
1305  setLibcallName(RTLIB::SHL_I128, nullptr);
1306  setLibcallName(RTLIB::SRL_I128, nullptr);
1307  setLibcallName(RTLIB::SRA_I128, nullptr);
1308  setLibcallName(RTLIB::MULO_I64, nullptr);
1309  }
1310 
1311  if (!isPPC64)
1313 
1314  setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1315 
1316  // We have target-specific dag combine patterns for the following nodes:
1325  if (Subtarget.hasFPCVT())
1330  if (Subtarget.useCRBits())
1336 
1340 
1343 
1344 
1345  if (Subtarget.useCRBits()) {
1349  }
1350 
1351  if (Subtarget.hasP9Altivec()) {
1354  }
1355 
1356  setLibcallName(RTLIB::LOG_F128, "logf128");
1357  setLibcallName(RTLIB::LOG2_F128, "log2f128");
1358  setLibcallName(RTLIB::LOG10_F128, "log10f128");
1359  setLibcallName(RTLIB::EXP_F128, "expf128");
1360  setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1361  setLibcallName(RTLIB::SIN_F128, "sinf128");
1362  setLibcallName(RTLIB::COS_F128, "cosf128");
1363  setLibcallName(RTLIB::POW_F128, "powf128");
1364  setLibcallName(RTLIB::FMIN_F128, "fminf128");
1365  setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1366  setLibcallName(RTLIB::REM_F128, "fmodf128");
1367  setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1368  setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1369  setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1370  setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1371  setLibcallName(RTLIB::ROUND_F128, "roundf128");
1372  setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1373  setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1374  setLibcallName(RTLIB::RINT_F128, "rintf128");
1375  setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1376  setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1377  setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1378  setLibcallName(RTLIB::FMA_F128, "fmaf128");
1379 
1380  // With 32 condition bits, we don't need to sink (and duplicate) compares
1381  // aggressively in CodeGenPrep.
1382  if (Subtarget.useCRBits()) {
1385  }
1386 
1388 
1389  switch (Subtarget.getCPUDirective()) {
1390  default: break;
1391  case PPC::DIR_970:
1392  case PPC::DIR_A2:
1393  case PPC::DIR_E500:
1394  case PPC::DIR_E500mc:
1395  case PPC::DIR_E5500:
1396  case PPC::DIR_PWR4:
1397  case PPC::DIR_PWR5:
1398  case PPC::DIR_PWR5X:
1399  case PPC::DIR_PWR6:
1400  case PPC::DIR_PWR6X:
1401  case PPC::DIR_PWR7:
1402  case PPC::DIR_PWR8:
1403  case PPC::DIR_PWR9:
1404  case PPC::DIR_PWR10:
1405  case PPC::DIR_PWR_FUTURE:
1408  break;
1409  }
1410 
1411  if (Subtarget.enableMachineScheduler())
1413  else
1415 
1417 
1418  // The Freescale cores do better with aggressive inlining of memcpy and
1419  // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1420  if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1421  Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1422  MaxStoresPerMemset = 32;
1424  MaxStoresPerMemcpy = 32;
1426  MaxStoresPerMemmove = 32;
1428  } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1429  // The A2 also benefits from (very) aggressive inlining of memcpy and
1430  // friends. The overhead of a the function call, even when warm, can be
1431  // over one hundred cycles.
1432  MaxStoresPerMemset = 128;
1433  MaxStoresPerMemcpy = 128;
1434  MaxStoresPerMemmove = 128;
1435  MaxLoadsPerMemcmp = 128;
1436  } else {
1437  MaxLoadsPerMemcmp = 8;
1439  }
1440 
1441  IsStrictFPEnabled = true;
1442 
1443  // Let the subtarget (CPU) decide if a predictable select is more expensive
1444  // than the corresponding branch. This information is used in CGP to decide
1445  // when to convert selects into branches.
1447 }
1448 
1449 // *********************************** NOTE ************************************
1450 // For selecting load and store instructions, the addressing modes are defined
1451 // as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1452 // patterns to match the load the store instructions.
1453 //
1454 // The TD definitions for the addressing modes correspond to their respective
1455 // Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1456 // on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1457 // address mode flags of a particular node. Afterwards, the computed address
1458 // flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1459 // addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1460 // accordingly, based on the preferred addressing mode.
1461 //
1462 // Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1463 // MemOpFlags contains all the possible flags that can be used to compute the
1464 // optimal addressing mode for load and store instructions.
1465 // AddrMode contains all the possible load and store addressing modes available
1466 // on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1467 //
1468 // When adding new load and store instructions, it is possible that new address
1469 // flags may need to be added into MemOpFlags, and a new addressing mode will
1470 // need to be added to AddrMode. An entry of the new addressing mode (consisting
1471 // of the minimal and main distinguishing address flags for the new load/store
1472 // instructions) will need to be added into initializeAddrModeMap() below.
1473 // Finally, when adding new addressing modes, the getAddrModeForFlags() will
1474 // need to be updated to account for selecting the optimal addressing mode.
1475 // *****************************************************************************
1476 /// Initialize the map that relates the different addressing modes of the load
1477 /// and store instructions to a set of flags. This ensures the load/store
1478 /// instruction is correctly matched during instruction selection.
1479 void PPCTargetLowering::initializeAddrModeMap() {
1480  AddrModesMap[PPC::AM_DForm] = {
1481  // LWZ, STW
1486  // LBZ, LHZ, STB, STH
1491  // LHA
1496  // LFS, LFD, STFS, STFD
1501  };
1502  AddrModesMap[PPC::AM_DSForm] = {
1503  // LWA
1507  // LD, STD
1511  // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1515  };
1516  AddrModesMap[PPC::AM_DQForm] = {
1517  // LXV, STXV
1521  };
1522  AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1524  // TODO: Add mapping for quadword load/store.
1525 }
1526 
1527 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1528 /// the desired ByVal argument alignment.
1529 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1530  if (MaxAlign == MaxMaxAlign)
1531  return;
1532  if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1533  if (MaxMaxAlign >= 32 &&
1534  VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1535  MaxAlign = Align(32);
1536  else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1537  MaxAlign < 16)
1538  MaxAlign = Align(16);
1539  } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1540  Align EltAlign;
1541  getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1542  if (EltAlign > MaxAlign)
1543  MaxAlign = EltAlign;
1544  } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1545  for (auto *EltTy : STy->elements()) {
1546  Align EltAlign;
1547  getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1548  if (EltAlign > MaxAlign)
1549  MaxAlign = EltAlign;
1550  if (MaxAlign == MaxMaxAlign)
1551  break;
1552  }
1553  }
1554 }
1555 
1556 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1557 /// function arguments in the caller parameter area.
1559  const DataLayout &DL) const {
1560  // 16byte and wider vectors are passed on 16byte boundary.
1561  // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1562  Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1563  if (Subtarget.hasAltivec())
1564  getMaxByValAlign(Ty, Alignment, Align(16));
1565  return Alignment.value();
1566 }
1567 
1569  return Subtarget.useSoftFloat();
1570 }
1571 
1573  return Subtarget.hasSPE();
1574 }
1575 
1577  return VT.isScalarInteger();
1578 }
1579 
1580 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1581  switch ((PPCISD::NodeType)Opcode) {
1582  case PPCISD::FIRST_NUMBER: break;
1583  case PPCISD::FSEL: return "PPCISD::FSEL";
1584  case PPCISD::XSMAXCDP: return "PPCISD::XSMAXCDP";
1585  case PPCISD::XSMINCDP: return "PPCISD::XSMINCDP";
1586  case PPCISD::FCFID: return "PPCISD::FCFID";
1587  case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1588  case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1589  case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1590  case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1591  case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1592  case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1593  case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1595  return "PPCISD::FP_TO_UINT_IN_VSR,";
1597  return "PPCISD::FP_TO_SINT_IN_VSR";
1598  case PPCISD::FRE: return "PPCISD::FRE";
1599  case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1600  case PPCISD::FTSQRT:
1601  return "PPCISD::FTSQRT";
1602  case PPCISD::FSQRT:
1603  return "PPCISD::FSQRT";
1604  case PPCISD::STFIWX: return "PPCISD::STFIWX";
1605  case PPCISD::VPERM: return "PPCISD::VPERM";
1606  case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1608  return "PPCISD::XXSPLTI_SP_TO_DP";
1609  case PPCISD::XXSPLTI32DX:
1610  return "PPCISD::XXSPLTI32DX";
1611  case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1612  case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1613  case PPCISD::VECSHL: return "PPCISD::VECSHL";
1614  case PPCISD::CMPB: return "PPCISD::CMPB";
1615  case PPCISD::Hi: return "PPCISD::Hi";
1616  case PPCISD::Lo: return "PPCISD::Lo";
1617  case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1618  case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1619  case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1620  case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1621  case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1622  case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1623  case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1624  case PPCISD::SRL: return "PPCISD::SRL";
1625  case PPCISD::SRA: return "PPCISD::SRA";
1626  case PPCISD::SHL: return "PPCISD::SHL";
1627  case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1628  case PPCISD::CALL: return "PPCISD::CALL";
1629  case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1630  case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1631  case PPCISD::MTCTR: return "PPCISD::MTCTR";
1632  case PPCISD::BCTRL: return "PPCISD::BCTRL";
1633  case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1634  case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1635  case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1636  case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1637  case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1638  case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1639  case PPCISD::MFVSR: return "PPCISD::MFVSR";
1640  case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1641  case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1642  case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1643  case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1645  return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1647  return "PPCISD::ANDI_rec_1_EQ_BIT";
1649  return "PPCISD::ANDI_rec_1_GT_BIT";
1650  case PPCISD::VCMP: return "PPCISD::VCMP";
1651  case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1652  case PPCISD::LBRX: return "PPCISD::LBRX";
1653  case PPCISD::STBRX: return "PPCISD::STBRX";
1654  case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1655  case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1656  case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1657  case PPCISD::STXSIX: return "PPCISD::STXSIX";
1658  case PPCISD::VEXTS: return "PPCISD::VEXTS";
1659  case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1660  case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1661  case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1662  case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1664  return "PPCISD::ST_VSR_SCAL_INT";
1665  case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1666  case PPCISD::BDNZ: return "PPCISD::BDNZ";
1667  case PPCISD::BDZ: return "PPCISD::BDZ";
1668  case PPCISD::MFFS: return "PPCISD::MFFS";
1669  case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1670  case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1671  case PPCISD::CR6SET: return "PPCISD::CR6SET";
1672  case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1673  case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1674  case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1675  case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1676  case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1677  case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1678  case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1679  case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1680  case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1681  case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1682  case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1683  case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1684  case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1685  case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1686  case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1687  case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1688  case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1689  case PPCISD::PADDI_DTPREL:
1690  return "PPCISD::PADDI_DTPREL";
1691  case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1692  case PPCISD::SC: return "PPCISD::SC";
1693  case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1694  case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1695  case PPCISD::RFEBB: return "PPCISD::RFEBB";
1696  case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1697  case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1698  case PPCISD::VABSD: return "PPCISD::VABSD";
1699  case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1700  case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1701  case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1702  case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1703  case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1704  case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1705  case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1707  return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1709  return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1710  case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1711  case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1712  case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1713  case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1714  case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1715  case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1717  return "PPCISD::STRICT_FADDRTZ";
1718  case PPCISD::STRICT_FCTIDZ:
1719  return "PPCISD::STRICT_FCTIDZ";
1720  case PPCISD::STRICT_FCTIWZ:
1721  return "PPCISD::STRICT_FCTIWZ";
1723  return "PPCISD::STRICT_FCTIDUZ";
1725  return "PPCISD::STRICT_FCTIWUZ";
1726  case PPCISD::STRICT_FCFID:
1727  return "PPCISD::STRICT_FCFID";
1728  case PPCISD::STRICT_FCFIDU:
1729  return "PPCISD::STRICT_FCFIDU";
1730  case PPCISD::STRICT_FCFIDS:
1731  return "PPCISD::STRICT_FCFIDS";
1733  return "PPCISD::STRICT_FCFIDUS";
1734  case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1735  }
1736  return nullptr;
1737 }
1738 
1740  EVT VT) const {
1741  if (!VT.isVector())
1742  return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1743 
1745 }
1746 
1748  assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1749  return true;
1750 }
1751 
1752 //===----------------------------------------------------------------------===//
1753 // Node matching predicates, for use by the tblgen matching code.
1754 //===----------------------------------------------------------------------===//
1755 
1756 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1758  if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1759  return CFP->getValueAPF().isZero();
1760  else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1761  // Maybe this has already been legalized into the constant pool?
1762  if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1763  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1764  return CFP->getValueAPF().isZero();
1765  }
1766  return false;
1767 }
1768 
1769 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1770 /// true if Op is undef or if it matches the specified value.
1771 static bool isConstantOrUndef(int Op, int Val) {
1772  return Op < 0 || Op == Val;
1773 }
1774 
1775 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1776 /// VPKUHUM instruction.
1777 /// The ShuffleKind distinguishes between big-endian operations with
1778 /// two different inputs (0), either-endian operations with two identical
1779 /// inputs (1), and little-endian operations with two different inputs (2).
1780 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1782  SelectionDAG &DAG) {
1783  bool IsLE = DAG.getDataLayout().isLittleEndian();
1784  if (ShuffleKind == 0) {
1785  if (IsLE)
1786  return false;
1787  for (unsigned i = 0; i != 16; ++i)
1788  if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1789  return false;
1790  } else if (ShuffleKind == 2) {
1791  if (!IsLE)
1792  return false;
1793  for (unsigned i = 0; i != 16; ++i)
1794  if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1795  return false;
1796  } else if (ShuffleKind == 1) {
1797  unsigned j = IsLE ? 0 : 1;
1798  for (unsigned i = 0; i != 8; ++i)
1799  if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1800  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1801  return false;
1802  }
1803  return true;
1804 }
1805 
1806 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1807 /// VPKUWUM instruction.
1808 /// The ShuffleKind distinguishes between big-endian operations with
1809 /// two different inputs (0), either-endian operations with two identical
1810 /// inputs (1), and little-endian operations with two different inputs (2).
1811 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1813  SelectionDAG &DAG) {
1814  bool IsLE = DAG.getDataLayout().isLittleEndian();
1815  if (ShuffleKind == 0) {
1816  if (IsLE)
1817  return false;
1818  for (unsigned i = 0; i != 16; i += 2)
1819  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1820  !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1821  return false;
1822  } else if (ShuffleKind == 2) {
1823  if (!IsLE)
1824  return false;
1825  for (unsigned i = 0; i != 16; i += 2)
1826  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1827  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1828  return false;
1829  } else if (ShuffleKind == 1) {
1830  unsigned j = IsLE ? 0 : 2;
1831  for (unsigned i = 0; i != 8; i += 2)
1832  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1833  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1834  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1835  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1836  return false;
1837  }
1838  return true;
1839 }
1840 
1841 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1842 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1843 /// current subtarget.
1844 ///
1845 /// The ShuffleKind distinguishes between big-endian operations with
1846 /// two different inputs (0), either-endian operations with two identical
1847 /// inputs (1), and little-endian operations with two different inputs (2).
1848 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1850  SelectionDAG &DAG) {
1851  const PPCSubtarget& Subtarget =
1852  static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1853  if (!Subtarget.hasP8Vector())
1854  return false;
1855 
1856  bool IsLE = DAG.getDataLayout().isLittleEndian();
1857  if (ShuffleKind == 0) {
1858  if (IsLE)
1859  return false;
1860  for (unsigned i = 0; i != 16; i += 4)
1861  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1862  !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1863  !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1864  !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1865  return false;
1866  } else if (ShuffleKind == 2) {
1867  if (!IsLE)
1868  return false;
1869  for (unsigned i = 0; i != 16; i += 4)
1870  if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1871  !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1872  !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1873  !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1874  return false;
1875  } else if (ShuffleKind == 1) {
1876  unsigned j = IsLE ? 0 : 4;
1877  for (unsigned i = 0; i != 8; i += 4)
1878  if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1879  !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1880  !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1881  !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1882  !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1883  !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1884  !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1885  !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1886  return false;
1887  }
1888  return true;
1889 }
1890 
1891 /// isVMerge - Common function, used to match vmrg* shuffles.
1892 ///
1893 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1894  unsigned LHSStart, unsigned RHSStart) {
1895  if (N->getValueType(0) != MVT::v16i8)
1896  return false;
1897  assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1898  "Unsupported merge size!");
1899 
1900  for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1901  for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1902  if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1903  LHSStart+j+i*UnitSize) ||
1904  !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1905  RHSStart+j+i*UnitSize))
1906  return false;
1907  }
1908  return true;
1909 }
1910 
1911 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1912 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1913 /// The ShuffleKind distinguishes between big-endian merges with two
1914 /// different inputs (0), either-endian merges with two identical inputs (1),
1915 /// and little-endian merges with two different inputs (2). For the latter,
1916 /// the input operands are swapped (see PPCInstrAltivec.td).
1918  unsigned ShuffleKind, SelectionDAG &DAG) {
1919  if (DAG.getDataLayout().isLittleEndian()) {
1920  if (ShuffleKind == 1) // unary
1921  return isVMerge(N, UnitSize, 0, 0);
1922  else if (ShuffleKind == 2) // swapped
1923  return isVMerge(N, UnitSize, 0, 16);
1924  else
1925  return false;
1926  } else {
1927  if (ShuffleKind == 1) // unary
1928  return isVMerge(N, UnitSize, 8, 8);
1929  else if (ShuffleKind == 0) // normal
1930  return isVMerge(N, UnitSize, 8, 24);
1931  else
1932  return false;
1933  }
1934 }
1935 
1936 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1937 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1938 /// The ShuffleKind distinguishes between big-endian merges with two
1939 /// different inputs (0), either-endian merges with two identical inputs (1),
1940 /// and little-endian merges with two different inputs (2). For the latter,
1941 /// the input operands are swapped (see PPCInstrAltivec.td).
1943  unsigned ShuffleKind, SelectionDAG &DAG) {
1944  if (DAG.getDataLayout().isLittleEndian()) {
1945  if (ShuffleKind == 1) // unary
1946  return isVMerge(N, UnitSize, 8, 8);
1947  else if (ShuffleKind == 2) // swapped
1948  return isVMerge(N, UnitSize, 8, 24);
1949  else
1950  return false;
1951  } else {
1952  if (ShuffleKind == 1) // unary
1953  return isVMerge(N, UnitSize, 0, 0);
1954  else if (ShuffleKind == 0) // normal
1955  return isVMerge(N, UnitSize, 0, 16);
1956  else
1957  return false;
1958  }
1959 }
1960 
1961 /**
1962  * Common function used to match vmrgew and vmrgow shuffles
1963  *
1964  * The indexOffset determines whether to look for even or odd words in
1965  * the shuffle mask. This is based on the of the endianness of the target
1966  * machine.
1967  * - Little Endian:
1968  * - Use offset of 0 to check for odd elements
1969  * - Use offset of 4 to check for even elements
1970  * - Big Endian:
1971  * - Use offset of 0 to check for even elements
1972  * - Use offset of 4 to check for odd elements
1973  * A detailed description of the vector element ordering for little endian and
1974  * big endian can be found at
1975  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1976  * Targeting your applications - what little endian and big endian IBM XL C/C++
1977  * compiler differences mean to you
1978  *
1979  * The mask to the shuffle vector instruction specifies the indices of the
1980  * elements from the two input vectors to place in the result. The elements are
1981  * numbered in array-access order, starting with the first vector. These vectors
1982  * are always of type v16i8, thus each vector will contain 16 elements of size
1983  * 8. More info on the shuffle vector can be found in the
1984  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1985  * Language Reference.
1986  *
1987  * The RHSStartValue indicates whether the same input vectors are used (unary)
1988  * or two different input vectors are used, based on the following:
1989  * - If the instruction uses the same vector for both inputs, the range of the
1990  * indices will be 0 to 15. In this case, the RHSStart value passed should
1991  * be 0.
1992  * - If the instruction has two different vectors then the range of the
1993  * indices will be 0 to 31. In this case, the RHSStart value passed should
1994  * be 16 (indices 0-15 specify elements in the first vector while indices 16
1995  * to 31 specify elements in the second vector).
1996  *
1997  * \param[in] N The shuffle vector SD Node to analyze
1998  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1999  * \param[in] RHSStartValue Specifies the starting index for the righthand input
2000  * vector to the shuffle_vector instruction
2001  * \return true iff this shuffle vector represents an even or odd word merge
2002  */
2003 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2004  unsigned RHSStartValue) {
2005  if (N->getValueType(0) != MVT::v16i8)
2006  return false;
2007 
2008  for (unsigned i = 0; i < 2; ++i)
2009  for (unsigned j = 0; j < 4; ++j)
2010  if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2011  i*RHSStartValue+j+IndexOffset) ||
2012  !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2013  i*RHSStartValue+j+IndexOffset+8))
2014  return false;
2015  return true;
2016 }
2017 
2018 /**
2019  * Determine if the specified shuffle mask is suitable for the vmrgew or
2020  * vmrgow instructions.
2021  *
2022  * \param[in] N The shuffle vector SD Node to analyze
2023  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2024  * \param[in] ShuffleKind Identify the type of merge:
2025  * - 0 = big-endian merge with two different inputs;
2026  * - 1 = either-endian merge with two identical inputs;
2027  * - 2 = little-endian merge with two different inputs (inputs are swapped for
2028  * little-endian merges).
2029  * \param[in] DAG The current SelectionDAG
2030  * \return true iff this shuffle mask
2031  */
2033  unsigned ShuffleKind, SelectionDAG &DAG) {
2034  if (DAG.getDataLayout().isLittleEndian()) {
2035  unsigned indexOffset = CheckEven ? 4 : 0;
2036  if (ShuffleKind == 1) // Unary
2037  return isVMerge(N, indexOffset, 0);
2038  else if (ShuffleKind == 2) // swapped
2039  return isVMerge(N, indexOffset, 16);
2040  else
2041  return false;
2042  }
2043  else {
2044  unsigned indexOffset = CheckEven ? 0 : 4;
2045  if (ShuffleKind == 1) // Unary
2046  return isVMerge(N, indexOffset, 0);
2047  else if (ShuffleKind == 0) // Normal
2048  return isVMerge(N, indexOffset, 16);
2049  else
2050  return false;
2051  }
2052  return false;
2053 }
2054 
2055 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2056 /// amount, otherwise return -1.
2057 /// The ShuffleKind distinguishes between big-endian operations with two
2058 /// different inputs (0), either-endian operations with two identical inputs
2059 /// (1), and little-endian operations with two different inputs (2). For the
2060 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
2061 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2062  SelectionDAG &DAG) {
2063  if (N->getValueType(0) != MVT::v16i8)
2064  return -1;
2065 
2066  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2067 
2068  // Find the first non-undef value in the shuffle mask.
2069  unsigned i;
2070  for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2071  /*search*/;
2072 
2073  if (i == 16) return -1; // all undef.
2074 
2075  // Otherwise, check to see if the rest of the elements are consecutively
2076  // numbered from this value.
2077  unsigned ShiftAmt = SVOp->getMaskElt(i);
2078  if (ShiftAmt < i) return -1;
2079 
2080  ShiftAmt -= i;
2081  bool isLE = DAG.getDataLayout().isLittleEndian();
2082 
2083  if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2084  // Check the rest of the elements to see if they are consecutive.
2085  for (++i; i != 16; ++i)
2086  if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2087  return -1;
2088  } else if (ShuffleKind == 1) {
2089  // Check the rest of the elements to see if they are consecutive.
2090  for (++i; i != 16; ++i)
2091  if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2092  return -1;
2093  } else
2094  return -1;
2095 
2096  if (isLE)
2097  ShiftAmt = 16 - ShiftAmt;
2098 
2099  return ShiftAmt;
2100 }
2101 
2102 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2103 /// specifies a splat of a single element that is suitable for input to
2104 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2106  assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2107  EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2108 
2109  // The consecutive indices need to specify an element, not part of two
2110  // different elements. So abandon ship early if this isn't the case.
2111  if (N->getMaskElt(0) % EltSize != 0)
2112  return false;
2113 
2114  // This is a splat operation if each element of the permute is the same, and
2115  // if the value doesn't reference the second vector.
2116  unsigned ElementBase = N->getMaskElt(0);
2117 
2118  // FIXME: Handle UNDEF elements too!
2119  if (ElementBase >= 16)
2120  return false;
2121 
2122  // Check that the indices are consecutive, in the case of a multi-byte element
2123  // splatted with a v16i8 mask.
2124  for (unsigned i = 1; i != EltSize; ++i)
2125  if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2126  return false;
2127 
2128  for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2129  if (N->getMaskElt(i) < 0) continue;
2130  for (unsigned j = 0; j != EltSize; ++j)
2131  if (N->getMaskElt(i+j) != N->getMaskElt(j))
2132  return false;
2133  }
2134  return true;
2135 }
2136 
2137 /// Check that the mask is shuffling N byte elements. Within each N byte
2138 /// element of the mask, the indices could be either in increasing or
2139 /// decreasing order as long as they are consecutive.
2140 /// \param[in] N the shuffle vector SD Node to analyze
2141 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2142 /// Word/DoubleWord/QuadWord).
2143 /// \param[in] StepLen the delta indices number among the N byte element, if
2144 /// the mask is in increasing/decreasing order then it is 1/-1.
2145 /// \return true iff the mask is shuffling N byte elements.
2147  int StepLen) {
2148  assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2149  "Unexpected element width.");
2150  assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2151 
2152  unsigned NumOfElem = 16 / Width;
2153  unsigned MaskVal[16]; // Width is never greater than 16
2154  for (unsigned i = 0; i < NumOfElem; ++i) {
2155  MaskVal[0] = N->getMaskElt(i * Width);
2156  if ((StepLen == 1) && (MaskVal[0] % Width)) {
2157  return false;
2158  } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2159  return false;
2160  }
2161 
2162  for (unsigned int j = 1; j < Width; ++j) {
2163  MaskVal[j] = N->getMaskElt(i * Width + j);
2164  if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2165  return false;
2166  }
2167  }
2168  }
2169 
2170  return true;
2171 }
2172 
2173 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2174  unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2175  if (!isNByteElemShuffleMask(N, 4, 1))
2176  return false;
2177 
2178  // Now we look at mask elements 0,4,8,12
2179  unsigned M0 = N->getMaskElt(0) / 4;
2180  unsigned M1 = N->getMaskElt(4) / 4;
2181  unsigned M2 = N->getMaskElt(8) / 4;
2182  unsigned M3 = N->getMaskElt(12) / 4;
2183  unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2184  unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2185 
2186  // Below, let H and L be arbitrary elements of the shuffle mask
2187  // where H is in the range [4,7] and L is in the range [0,3].
2188  // H, 1, 2, 3 or L, 5, 6, 7
2189  if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2190  (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2191  ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2192  InsertAtByte = IsLE ? 12 : 0;
2193  Swap = M0 < 4;
2194  return true;
2195  }
2196  // 0, H, 2, 3 or 4, L, 6, 7
2197  if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2198  (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2199  ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2200  InsertAtByte = IsLE ? 8 : 4;
2201  Swap = M1 < 4;
2202  return true;
2203  }
2204  // 0, 1, H, 3 or 4, 5, L, 7
2205  if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2206  (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2207  ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2208  InsertAtByte = IsLE ? 4 : 8;
2209  Swap = M2 < 4;
2210  return true;
2211  }
2212  // 0, 1, 2, H or 4, 5, 6, L
2213  if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2214  (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2215  ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2216  InsertAtByte = IsLE ? 0 : 12;
2217  Swap = M3 < 4;
2218  return true;
2219  }
2220 
2221  // If both vector operands for the shuffle are the same vector, the mask will
2222  // contain only elements from the first one and the second one will be undef.
2223  if (N->getOperand(1).isUndef()) {
2224  ShiftElts = 0;
2225  Swap = true;
2226  unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2227  if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2228  InsertAtByte = IsLE ? 12 : 0;
2229  return true;
2230  }
2231  if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2232  InsertAtByte = IsLE ? 8 : 4;
2233  return true;
2234  }
2235  if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2236  InsertAtByte = IsLE ? 4 : 8;
2237  return true;
2238  }
2239  if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2240  InsertAtByte = IsLE ? 0 : 12;
2241  return true;
2242  }
2243  }
2244 
2245  return false;
2246 }
2247 
2249  bool &Swap, bool IsLE) {
2250  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2251  // Ensure each byte index of the word is consecutive.
2252  if (!isNByteElemShuffleMask(N, 4, 1))
2253  return false;
2254 
2255  // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2256  unsigned M0 = N->getMaskElt(0) / 4;
2257  unsigned M1 = N->getMaskElt(4) / 4;
2258  unsigned M2 = N->getMaskElt(8) / 4;
2259  unsigned M3 = N->getMaskElt(12) / 4;
2260 
2261  // If both vector operands for the shuffle are the same vector, the mask will
2262  // contain only elements from the first one and the second one will be undef.
2263  if (N->getOperand(1).isUndef()) {
2264  assert(M0 < 4 && "Indexing into an undef vector?");
2265  if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2266  return false;
2267 
2268  ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2269  Swap = false;
2270  return true;
2271  }
2272 
2273  // Ensure each word index of the ShuffleVector Mask is consecutive.
2274  if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2275  return false;
2276 
2277  if (IsLE) {
2278  if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2279  // Input vectors don't need to be swapped if the leading element
2280  // of the result is one of the 3 left elements of the second vector
2281  // (or if there is no shift to be done at all).
2282  Swap = false;
2283  ShiftElts = (8 - M0) % 8;
2284  } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2285  // Input vectors need to be swapped if the leading element
2286  // of the result is one of the 3 left elements of the first vector
2287  // (or if we're shifting by 4 - thereby simply swapping the vectors).
2288  Swap = true;
2289  ShiftElts = (4 - M0) % 4;
2290  }
2291 
2292  return true;
2293  } else { // BE
2294  if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2295  // Input vectors don't need to be swapped if the leading element
2296  // of the result is one of the 4 elements of the first vector.
2297  Swap = false;
2298  ShiftElts = M0;
2299  } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2300  // Input vectors need to be swapped if the leading element
2301  // of the result is one of the 4 elements of the right vector.
2302  Swap = true;
2303  ShiftElts = M0 - 4;
2304  }
2305 
2306  return true;
2307  }
2308 }
2309 
2311  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2312 
2313  if (!isNByteElemShuffleMask(N, Width, -1))
2314  return false;
2315 
2316  for (int i = 0; i < 16; i += Width)
2317  if (N->getMaskElt(i) != i + Width - 1)
2318  return false;
2319 
2320  return true;
2321 }
2322 
2324  return isXXBRShuffleMaskHelper(N, 2);
2325 }
2326 
2328  return isXXBRShuffleMaskHelper(N, 4);
2329 }
2330 
2332  return isXXBRShuffleMaskHelper(N, 8);
2333 }
2334 
2336  return isXXBRShuffleMaskHelper(N, 16);
2337 }
2338 
2339 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2340 /// if the inputs to the instruction should be swapped and set \p DM to the
2341 /// value for the immediate.
2342 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2343 /// AND element 0 of the result comes from the first input (LE) or second input
2344 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2345 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2346 /// mask.
2348  bool &Swap, bool IsLE) {
2349  assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2350 
2351  // Ensure each byte index of the double word is consecutive.
2352  if (!isNByteElemShuffleMask(N, 8, 1))
2353  return false;
2354 
2355  unsigned M0 = N->getMaskElt(0) / 8;
2356  unsigned M1 = N->getMaskElt(8) / 8;
2357  assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2358 
2359  // If both vector operands for the shuffle are the same vector, the mask will
2360  // contain only elements from the first one and the second one will be undef.
2361  if (N->getOperand(1).isUndef()) {
2362  if ((M0 | M1) < 2) {
2363  DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2364  Swap = false;
2365  return true;
2366  } else
2367  return false;
2368  }
2369 
2370  if (IsLE) {
2371  if (M0 > 1 && M1 < 2) {
2372  Swap = false;
2373  } else if (M0 < 2 && M1 > 1) {
2374  M0 = (M0 + 2) % 4;
2375  M1 = (M1 + 2) % 4;
2376  Swap = true;
2377  } else
2378  return false;
2379 
2380  // Note: if control flow comes here that means Swap is already set above
2381  DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2382  return true;
2383  } else { // BE
2384  if (M0 < 2 && M1 > 1) {
2385  Swap = false;
2386  } else if (M0 > 1 && M1 < 2) {
2387  M0 = (M0 + 2) % 4;
2388  M1 = (M1 + 2) % 4;
2389  Swap = true;
2390  } else
2391  return false;
2392 
2393  // Note: if control flow comes here that means Swap is already set above
2394  DM = (M0 << 1) + (M1 & 1);
2395  return true;
2396  }
2397 }
2398 
2399 
2400 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2401 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2402 /// elements are counted from the left of the vector register).
2403 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2404  SelectionDAG &DAG) {
2405  ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2406  assert(isSplatShuffleMask(SVOp, EltSize));
2407  if (DAG.getDataLayout().isLittleEndian())
2408  return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2409  else
2410  return SVOp->getMaskElt(0) / EltSize;
2411 }
2412 
2413 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2414 /// by using a vspltis[bhw] instruction of the specified element size, return
2415 /// the constant being splatted. The ByteSize field indicates the number of
2416 /// bytes of each element [124] -> [bhw].
2417 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2418  SDValue OpVal(nullptr, 0);
2419 
2420  // If ByteSize of the splat is bigger than the element size of the
2421  // build_vector, then we have a case where we are checking for a splat where
2422  // multiple elements of the buildvector are folded together into a single
2423  // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2424  unsigned EltSize = 16/N->getNumOperands();
2425  if (EltSize < ByteSize) {
2426  unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2427  SDValue UniquedVals[4];
2428  assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2429 
2430  // See if all of the elements in the buildvector agree across.
2431  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2432  if (N->getOperand(i).isUndef()) continue;
2433  // If the element isn't a constant, bail fully out.
2434  if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2435 
2436  if (!UniquedVals[i&(Multiple-1)].getNode())
2437  UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2438  else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2439  return SDValue(); // no match.
2440  }
2441 
2442  // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2443  // either constant or undef values that are identical for each chunk. See
2444  // if these chunks can form into a larger vspltis*.
2445 
2446  // Check to see if all of the leading entries are either 0 or -1. If
2447  // neither, then this won't fit into the immediate field.
2448  bool LeadingZero = true;
2449  bool LeadingOnes = true;
2450  for (unsigned i = 0; i != Multiple-1; ++i) {
2451  if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2452 
2453  LeadingZero &= isNullConstant(UniquedVals[i]);
2454  LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2455  }
2456  // Finally, check the least significant entry.
2457  if (LeadingZero) {
2458  if (!UniquedVals[Multiple-1].getNode())
2459  return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2460  int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2461  if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2462  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2463  }
2464  if (LeadingOnes) {
2465  if (!UniquedVals[Multiple-1].getNode())
2466  return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2467  int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2468  if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2469  return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2470  }
2471 
2472  return SDValue();
2473  }
2474 
2475  // Check to see if this buildvec has a single non-undef value in its elements.
2476  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2477  if (N->getOperand(i).isUndef()) continue;
2478  if (!OpVal.getNode())
2479  OpVal = N->getOperand(i);
2480  else if (OpVal != N->getOperand(i))
2481  return SDValue();
2482  }
2483 
2484  if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2485 
2486  unsigned ValSizeInBytes = EltSize;
2487  uint64_t Value = 0;
2488  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2489  Value = CN->getZExtValue();
2490  } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2491  assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2492  Value = FloatToBits(CN->getValueAPF().convertToFloat());
2493  }
2494 
2495  // If the splat value is larger than the element value, then we can never do
2496  // this splat. The only case that we could fit the replicated bits into our
2497  // immediate field for would be zero, and we prefer to use vxor for it.
2498  if (ValSizeInBytes < ByteSize) return SDValue();
2499 
2500  // If the element value is larger than the splat value, check if it consists
2501  // of a repeated bit pattern of size ByteSize.
2502  if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2503  return SDValue();
2504 
2505  // Properly sign extend the value.
2506  int MaskVal = SignExtend32(Value, ByteSize * 8);
2507 
2508  // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2509  if (MaskVal == 0) return SDValue();
2510 
2511  // Finally, if this value fits in a 5 bit sext field, return it
2512  if (SignExtend32<5>(MaskVal) == MaskVal)
2513  return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2514  return SDValue();
2515 }
2516 
2517 //===----------------------------------------------------------------------===//
2518 // Addressing Mode Selection
2519 //===----------------------------------------------------------------------===//
2520 
2521 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2522 /// or 64-bit immediate, and if the value can be accurately represented as a
2523 /// sign extension from a 16-bit value. If so, this returns true and the
2524 /// immediate.
2525 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2526  if (!isa<ConstantSDNode>(N))
2527  return false;
2528 
2529  Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2530  if (N->getValueType(0) == MVT::i32)
2531  return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2532  else
2533  return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2534 }
2535 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2536  return isIntS16Immediate(Op.getNode(), Imm);
2537 }
2538 
2539 /// Used when computing address flags for selecting loads and stores.
2540 /// If we have an OR, check if the LHS and RHS are provably disjoint.
2541 /// An OR of two provably disjoint values is equivalent to an ADD.
2542 /// Most PPC load/store instructions compute the effective address as a sum,
2543 /// so doing this conversion is useful.
2544 static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2545  if (N.getOpcode() != ISD::OR)
2546  return false;
2547  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2548  if (!LHSKnown.Zero.getBoolValue())
2549  return false;
2550  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2551  return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2552 }
2553 
2554 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2555 /// be represented as an indexed [r+r] operation.
2557  SDValue &Index,
2558  SelectionDAG &DAG) const {
2559  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2560  UI != E; ++UI) {
2561  if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2562  if (Memop->getMemoryVT() == MVT::f64) {
2563  Base = N.getOperand(0);
2564  Index = N.getOperand(1);
2565  return true;
2566  }
2567  }
2568  }
2569  return false;
2570 }
2571 
2572 /// isIntS34Immediate - This method tests if value of node given can be
2573 /// accurately represented as a sign extension from a 34-bit value. If so,
2574 /// this returns true and the immediate.
2575 bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2576  if (!isa<ConstantSDNode>(N))
2577  return false;
2578 
2579  Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2580  return isInt<34>(Imm);
2581 }
2582 bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2583  return isIntS34Immediate(Op.getNode(), Imm);
2584 }
2585 
2586 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2587 /// can be represented as an indexed [r+r] operation. Returns false if it
2588 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2589 /// non-zero and N can be represented by a base register plus a signed 16-bit
2590 /// displacement, make a more precise judgement by checking (displacement % \p
2591 /// EncodingAlignment).
2594  MaybeAlign EncodingAlignment) const {
2595  // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2596  // a [pc+imm].
2597  if (SelectAddressPCRel(N, Base))
2598  return false;
2599 
2600  int16_t Imm = 0;
2601  if (N.getOpcode() == ISD::ADD) {
2602  // Is there any SPE load/store (f64), which can't handle 16bit offset?
2603  // SPE load/store can only handle 8-bit offsets.
2604  if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2605  return true;
2606  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2607  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2608  return false; // r+i
2609  if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2610  return false; // r+i
2611 
2612  Base = N.getOperand(0);
2613  Index = N.getOperand(1);
2614  return true;
2615  } else if (N.getOpcode() == ISD::OR) {
2616  if (isIntS16Immediate(N.getOperand(1), Imm) &&
2617  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2618  return false; // r+i can fold it if we can.
2619 
2620  // If this is an or of disjoint bitfields, we can codegen this as an add
2621  // (for better address arithmetic) if the LHS and RHS of the OR are provably
2622  // disjoint.
2623  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2624 
2625  if (LHSKnown.Zero.getBoolValue()) {
2626  KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2627  // If all of the bits are known zero on the LHS or RHS, the add won't
2628  // carry.
2629  if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2630  Base = N.getOperand(0);
2631  Index = N.getOperand(1);
2632  return true;
2633  }
2634  }
2635  }
2636 
2637  return false;
2638 }
2639 
2640 // If we happen to be doing an i64 load or store into a stack slot that has
2641 // less than a 4-byte alignment, then the frame-index elimination may need to
2642 // use an indexed load or store instruction (because the offset may not be a
2643 // multiple of 4). The extra register needed to hold the offset comes from the
2644 // register scavenger, and it is possible that the scavenger will need to use
2645 // an emergency spill slot. As a result, we need to make sure that a spill slot
2646 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2647 // stack slot.
2648 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2649  // FIXME: This does not handle the LWA case.
2650  if (VT != MVT::i64)
2651  return;
2652 
2653  // NOTE: We'll exclude negative FIs here, which come from argument
2654  // lowering, because there are no known test cases triggering this problem
2655  // using packed structures (or similar). We can remove this exclusion if
2656  // we find such a test case. The reason why this is so test-case driven is
2657  // because this entire 'fixup' is only to prevent crashes (from the
2658  // register scavenger) on not-really-valid inputs. For example, if we have:
2659  // %a = alloca i1
2660  // %b = bitcast i1* %a to i64*
2661  // store i64* a, i64 b
2662  // then the store should really be marked as 'align 1', but is not. If it
2663  // were marked as 'align 1' then the indexed form would have been
2664  // instruction-selected initially, and the problem this 'fixup' is preventing
2665  // won't happen regardless.
2666  if (FrameIdx < 0)
2667  return;
2668 
2669  MachineFunction &MF = DAG.getMachineFunction();
2670  MachineFrameInfo &MFI = MF.getFrameInfo();
2671 
2672  if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2673  return;
2674 
2675  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2676  FuncInfo->setHasNonRISpills();
2677 }
2678 
2679 /// Returns true if the address N can be represented by a base register plus
2680 /// a signed 16-bit displacement [r+imm], and if it is not better
2681 /// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2682 /// displacements that are multiples of that value.
2684  SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2685  MaybeAlign EncodingAlignment) const {
2686  // FIXME dl should come from parent load or store, not from address
2687  SDLoc dl(N);
2688 
2689  // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2690  // a [pc+imm].
2691  if (SelectAddressPCRel(N, Base))
2692  return false;
2693 
2694  // If this can be more profitably realized as r+r, fail.
2695  if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2696  return false;
2697 
2698  if (N.getOpcode() == ISD::ADD) {
2699  int16_t imm = 0;
2700  if (isIntS16Immediate(N.getOperand(1), imm) &&
2701  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2702  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2703  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2704  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2705  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2706  } else {
2707  Base = N.getOperand(0);
2708  }
2709  return true; // [r+i]
2710  } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2711  // Match LOAD (ADD (X, Lo(G))).
2712  assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2713  && "Cannot handle constant offsets yet!");
2714  Disp = N.getOperand(1).getOperand(0); // The global address.
2717  Disp.getOpcode() == ISD::TargetConstantPool ||
2718  Disp.getOpcode() == ISD::TargetJumpTable);
2719  Base = N.getOperand(0);
2720  return true; // [&g+r]
2721  }
2722  } else if (N.getOpcode() == ISD::OR) {
2723  int16_t imm = 0;
2724  if (isIntS16Immediate(N.getOperand(1), imm) &&
2725  (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2726  // If this is an or of disjoint bitfields, we can codegen this as an add
2727  // (for better address arithmetic) if the LHS and RHS of the OR are
2728  // provably disjoint.
2729  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2730 
2731  if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2732  // If all of the bits are known zero on the LHS or RHS, the add won't
2733  // carry.
2734  if (FrameIndexSDNode *FI =
2735  dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2736  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2737  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2738  } else {
2739  Base = N.getOperand(0);
2740  }
2741  Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2742  return true;
2743  }
2744  }
2745  } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2746  // Loading from a constant address.
2747 
2748  // If this address fits entirely in a 16-bit sext immediate field, codegen
2749  // this as "d, 0"
2750  int16_t Imm;
2751  if (isIntS16Immediate(CN, Imm) &&
2752  (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2753  Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2754  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2755  CN->getValueType(0));
2756  return true;
2757  }
2758 
2759  // Handle 32-bit sext immediates with LIS + addr mode.
2760  if ((CN->getValueType(0) == MVT::i32 ||
2761  (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2762  (!EncodingAlignment ||
2763  isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2764  int Addr = (int)CN->getZExtValue();
2765 
2766  // Otherwise, break this down into an LIS + disp.
2767  Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2768 
2769  Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2770  MVT::i32);
2771  unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2772  Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2773  return true;
2774  }
2775  }
2776 
2777  Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2778  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2779  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2780  fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2781  } else
2782  Base = N;
2783  return true; // [r+0]
2784 }
2785 
2786 /// Similar to the 16-bit case but for instructions that take a 34-bit
2787 /// displacement field (prefixed loads/stores).
2789  SDValue &Base,
2790  SelectionDAG &DAG) const {
2791  // Only on 64-bit targets.
2792  if (N.getValueType() != MVT::i64)
2793  return false;
2794 
2795  SDLoc dl(N);
2796  int64_t Imm = 0;
2797 
2798  if (N.getOpcode() == ISD::ADD) {
2799  if (!isIntS34Immediate(N.getOperand(1), Imm))
2800  return false;
2801  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2802  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2803  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2804  else
2805  Base = N.getOperand(0);
2806  return true;
2807  }
2808 
2809  if (N.getOpcode() == ISD::OR) {
2810  if (!isIntS34Immediate(N.getOperand(1), Imm))
2811  return false;
2812  // If this is an or of disjoint bitfields, we can codegen this as an add
2813  // (for better address arithmetic) if the LHS and RHS of the OR are
2814  // provably disjoint.
2815  KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2816  if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2817  return false;
2818  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2819  Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2820  else
2821  Base = N.getOperand(0);
2822  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2823  return true;
2824  }
2825 
2826  if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2827  Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2828  Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2829  return true;
2830  }
2831 
2832  return false;
2833 }
2834 
2835 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2836 /// represented as an indexed [r+r] operation.
2838  SDValue &Index,
2839  SelectionDAG &DAG) const {
2840  // Check to see if we can easily represent this as an [r+r] address. This
2841  // will fail if it thinks that the address is more profitably represented as
2842  // reg+imm, e.g. where imm = 0.
2843  if (SelectAddressRegReg(N, Base, Index, DAG))
2844  return true;
2845 
2846  // If the address is the result of an add, we will utilize the fact that the
2847  // address calculation includes an implicit add. However, we can reduce
2848  // register pressure if we do not materialize a constant just for use as the
2849  // index register. We only get rid of the add if it is not an add of a
2850  // value and a 16-bit signed constant and both have a single use.
2851  int16_t imm = 0;
2852  if (N.getOpcode() == ISD::ADD &&
2853  (!isIntS16Immediate(N.getOperand(1), imm) ||
2854  !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2855  Base = N.getOperand(0);
2856  Index = N.getOperand(1);
2857  return true;
2858  }
2859 
2860  // Otherwise, do it the hard way, using R0 as the base register.
2861  Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2862  N.getValueType());
2863  Index = N;
2864  return true;
2865 }
2866 
2867 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2868  Ty *PCRelCand = dyn_cast<Ty>(N);
2869  return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2870 }
2871 
2872 /// Returns true if this address is a PC Relative address.
2873 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2874 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2876  // This is a materialize PC Relative node. Always select this as PC Relative.
2877  Base = N;
2878  if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2879  return true;
2880  if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2881  isValidPCRelNode<GlobalAddressSDNode>(N) ||
2882  isValidPCRelNode<JumpTableSDNode>(N) ||
2883  isValidPCRelNode<BlockAddressSDNode>(N))
2884  return true;
2885  return false;
2886 }
2887 
2888 /// Returns true if we should use a direct load into vector instruction
2889 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2891 
2892  // If there are any other uses other than scalar to vector, then we should
2893  // keep it as a scalar load -> direct move pattern to prevent multiple
2894  // loads.
2895  LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2896  if (!LD)
2897  return false;
2898 
2899  EVT MemVT = LD->getMemoryVT();
2900  if (!MemVT.isSimple())
2901  return false;
2902  switch(MemVT.getSimpleVT().SimpleTy) {
2903  case MVT::i64:
2904  break;
2905  case MVT::i32:
2906  if (!ST.hasP8Vector())
2907  return false;
2908  break;
2909  case MVT::i16:
2910  case MVT::i8:
2911  if (!ST.hasP9Vector())
2912  return false;
2913  break;
2914  default:
2915  return false;
2916  }
2917 
2918  SDValue LoadedVal(N, 0);
2919  if (!LoadedVal.hasOneUse())
2920  return false;
2921 
2922  for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2923  UI != UE; ++UI)
2924  if (UI.getUse().get().getResNo() == 0 &&
2925  UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2926  UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2927  return false;
2928 
2929  return true;
2930 }
2931 
2932 /// getPreIndexedAddressParts - returns true by value, base pointer and
2933 /// offset pointer and addressing mode by reference if the node's address
2934 /// can be legally represented as pre-indexed load / store address.
2936  SDValue &Offset,
2937  ISD::MemIndexedMode &AM,
2938  SelectionDAG &DAG) const {
2939  if (DisablePPCPreinc) return false;
2940 
2941  bool isLoad = true;
2942  SDValue Ptr;
2943  EVT VT;
2944  unsigned Alignment;
2945  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2946  Ptr = LD->getBasePtr();
2947  VT = LD->getMemoryVT();
2948  Alignment = LD->getAlignment();
2949  } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2950  Ptr = ST->getBasePtr();
2951  VT = ST->getMemoryVT();
2952  Alignment = ST->getAlignment();
2953  isLoad = false;
2954  } else
2955  return false;
2956 
2957  // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2958  // instructions because we can fold these into a more efficient instruction
2959  // instead, (such as LXSD).
2960  if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2961  return false;
2962  }
2963 
2964  // PowerPC doesn't have preinc load/store instructions for vectors
2965  if (VT.isVector())
2966  return false;
2967 
2968  if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2969  // Common code will reject creating a pre-inc form if the base pointer
2970  // is a frame index, or if N is a store and the base pointer is either
2971  // the same as or a predecessor of the value being stored. Check for
2972  // those situations here, and try with swapped Base/Offset instead.
2973  bool Swap = false;
2974 
2975  if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2976  Swap = true;
2977  else if (!isLoad) {
2978  SDValue Val = cast<StoreSDNode>(N)->getValue();
2979  if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2980  Swap = true;
2981  }
2982 
2983  if (Swap)
2984  std::swap(Base, Offset);
2985 
2986  AM = ISD::PRE_INC;
2987  return true;
2988  }
2989 
2990  // LDU/STU can only handle immediates that are a multiple of 4.
2991  if (VT != MVT::i64) {
2992  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2993  return false;
2994  } else {
2995  // LDU/STU need an address with at least 4-byte alignment.
2996  if (Alignment < 4)
2997  return false;
2998 
2999  if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3000  return false;
3001  }
3002 
3003  if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3004  // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3005  // sext i32 to i64 when addr mode is r+i.
3006  if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3007  LD->getExtensionType() == ISD::SEXTLOAD &&
3008  isa<ConstantSDNode>(Offset))
3009  return false;
3010  }
3011 
3012  AM = ISD::PRE_INC;
3013  return true;
3014 }
3015 
3016 //===----------------------------------------------------------------------===//
3017 // LowerOperation implementation
3018 //===----------------------------------------------------------------------===//
3019 
3020 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
3021 /// and LoOpFlags to the target MO flags.
3022 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3023  unsigned &HiOpFlags, unsigned &LoOpFlags,
3024  const GlobalValue *GV = nullptr) {
3025  HiOpFlags = PPCII::MO_HA;
3026  LoOpFlags = PPCII::MO_LO;
3027 
3028  // Don't use the pic base if not in PIC relocation model.
3029  if (IsPIC) {
3030  HiOpFlags |= PPCII::MO_PIC_FLAG;
3031  LoOpFlags |= PPCII::MO_PIC_FLAG;
3032  }
3033 }
3034 
3035 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3036  SelectionDAG &DAG) {
3037  SDLoc DL(HiPart);
3038  EVT PtrVT = HiPart.getValueType();
3039  SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3040 
3041  SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3042  SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3043 
3044  // With PIC, the first instruction is actually "GR+hi(&G)".
3045  if (isPIC)
3046  Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3047  DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3048 
3049  // Generate non-pic code that has direct accesses to the constant pool.
3050  // The address of the global is just (hi(&g)+lo(&g)).
3051  return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3052 }
3053 
3055  PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3056  FuncInfo->setUsesTOCBasePtr();
3057 }
3058 
3059 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
3061 }
3062 
3063 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3064  SDValue GA) const {
3065  const bool Is64Bit = Subtarget.isPPC64();
3066  EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3067  SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3068  : Subtarget.isAIXABI()
3069  ? DAG.getRegister(PPC::R2, VT)
3070  : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3071  SDValue Ops[] = { GA, Reg };
3072  return DAG.getMemIntrinsicNode(
3073  PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3076 }
3077 
3078 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3079  SelectionDAG &DAG) const {
3080  EVT PtrVT = Op.getValueType();
3081  ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3082  const Constant *C = CP->getConstVal();
3083 
3084  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3085  // The actual address of the GlobalValue is stored in the TOC.
3086  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3087  if (Subtarget.isUsingPCRelativeCalls()) {
3088  SDLoc DL(CP);
3089  EVT Ty = getPointerTy(DAG.getDataLayout());
3090  SDValue ConstPool = DAG.getTargetConstantPool(
3091  C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3092  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3093  }
3094  setUsesTOCBasePtr(DAG);
3095  SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3096  return getTOCEntry(DAG, SDLoc(CP), GA);
3097  }
3098 
3099  unsigned MOHiFlag, MOLoFlag;
3100  bool IsPIC = isPositionIndependent();
3101  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3102 
3103  if (IsPIC && Subtarget.isSVR4ABI()) {
3104  SDValue GA =
3105  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3106  return getTOCEntry(DAG, SDLoc(CP), GA);
3107  }
3108 
3109  SDValue CPIHi =
3110  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3111  SDValue CPILo =
3112  DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3113  return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3114 }
3115 
3116 // For 64-bit PowerPC, prefer the more compact relative encodings.
3117 // This trades 32 bits per jump table entry for one or two instructions
3118 // on the jump site.
3120  if (isJumpTableRelative())
3122 
3124 }
3125 
3128  return false;
3129  if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3130  return true;
3132 }
3133 
3135  SelectionDAG &DAG) const {
3136  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3137  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3138 
3139  switch (getTargetMachine().getCodeModel()) {
3140  case CodeModel::Small:
3141  case CodeModel::Medium:
3142  return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
3143  default:
3144  return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3145  getPointerTy(DAG.getDataLayout()));
3146  }
3147 }
3148 
3149 const MCExpr *
3151  unsigned JTI,
3152  MCContext &Ctx) const {
3153  if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3154  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3155 
3156  switch (getTargetMachine().getCodeModel()) {
3157  case CodeModel::Small:
3158  case CodeModel::Medium:
3159  return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
3160  default:
3161  return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3162  }
3163 }
3164 
3165 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3166  EVT PtrVT = Op.getValueType();
3167  JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3168 
3169  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3170  if (Subtarget.isUsingPCRelativeCalls()) {
3171  SDLoc DL(JT);
3172  EVT Ty = getPointerTy(DAG.getDataLayout());
3173  SDValue GA =
3174  DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3175  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3176  return MatAddr;
3177  }
3178 
3179  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3180  // The actual address of the GlobalValue is stored in the TOC.
3181  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3182  setUsesTOCBasePtr(DAG);
3183  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3184  return getTOCEntry(DAG, SDLoc(JT), GA);
3185  }
3186 
3187  unsigned MOHiFlag, MOLoFlag;
3188  bool IsPIC = isPositionIndependent();
3189  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3190 
3191  if (IsPIC && Subtarget.isSVR4ABI()) {
3192  SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3194  return getTOCEntry(DAG, SDLoc(GA), GA);
3195  }
3196 
3197  SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3198  SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3199  return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3200 }
3201 
3202 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3203  SelectionDAG &DAG) const {
3204  EVT PtrVT = Op.getValueType();
3205  BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3206  const BlockAddress *BA = BASDN->getBlockAddress();
3207 
3208  // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3209  if (Subtarget.isUsingPCRelativeCalls()) {
3210  SDLoc DL(BASDN);
3211  EVT Ty = getPointerTy(DAG.getDataLayout());
3212  SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3214  SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3215  return MatAddr;
3216  }
3217 
3218  // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3219  // The actual BlockAddress is stored in the TOC.
3220  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3221  setUsesTOCBasePtr(DAG);
3222  SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3223  return getTOCEntry(DAG, SDLoc(BASDN), GA);
3224  }
3225 
3226  // 32-bit position-independent ELF stores the BlockAddress in the .got.
3227  if (Subtarget.is32BitELFABI() && isPositionIndependent())
3228  return getTOCEntry(
3229  DAG, SDLoc(BASDN),
3230  DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3231 
3232  unsigned MOHiFlag, MOLoFlag;
3233  bool IsPIC = isPositionIndependent();
3234  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3235  SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3236  SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3237  return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3238 }
3239 
3240 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3241  SelectionDAG &DAG) const {
3242  if (Subtarget.isAIXABI())
3243  return LowerGlobalTLSAddressAIX(Op, DAG);
3244 
3245  return LowerGlobalTLSAddressLinux(Op, DAG);
3246 }
3247 
3248 SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3249  SelectionDAG &DAG) const {
3250  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3251 
3252  if (DAG.getTarget().useEmulatedTLS())
3253  report_fatal_error("Emulated TLS is not yet supported on AIX");
3254 
3255  SDLoc dl(GA);
3256  const GlobalValue *GV = GA->getGlobal();
3257  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3258 
3259  // The general-dynamic model is the only access model supported for now, so
3260  // all the GlobalTLSAddress nodes are lowered with this model.
3261  // We need to generate two TOC entries, one for the variable offset, one for
3262  // the region handle. The global address for the TOC entry of the region
3263  // handle is created with the MO_TLSGDM_FLAG flag and the global address
3264  // for the TOC entry of the variable offset is created with MO_TLSGD_FLAG.
3265  SDValue VariableOffsetTGA =
3266  DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3267  SDValue RegionHandleTGA =
3268  DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3269  SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3270  SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3271  return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3272  RegionHandle);
3273 }
3274 
3275 SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3276  SelectionDAG &DAG) const {
3277  // FIXME: TLS addresses currently use medium model code sequences,
3278  // which is the most useful form. Eventually support for small and
3279  // large models could be added if users need it, at the cost of
3280  // additional complexity.
3281  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3282  if (DAG.getTarget().useEmulatedTLS())
3283  return LowerToTLSEmulatedModel(GA, DAG);
3284 
3285  SDLoc dl(GA);
3286  const GlobalValue *GV = GA->getGlobal();
3287  EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288  bool is64bit = Subtarget.isPPC64();
3289  const Module *M = DAG.getMachineFunction().getFunction().getParent();
3290  PICLevel::Level picLevel = M->getPICLevel();
3291 
3292  const TargetMachine &TM = getTargetMachine();
3293  TLSModel::Model Model = TM.getTLSModel(GV);
3294 
3295  if (Model == TLSModel::LocalExec) {
3296  if (Subtarget.isUsingPCRelativeCalls()) {
3297  SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3298  SDValue TGA = DAG.getTargetGlobalAddress(
3299  GV, dl, PtrVT, 0, (PPCII::MO_PCREL_FLAG | PPCII::MO_TPREL_FLAG));
3300  SDValue MatAddr =
3301  DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3302  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3303  }
3304 
3305  SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3307  SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3309  SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3310  : DAG.getRegister(PPC::R2, MVT::i32);
3311 
3312  SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3313  return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3314  }
3315 
3316  if (Model == TLSModel::InitialExec) {
3317  bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3318  SDValue TGA = DAG.getTargetGlobalAddress(
3319  GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3320  SDValue TGATLS = DAG.getTargetGlobalAddress(
3321  GV, dl, PtrVT, 0,
3323  SDValue TPOffset;
3324  if (IsPCRel) {
3325  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3326  TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3327  MachinePointerInfo());
3328  } else {
3329  SDValue GOTPtr;
3330  if (is64bit) {
3331  setUsesTOCBasePtr(DAG);
3332  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3333  GOTPtr =
3334  DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3335  } else {
3336  if (!TM.isPositionIndependent())
3337  GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3338  else if (picLevel == PICLevel::SmallPIC)
3339  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3340  else
3341  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3342  }
3343  TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3344  }
3345  return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3346  }
3347 
3349  if (Subtarget.isUsingPCRelativeCalls()) {
3350  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3352  return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3353  }
3354 
3355  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3356  SDValue GOTPtr;
3357  if (is64bit) {
3358  setUsesTOCBasePtr(DAG);
3359  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3360  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3361  GOTReg, TGA);
3362  } else {
3363  if (picLevel == PICLevel::SmallPIC)
3364  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3365  else
3366  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3367  }
3368  return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3369  GOTPtr, TGA, TGA);
3370  }
3371 
3372  if (Model == TLSModel::LocalDynamic) {
3373  if (Subtarget.isUsingPCRelativeCalls()) {
3374  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3376  SDValue MatPCRel =
3377  DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3378  return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3379  }
3380 
3381  SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3382  SDValue GOTPtr;
3383  if (is64bit) {
3384  setUsesTOCBasePtr(DAG);
3385  SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3386  GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3387  GOTReg, TGA);
3388  } else {
3389  if (picLevel == PICLevel::SmallPIC)
3390  GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3391  else
3392  GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3393  }
3394  SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3395  PtrVT, GOTPtr, TGA, TGA);
3396  SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3397  PtrVT, TLSAddr, TGA);
3398  return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3399  }
3400 
3401  llvm_unreachable("Unknown TLS model!");
3402 }
3403 
3404 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3405  SelectionDAG &DAG) const {
3406  EVT PtrVT = Op.getValueType();
3407  GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3408  SDLoc DL(GSDN);
3409  const GlobalValue *GV = GSDN->getGlobal();
3410 
3411  // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3412  // The actual address of the GlobalValue is stored in the TOC.
3413  if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3414  if (Subtarget.isUsingPCRelativeCalls()) {
3415  EVT Ty = getPointerTy(DAG.getDataLayout());
3416  if (isAccessedAsGotIndirect(Op)) {
3417  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3420  SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3421  SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3422  MachinePointerInfo());
3423  return Load;
3424  } else {
3425  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3427  return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3428  }
3429  }
3430  setUsesTOCBasePtr(DAG);
3431  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3432  return getTOCEntry(DAG, DL, GA);
3433  }
3434 
3435  unsigned MOHiFlag, MOLoFlag;
3436  bool IsPIC = isPositionIndependent();
3437  getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3438 
3439  if (IsPIC && Subtarget.isSVR4ABI()) {
3440  SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3441  GSDN->getOffset(),
3443  return getTOCEntry(DAG, DL, GA);
3444  }
3445 
3446  SDValue GAHi =
3447  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3448  SDValue GALo =
3449  DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3450 
3451  return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3452 }
3453 
3454 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3455  bool IsStrict = Op->isStrictFPOpcode();
3456  ISD::CondCode CC =
3457  cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3458  SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3459  SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3460  SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3461  EVT LHSVT = LHS.getValueType();
3462  SDLoc dl(Op);
3463 
3464  // Soften the setcc with libcall if it is fp128.
3465  if (LHSVT == MVT::f128) {
3466  assert(!Subtarget.hasP9Vector() &&
3467  "SETCC for f128 is already legal under Power9!");
3468  softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3469  Op->getOpcode() == ISD::STRICT_FSETCCS);
3470  if (RHS.getNode())
3471  LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3472  DAG.getCondCode(CC));
3473  if (IsStrict)
3474  return DAG.getMergeValues({LHS, Chain}, dl);
3475  return LHS;
3476  }
3477 
3478  assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3479 
3480  if (Op.getValueType() == MVT::v2i64) {
3481  // When the operands themselves are v2i64 values, we need to do something
3482  // special because VSX has no underlying comparison operations for these.
3483  if (LHS.getValueType() == MVT::v2i64) {
3484  // Equality can be handled by casting to the legal type for Altivec
3485  // comparisons, everything else needs to be expanded.
3486  if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3487  return DAG.getNode(
3488  ISD::BITCAST, dl, MVT::v2i64,
3489  DAG.getSetCC(dl, MVT::v4i32,
3490  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3491  DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC));
3492  }
3493 
3494  return SDValue();
3495  }
3496 
3497  // We handle most of these in the usual way.
3498  return Op;
3499  }
3500 
3501  // If we're comparing for equality to zero, expose the fact that this is
3502  // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3503  // fold the new nodes.
3504  if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3505  return V;
3506 
3507  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3508  // Leave comparisons against 0 and -1 alone for now, since they're usually
3509  // optimized. FIXME: revisit this when we can custom lower all setcc
3510  // optimizations.
3511  if (C->isAllOnes() || C->isZero())
3512  return SDValue();
3513  }
3514 
3515  // If we have an integer seteq/setne, turn it into a compare against zero
3516  // by xor'ing the rhs