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