LLVM 17.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"
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/STLExtras.h"
31#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/StringRef.h"
57#include "llvm/IR/CallingConv.h"
58#include "llvm/IR/Constant.h"
59#include "llvm/IR/Constants.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/DebugLoc.h"
63#include "llvm/IR/Function.h"
64#include "llvm/IR/GlobalValue.h"
65#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/Intrinsics.h"
68#include "llvm/IR/IntrinsicsPowerPC.h"
69#include "llvm/IR/Module.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/Value.h"
73#include "llvm/MC/MCContext.h"
74#include "llvm/MC/MCExpr.h"
84#include "llvm/Support/Debug.h"
86#include "llvm/Support/Format.h"
93#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <iterator>
97#include <list>
98#include <optional>
99#include <utility>
100#include <vector>
101
102using namespace llvm;
103
104#define DEBUG_TYPE "ppc-lowering"
105
106static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108
109static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111
112static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114
115static cl::opt<bool> DisableSCO("disable-ppc-sco",
116cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117
118static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120
121static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122cl::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
129static cl::opt<bool>
130 DisablePerfectShuffle("ppc-disable-perfect-shuffle",
131 cl::desc("disable vector permute decomposition"),
132 cl::init(true), cl::Hidden);
133
135 "disable-auto-paired-vec-st",
136 cl::desc("disable automatically generated 32byte paired vector stores"),
137 cl::init(true), cl::Hidden);
138
139STATISTIC(NumTailCalls, "Number of tail calls");
140STATISTIC(NumSiblingCalls, "Number of sibling calls");
141STATISTIC(ShufflesHandledWithVPERM,
142 "Number of shuffles lowered to a VPERM or XXPERM");
143STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
144
145static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
146
147static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
148
149static const char AIXSSPCanaryWordName[] = "__ssp_canary_word";
150
151// FIXME: Remove this once the bug has been fixed!
153
155 const PPCSubtarget &STI)
156 : TargetLowering(TM), Subtarget(STI) {
157 // Initialize map that relates the PPC addressing modes to the computed flags
158 // of a load/store instruction. The map is used to determine the optimal
159 // addressing mode when selecting load and stores.
160 initializeAddrModeMap();
161 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
162 // arguments are at least 4/8 bytes aligned.
163 bool isPPC64 = Subtarget.isPPC64();
164 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
165
166 // Set up the register classes.
167 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
168 if (!useSoftFloat()) {
169 if (hasSPE()) {
170 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
171 // EFPU2 APU only supports f32
172 if (!Subtarget.hasEFPU2())
173 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
174 } else {
175 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
176 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
177 }
178 }
179
180 // Match BITREVERSE to customized fast code sequence in the td file.
183
184 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
186
187 // Custom lower inline assembly to check for special registers.
190
191 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
192 for (MVT VT : MVT::integer_valuetypes()) {
195 }
196
197 if (Subtarget.isISA3_0()) {
202 } else {
203 // No extending loads from f16 or HW conversions back and forth.
212 }
213
215
216 // PowerPC has pre-inc load and store's.
227 if (!Subtarget.hasSPE()) {
232 }
233
234 // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
235 const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
236 for (MVT VT : ScalarIntVTs) {
241 }
242
243 if (Subtarget.useCRBits()) {
245
246 if (isPPC64 || Subtarget.hasFPCVT()) {
249 isPPC64 ? MVT::i64 : MVT::i32);
252 isPPC64 ? MVT::i64 : MVT::i32);
253
256 isPPC64 ? MVT::i64 : MVT::i32);
259 isPPC64 ? MVT::i64 : MVT::i32);
260
263 isPPC64 ? MVT::i64 : MVT::i32);
266 isPPC64 ? MVT::i64 : MVT::i32);
267
270 isPPC64 ? MVT::i64 : MVT::i32);
273 isPPC64 ? MVT::i64 : MVT::i32);
274 } else {
279 }
280
281 // PowerPC does not support direct load/store of condition registers.
284
285 // FIXME: Remove this once the ANDI glue bug is fixed:
286 if (ANDIGlueBug)
288
289 for (MVT VT : MVT::integer_valuetypes()) {
293 }
294
295 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
296 }
297
298 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
299 // PPC (the libcall is not available).
304
305 // We do not currently implement these libm ops for PowerPC.
312
313 // PowerPC has no SREM/UREM instructions unless we are on P9
314 // On P9 we may use a hardware instruction to compute the remainder.
315 // When the result of both the remainder and the division is required it is
316 // more efficient to compute the remainder from the result of the division
317 // rather than use the remainder instruction. The instructions are legalized
318 // directly because the DivRemPairsPass performs the transformation at the IR
319 // level.
320 if (Subtarget.isISA3_0()) {
325 } else {
330 }
331
332 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
341
342 // Handle constrained floating-point operations of scalar.
343 // TODO: Handle SPE specific operation.
349
354
355 if (!Subtarget.hasSPE()) {
358 }
359
360 if (Subtarget.hasVSX()) {
363 }
364
365 if (Subtarget.hasFSQRT()) {
368 }
369
370 if (Subtarget.hasFPRND()) {
375
380 }
381
382 // We don't support sin/cos/sqrt/fmod/pow
393
394 // MASS transformation for LLVM intrinsics with replicating fast-math flag
395 // to be consistent to PPCGenScalarMASSEntries pass
396 if (TM.getOptLevel() == CodeGenOpt::Aggressive) {
409 }
410
411 if (Subtarget.hasSPE()) {
414 } else {
417 }
418
419 if (Subtarget.hasSPE())
421
423
424 // If we're enabling GP optimizations, use hardware square root
425 if (!Subtarget.hasFSQRT() &&
426 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
427 Subtarget.hasFRE()))
429
430 if (!Subtarget.hasFSQRT() &&
431 !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
432 Subtarget.hasFRES()))
434
435 if (Subtarget.hasFCPSGN()) {
438 } else {
441 }
442
443 if (Subtarget.hasFPRND()) {
448
453 }
454
455 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
456 // instruction xxbrd to speed up scalar BSWAP64.
457 if (Subtarget.isISA3_1()) {
460 } else {
464 (Subtarget.hasP9Vector() && Subtarget.isPPC64()) ? Custom : Expand);
465 }
466
467 // CTPOP or CTTZ were introduced in P8/P9 respectively
468 if (Subtarget.isISA3_0()) {
471 } else {
474 }
475
476 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
479 } else {
482 }
483
484 // PowerPC does not have ROTR
487
488 if (!Subtarget.useCRBits()) {
489 // PowerPC does not have Select
494 }
495
496 // PowerPC wants to turn select_cc of FP into fsel when possible.
499
500 // PowerPC wants to optimize integer setcc a bit
501 if (!Subtarget.useCRBits())
503
504 if (Subtarget.hasFPU()) {
508
512 }
513
514 // PowerPC does not have BRCOND which requires SetCC
515 if (!Subtarget.useCRBits())
517
519
520 if (Subtarget.hasSPE()) {
521 // SPE has built-in conversions
528
529 // SPE supports signaling compare of f32/f64.
532 } else {
533 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
536
537 // PowerPC does not have [U|S]INT_TO_FP
542 }
543
544 if (Subtarget.hasDirectMove() && isPPC64) {
549 if (TM.Options.UnsafeFPMath) {
558 }
559 } else {
564 }
565
566 // We cannot sextinreg(i1). Expand to shifts.
568
569 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
570 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
571 // support continuation, user-level threading, and etc.. As a result, no
572 // other SjLj exception interfaces are implemented and please don't build
573 // your own exception handling based on them.
574 // LLVM/Clang supports zero-cost DWARF exception handling.
577
578 // We want to legalize GlobalAddress and ConstantPool nodes into the
579 // appropriate instructions to materialize the address.
590
591 // TRAP is legal.
593
594 // TRAMPOLINE is custom lowered.
597
598 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
600
601 if (Subtarget.is64BitELFABI()) {
602 // VAARG always uses double-word chunks, so promote anything smaller.
612 } else if (Subtarget.is32BitELFABI()) {
613 // VAARG is custom lowered with the 32-bit SVR4 ABI.
616 } else
618
619 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
620 if (Subtarget.is32BitELFABI())
622 else
624
625 // Use the default implementation.
635
636 // We want to custom lower some of our intrinsics.
642
643 // To handle counter-based loop conditions.
645
650
651 // Comparisons that require checking two conditions.
652 if (Subtarget.hasSPE()) {
657 }
670
673
674 if (Subtarget.has64BitSupport()) {
675 // They also have instructions for converting between i64 and fp.
684 // This is just the low 32 bits of a (signed) fp->i64 conversion.
685 // We cannot do this with Promote because i64 is not a legal type.
688
689 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) {
692 }
693 } else {
694 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
695 if (Subtarget.hasSPE()) {
698 } else {
701 }
702 }
703
704 // With the instructions enabled under FPCVT, we can do everything.
705 if (Subtarget.hasFPCVT()) {
706 if (Subtarget.has64BitSupport()) {
715 }
716
725 }
726
727 if (Subtarget.use64BitRegs()) {
728 // 64-bit PowerPC implementations can support i64 types directly
729 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
730 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
732 // 64-bit PowerPC wants to expand i128 shifts itself.
736 } else {
737 // 32-bit PowerPC wants to expand i64 shifts itself.
741 }
742
743 // PowerPC has better expansions for funnel shifts than the generic
744 // TargetLowering::expandFunnelShift.
745 if (Subtarget.has64BitSupport()) {
748 }
751
752 if (Subtarget.hasVSX()) {
757 }
758
759 if (Subtarget.hasAltivec()) {
760 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
765 }
766 // First set operation action for all vector types to expand. Then we
767 // will selectively turn on ones that can be effectively codegen'd.
769 // add/sub are legal for all supported vector VT's.
772
773 // For v2i64, these are only valid with P8Vector. This is corrected after
774 // the loop.
775 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
780 }
781 else {
786 }
787
788 if (Subtarget.hasVSX()) {
791 }
792
793 // Vector instructions introduced in P8
794 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
797 }
798 else {
801 }
802
803 // Vector instructions introduced in P9
804 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
806 else
808
809 // We promote all shuffles to v16i8.
812
813 // We promote all non-typed operations to v4i32.
829
830 // No other operations are legal.
868
869 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
870 setTruncStoreAction(VT, InnerVT, Expand);
873 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
874 }
875 }
877 if (!Subtarget.hasP8Vector()) {
882 }
883
884 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
885 // with merges, splats, etc.
887
888 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
889 // are cheap, so handle them before they get expanded to scalar.
895
901 Subtarget.useCRBits() ? Legal : Expand);
915
916 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
918 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
919 if (Subtarget.hasAltivec())
920 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
922 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
923 if (Subtarget.hasP8Altivec())
925
926 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
927 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
928 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
929 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
930
933
934 if (Subtarget.hasVSX()) {
938 }
939
940 if (Subtarget.hasP8Altivec())
942 else
944
945 if (Subtarget.isISA3_1()) {
964 }
965
968
971
976
977 // Altivec does not contain unordered floating-point compare instructions
982
983 if (Subtarget.hasVSX()) {
986 if (Subtarget.hasP8Vector()) {
989 }
990 if (Subtarget.hasDirectMove() && isPPC64) {
999 }
1001
1002 // The nearbyint variants are not allowed to raise the inexact exception
1003 // so we can only code-gen them with unsafe math.
1004 if (TM.Options.UnsafeFPMath) {
1007 }
1008
1017
1023
1026
1029
1030 // Share the Altivec comparison restrictions.
1035
1038
1040
1041 if (Subtarget.hasP8Vector())
1042 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1043
1044 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1045
1046 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1047 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1048 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1049
1050 if (Subtarget.hasP8Altivec()) {
1054
1055 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1056 // SRL, but not for SRA because of the instructions available:
1057 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1058 // doing
1062
1064 }
1065 else {
1069
1071
1072 // VSX v2i64 only supports non-arithmetic operations.
1075 }
1076
1077 if (Subtarget.isISA3_1())
1079 else
1081
1086
1088
1097
1098 // Custom handling for partial vectors of integers converted to
1099 // floating point. We already have optimal handling for v2i32 through
1100 // the DAG combine, so those aren't necessary.
1117
1124
1127
1128 // Handle constrained floating-point operations of vector.
1129 // The predictor is `hasVSX` because altivec instruction has
1130 // no exception but VSX vector instruction has.
1144
1158
1159 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1160 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1161
1162 for (MVT FPT : MVT::fp_valuetypes())
1164
1165 // Expand the SELECT to SELECT_CC
1167
1170
1171 // No implementation for these ops for PowerPC.
1177 }
1178
1179 if (Subtarget.hasP8Altivec()) {
1180 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1181 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1182 }
1183
1184 if (Subtarget.hasP9Vector()) {
1187
1188 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1189 // SRL, but not for SRA because of the instructions available:
1190 // VS{RL} and VS{RL}O.
1194
1200
1208
1215
1219
1220 // Handle constrained floating-point operations of fp128
1241 } else if (Subtarget.hasVSX()) {
1244
1247
1248 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1249 // fp_to_uint and int_to_fp.
1252
1260
1261 // Expand the fp_extend if the target type is fp128.
1264
1265 // Expand the fp_round if the source type is fp128.
1266 for (MVT VT : {MVT::f32, MVT::f64}) {
1269 }
1270
1275
1276 // Lower following f128 select_cc pattern:
1277 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1279
1280 // We need to handle f128 SELECT_CC with integer result type.
1283 }
1284
1285 if (Subtarget.hasP9Altivec()) {
1286 if (Subtarget.isISA3_1()) {
1291 } else {
1294 }
1302 }
1303
1304 if (Subtarget.hasP10Vector()) {
1306 }
1307 }
1308
1309 if (Subtarget.pairedVectorMemops()) {
1310 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1313 }
1314 if (Subtarget.hasMMA()) {
1315 if (Subtarget.isISAFuture())
1316 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
1317 else
1318 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1322 }
1323
1324 if (Subtarget.has64BitSupport())
1326
1327 if (Subtarget.isISA3_1())
1329
1331
1332 if (!isPPC64) {
1335 }
1336
1341 }
1342
1344
1345 if (Subtarget.hasAltivec()) {
1346 // Altivec instructions set fields to all zeros or all ones.
1348 }
1349
1350 setLibcallName(RTLIB::MULO_I128, nullptr);
1351 if (!isPPC64) {
1352 // These libcalls are not available in 32-bit.
1353 setLibcallName(RTLIB::SHL_I128, nullptr);
1354 setLibcallName(RTLIB::SRL_I128, nullptr);
1355 setLibcallName(RTLIB::SRA_I128, nullptr);
1356 setLibcallName(RTLIB::MUL_I128, nullptr);
1357 setLibcallName(RTLIB::MULO_I64, nullptr);
1358 }
1359
1360 if (!isPPC64)
1362 else if (shouldInlineQuadwordAtomics())
1364 else
1366
1367 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1368
1369 // We have target-specific dag combine patterns for the following nodes:
1372 if (Subtarget.hasFPCVT())
1375 if (Subtarget.useCRBits())
1379
1381
1383
1384 if (Subtarget.useCRBits()) {
1386 }
1387
1388 if (Subtarget.hasP9Altivec()) {
1390 }
1391
1392 setLibcallName(RTLIB::LOG_F128, "logf128");
1393 setLibcallName(RTLIB::LOG2_F128, "log2f128");
1394 setLibcallName(RTLIB::LOG10_F128, "log10f128");
1395 setLibcallName(RTLIB::EXP_F128, "expf128");
1396 setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1397 setLibcallName(RTLIB::SIN_F128, "sinf128");
1398 setLibcallName(RTLIB::COS_F128, "cosf128");
1399 setLibcallName(RTLIB::POW_F128, "powf128");
1400 setLibcallName(RTLIB::FMIN_F128, "fminf128");
1401 setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1402 setLibcallName(RTLIB::REM_F128, "fmodf128");
1403 setLibcallName(RTLIB::SQRT_F128, "sqrtf128");
1404 setLibcallName(RTLIB::CEIL_F128, "ceilf128");
1405 setLibcallName(RTLIB::FLOOR_F128, "floorf128");
1406 setLibcallName(RTLIB::TRUNC_F128, "truncf128");
1407 setLibcallName(RTLIB::ROUND_F128, "roundf128");
1408 setLibcallName(RTLIB::LROUND_F128, "lroundf128");
1409 setLibcallName(RTLIB::LLROUND_F128, "llroundf128");
1410 setLibcallName(RTLIB::RINT_F128, "rintf128");
1411 setLibcallName(RTLIB::LRINT_F128, "lrintf128");
1412 setLibcallName(RTLIB::LLRINT_F128, "llrintf128");
1413 setLibcallName(RTLIB::NEARBYINT_F128, "nearbyintf128");
1414 setLibcallName(RTLIB::FMA_F128, "fmaf128");
1415
1416 // With 32 condition bits, we don't need to sink (and duplicate) compares
1417 // aggressively in CodeGenPrep.
1418 if (Subtarget.useCRBits()) {
1421 }
1422
1424
1425 switch (Subtarget.getCPUDirective()) {
1426 default: break;
1427 case PPC::DIR_970:
1428 case PPC::DIR_A2:
1429 case PPC::DIR_E500:
1430 case PPC::DIR_E500mc:
1431 case PPC::DIR_E5500:
1432 case PPC::DIR_PWR4:
1433 case PPC::DIR_PWR5:
1434 case PPC::DIR_PWR5X:
1435 case PPC::DIR_PWR6:
1436 case PPC::DIR_PWR6X:
1437 case PPC::DIR_PWR7:
1438 case PPC::DIR_PWR8:
1439 case PPC::DIR_PWR9:
1440 case PPC::DIR_PWR10:
1444 break;
1445 }
1446
1447 if (Subtarget.enableMachineScheduler())
1449 else
1451
1453
1454 // The Freescale cores do better with aggressive inlining of memcpy and
1455 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1456 if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1457 Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1458 MaxStoresPerMemset = 32;
1460 MaxStoresPerMemcpy = 32;
1464 } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1465 // The A2 also benefits from (very) aggressive inlining of memcpy and
1466 // friends. The overhead of a the function call, even when warm, can be
1467 // over one hundred cycles.
1468 MaxStoresPerMemset = 128;
1469 MaxStoresPerMemcpy = 128;
1470 MaxStoresPerMemmove = 128;
1471 MaxLoadsPerMemcmp = 128;
1472 } else {
1475 }
1476
1477 IsStrictFPEnabled = true;
1478
1479 // Let the subtarget (CPU) decide if a predictable select is more expensive
1480 // than the corresponding branch. This information is used in CGP to decide
1481 // when to convert selects into branches.
1483}
1484
1485// *********************************** NOTE ************************************
1486// For selecting load and store instructions, the addressing modes are defined
1487// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1488// patterns to match the load the store instructions.
1489//
1490// The TD definitions for the addressing modes correspond to their respective
1491// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1492// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1493// address mode flags of a particular node. Afterwards, the computed address
1494// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1495// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1496// accordingly, based on the preferred addressing mode.
1497//
1498// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1499// MemOpFlags contains all the possible flags that can be used to compute the
1500// optimal addressing mode for load and store instructions.
1501// AddrMode contains all the possible load and store addressing modes available
1502// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1503//
1504// When adding new load and store instructions, it is possible that new address
1505// flags may need to be added into MemOpFlags, and a new addressing mode will
1506// need to be added to AddrMode. An entry of the new addressing mode (consisting
1507// of the minimal and main distinguishing address flags for the new load/store
1508// instructions) will need to be added into initializeAddrModeMap() below.
1509// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1510// need to be updated to account for selecting the optimal addressing mode.
1511// *****************************************************************************
1512/// Initialize the map that relates the different addressing modes of the load
1513/// and store instructions to a set of flags. This ensures the load/store
1514/// instruction is correctly matched during instruction selection.
1515void PPCTargetLowering::initializeAddrModeMap() {
1516 AddrModesMap[PPC::AM_DForm] = {
1517 // LWZ, STW
1522 // LBZ, LHZ, STB, STH
1527 // LHA
1532 // LFS, LFD, STFS, STFD
1537 };
1538 AddrModesMap[PPC::AM_DSForm] = {
1539 // LWA
1543 // LD, STD
1547 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1551 };
1552 AddrModesMap[PPC::AM_DQForm] = {
1553 // LXV, STXV
1557 };
1558 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1560 // TODO: Add mapping for quadword load/store.
1561}
1562
1563/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1564/// the desired ByVal argument alignment.
1565static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1566 if (MaxAlign == MaxMaxAlign)
1567 return;
1568 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1569 if (MaxMaxAlign >= 32 &&
1570 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
1571 MaxAlign = Align(32);
1572 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
1573 MaxAlign < 16)
1574 MaxAlign = Align(16);
1575 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1576 Align EltAlign;
1577 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1578 if (EltAlign > MaxAlign)
1579 MaxAlign = EltAlign;
1580 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1581 for (auto *EltTy : STy->elements()) {
1582 Align EltAlign;
1583 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1584 if (EltAlign > MaxAlign)
1585 MaxAlign = EltAlign;
1586 if (MaxAlign == MaxMaxAlign)
1587 break;
1588 }
1589 }
1590}
1591
1592/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1593/// function arguments in the caller parameter area.
1595 const DataLayout &DL) const {
1596 // 16byte and wider vectors are passed on 16byte boundary.
1597 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1598 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1599 if (Subtarget.hasAltivec())
1600 getMaxByValAlign(Ty, Alignment, Align(16));
1601 return Alignment.value();
1602}
1603
1605 return Subtarget.useSoftFloat();
1606}
1607
1609 return Subtarget.hasSPE();
1610}
1611
1613 return VT.isScalarInteger();
1614}
1615
1616const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1617 switch ((PPCISD::NodeType)Opcode) {
1618 case PPCISD::FIRST_NUMBER: break;
1619 case PPCISD::FSEL: return "PPCISD::FSEL";
1620 case PPCISD::XSMAXC: return "PPCISD::XSMAXC";
1621 case PPCISD::XSMINC: return "PPCISD::XSMINC";
1622 case PPCISD::FCFID: return "PPCISD::FCFID";
1623 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
1624 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
1625 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
1626 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
1627 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
1628 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
1629 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
1631 return "PPCISD::FP_TO_UINT_IN_VSR,";
1633 return "PPCISD::FP_TO_SINT_IN_VSR";
1634 case PPCISD::FRE: return "PPCISD::FRE";
1635 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
1636 case PPCISD::FTSQRT:
1637 return "PPCISD::FTSQRT";
1638 case PPCISD::FSQRT:
1639 return "PPCISD::FSQRT";
1640 case PPCISD::STFIWX: return "PPCISD::STFIWX";
1641 case PPCISD::VPERM: return "PPCISD::VPERM";
1642 case PPCISD::XXSPLT: return "PPCISD::XXSPLT";
1644 return "PPCISD::XXSPLTI_SP_TO_DP";
1646 return "PPCISD::XXSPLTI32DX";
1647 case PPCISD::VECINSERT: return "PPCISD::VECINSERT";
1648 case PPCISD::XXPERMDI: return "PPCISD::XXPERMDI";
1649 case PPCISD::XXPERM:
1650 return "PPCISD::XXPERM";
1651 case PPCISD::VECSHL: return "PPCISD::VECSHL";
1652 case PPCISD::CMPB: return "PPCISD::CMPB";
1653 case PPCISD::Hi: return "PPCISD::Hi";
1654 case PPCISD::Lo: return "PPCISD::Lo";
1655 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
1656 case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1657 case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1658 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
1659 case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET";
1660 case PPCISD::PROBED_ALLOCA: return "PPCISD::PROBED_ALLOCA";
1661 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
1662 case PPCISD::SRL: return "PPCISD::SRL";
1663 case PPCISD::SRA: return "PPCISD::SRA";
1664 case PPCISD::SHL: return "PPCISD::SHL";
1665 case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE";
1666 case PPCISD::CALL: return "PPCISD::CALL";
1667 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
1668 case PPCISD::CALL_NOTOC: return "PPCISD::CALL_NOTOC";
1669 case PPCISD::CALL_RM:
1670 return "PPCISD::CALL_RM";
1672 return "PPCISD::CALL_NOP_RM";
1674 return "PPCISD::CALL_NOTOC_RM";
1675 case PPCISD::MTCTR: return "PPCISD::MTCTR";
1676 case PPCISD::BCTRL: return "PPCISD::BCTRL";
1677 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
1678 case PPCISD::BCTRL_RM:
1679 return "PPCISD::BCTRL_RM";
1681 return "PPCISD::BCTRL_LOAD_TOC_RM";
1682 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
1683 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
1684 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
1685 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1686 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
1687 case PPCISD::MFVSR: return "PPCISD::MFVSR";
1688 case PPCISD::MTVSRA: return "PPCISD::MTVSRA";
1689 case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ";
1690 case PPCISD::SINT_VEC_TO_FP: return "PPCISD::SINT_VEC_TO_FP";
1691 case PPCISD::UINT_VEC_TO_FP: return "PPCISD::UINT_VEC_TO_FP";
1693 return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1695 return "PPCISD::ANDI_rec_1_EQ_BIT";
1697 return "PPCISD::ANDI_rec_1_GT_BIT";
1698 case PPCISD::VCMP: return "PPCISD::VCMP";
1699 case PPCISD::VCMP_rec: return "PPCISD::VCMP_rec";
1700 case PPCISD::LBRX: return "PPCISD::LBRX";
1701 case PPCISD::STBRX: return "PPCISD::STBRX";
1702 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
1703 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
1704 case PPCISD::LXSIZX: return "PPCISD::LXSIZX";
1705 case PPCISD::STXSIX: return "PPCISD::STXSIX";
1706 case PPCISD::VEXTS: return "PPCISD::VEXTS";
1707 case PPCISD::LXVD2X: return "PPCISD::LXVD2X";
1708 case PPCISD::STXVD2X: return "PPCISD::STXVD2X";
1709 case PPCISD::LOAD_VEC_BE: return "PPCISD::LOAD_VEC_BE";
1710 case PPCISD::STORE_VEC_BE: return "PPCISD::STORE_VEC_BE";
1712 return "PPCISD::ST_VSR_SCAL_INT";
1713 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
1714 case PPCISD::BDNZ: return "PPCISD::BDNZ";
1715 case PPCISD::BDZ: return "PPCISD::BDZ";
1716 case PPCISD::MFFS: return "PPCISD::MFFS";
1717 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
1718 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
1719 case PPCISD::CR6SET: return "PPCISD::CR6SET";
1720 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
1721 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
1722 case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT";
1723 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1724 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
1725 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
1726 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
1727 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
1728 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
1729 case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1730 case PPCISD::TLSGD_AIX: return "PPCISD::TLSGD_AIX";
1731 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
1732 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
1733 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
1734 case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1735 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1736 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
1738 return "PPCISD::PADDI_DTPREL";
1739 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
1740 case PPCISD::SC: return "PPCISD::SC";
1741 case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB";
1742 case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE";
1743 case PPCISD::RFEBB: return "PPCISD::RFEBB";
1744 case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD";
1745 case PPCISD::SWAP_NO_CHAIN: return "PPCISD::SWAP_NO_CHAIN";
1746 case PPCISD::VABSD: return "PPCISD::VABSD";
1747 case PPCISD::BUILD_FP128: return "PPCISD::BUILD_FP128";
1748 case PPCISD::BUILD_SPE64: return "PPCISD::BUILD_SPE64";
1749 case PPCISD::EXTRACT_SPE: return "PPCISD::EXTRACT_SPE";
1750 case PPCISD::EXTSWSLI: return "PPCISD::EXTSWSLI";
1751 case PPCISD::LD_VSX_LH: return "PPCISD::LD_VSX_LH";
1752 case PPCISD::FP_EXTEND_HALF: return "PPCISD::FP_EXTEND_HALF";
1753 case PPCISD::MAT_PCREL_ADDR: return "PPCISD::MAT_PCREL_ADDR";
1755 return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1757 return "PPCISD::TLS_LOCAL_EXEC_MAT_ADDR";
1758 case PPCISD::ACC_BUILD: return "PPCISD::ACC_BUILD";
1759 case PPCISD::PAIR_BUILD: return "PPCISD::PAIR_BUILD";
1760 case PPCISD::EXTRACT_VSX_REG: return "PPCISD::EXTRACT_VSX_REG";
1761 case PPCISD::XXMFACC: return "PPCISD::XXMFACC";
1762 case PPCISD::LD_SPLAT: return "PPCISD::LD_SPLAT";
1763 case PPCISD::ZEXT_LD_SPLAT: return "PPCISD::ZEXT_LD_SPLAT";
1764 case PPCISD::SEXT_LD_SPLAT: return "PPCISD::SEXT_LD_SPLAT";
1765 case PPCISD::FNMSUB: return "PPCISD::FNMSUB";
1767 return "PPCISD::STRICT_FADDRTZ";
1769 return "PPCISD::STRICT_FCTIDZ";
1771 return "PPCISD::STRICT_FCTIWZ";
1773 return "PPCISD::STRICT_FCTIDUZ";
1775 return "PPCISD::STRICT_FCTIWUZ";
1777 return "PPCISD::STRICT_FCFID";
1779 return "PPCISD::STRICT_FCFIDU";
1781 return "PPCISD::STRICT_FCFIDS";
1783 return "PPCISD::STRICT_FCFIDUS";
1784 case PPCISD::LXVRZX: return "PPCISD::LXVRZX";
1785 case PPCISD::STORE_COND:
1786 return "PPCISD::STORE_COND";
1787 }
1788 return nullptr;
1789}
1790
1792 EVT VT) const {
1793 if (!VT.isVector())
1794 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1795
1797}
1798
1800 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1801 return true;
1802}
1803
1804//===----------------------------------------------------------------------===//
1805// Node matching predicates, for use by the tblgen matching code.
1806//===----------------------------------------------------------------------===//
1807
1808/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1810 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1811 return CFP->getValueAPF().isZero();
1812 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1813 // Maybe this has already been legalized into the constant pool?
1814 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1815 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1816 return CFP->getValueAPF().isZero();
1817 }
1818 return false;
1819}
1820
1821/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1822/// true if Op is undef or if it matches the specified value.
1823static bool isConstantOrUndef(int Op, int Val) {
1824 return Op < 0 || Op == Val;
1825}
1826
1827/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1828/// VPKUHUM instruction.
1829/// The ShuffleKind distinguishes between big-endian operations with
1830/// two different inputs (0), either-endian operations with two identical
1831/// inputs (1), and little-endian operations with two different inputs (2).
1832/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1834 SelectionDAG &DAG) {
1835 bool IsLE = DAG.getDataLayout().isLittleEndian();
1836 if (ShuffleKind == 0) {
1837 if (IsLE)
1838 return false;
1839 for (unsigned i = 0; i != 16; ++i)
1840 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1841 return false;
1842 } else if (ShuffleKind == 2) {
1843 if (!IsLE)
1844 return false;
1845 for (unsigned i = 0; i != 16; ++i)
1846 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1847 return false;
1848 } else if (ShuffleKind == 1) {
1849 unsigned j = IsLE ? 0 : 1;
1850 for (unsigned i = 0; i != 8; ++i)
1851 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1852 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1853 return false;
1854 }
1855 return true;
1856}
1857
1858/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1859/// VPKUWUM instruction.
1860/// The ShuffleKind distinguishes between big-endian operations with
1861/// two different inputs (0), either-endian operations with two identical
1862/// inputs (1), and little-endian operations with two different inputs (2).
1863/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1865 SelectionDAG &DAG) {
1866 bool IsLE = DAG.getDataLayout().isLittleEndian();
1867 if (ShuffleKind == 0) {
1868 if (IsLE)
1869 return false;
1870 for (unsigned i = 0; i != 16; i += 2)
1871 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1872 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1873 return false;
1874 } else if (ShuffleKind == 2) {
1875 if (!IsLE)
1876 return false;
1877 for (unsigned i = 0; i != 16; i += 2)
1878 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1879 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1880 return false;
1881 } else if (ShuffleKind == 1) {
1882 unsigned j = IsLE ? 0 : 2;
1883 for (unsigned i = 0; i != 8; i += 2)
1884 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1885 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1886 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1887 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1888 return false;
1889 }
1890 return true;
1891}
1892
1893/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1894/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1895/// current subtarget.
1896///
1897/// The ShuffleKind distinguishes between big-endian operations with
1898/// two different inputs (0), either-endian operations with two identical
1899/// inputs (1), and little-endian operations with two different inputs (2).
1900/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1902 SelectionDAG &DAG) {
1903 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1904 if (!Subtarget.hasP8Vector())
1905 return false;
1906
1907 bool IsLE = DAG.getDataLayout().isLittleEndian();
1908 if (ShuffleKind == 0) {
1909 if (IsLE)
1910 return false;
1911 for (unsigned i = 0; i != 16; i += 4)
1912 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1913 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1914 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1915 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1916 return false;
1917 } else if (ShuffleKind == 2) {
1918 if (!IsLE)
1919 return false;
1920 for (unsigned i = 0; i != 16; i += 4)
1921 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1922 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1923 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1924 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1925 return false;
1926 } else if (ShuffleKind == 1) {
1927 unsigned j = IsLE ? 0 : 4;
1928 for (unsigned i = 0; i != 8; i += 4)
1929 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1930 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1931 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1932 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1933 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1934 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1935 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1936 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1937 return false;
1938 }
1939 return true;
1940}
1941
1942/// isVMerge - Common function, used to match vmrg* shuffles.
1943///
1944static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1945 unsigned LHSStart, unsigned RHSStart) {
1946 if (N->getValueType(0) != MVT::v16i8)
1947 return false;
1948 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1949 "Unsupported merge size!");
1950
1951 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1952 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1953 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1954 LHSStart+j+i*UnitSize) ||
1955 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1956 RHSStart+j+i*UnitSize))
1957 return false;
1958 }
1959 return true;
1960}
1961
1962/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1963/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1964/// The ShuffleKind distinguishes between big-endian merges with two
1965/// different inputs (0), either-endian merges with two identical inputs (1),
1966/// and little-endian merges with two different inputs (2). For the latter,
1967/// the input operands are swapped (see PPCInstrAltivec.td).
1969 unsigned ShuffleKind, SelectionDAG &DAG) {
1970 if (DAG.getDataLayout().isLittleEndian()) {
1971 if (ShuffleKind == 1) // unary
1972 return isVMerge(N, UnitSize, 0, 0);
1973 else if (ShuffleKind == 2) // swapped
1974 return isVMerge(N, UnitSize, 0, 16);
1975 else
1976 return false;
1977 } else {
1978 if (ShuffleKind == 1) // unary
1979 return isVMerge(N, UnitSize, 8, 8);
1980 else if (ShuffleKind == 0) // normal
1981 return isVMerge(N, UnitSize, 8, 24);
1982 else
1983 return false;
1984 }
1985}
1986
1987/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1988/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1989/// The ShuffleKind distinguishes between big-endian merges with two
1990/// different inputs (0), either-endian merges with two identical inputs (1),
1991/// and little-endian merges with two different inputs (2). For the latter,
1992/// the input operands are swapped (see PPCInstrAltivec.td).
1994 unsigned ShuffleKind, SelectionDAG &DAG) {
1995 if (DAG.getDataLayout().isLittleEndian()) {
1996 if (ShuffleKind == 1) // unary
1997 return isVMerge(N, UnitSize, 8, 8);
1998 else if (ShuffleKind == 2) // swapped
1999 return isVMerge(N, UnitSize, 8, 24);
2000 else
2001 return false;
2002 } else {
2003 if (ShuffleKind == 1) // unary
2004 return isVMerge(N, UnitSize, 0, 0);
2005 else if (ShuffleKind == 0) // normal
2006 return isVMerge(N, UnitSize, 0, 16);
2007 else
2008 return false;
2009 }
2010}
2011
2012/**
2013 * Common function used to match vmrgew and vmrgow shuffles
2014 *
2015 * The indexOffset determines whether to look for even or odd words in
2016 * the shuffle mask. This is based on the of the endianness of the target
2017 * machine.
2018 * - Little Endian:
2019 * - Use offset of 0 to check for odd elements
2020 * - Use offset of 4 to check for even elements
2021 * - Big Endian:
2022 * - Use offset of 0 to check for even elements
2023 * - Use offset of 4 to check for odd elements
2024 * A detailed description of the vector element ordering for little endian and
2025 * big endian can be found at
2026 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
2027 * Targeting your applications - what little endian and big endian IBM XL C/C++
2028 * compiler differences mean to you
2029 *
2030 * The mask to the shuffle vector instruction specifies the indices of the
2031 * elements from the two input vectors to place in the result. The elements are
2032 * numbered in array-access order, starting with the first vector. These vectors
2033 * are always of type v16i8, thus each vector will contain 16 elements of size
2034 * 8. More info on the shuffle vector can be found in the
2035 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
2036 * Language Reference.
2037 *
2038 * The RHSStartValue indicates whether the same input vectors are used (unary)
2039 * or two different input vectors are used, based on the following:
2040 * - If the instruction uses the same vector for both inputs, the range of the
2041 * indices will be 0 to 15. In this case, the RHSStart value passed should
2042 * be 0.
2043 * - If the instruction has two different vectors then the range of the
2044 * indices will be 0 to 31. In this case, the RHSStart value passed should
2045 * be 16 (indices 0-15 specify elements in the first vector while indices 16
2046 * to 31 specify elements in the second vector).
2047 *
2048 * \param[in] N The shuffle vector SD Node to analyze
2049 * \param[in] IndexOffset Specifies whether to look for even or odd elements
2050 * \param[in] RHSStartValue Specifies the starting index for the righthand input
2051 * vector to the shuffle_vector instruction
2052 * \return true iff this shuffle vector represents an even or odd word merge
2053 */
2054static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
2055 unsigned RHSStartValue) {
2056 if (N->getValueType(0) != MVT::v16i8)
2057 return false;
2058
2059 for (unsigned i = 0; i < 2; ++i)
2060 for (unsigned j = 0; j < 4; ++j)
2061 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2062 i*RHSStartValue+j+IndexOffset) ||
2063 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2064 i*RHSStartValue+j+IndexOffset+8))
2065 return false;
2066 return true;
2067}
2068
2069/**
2070 * Determine if the specified shuffle mask is suitable for the vmrgew or
2071 * vmrgow instructions.
2072 *
2073 * \param[in] N The shuffle vector SD Node to analyze
2074 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2075 * \param[in] ShuffleKind Identify the type of merge:
2076 * - 0 = big-endian merge with two different inputs;
2077 * - 1 = either-endian merge with two identical inputs;
2078 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2079 * little-endian merges).
2080 * \param[in] DAG The current SelectionDAG
2081 * \return true iff this shuffle mask
2082 */
2084 unsigned ShuffleKind, SelectionDAG &DAG) {
2085 if (DAG.getDataLayout().isLittleEndian()) {
2086 unsigned indexOffset = CheckEven ? 4 : 0;
2087 if (ShuffleKind == 1) // Unary
2088 return isVMerge(N, indexOffset, 0);
2089 else if (ShuffleKind == 2) // swapped
2090 return isVMerge(N, indexOffset, 16);
2091 else
2092 return false;
2093 }
2094 else {
2095 unsigned indexOffset = CheckEven ? 0 : 4;
2096 if (ShuffleKind == 1) // Unary
2097 return isVMerge(N, indexOffset, 0);
2098 else if (ShuffleKind == 0) // Normal
2099 return isVMerge(N, indexOffset, 16);
2100 else
2101 return false;
2102 }
2103 return false;
2104}
2105
2106/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2107/// amount, otherwise return -1.
2108/// The ShuffleKind distinguishes between big-endian operations with two
2109/// different inputs (0), either-endian operations with two identical inputs
2110/// (1), and little-endian operations with two different inputs (2). For the
2111/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2112int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2113 SelectionDAG &DAG) {
2114 if (N->getValueType(0) != MVT::v16i8)
2115 return -1;
2116
2117 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2118
2119 // Find the first non-undef value in the shuffle mask.
2120 unsigned i;
2121 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2122 /*search*/;
2123
2124 if (i == 16) return -1; // all undef.
2125
2126 // Otherwise, check to see if the rest of the elements are consecutively
2127 // numbered from this value.
2128 unsigned ShiftAmt = SVOp->getMaskElt(i);
2129 if (ShiftAmt < i) return -1;
2130
2131 ShiftAmt -= i;
2132 bool isLE = DAG.getDataLayout().isLittleEndian();
2133
2134 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2135 // Check the rest of the elements to see if they are consecutive.
2136 for (++i; i != 16; ++i)
2137 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2138 return -1;
2139 } else if (ShuffleKind == 1) {
2140 // Check the rest of the elements to see if they are consecutive.
2141 for (++i; i != 16; ++i)
2142 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2143 return -1;
2144 } else
2145 return -1;
2146
2147 if (isLE)
2148 ShiftAmt = 16 - ShiftAmt;
2149
2150 return ShiftAmt;
2151}
2152
2153/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2154/// specifies a splat of a single element that is suitable for input to
2155/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2157 EVT VT = N->getValueType(0);
2158 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2159 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2160
2161 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2162 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2163
2164 // The consecutive indices need to specify an element, not part of two
2165 // different elements. So abandon ship early if this isn't the case.
2166 if (N->getMaskElt(0) % EltSize != 0)
2167 return false;
2168
2169 // This is a splat operation if each element of the permute is the same, and
2170 // if the value doesn't reference the second vector.
2171 unsigned ElementBase = N->getMaskElt(0);
2172
2173 // FIXME: Handle UNDEF elements too!
2174 if (ElementBase >= 16)
2175 return false;
2176
2177 // Check that the indices are consecutive, in the case of a multi-byte element
2178 // splatted with a v16i8 mask.
2179 for (unsigned i = 1; i != EltSize; ++i)
2180 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2181 return false;
2182
2183 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2184 if (N->getMaskElt(i) < 0) continue;
2185 for (unsigned j = 0; j != EltSize; ++j)
2186 if (N->getMaskElt(i+j) != N->getMaskElt(j))
2187 return false;
2188 }
2189 return true;
2190}
2191
2192/// Check that the mask is shuffling N byte elements. Within each N byte
2193/// element of the mask, the indices could be either in increasing or
2194/// decreasing order as long as they are consecutive.
2195/// \param[in] N the shuffle vector SD Node to analyze
2196/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2197/// Word/DoubleWord/QuadWord).
2198/// \param[in] StepLen the delta indices number among the N byte element, if
2199/// the mask is in increasing/decreasing order then it is 1/-1.
2200/// \return true iff the mask is shuffling N byte elements.
2201static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2202 int StepLen) {
2203 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2204 "Unexpected element width.");
2205 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2206
2207 unsigned NumOfElem = 16 / Width;
2208 unsigned MaskVal[16]; // Width is never greater than 16
2209 for (unsigned i = 0; i < NumOfElem; ++i) {
2210 MaskVal[0] = N->getMaskElt(i * Width);
2211 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2212 return false;
2213 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2214 return false;
2215 }
2216
2217 for (unsigned int j = 1; j < Width; ++j) {
2218 MaskVal[j] = N->getMaskElt(i * Width + j);
2219 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2220 return false;
2221 }
2222 }
2223 }
2224
2225 return true;
2226}
2227
2228bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2229 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2230 if (!isNByteElemShuffleMask(N, 4, 1))
2231 return false;
2232
2233 // Now we look at mask elements 0,4,8,12
2234 unsigned M0 = N->getMaskElt(0) / 4;
2235 unsigned M1 = N->getMaskElt(4) / 4;
2236 unsigned M2 = N->getMaskElt(8) / 4;
2237 unsigned M3 = N->getMaskElt(12) / 4;
2238 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2239 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2240
2241 // Below, let H and L be arbitrary elements of the shuffle mask
2242 // where H is in the range [4,7] and L is in the range [0,3].
2243 // H, 1, 2, 3 or L, 5, 6, 7
2244 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2245 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2246 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2247 InsertAtByte = IsLE ? 12 : 0;
2248 Swap = M0 < 4;
2249 return true;
2250 }
2251 // 0, H, 2, 3 or 4, L, 6, 7
2252 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2253 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2254 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2255 InsertAtByte = IsLE ? 8 : 4;
2256 Swap = M1 < 4;
2257 return true;
2258 }
2259 // 0, 1, H, 3 or 4, 5, L, 7
2260 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2261 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2262 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2263 InsertAtByte = IsLE ? 4 : 8;
2264 Swap = M2 < 4;
2265 return true;
2266 }
2267 // 0, 1, 2, H or 4, 5, 6, L
2268 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2269 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2270 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2271 InsertAtByte = IsLE ? 0 : 12;
2272 Swap = M3 < 4;
2273 return true;
2274 }
2275
2276 // If both vector operands for the shuffle are the same vector, the mask will
2277 // contain only elements from the first one and the second one will be undef.
2278 if (N->getOperand(1).isUndef()) {
2279 ShiftElts = 0;
2280 Swap = true;
2281 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2282 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2283 InsertAtByte = IsLE ? 12 : 0;
2284 return true;
2285 }
2286 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2287 InsertAtByte = IsLE ? 8 : 4;
2288 return true;
2289 }
2290 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2291 InsertAtByte = IsLE ? 4 : 8;
2292 return true;
2293 }
2294 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2295 InsertAtByte = IsLE ? 0 : 12;
2296 return true;
2297 }
2298 }
2299
2300 return false;
2301}
2302
2304 bool &Swap, bool IsLE) {
2305 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2306 // Ensure each byte index of the word is consecutive.
2307 if (!isNByteElemShuffleMask(N, 4, 1))
2308 return false;
2309
2310 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2311 unsigned M0 = N->getMaskElt(0) / 4;
2312 unsigned M1 = N->getMaskElt(4) / 4;
2313 unsigned M2 = N->getMaskElt(8) / 4;
2314 unsigned M3 = N->getMaskElt(12) / 4;
2315
2316 // If both vector operands for the shuffle are the same vector, the mask will
2317 // contain only elements from the first one and the second one will be undef.
2318 if (N->getOperand(1).isUndef()) {
2319 assert(M0 < 4 && "Indexing into an undef vector?");
2320 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2321 return false;
2322
2323 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2324 Swap = false;
2325 return true;
2326 }
2327
2328 // Ensure each word index of the ShuffleVector Mask is consecutive.
2329 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2330 return false;
2331
2332 if (IsLE) {
2333 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2334 // Input vectors don't need to be swapped if the leading element
2335 // of the result is one of the 3 left elements of the second vector
2336 // (or if there is no shift to be done at all).
2337 Swap = false;
2338 ShiftElts = (8 - M0) % 8;
2339 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2340 // Input vectors need to be swapped if the leading element
2341 // of the result is one of the 3 left elements of the first vector
2342 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2343 Swap = true;
2344 ShiftElts = (4 - M0) % 4;
2345 }
2346
2347 return true;
2348 } else { // BE
2349 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2350 // Input vectors don't need to be swapped if the leading element
2351 // of the result is one of the 4 elements of the first vector.
2352 Swap = false;
2353 ShiftElts = M0;
2354 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2355 // Input vectors need to be swapped if the leading element
2356 // of the result is one of the 4 elements of the right vector.
2357 Swap = true;
2358 ShiftElts = M0 - 4;
2359 }
2360
2361 return true;
2362 }
2363}
2364
2366 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2367
2368 if (!isNByteElemShuffleMask(N, Width, -1))
2369 return false;
2370
2371 for (int i = 0; i < 16; i += Width)
2372 if (N->getMaskElt(i) != i + Width - 1)
2373 return false;
2374
2375 return true;
2376}
2377
2379 return isXXBRShuffleMaskHelper(N, 2);
2380}
2381
2383 return isXXBRShuffleMaskHelper(N, 4);
2384}
2385
2387 return isXXBRShuffleMaskHelper(N, 8);
2388}
2389
2391 return isXXBRShuffleMaskHelper(N, 16);
2392}
2393
2394/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2395/// if the inputs to the instruction should be swapped and set \p DM to the
2396/// value for the immediate.
2397/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2398/// AND element 0 of the result comes from the first input (LE) or second input
2399/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2400/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2401/// mask.
2403 bool &Swap, bool IsLE) {
2404 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2405
2406 // Ensure each byte index of the double word is consecutive.
2407 if (!isNByteElemShuffleMask(N, 8, 1))
2408 return false;
2409
2410 unsigned M0 = N->getMaskElt(0) / 8;
2411 unsigned M1 = N->getMaskElt(8) / 8;
2412 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2413
2414 // If both vector operands for the shuffle are the same vector, the mask will
2415 // contain only elements from the first one and the second one will be undef.
2416 if (N->getOperand(1).isUndef()) {
2417 if ((M0 | M1) < 2) {
2418 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2419 Swap = false;
2420 return true;
2421 } else
2422 return false;
2423 }
2424
2425 if (IsLE) {
2426 if (M0 > 1 && M1 < 2) {
2427 Swap = false;
2428 } else if (M0 < 2 && M1 > 1) {
2429 M0 = (M0 + 2) % 4;
2430 M1 = (M1 + 2) % 4;
2431 Swap = true;
2432 } else
2433 return false;
2434
2435 // Note: if control flow comes here that means Swap is already set above
2436 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2437 return true;
2438 } else { // BE
2439 if (M0 < 2 && M1 > 1) {
2440 Swap = false;
2441 } else if (M0 > 1 && M1 < 2) {
2442 M0 = (M0 + 2) % 4;
2443 M1 = (M1 + 2) % 4;
2444 Swap = true;
2445 } else
2446 return false;
2447
2448 // Note: if control flow comes here that means Swap is already set above
2449 DM = (M0 << 1) + (M1 & 1);
2450 return true;
2451 }
2452}
2453
2454
2455/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2456/// appropriate for PPC mnemonics (which have a big endian bias - namely
2457/// elements are counted from the left of the vector register).
2458unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2459 SelectionDAG &DAG) {
2460 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2461 assert(isSplatShuffleMask(SVOp, EltSize));
2462 EVT VT = SVOp->getValueType(0);
2463
2464 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2465 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2466 : SVOp->getMaskElt(0);
2467
2468 if (DAG.getDataLayout().isLittleEndian())
2469 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2470 else
2471 return SVOp->getMaskElt(0) / EltSize;
2472}
2473
2474/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2475/// by using a vspltis[bhw] instruction of the specified element size, return
2476/// the constant being splatted. The ByteSize field indicates the number of
2477/// bytes of each element [124] -> [bhw].
2479 SDValue OpVal;
2480
2481 // If ByteSize of the splat is bigger than the element size of the
2482 // build_vector, then we have a case where we are checking for a splat where
2483 // multiple elements of the buildvector are folded together into a single
2484 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2485 unsigned EltSize = 16/N->getNumOperands();
2486 if (EltSize < ByteSize) {
2487 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2488 SDValue UniquedVals[4];
2489 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2490
2491 // See if all of the elements in the buildvector agree across.
2492 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2493 if (N->getOperand(i).isUndef()) continue;
2494 // If the element isn't a constant, bail fully out.
2495 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2496
2497 if (!UniquedVals[i&(Multiple-1)].getNode())
2498 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2499 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2500 return SDValue(); // no match.
2501 }
2502
2503 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2504 // either constant or undef values that are identical for each chunk. See
2505 // if these chunks can form into a larger vspltis*.
2506
2507 // Check to see if all of the leading entries are either 0 or -1. If
2508 // neither, then this won't fit into the immediate field.
2509 bool LeadingZero = true;
2510 bool LeadingOnes = true;
2511 for (unsigned i = 0; i != Multiple-1; ++i) {
2512 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2513
2514 LeadingZero &= isNullConstant(UniquedVals[i]);
2515 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2516 }
2517 // Finally, check the least significant entry.
2518 if (LeadingZero) {
2519 if (!UniquedVals[Multiple-1].getNode())
2520 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2521 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2522 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2523 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2524 }
2525 if (LeadingOnes) {
2526 if (!UniquedVals[Multiple-1].getNode())
2527 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2528 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2529 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2530 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2531 }
2532
2533 return SDValue();
2534 }
2535
2536 // Check to see if this buildvec has a single non-undef value in its elements.
2537 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2538 if (N->getOperand(i).isUndef()) continue;
2539 if (!OpVal.getNode())
2540 OpVal = N->getOperand(i);
2541 else if (OpVal != N->getOperand(i))
2542 return SDValue();
2543 }
2544
2545 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2546
2547 unsigned ValSizeInBytes = EltSize;
2548 uint64_t Value = 0;
2549 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2550 Value = CN->getZExtValue();
2551 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2552 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2553 Value = FloatToBits(CN->getValueAPF().convertToFloat());
2554 }
2555
2556 // If the splat value is larger than the element value, then we can never do
2557 // this splat. The only case that we could fit the replicated bits into our
2558 // immediate field for would be zero, and we prefer to use vxor for it.
2559 if (ValSizeInBytes < ByteSize) return SDValue();
2560
2561 // If the element value is larger than the splat value, check if it consists
2562 // of a repeated bit pattern of size ByteSize.
2563 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2564 return SDValue();
2565
2566 // Properly sign extend the value.
2567 int MaskVal = SignExtend32(Value, ByteSize * 8);
2568
2569 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2570 if (MaskVal == 0) return SDValue();
2571
2572 // Finally, if this value fits in a 5 bit sext field, return it
2573 if (SignExtend32<5>(MaskVal) == MaskVal)
2574 return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2575 return SDValue();
2576}
2577
2578//===----------------------------------------------------------------------===//
2579// Addressing Mode Selection
2580//===----------------------------------------------------------------------===//
2581
2582/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2583/// or 64-bit immediate, and if the value can be accurately represented as a
2584/// sign extension from a 16-bit value. If so, this returns true and the
2585/// immediate.
2586bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2587 if (!isa<ConstantSDNode>(N))
2588 return false;
2589
2590 Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2591 if (N->getValueType(0) == MVT::i32)
2592 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2593 else
2594 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2595}
2596bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2597 return isIntS16Immediate(Op.getNode(), Imm);
2598}
2599
2600/// Used when computing address flags for selecting loads and stores.
2601/// If we have an OR, check if the LHS and RHS are provably disjoint.
2602/// An OR of two provably disjoint values is equivalent to an ADD.
2603/// Most PPC load/store instructions compute the effective address as a sum,
2604/// so doing this conversion is useful.
2605static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2606 if (N.getOpcode() != ISD::OR)
2607 return false;
2608 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2609 if (!LHSKnown.Zero.getBoolValue())
2610 return false;
2611 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2612 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2613}
2614
2615/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2616/// be represented as an indexed [r+r] operation.
2618 SDValue &Index,
2619 SelectionDAG &DAG) const {
2620 for (SDNode *U : N->uses()) {
2621 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2622 if (Memop->getMemoryVT() == MVT::f64) {
2623 Base = N.getOperand(0);
2624 Index = N.getOperand(1);
2625 return true;
2626 }
2627 }
2628 }
2629 return false;
2630}
2631
2632/// isIntS34Immediate - This method tests if value of node given can be
2633/// accurately represented as a sign extension from a 34-bit value. If so,
2634/// this returns true and the immediate.
2635bool llvm::isIntS34Immediate(SDNode *N, int64_t &Imm) {
2636 if (!isa<ConstantSDNode>(N))
2637 return false;
2638
2639 Imm = (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2640 return isInt<34>(Imm);
2641}
2642bool llvm::isIntS34Immediate(SDValue Op, int64_t &Imm) {
2643 return isIntS34Immediate(Op.getNode(), Imm);
2644}
2645
2646/// SelectAddressRegReg - Given the specified addressed, check to see if it
2647/// can be represented as an indexed [r+r] operation. Returns false if it
2648/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2649/// non-zero and N can be represented by a base register plus a signed 16-bit
2650/// displacement, make a more precise judgement by checking (displacement % \p
2651/// EncodingAlignment).
2654 MaybeAlign EncodingAlignment) const {
2655 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2656 // a [pc+imm].
2658 return false;
2659
2660 int16_t Imm = 0;
2661 if (N.getOpcode() == ISD::ADD) {
2662 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2663 // SPE load/store can only handle 8-bit offsets.
2664 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2665 return true;
2666 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2667 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2668 return false; // r+i
2669 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2670 return false; // r+i
2671
2672 Base = N.getOperand(0);
2673 Index = N.getOperand(1);
2674 return true;
2675 } else if (N.getOpcode() == ISD::OR) {
2676 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2677 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2678 return false; // r+i can fold it if we can.
2679
2680 // If this is an or of disjoint bitfields, we can codegen this as an add
2681 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2682 // disjoint.
2683 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2684
2685 if (LHSKnown.Zero.getBoolValue()) {
2686 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2687 // If all of the bits are known zero on the LHS or RHS, the add won't
2688 // carry.
2689 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2690 Base = N.getOperand(0);
2691 Index = N.getOperand(1);
2692 return true;
2693 }
2694 }
2695 }
2696
2697 return false;
2698}
2699
2700// If we happen to be doing an i64 load or store into a stack slot that has
2701// less than a 4-byte alignment, then the frame-index elimination may need to
2702// use an indexed load or store instruction (because the offset may not be a
2703// multiple of 4). The extra register needed to hold the offset comes from the
2704// register scavenger, and it is possible that the scavenger will need to use
2705// an emergency spill slot. As a result, we need to make sure that a spill slot
2706// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2707// stack slot.
2708static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2709 // FIXME: This does not handle the LWA case.
2710 if (VT != MVT::i64)
2711 return;
2712
2713 // NOTE: We'll exclude negative FIs here, which come from argument
2714 // lowering, because there are no known test cases triggering this problem
2715 // using packed structures (or similar). We can remove this exclusion if
2716 // we find such a test case. The reason why this is so test-case driven is
2717 // because this entire 'fixup' is only to prevent crashes (from the
2718 // register scavenger) on not-really-valid inputs. For example, if we have:
2719 // %a = alloca i1
2720 // %b = bitcast i1* %a to i64*
2721 // store i64* a, i64 b
2722 // then the store should really be marked as 'align 1', but is not. If it
2723 // were marked as 'align 1' then the indexed form would have been
2724 // instruction-selected initially, and the problem this 'fixup' is preventing
2725 // won't happen regardless.
2726 if (FrameIdx < 0)
2727 return;
2728
2730 MachineFrameInfo &MFI = MF.getFrameInfo();
2731
2732 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2733 return;
2734
2735 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2736 FuncInfo->setHasNonRISpills();
2737}
2738
2739/// Returns true if the address N can be represented by a base register plus
2740/// a signed 16-bit displacement [r+imm], and if it is not better
2741/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2742/// displacements that are multiples of that value.
2744 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2745 MaybeAlign EncodingAlignment) const {
2746 // FIXME dl should come from parent load or store, not from address
2747 SDLoc dl(N);
2748
2749 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2750 // a [pc+imm].
2752 return false;
2753
2754 // If this can be more profitably realized as r+r, fail.
2755 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2756 return false;
2757
2758 if (N.getOpcode() == ISD::ADD) {
2759 int16_t imm = 0;
2760 if (isIntS16Immediate(N.getOperand(1), imm) &&
2761 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2762 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2763 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2764 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2765 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2766 } else {
2767 Base = N.getOperand(0);
2768 }
2769 return true; // [r+i]
2770 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2771 // Match LOAD (ADD (X, Lo(G))).
2772 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2773 && "Cannot handle constant offsets yet!");
2774 Disp = N.getOperand(1).getOperand(0); // The global address.
2779 Base = N.getOperand(0);
2780 return true; // [&g+r]
2781 }
2782 } else if (N.getOpcode() == ISD::OR) {
2783 int16_t imm = 0;
2784 if (isIntS16Immediate(N.getOperand(1), imm) &&
2785 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2786 // If this is an or of disjoint bitfields, we can codegen this as an add
2787 // (for better address arithmetic) if the LHS and RHS of the OR are
2788 // provably disjoint.
2789 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2790
2791 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2792 // If all of the bits are known zero on the LHS or RHS, the add won't
2793 // carry.
2794 if (FrameIndexSDNode *FI =
2795 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2796 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2797 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2798 } else {
2799 Base = N.getOperand(0);
2800 }
2801 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2802 return true;
2803 }
2804 }
2805 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2806 // Loading from a constant address.
2807
2808 // If this address fits entirely in a 16-bit sext immediate field, codegen
2809 // this as "d, 0"
2810 int16_t Imm;
2811 if (isIntS16Immediate(CN, Imm) &&
2812 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2813 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2814 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2815 CN->getValueType(0));
2816 return true;
2817 }
2818
2819 // Handle 32-bit sext immediates with LIS + addr mode.
2820 if ((CN->getValueType(0) == MVT::i32 ||
2821 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2822 (!EncodingAlignment ||
2823 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2824 int Addr = (int)CN->getZExtValue();
2825
2826 // Otherwise, break this down into an LIS + disp.
2827 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2828
2829 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2830 MVT::i32);
2831 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2832 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2833 return true;
2834 }
2835 }
2836
2837 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2838 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2839 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2840 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2841 } else
2842 Base = N;
2843 return true; // [r+0]
2844}
2845
2846/// Similar to the 16-bit case but for instructions that take a 34-bit
2847/// displacement field (prefixed loads/stores).
2849 SDValue &Base,
2850 SelectionDAG &DAG) const {
2851 // Only on 64-bit targets.
2852 if (N.getValueType() != MVT::i64)
2853 return false;
2854
2855 SDLoc dl(N);
2856 int64_t Imm = 0;
2857
2858 if (N.getOpcode() == ISD::ADD) {
2859 if (!isIntS34Immediate(N.getOperand(1), Imm))
2860 return false;
2861 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2862 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2863 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2864 else
2865 Base = N.getOperand(0);
2866 return true;
2867 }
2868
2869 if (N.getOpcode() == ISD::OR) {
2870 if (!isIntS34Immediate(N.getOperand(1), Imm))
2871 return false;
2872 // If this is an or of disjoint bitfields, we can codegen this as an add
2873 // (for better address arithmetic) if the LHS and RHS of the OR are
2874 // provably disjoint.
2875 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2876 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2877 return false;
2878 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2879 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2880 else
2881 Base = N.getOperand(0);
2882 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2883 return true;
2884 }
2885
2886 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2887 Disp = DAG.getTargetConstant(Imm, dl, N.getValueType());
2888 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2889 return true;
2890 }
2891
2892 return false;
2893}
2894
2895/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2896/// represented as an indexed [r+r] operation.
2898 SDValue &Index,
2899 SelectionDAG &DAG) const {
2900 // Check to see if we can easily represent this as an [r+r] address. This
2901 // will fail if it thinks that the address is more profitably represented as
2902 // reg+imm, e.g. where imm = 0.
2903 if (SelectAddressRegReg(N, Base, Index, DAG))
2904 return true;
2905
2906 // If the address is the result of an add, we will utilize the fact that the
2907 // address calculation includes an implicit add. However, we can reduce
2908 // register pressure if we do not materialize a constant just for use as the
2909 // index register. We only get rid of the add if it is not an add of a
2910 // value and a 16-bit signed constant and both have a single use.
2911 int16_t imm = 0;
2912 if (N.getOpcode() == ISD::ADD &&
2913 (!isIntS16Immediate(N.getOperand(1), imm) ||
2914 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2915 Base = N.getOperand(0);
2916 Index = N.getOperand(1);
2917 return true;
2918 }
2919
2920 // Otherwise, do it the hard way, using R0 as the base register.
2921 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2922 N.getValueType());
2923 Index = N;
2924 return true;
2925}
2926
2927template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2928 Ty *PCRelCand = dyn_cast<Ty>(N);
2929 return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2930}
2931
2932/// Returns true if this address is a PC Relative address.
2933/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2934/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2936 // This is a materialize PC Relative node. Always select this as PC Relative.
2937 Base = N;
2938 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2939 return true;
2940 if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2941 isValidPCRelNode<GlobalAddressSDNode>(N) ||
2942 isValidPCRelNode<JumpTableSDNode>(N) ||
2943 isValidPCRelNode<BlockAddressSDNode>(N))
2944 return true;
2945 return false;
2946}
2947
2948/// Returns true if we should use a direct load into vector instruction
2949/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2950static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2951
2952 // If there are any other uses other than scalar to vector, then we should
2953 // keep it as a scalar load -> direct move pattern to prevent multiple
2954 // loads.
2955 LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2956 if (!LD)
2957 return false;
2958
2959 EVT MemVT = LD->getMemoryVT();
2960 if (!MemVT.isSimple())
2961 return false;
2962 switch(MemVT.getSimpleVT().SimpleTy) {
2963 case MVT::i64:
2964 break;
2965 case MVT::i32:
2966 if (!ST.hasP8Vector())
2967 return false;
2968 break;
2969 case MVT::i16:
2970 case MVT::i8:
2971 if (!ST.hasP9Vector())
2972 return false;
2973 break;
2974 default:
2975 return false;
2976 }
2977
2978 SDValue LoadedVal(N, 0);
2979 if (!LoadedVal.hasOneUse())
2980 return false;
2981
2982 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2983 UI != UE; ++UI)
2984 if (UI.getUse().get().getResNo() == 0 &&
2985 UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2986 UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2987 return false;
2988
2989 return true;
2990}
2991
2992/// getPreIndexedAddressParts - returns true by value, base pointer and
2993/// offset pointer and addressing mode by reference if the node's address
2994/// can be legally represented as pre-indexed load / store address.
2996 SDValue &Offset,
2998 SelectionDAG &DAG) const {
2999 if (DisablePPCPreinc) return false;
3000
3001 bool isLoad = true;
3002 SDValue Ptr;
3003 EVT VT;
3004 Align Alignment;
3005 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3006 Ptr = LD->getBasePtr();
3007 VT = LD->getMemoryVT();
3008 Alignment = LD->getAlign();
3009 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3010 Ptr = ST->getBasePtr();
3011 VT = ST->getMemoryVT();
3012 Alignment = ST->getAlign();
3013 isLoad = false;
3014 } else
3015 return false;
3016
3017 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
3018 // instructions because we can fold these into a more efficient instruction
3019 // instead, (such as LXSD).
3020 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
3021 return false;
3022 }
3023
3024 // PowerPC doesn't have preinc load/store instructions for vectors
3025 if (VT.isVector())
3026 return false;
3027
3028 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
3029 // Common code will reject creating a pre-inc form if the base pointer
3030 // is a frame index, or if N is a store and the base pointer is either
3031 // the same as or a predecessor of the value being stored. Check for
3032 // those situations here, and try with swapped Base/Offset instead.
3033 bool Swap = false;
3034
3035 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
3036 Swap = true;
3037 else if (!isLoad) {
3038 SDValue Val = cast<StoreSDNode>(N)->getValue();
3039 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
3040 Swap = true;
3041 }
3042
3043 if (Swap)
3045
3046 AM = ISD::PRE_INC;
3047 return true;
3048 }
3049
3050 // LDU/STU can only handle immediates that are a multiple of 4.
3051 if (VT != MVT::i64) {
3052 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
3053 return false;
3054 } else {
3055 // LDU/STU need an address with at least 4-byte alignment.
3056 if (Alignment < Align(4))
3057 return false;
3058
3059 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3060 return false;
3061 }
3062
3063 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3064 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3065 // sext i32 to i64 when addr mode is r+i.
3066 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3067 LD->getExtensionType() == ISD::SEXTLOAD &&
3068 isa<ConstantSDNode>(Offset))
3069 return false;
3070 }
3071
3072 AM = ISD::PRE_INC;
3073 return true;
3074}
3075
3076//===----------------------------------------------------------------------===//
3077// LowerOperation implementation
3078//===----------------------------------------------------------------------===//
3079
3080/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3081/// and LoOpFlags to the target MO flags.
3082static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3083 unsigned &HiOpFlags, unsigned &LoOpFlags,
3084 const GlobalValue *GV = nullptr) {
3085 HiOpFlags = PPCII::MO_HA;
3086 LoOpFlags = PPCII::MO_LO;
3087
3088 // Don't use the pic base if not in PIC relocation model.
3089 if (IsPIC) {
3090 HiOpFlags |= PPCII::MO_PIC_FLAG;
3091 LoOpFlags |= PPCII::MO_PIC_FLAG;
3092 }
3093}
3094
3095static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3096 SelectionDAG &DAG) {
3097 SDLoc DL(HiPart);
3098 EVT PtrVT = HiPart.getValueType();
3099 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3100
3101 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3102 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3103
3104 // With PIC, the first instruction is actually "GR+hi(&G)".
3105 if (isPIC)
3106 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3107 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3108
3109 // Generate non-pic code that has direct accesses to the constant pool.
3110 // The address of the global is just (hi(&g)+lo(&g)).
3111 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3112}
3113
3115 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3116 FuncInfo->setUsesTOCBasePtr();
3117}
3118
3121}
3122
3123SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3124 SDValue GA) const {
3125 const bool Is64Bit = Subtarget.isPPC64();
3126 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
3127 SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
3128 : Subtarget.isAIXABI()
3129 ? DAG.getRegister(PPC::R2, VT)
3130 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3131 SDValue Ops[] = { GA, Reg };
3132 return DAG.getMemIntrinsicNode(
3133 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3136}
3137
3138SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3139 SelectionDAG &DAG) const {
3140 EVT PtrVT = Op.getValueType();
3141 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3142 const Constant *C = CP->getConstVal();
3143
3144 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3145 // The actual address of the GlobalValue is stored in the TOC.
3146 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3147 if (Subtarget.isUsingPCRelativeCalls()) {
3148 SDLoc DL(CP);
3149 EVT Ty = getPointerTy(DAG.getDataLayout());
3150 SDValue ConstPool = DAG.getTargetConstantPool(
3151 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3152 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3153 }
3154 setUsesTOCBasePtr(DAG);
3155 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3156 return getTOCEntry(DAG, SDLoc(CP), GA);
3157 }
3158
3159 unsigned MOHiFlag, MOLoFlag;
3160 bool IsPIC = isPositionIndependent();
3161 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3162
3163 if (IsPIC && Subtarget.isSVR4ABI()) {
3164 SDValue GA =
3165 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
3166 return getTOCEntry(DAG, SDLoc(CP), GA);
3167 }
3168
3169 SDValue CPIHi =
3170 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3171 SDValue CPILo =
3172 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3173 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3174}
3175
3176// For 64-bit PowerPC, prefer the more compact relative encodings.
3177// This trades 32 bits per jump table entry for one or two instructions
3178// on the jump site.
3180 if (isJumpTableRelative())
3182
3184}
3185
3188 return false;
3189 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3190 return true;
3192}
3193
3195 SelectionDAG &DAG) const {
3196 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3198
3199 switch (getTargetMachine().getCodeModel()) {
3200 case CodeModel::Small:
3201 case CodeModel::Medium:
3203 default:
3204 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3206 }
3207}
3208
3209const MCExpr *
3211 unsigned JTI,
3212 MCContext &Ctx) const {
3213 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3215
3216 switch (getTargetMachine().getCodeModel()) {
3217 case CodeModel::Small:
3218 case CodeModel::Medium:
3220 default:
3221 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3222 }
3223}
3224
3225SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3226 EVT PtrVT = Op.getValueType();
3227 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3228
3229 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3230 if (Subtarget.isUsingPCRelativeCalls()) {
3231 SDLoc DL(JT);
3232 EVT Ty = getPointerTy(DAG.getDataLayout());
3233 SDValue GA =
3234 DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
3235 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3236 return MatAddr;
3237 }
3238
3239 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3240 // The actual address of the GlobalValue is stored in the TOC.
3241 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3242 setUsesTOCBasePtr(DAG);
3243 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3244 return getTOCEntry(DAG, SDLoc(JT), GA);
3245 }
3246
3247 unsigned MOHiFlag, MOLoFlag;
3248 bool IsPIC = isPositionIndependent();
3249 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3250
3251 if (IsPIC && Subtarget.isSVR4ABI()) {
3252 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3254 return getTOCEntry(DAG, SDLoc(GA), GA);
3255 }
3256
3257 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3258 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3259 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3260}
3261
3262SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3263 SelectionDAG &DAG) const {
3264 EVT PtrVT = Op.getValueType();
3265 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3266 const BlockAddress *BA = BASDN->getBlockAddress();
3267
3268 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3269 if (Subtarget.isUsingPCRelativeCalls()) {
3270 SDLoc DL(BASDN);
3271 EVT Ty = getPointerTy(DAG.getDataLayout());
3272 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3274 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3275 return MatAddr;
3276 }
3277
3278 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3279 // The actual BlockAddress is stored in the TOC.
3280 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3281 setUsesTOCBasePtr(DAG);
3282 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3283 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3284 }
3285
3286 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3287 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3288 return getTOCEntry(
3289 DAG, SDLoc(BASDN),
3290 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3291
3292 unsigned MOHiFlag, MOLoFlag;
3293 bool IsPIC = isPositionIndependent();
3294 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3295 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3296 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3297 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3298}
3299
3300SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3301 SelectionDAG &DAG) const {
3302 if (Subtarget.isAIXABI())
3303 return LowerGlobalTLSAddressAIX(Op, DAG);
3304
3305 return LowerGlobalTLSAddressLinux(Op, DAG);
3306}
3307
3308SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3309 SelectionDAG &DAG) const {
3310 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3311
3312 if (DAG.getTarget().useEmulatedTLS())
3313 report_fatal_error("Emulated TLS is not yet supported on AIX");
3314
3315 SDLoc dl(GA);
3316 const GlobalValue *GV = GA->getGlobal();
3317 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3318
3319 // The general-dynamic model is the only access model supported for now, so
3320 // all the GlobalTLSAddress nodes are lowered with this model.
3321 // We need to generate two TOC entries, one for the variable offset, on