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