LLVM 24.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"
16#include "PPC.h"
17#include "PPCCallingConv.h"
18#include "PPCFrameLowering.h"
19#include "PPCInstrInfo.h"
21#include "PPCPerfectShuffle.h"
22#include "PPCRegisterInfo.h"
23#include "PPCSelectionDAGInfo.h"
24#include "PPCSubtarget.h"
25#include "PPCTargetMachine.h"
26#include "llvm/ADT/APFloat.h"
27#include "llvm/ADT/APInt.h"
28#include "llvm/ADT/APSInt.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/StringRef.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"
64#include "llvm/IR/Function.h"
65#include "llvm/IR/GlobalValue.h"
66#include "llvm/IR/IRBuilder.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"
84#include "llvm/Support/Debug.h"
86#include "llvm/Support/Format.h"
92#include <algorithm>
93#include <cassert>
94#include <cstdint>
95#include <iterator>
96#include <list>
97#include <optional>
98#include <utility>
99#include <vector>
100
101using namespace llvm;
102
103#define DEBUG_TYPE "ppc-lowering"
104
106
108 "ppc-p10-store-forward",
109 cl::desc("enable P10 store forward-friendly conversion"), cl::init(true),
110 cl::Hidden);
111
113 "ppc-preinc", cl::desc("enable preincrement load/store generation on PPC"),
114 cl::init(true), cl::Hidden);
115
116static cl::opt<bool>
117 EnableILPPref("ppc-ilp-pref",
118 cl::desc("Set the node scheduling preference to ILP on PPC"),
119 cl::init(true), cl::Hidden);
120
122 "ppc-unaligned", cl::desc("enable unaligned load/store generation on PPC"),
123 cl::init(true), cl::Hidden);
124
125static cl::opt<bool>
126 EnableSCO("ppc-sco", cl::desc("enable sibling call optimization on ppc"),
127 cl::init(true), cl::Hidden);
128
130 "ppc-innermost-loop-align32",
131 cl::desc("Align innermost loops to 32 bytes on ppc"), cl::init(true),
132 cl::Hidden);
133
134static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
135cl::desc("use absolute jump tables on ppc"), cl::Hidden);
136
137static cl::opt<bool>
138 EnablePerfectShuffle("ppc-perfect-shuffle",
139 cl::desc("enable vector permute decomposition"),
140 cl::init(false), cl::Hidden);
141
143 "ppc-auto-paired-vec-st",
144 cl::desc("enable automatically generated 32byte paired vector stores"),
145 cl::init(false), cl::Hidden);
146
148 "ppc-min-jump-table-entries", cl::init(64), cl::Hidden,
149 cl::desc("Set minimum number of entries to use a jump table on PPC"));
150
152 "ppc-min-bit-test-cmps", cl::init(3), cl::Hidden,
153 cl::desc("Set minimum of largest number of comparisons to use bit test for "
154 "switch on PPC."));
155
157 "ppc-gather-alias-max-depth", cl::init(18), cl::Hidden,
158 cl::desc("max depth when checking alias info in GatherAllAliases()"));
159
161 "ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden,
162 cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a "
163 "function to use initial-exec"));
164
165STATISTIC(NumTailCalls, "Number of tail calls");
166STATISTIC(NumSiblingCalls, "Number of sibling calls");
167STATISTIC(ShufflesHandledWithVPERM,
168 "Number of shuffles lowered to a VPERM or XXPERM");
169STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
170
171static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
172
173static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
174
176 unsigned OpIdx, bool IsByte,
177 const PPCInstrInfo *TII);
178
179// A faster local-[exec|dynamic] TLS access sequence (enabled with the
180// -maix-small-local-[exec|dynamic]-tls option) can be produced for TLS
181// variables; consistent with the IBM XL compiler, we apply a max size of
182// slightly under 32KB.
184
185// FIXME: Remove this once the bug has been fixed!
187
189 const PPCSubtarget &STI)
190 : TargetLowering(TM, STI), Subtarget(STI) {
191 // Initialize map that relates the PPC addressing modes to the computed flags
192 // of a load/store instruction. The map is used to determine the optimal
193 // addressing mode when selecting load and stores.
194 initializeAddrModeMap();
195 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
196 // arguments are at least 4/8 bytes aligned.
197 bool isPPC64 = Subtarget.isPPC64();
198 setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
199 const MVT RegVT = Subtarget.getScalarIntVT();
200
201 // Set up the register classes.
202 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
203 if (!useSoftFloat()) {
204 if (hasSPE()) {
205 addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
206 // EFPU2 APU only supports f32
207 if (!Subtarget.hasEFPU2())
208 addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
209 } else {
210 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
211 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
212 }
213 }
214
217
218 // PowerPC uses addo_carry,subo_carry to propagate carry.
221
222 // On P10, the default lowering generates better code using the
223 // setbc instruction.
224 if (!Subtarget.hasP10Vector()) {
227 if (isPPC64) {
230 }
231 }
232
233 // Match BITREVERSE to customized fast code sequence in the td file.
236
237 // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
239
240 // Custom lower inline assembly to check for special registers.
243
244 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
245 for (MVT VT : MVT::integer_valuetypes()) {
248 }
249
250 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
252
253 if (Subtarget.isISA3_0()) {
254 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Legal);
255 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
256 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
257 setTruncStoreAction(MVT::f64, MVT::f16, Legal);
258 setTruncStoreAction(MVT::f32, MVT::f16, Legal);
259 } else {
260 // No extending loads from f16 or HW conversions back and forth.
261 setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f16, Expand);
263 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
266 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
269 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
270 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
271 }
272
273 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
274
275 // PowerPC has pre-inc load and store's.
286 if (!Subtarget.hasSPE()) {
291 }
292
293 if (Subtarget.useCRBits()) {
295
296 if (isPPC64 || Subtarget.hasFPCVT()) {
301
303 AddPromotedToType(ISD::SINT_TO_FP, MVT::i1, RegVT);
305 AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, RegVT);
306
311
313 AddPromotedToType(ISD::FP_TO_SINT, MVT::i1, RegVT);
315 AddPromotedToType(ISD::FP_TO_UINT, MVT::i1, RegVT);
316 } else {
321 }
322
323 // PowerPC does not support direct load/store of condition registers.
326
327 // FIXME: Remove this once the ANDI glue bug is fixed:
328 if (ANDIGlueBug)
330
331 for (MVT VT : MVT::integer_valuetypes()) {
334 setTruncStoreAction(VT, MVT::i1, Expand);
335 }
336
337 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
338 }
339
340 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
341 // PPC (the libcall is not available).
346
347 // We do not currently implement these libm ops for PowerPC.
348 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
349 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
350 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
351 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
353 setOperationAction(ISD::FREM, MVT::ppcf128, LibCall);
354
355 // PowerPC has no SREM/UREM instructions unless we are on P9
356 // On P9 we may use a hardware instruction to compute the remainder.
357 // When the result of both the remainder and the division is required it is
358 // more efficient to compute the remainder from the result of the division
359 // rather than use the remainder instruction. The instructions are legalized
360 // directly because the DivRemPairsPass performs the transformation at the IR
361 // level.
362 if (Subtarget.isISA3_0()) {
367 } else {
372 }
373
374 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
383
384 // Handle constrained floating-point operations of scalar.
385 // TODO: Handle SPE specific operation.
391
396
397 if (!Subtarget.hasSPE()) {
400 }
401
402 if (Subtarget.hasVSX()) {
405 }
406
407 if (Subtarget.hasFSQRT()) {
410 }
411
412 if (Subtarget.hasFPRND()) {
417
422 }
423
424 // We don't support sin/cos/sqrt/fmod/pow
435
436 // MASS transformation for LLVM intrinsics with replicating fast-math flag
437 // to be consistent to PPCGenScalarMASSEntries pass
438 if (TM.getOptLevel() == CodeGenOptLevel::Aggressive) {
451 }
452
453 if (Subtarget.hasSPE()) {
456 } else {
457 setOperationAction(ISD::FMA , MVT::f64, Legal);
458 setOperationAction(ISD::FMA , MVT::f32, Legal);
461 }
462
463 if (Subtarget.hasSPE())
464 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
465
466 // If we're enabling GP optimizations, use hardware square root
467 if (!Subtarget.hasFSQRT() && !(Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
469
470 if (!Subtarget.hasFSQRT() &&
471 !(Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
473
474 if (Subtarget.hasFCPSGN()) {
477 } else {
480 }
481
482 if (Subtarget.hasFPRND()) {
487
492 }
493
494 // Prior to P10, PowerPC does not have BSWAP, but we can use vector BSWAP
495 // instruction xxbrd to speed up scalar BSWAP64.
496 if (Subtarget.isISA3_1()) {
499 } else {
502 ((Subtarget.hasP8Vector()) && isPPC64) ? Custom
503 : Expand);
504 }
505
506 // CTPOP or CTTZ were introduced in P8/P9 respectively
507 if (Subtarget.isISA3_0()) {
508 setOperationAction(ISD::CTTZ , MVT::i32 , Legal);
509 setOperationAction(ISD::CTTZ , MVT::i64 , Legal);
510 } else {
511 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
512 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
513 }
514
515 if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
518 } else {
521 }
522
523 // PowerPC does not have ROTR
526
527 if (!Subtarget.useCRBits()) {
528 // PowerPC does not have Select
533 }
534
535 // PowerPC wants to turn select_cc of FP into fsel when possible.
538
539 // PowerPC wants to optimize integer setcc a bit
540 if (!Subtarget.useCRBits())
542
543 if (Subtarget.hasFPU()) {
547
551 }
552
553 // PowerPC does not have BRCOND which requires SetCC
554 if (!Subtarget.useCRBits())
556
558
559 if (Subtarget.hasSPE()) {
560 // SPE has built-in conversions
567
568 // SPE supports signaling compare of f32/f64.
569 // But it doesn't comply IEEE-754 rules for comparing
570 // special values like NaNs, Infs.
579 } else {
580 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
583
584 // PowerPC does not have [U|S]INT_TO_FP
589 }
590
591 if (Subtarget.hasDirectMove() && isPPC64) {
596
605 } else {
610 }
611
612 // We cannot sextinreg(i1). Expand to shifts.
614
615 // Custom handling for PowerPC ucmp and scmp instructions
617 setOperationAction(ISD::UCMP, MVT::i64, isPPC64 ? Custom : Expand);
619 setOperationAction(ISD::ABDU, MVT::i64, isPPC64 ? Custom : Expand);
621 setOperationAction(ISD::SCMP, MVT::i64, isPPC64 ? Custom : Expand);
622
623 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
624 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
625 // support continuation, user-level threading, and etc.. As a result, no
626 // other SjLj exception interfaces are implemented and please don't build
627 // your own exception handling based on them.
628 // LLVM/Clang supports zero-cost DWARF exception handling.
631
632 // We want to legalize GlobalAddress and ConstantPool nodes into the
633 // appropriate instructions to materialize the address.
644
645 // TRAP is legal.
646 setOperationAction(ISD::TRAP, MVT::Other, Legal);
647
648 // TRAMPOLINE is custom lowered.
651
652 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
654
655 if (Subtarget.is64BitELFABI()) {
656 // VAARG always uses double-word chunks, so promote anything smaller.
658 AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
660 AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
662 AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
664 AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
666 } else if (Subtarget.is32BitELFABI()) {
667 // VAARG is custom lowered with the 32-bit SVR4 ABI.
670 } else
672
673 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
674 if (Subtarget.is32BitELFABI())
676 else
678
679 // Use the default implementation.
680 setOperationAction(ISD::VAEND , MVT::Other, Expand);
689
690 if (Subtarget.isISA3_0() && isPPC64) {
691 setOperationAction(ISD::VP_STORE, MVT::v16i1, Custom);
692 setOperationAction(ISD::VP_STORE, MVT::v8i1, Custom);
693 setOperationAction(ISD::VP_STORE, MVT::v4i1, Custom);
694 setOperationAction(ISD::VP_STORE, MVT::v2i1, Custom);
695 setOperationAction(ISD::VP_LOAD, MVT::v16i1, Custom);
696 setOperationAction(ISD::VP_LOAD, MVT::v8i1, Custom);
697 setOperationAction(ISD::VP_LOAD, MVT::v4i1, Custom);
698 setOperationAction(ISD::VP_LOAD, MVT::v2i1, Custom);
699 }
700
701 // We want to custom lower some of our intrinsics.
707
708 // To handle counter-based loop conditions.
711
716
717 // Comparisons that require checking two conditions.
718 if (Subtarget.hasSPE()) {
723 }
736
739
740 if (Subtarget.has64BitSupport()) {
741 // They also have instructions for converting between i64 and fp.
750 // This is just the low 32 bits of a (signed) fp->i64 conversion.
751 // We cannot do this with Promote because i64 is not a legal type.
754
755 if (Subtarget.hasLFIWAX() || isPPC64) {
758 }
759 } else {
760 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
761 if (Subtarget.hasSPE()) {
764 } else {
767 }
768 }
769
770 // With the instructions enabled under FPCVT, we can do everything.
771 if (Subtarget.hasFPCVT()) {
772 if (Subtarget.has64BitSupport()) {
781 }
782
791 }
792
793 if (Subtarget.use64BitRegs()) {
794 // 64-bit PowerPC implementations can support i64 types directly
795 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
796 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
798 // 64-bit PowerPC wants to expand i128 shifts itself.
802 } else {
803 // 32-bit PowerPC wants to expand i64 shifts itself.
807 }
808
809 // PowerPC has better expansions for funnel shifts than the generic
810 // TargetLowering::expandFunnelShift.
811 if (Subtarget.has64BitSupport()) {
814 }
817
818 if (Subtarget.hasVSX()) {
829 }
830
831 if (Subtarget.hasAltivec()) {
832 for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
839 }
840 // First set operation action for all vector types to expand. Then we
841 // will selectively turn on ones that can be effectively codegen'd.
843 // add/sub are legal for all supported vector VT's.
846
847 // For v2i64, these are only valid with P8Vector. This is corrected after
848 // the loop.
849 if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
854 }
855 else {
860 }
861
862 if (Subtarget.hasVSX()) {
868 }
869
870 // Vector instructions introduced in P8
871 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
874 }
875 else {
878 }
879
880 // Vector instructions introduced in P9
881 if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
883 else
885
886 // We promote all shuffles to v16i8.
888 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
889
890 // We promote all non-typed operations to v4i32.
892 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
894 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
896 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
898 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
900 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
903 AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
905 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
906
907 // No other operations are legal.
946
947 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
948 setTruncStoreAction(VT, InnerVT, Expand);
951 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
952 }
953 }
955 if (!Subtarget.hasP8Vector()) {
956 setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
957 setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
958 setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
959 setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
960 }
961
962 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
963 // with merges, splats, etc.
965
966 // Vector truncates to sub-word integer that fit in an Altivec/VSX register
967 // are cheap, so handle them before they get expanded to scalar.
973
974 setOperationAction(ISD::AND , MVT::v4i32, Legal);
975 setOperationAction(ISD::OR , MVT::v4i32, Legal);
976 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
977 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
979 Subtarget.useCRBits() ? Legal : Expand);
980 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
990 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
993
994 // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
995 setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
996 // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
997 if (Subtarget.hasAltivec())
998 for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
1000 // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
1001 if (Subtarget.hasP8Altivec())
1002 setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
1003
1004 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
1005 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
1006 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
1007 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
1008
1009 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
1010 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1011
1012 if (Subtarget.hasVSX()) {
1013 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1014 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1016 }
1017
1018 if (Subtarget.hasP8Altivec())
1019 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1020 else
1021 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
1022
1023 if (Subtarget.isISA3_1()) {
1024 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
1025 setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
1026 setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
1027 setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
1028 setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
1029 setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
1030 setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
1031 setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
1032 setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
1033 setOperationAction(ISD::UREM, MVT::v2i64, Legal);
1034 setOperationAction(ISD::SREM, MVT::v2i64, Legal);
1035 setOperationAction(ISD::UREM, MVT::v4i32, Legal);
1036 setOperationAction(ISD::SREM, MVT::v4i32, Legal);
1037 setOperationAction(ISD::UREM, MVT::v1i128, Legal);
1038 setOperationAction(ISD::SREM, MVT::v1i128, Legal);
1039 setOperationAction(ISD::UDIV, MVT::v1i128, Legal);
1040 setOperationAction(ISD::SDIV, MVT::v1i128, Legal);
1041 setOperationAction(ISD::ROTL, MVT::v1i128, Legal);
1042 }
1043
1044 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
1045 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
1046
1049 // LE is P8+/64-bit so direct moves are supported and these operations
1050 // are legal. The custom transformation requires 64-bit since we need a
1051 // pair of stores that will cover a 128-bit load for P10.
1052 if (EnableP10StoreForward && isPPC64 && !Subtarget.isLittleEndian()) {
1056 }
1057
1062
1063 // Altivec does not contain unordered floating-point compare instructions
1064 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
1065 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
1066 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
1067 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
1068
1069 if (Subtarget.hasVSX()) {
1072 if (Subtarget.hasP8Vector()) {
1075 }
1076 if (Subtarget.hasDirectMove() && isPPC64) {
1085 }
1087
1088 // The nearbyint variants are not allowed to raise the inexact exception
1089 // so we can only code-gen them with fpexcept.ignore.
1094
1095 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1096 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1097 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1098 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1099 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
1102
1103 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1107
1108 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1110
1111 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
1112 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
1113
1114 // Share the Altivec comparison restrictions.
1115 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
1116 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
1117 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
1118 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
1119
1120 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1121 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
1122
1124
1125 if (Subtarget.hasP8Vector())
1126 addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
1127
1128 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
1129
1130 addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
1131 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
1132 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
1133
1134 if (Subtarget.hasP8Altivec()) {
1135 setOperationAction(ISD::SHL, MVT::v2i64, Legal);
1136 setOperationAction(ISD::SRA, MVT::v2i64, Legal);
1137 setOperationAction(ISD::SRL, MVT::v2i64, Legal);
1138
1139 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1140 // SRL, but not for SRA because of the instructions available:
1141 // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
1142 // doing
1143 setOperationAction(ISD::SHL, MVT::v1i128, Expand);
1144 setOperationAction(ISD::SRL, MVT::v1i128, Expand);
1145 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1146
1147 setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
1148 }
1149 else {
1150 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
1151 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
1152 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
1153
1154 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
1155
1156 // VSX v2i64 only supports non-arithmetic operations.
1157 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
1158 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
1159 }
1160
1161 if (Subtarget.isISA3_1())
1162 setOperationAction(ISD::SETCC, MVT::v1i128, Legal);
1163 else
1164 setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
1165
1166 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
1167 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
1169 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
1170
1172
1181
1182 // Custom handling for partial vectors of integers converted to
1183 // floating point. We already have optimal handling for v2i32 through
1184 // the DAG combine, so those aren't necessary.
1201
1202 setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1203 setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1204 setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1205 setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1208
1211
1212 // Handle constrained floating-point operations of vector.
1213 // The predictor is `hasVSX` because altivec instruction has
1214 // no exception but VSX vector instruction has.
1228
1242
1243 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1244 addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1245
1246 for (MVT FPT : MVT::fp_valuetypes())
1247 setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1248
1249 // Expand the SELECT to SELECT_CC
1251
1252 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1253 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1254
1255 // No implementation for these ops for PowerPC.
1257 setOperationAction(ISD::FSIN, MVT::f128, Expand);
1258 setOperationAction(ISD::FCOS, MVT::f128, Expand);
1259 setOperationAction(ISD::FPOW, MVT::f128, Expand);
1262 }
1263
1264 if (Subtarget.hasP8Altivec()) {
1265 addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1266 addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1267 }
1268
1269 if (Subtarget.hasP9Vector()) {
1272
1273 // Test data class instructions store results in CR bits.
1274 if (Subtarget.useCRBits()) {
1279 }
1280
1281 // 128 bit shifts can be accomplished via 3 instructions for SHL and
1282 // SRL, but not for SRA because of the instructions available:
1283 // VS{RL} and VS{RL}O.
1284 setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1285 setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1286 setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1287
1288 setOperationAction(ISD::FADD, MVT::f128, Legal);
1289 setOperationAction(ISD::FSUB, MVT::f128, Legal);
1290 setOperationAction(ISD::FDIV, MVT::f128, Legal);
1291 setOperationAction(ISD::FMUL, MVT::f128, Legal);
1293
1294 setOperationAction(ISD::FMA, MVT::f128, Legal);
1301
1303 setOperationAction(ISD::FRINT, MVT::f128, Legal);
1305 setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1308
1312
1313 // Handle constrained floating-point operations of fp128
1330 setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1331 setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1332 setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1333 setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1334 } else if (Subtarget.hasVSX()) {
1337
1338 AddPromotedToType(ISD::LOAD, MVT::f128, MVT::v4i32);
1339 AddPromotedToType(ISD::STORE, MVT::f128, MVT::v4i32);
1340
1341 // Set FADD/FSUB as libcall to avoid the legalizer to expand the
1342 // fp_to_uint and int_to_fp.
1345
1346 setOperationAction(ISD::FMUL, MVT::f128, Expand);
1347 setOperationAction(ISD::FDIV, MVT::f128, Expand);
1348 setOperationAction(ISD::FNEG, MVT::f128, Expand);
1349 setOperationAction(ISD::FABS, MVT::f128, Expand);
1351 setOperationAction(ISD::FMA, MVT::f128, Expand);
1353
1354 // Expand the fp_extend if the target type is fp128.
1357
1358 // Expand the fp_round if the source type is fp128.
1359 for (MVT VT : {MVT::f32, MVT::f64}) {
1362 }
1363
1368
1369 // Lower following f128 select_cc pattern:
1370 // select_cc x, y, tv, fv, cc -> select_cc (setcc x, y, cc), 0, tv, fv, NE
1372
1373 // We need to handle f128 SELECT_CC with integer result type.
1375 setOperationAction(ISD::SELECT_CC, MVT::i64, isPPC64 ? Custom : Expand);
1376 }
1377
1378 if (Subtarget.hasP9Altivec()) {
1379 if (Subtarget.isISA3_1()) {
1384 } else {
1387 }
1395
1396 setOperationAction(ISD::ABDU, MVT::v16i8, Legal);
1397 setOperationAction(ISD::ABDU, MVT::v8i16, Legal);
1398 setOperationAction(ISD::ABDU, MVT::v4i32, Legal);
1399 setOperationAction(ISD::ABDS, MVT::v4i32, Legal);
1400 }
1401
1402 if (Subtarget.hasP10Vector()) {
1404 }
1405
1408 Legal);
1410 Legal);
1412 Legal);
1414 Legal);
1415 }
1416
1417 if (Subtarget.pairedVectorMemops()) {
1418 addRegisterClass(MVT::v256i1, &PPC::VSRpRCRegClass);
1419 setOperationAction(ISD::LOAD, MVT::v256i1, Custom);
1420 setOperationAction(ISD::STORE, MVT::v256i1, Custom);
1421 }
1422 if (Subtarget.hasMMA()) {
1423 if (Subtarget.isISAFuture()) {
1424 addRegisterClass(MVT::v512i1, &PPC::WACCRCRegClass);
1425 addRegisterClass(MVT::v1024i1, &PPC::DMRRCRegClass);
1426 addRegisterClass(MVT::v2048i1, &PPC::DMRpRCRegClass);
1427 setOperationAction(ISD::LOAD, MVT::v1024i1, Custom);
1428 setOperationAction(ISD::STORE, MVT::v1024i1, Custom);
1429 setOperationAction(ISD::LOAD, MVT::v2048i1, Custom);
1430 setOperationAction(ISD::STORE, MVT::v2048i1, Custom);
1431 } else {
1432 addRegisterClass(MVT::v512i1, &PPC::UACCRCRegClass);
1433 }
1434 setOperationAction(ISD::LOAD, MVT::v512i1, Custom);
1435 setOperationAction(ISD::STORE, MVT::v512i1, Custom);
1437 }
1438
1439 if (Subtarget.has64BitSupport())
1441
1442 if (Subtarget.isISA3_1())
1443 setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1444
1445 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1446
1447 if (!isPPC64) {
1450 }
1451
1456 }
1457
1459
1460 if (Subtarget.hasAltivec()) {
1461 // Altivec instructions set fields to all zeros or all ones.
1463 }
1464
1467 else if (isPPC64)
1469 else
1471
1472 setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1473
1474 // We have target-specific dag combine patterns for the following nodes:
1478 if (Subtarget.hasFPCVT())
1481 if (Subtarget.useCRBits())
1485
1487
1489
1490 if (Subtarget.useCRBits()) {
1492 }
1493
1494 if (Subtarget.hasP8Vector())
1496
1497 // With 32 condition bits, we don't need to sink (and duplicate) compares
1498 // aggressively in CodeGenPrep.
1499 if (Subtarget.useCRBits()) {
1501 }
1502
1503 // TODO: The default entry number is set to 64. This stops most jump table
1504 // generation on PPC. But it is good for current PPC HWs because the indirect
1505 // branch instruction mtctr to the jump table may lead to bad branch predict.
1506 // Re-evaluate this value on future HWs that can do better with mtctr.
1508
1509 // The default minimum of largest number in a BitTest cluster is 3.
1511
1513 setMinCmpXchgSizeInBits(Subtarget.hasPartwordAtomics() ? 8 : 32);
1514
1515 auto CPUDirective = Subtarget.getCPUDirective();
1516 switch (CPUDirective) {
1517 default: break;
1518 case PPC::DIR_970:
1519 case PPC::DIR_A2:
1520 case PPC::DIR_E500:
1521 case PPC::DIR_E500mc:
1522 case PPC::DIR_E5500:
1523 case PPC::DIR_PWR4:
1524 case PPC::DIR_PWR5:
1525 case PPC::DIR_PWR5X:
1526 case PPC::DIR_PWR6:
1527 case PPC::DIR_PWR6X:
1528 case PPC::DIR_PWR7:
1529 case PPC::DIR_PWR8:
1530 case PPC::DIR_PWR9:
1531 case PPC::DIR_PWR10:
1532 case PPC::DIR_PWR11:
1536 break;
1537 }
1538
1539 if (Subtarget.enableMachineScheduler())
1541 else
1543
1545
1546 // The Freescale cores do better with aggressive inlining of memcpy and
1547 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1548 if (CPUDirective == PPC::DIR_E500mc || CPUDirective == PPC::DIR_E5500) {
1549 MaxStoresPerMemset = 32;
1551 MaxStoresPerMemcpy = 32;
1555 } else if (CPUDirective == PPC::DIR_A2) {
1556 // The A2 also benefits from (very) aggressive inlining of memcpy and
1557 // friends. The overhead of a the function call, even when warm, can be
1558 // over one hundred cycles.
1559 MaxStoresPerMemset = 128;
1560 MaxStoresPerMemcpy = 128;
1561 MaxStoresPerMemmove = 128;
1562 MaxLoadsPerMemcmp = 128;
1563 } else {
1566 }
1567
1568 // Enable generation of STXVP instructions by default for mcpu=future.
1569 if (CPUDirective == PPC::DIR_PWR_FUTURE &&
1570 EnableAutoPairedVecSt.getNumOccurrences() == 0)
1571 EnableAutoPairedVecSt = true;
1572
1573 IsStrictFPEnabled = true;
1574
1575 // Let the subtarget (CPU) decide if a predictable select is more expensive
1576 // than the corresponding branch. This information is used in CGP to decide
1577 // when to convert selects into branches.
1578 PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1579
1581}
1582
1583// *********************************** NOTE ************************************
1584// For selecting load and store instructions, the addressing modes are defined
1585// as ComplexPatterns in PPCInstrInfo.td, which are then utilized in the TD
1586// patterns to match the load the store instructions.
1587//
1588// The TD definitions for the addressing modes correspond to their respective
1589// Select<AddrMode>Form() function in PPCISelDAGToDAG.cpp. These functions rely
1590// on SelectOptimalAddrMode(), which calls computeMOFlags() to compute the
1591// address mode flags of a particular node. Afterwards, the computed address
1592// flags are passed into getAddrModeForFlags() in order to retrieve the optimal
1593// addressing mode. SelectOptimalAddrMode() then sets the Base and Displacement
1594// accordingly, based on the preferred addressing mode.
1595//
1596// Within PPCISelLowering.h, there are two enums: MemOpFlags and AddrMode.
1597// MemOpFlags contains all the possible flags that can be used to compute the
1598// optimal addressing mode for load and store instructions.
1599// AddrMode contains all the possible load and store addressing modes available
1600// on Power (such as DForm, DSForm, DQForm, XForm, etc.)
1601//
1602// When adding new load and store instructions, it is possible that new address
1603// flags may need to be added into MemOpFlags, and a new addressing mode will
1604// need to be added to AddrMode. An entry of the new addressing mode (consisting
1605// of the minimal and main distinguishing address flags for the new load/store
1606// instructions) will need to be added into initializeAddrModeMap() below.
1607// Finally, when adding new addressing modes, the getAddrModeForFlags() will
1608// need to be updated to account for selecting the optimal addressing mode.
1609// *****************************************************************************
1610/// Initialize the map that relates the different addressing modes of the load
1611/// and store instructions to a set of flags. This ensures the load/store
1612/// instruction is correctly matched during instruction selection.
1613void PPCTargetLowering::initializeAddrModeMap() {
1614 AddrModesMap[PPC::AM_DForm] = {
1615 // LWZ, STW
1620 // LBZ, LHZ, STB, STH
1625 // LHA
1630 // LFS, LFD, STFS, STFD
1635 };
1636 AddrModesMap[PPC::AM_DSForm] = {
1637 // LWA
1641 // LD, STD
1645 // DFLOADf32, DFLOADf64, DSTOREf32, DSTOREf64
1649 };
1650 AddrModesMap[PPC::AM_DQForm] = {
1651 // LXV, STXV
1655 };
1656 AddrModesMap[PPC::AM_PrefixDForm] = {PPC::MOF_RPlusSImm34 |
1658 // TODO: Add mapping for quadword load/store.
1659}
1660
1661/// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1662/// the desired ByVal argument alignment.
1663static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1664 if (MaxAlign == MaxMaxAlign)
1665 return;
1666 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1667 if (MaxMaxAlign >= 32 &&
1668 VTy->getPrimitiveSizeInBits().getFixedValue() >= 256)
1669 MaxAlign = Align(32);
1670 else if (VTy->getPrimitiveSizeInBits().getFixedValue() >= 128 &&
1671 MaxAlign < 16)
1672 MaxAlign = Align(16);
1673 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1674 Align EltAlign;
1675 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1676 if (EltAlign > MaxAlign)
1677 MaxAlign = EltAlign;
1678 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1679 for (auto *EltTy : STy->elements()) {
1680 Align EltAlign;
1681 getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1682 if (EltAlign > MaxAlign)
1683 MaxAlign = EltAlign;
1684 if (MaxAlign == MaxMaxAlign)
1685 break;
1686 }
1687 }
1688}
1689
1690/// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1691/// function arguments in the caller parameter area.
1693 const DataLayout &DL) const {
1694 // 16byte and wider vectors are passed on 16byte boundary.
1695 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1696 Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1697 if (Subtarget.hasAltivec())
1698 getMaxByValAlign(Ty, Alignment, Align(16));
1699 return Alignment;
1700}
1701
1703 return Subtarget.useSoftFloat();
1704}
1705
1707 return Subtarget.hasSPE();
1708}
1709
1711 return VT.isScalarInteger();
1712}
1713
1715 Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const {
1716 if (!Subtarget.isPPC64() || !Subtarget.hasVSX())
1717 return false;
1718
1719 if (auto *VTy = dyn_cast<VectorType>(VectorTy)) {
1720 if (VTy->getScalarType()->isIntegerTy()) {
1721 // ElemSizeInBits 8/16 can fit in immediate field, not needed here.
1722 if (ElemSizeInBits == 32) {
1723 Index = Subtarget.isLittleEndian() ? 2 : 1;
1724 return true;
1725 }
1726 if (ElemSizeInBits == 64) {
1727 Index = Subtarget.isLittleEndian() ? 1 : 0;
1728 return true;
1729 }
1730 }
1731 }
1732 return false;
1733}
1734
1736 EVT VT) const {
1737 if (!VT.isVector())
1738 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1739
1741}
1742
1744 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1745 return true;
1746}
1747
1748//===----------------------------------------------------------------------===//
1749// Node matching predicates, for use by the tblgen matching code.
1750//===----------------------------------------------------------------------===//
1751
1752/// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1755 return CFP->getValueAPF().isZero();
1756 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1757 // Maybe this has already been legalized into the constant pool?
1758 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1759 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1760 return CFP->getValueAPF().isZero();
1761 }
1762 return false;
1763}
1764
1765/// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
1766/// true if Op is undef or if it matches the specified value.
1767static bool isConstantOrUndef(int Op, int Val) {
1768 return Op < 0 || Op == Val;
1769}
1770
1771/// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1772/// VPKUHUM instruction.
1773/// The ShuffleKind distinguishes between big-endian operations with
1774/// two different inputs (0), either-endian operations with two identical
1775/// inputs (1), and little-endian operations with two different inputs (2).
1776/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1778 SelectionDAG &DAG) {
1779 bool IsLE = DAG.getDataLayout().isLittleEndian();
1780 if (ShuffleKind == 0) {
1781 if (IsLE)
1782 return false;
1783 for (unsigned i = 0; i != 16; ++i)
1784 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1785 return false;
1786 } else if (ShuffleKind == 2) {
1787 if (!IsLE)
1788 return false;
1789 for (unsigned i = 0; i != 16; ++i)
1790 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1791 return false;
1792 } else if (ShuffleKind == 1) {
1793 unsigned j = IsLE ? 0 : 1;
1794 for (unsigned i = 0; i != 8; ++i)
1795 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
1796 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
1797 return false;
1798 }
1799 return true;
1800}
1801
1802/// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1803/// VPKUWUM instruction.
1804/// The ShuffleKind distinguishes between big-endian operations with
1805/// two different inputs (0), either-endian operations with two identical
1806/// inputs (1), and little-endian operations with two different inputs (2).
1807/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1809 SelectionDAG &DAG) {
1810 bool IsLE = DAG.getDataLayout().isLittleEndian();
1811 if (ShuffleKind == 0) {
1812 if (IsLE)
1813 return false;
1814 for (unsigned i = 0; i != 16; i += 2)
1815 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
1816 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
1817 return false;
1818 } else if (ShuffleKind == 2) {
1819 if (!IsLE)
1820 return false;
1821 for (unsigned i = 0; i != 16; i += 2)
1822 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1823 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
1824 return false;
1825 } else if (ShuffleKind == 1) {
1826 unsigned j = IsLE ? 0 : 2;
1827 for (unsigned i = 0; i != 8; i += 2)
1828 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1829 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1830 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1831 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
1832 return false;
1833 }
1834 return true;
1835}
1836
1837/// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1838/// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1839/// current subtarget.
1840///
1841/// The ShuffleKind distinguishes between big-endian operations with
1842/// two different inputs (0), either-endian operations with two identical
1843/// inputs (1), and little-endian operations with two different inputs (2).
1844/// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1846 SelectionDAG &DAG) {
1847 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
1848 if (!Subtarget.hasP8Vector())
1849 return false;
1850
1851 bool IsLE = DAG.getDataLayout().isLittleEndian();
1852 if (ShuffleKind == 0) {
1853 if (IsLE)
1854 return false;
1855 for (unsigned i = 0; i != 16; i += 4)
1856 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) ||
1857 !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) ||
1858 !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) ||
1859 !isConstantOrUndef(N->getMaskElt(i+3), i*2+7))
1860 return false;
1861 } else if (ShuffleKind == 2) {
1862 if (!IsLE)
1863 return false;
1864 for (unsigned i = 0; i != 16; i += 4)
1865 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
1866 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) ||
1867 !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) ||
1868 !isConstantOrUndef(N->getMaskElt(i+3), i*2+3))
1869 return false;
1870 } else if (ShuffleKind == 1) {
1871 unsigned j = IsLE ? 0 : 4;
1872 for (unsigned i = 0; i != 8; i += 4)
1873 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
1874 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
1875 !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) ||
1876 !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) ||
1877 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
1878 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) ||
1879 !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1880 !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1881 return false;
1882 }
1883 return true;
1884}
1885
1886/// isVMerge - Common function, used to match vmrg* shuffles.
1887///
1888static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1889 unsigned LHSStart, unsigned RHSStart) {
1890 if (N->getValueType(0) != MVT::v16i8)
1891 return false;
1892 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1893 "Unsupported merge size!");
1894
1895 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
1896 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
1897 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1898 LHSStart+j+i*UnitSize) ||
1899 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1900 RHSStart+j+i*UnitSize))
1901 return false;
1902 }
1903 return true;
1904}
1905
1906/// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1907/// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1908/// The ShuffleKind distinguishes between big-endian merges with two
1909/// different inputs (0), either-endian merges with two identical inputs (1),
1910/// and little-endian merges with two different inputs (2). For the latter,
1911/// the input operands are swapped (see PPCInstrAltivec.td).
1913 unsigned ShuffleKind, SelectionDAG &DAG) {
1914 if (DAG.getDataLayout().isLittleEndian()) {
1915 if (ShuffleKind == 1) // unary
1916 return isVMerge(N, UnitSize, 0, 0);
1917 else if (ShuffleKind == 2) // swapped
1918 return isVMerge(N, UnitSize, 0, 16);
1919 else
1920 return false;
1921 } else {
1922 if (ShuffleKind == 1) // unary
1923 return isVMerge(N, UnitSize, 8, 8);
1924 else if (ShuffleKind == 0) // normal
1925 return isVMerge(N, UnitSize, 8, 24);
1926 else
1927 return false;
1928 }
1929}
1930
1931/// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1932/// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1933/// The ShuffleKind distinguishes between big-endian merges with two
1934/// different inputs (0), either-endian merges with two identical inputs (1),
1935/// and little-endian merges with two different inputs (2). For the latter,
1936/// the input operands are swapped (see PPCInstrAltivec.td).
1938 unsigned ShuffleKind, SelectionDAG &DAG) {
1939 if (DAG.getDataLayout().isLittleEndian()) {
1940 if (ShuffleKind == 1) // unary
1941 return isVMerge(N, UnitSize, 8, 8);
1942 else if (ShuffleKind == 2) // swapped
1943 return isVMerge(N, UnitSize, 8, 24);
1944 else
1945 return false;
1946 } else {
1947 if (ShuffleKind == 1) // unary
1948 return isVMerge(N, UnitSize, 0, 0);
1949 else if (ShuffleKind == 0) // normal
1950 return isVMerge(N, UnitSize, 0, 16);
1951 else
1952 return false;
1953 }
1954}
1955
1956/**
1957 * Common function used to match vmrgew and vmrgow shuffles
1958 *
1959 * The indexOffset determines whether to look for even or odd words in
1960 * the shuffle mask. This is based on the of the endianness of the target
1961 * machine.
1962 * - Little Endian:
1963 * - Use offset of 0 to check for odd elements
1964 * - Use offset of 4 to check for even elements
1965 * - Big Endian:
1966 * - Use offset of 0 to check for even elements
1967 * - Use offset of 4 to check for odd elements
1968 * A detailed description of the vector element ordering for little endian and
1969 * big endian can be found at
1970 * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1971 * Targeting your applications - what little endian and big endian IBM XL C/C++
1972 * compiler differences mean to you
1973 *
1974 * The mask to the shuffle vector instruction specifies the indices of the
1975 * elements from the two input vectors to place in the result. The elements are
1976 * numbered in array-access order, starting with the first vector. These vectors
1977 * are always of type v16i8, thus each vector will contain 16 elements of size
1978 * 8. More info on the shuffle vector can be found in the
1979 * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1980 * Language Reference.
1981 *
1982 * The RHSStartValue indicates whether the same input vectors are used (unary)
1983 * or two different input vectors are used, based on the following:
1984 * - If the instruction uses the same vector for both inputs, the range of the
1985 * indices will be 0 to 15. In this case, the RHSStart value passed should
1986 * be 0.
1987 * - If the instruction has two different vectors then the range of the
1988 * indices will be 0 to 31. In this case, the RHSStart value passed should
1989 * be 16 (indices 0-15 specify elements in the first vector while indices 16
1990 * to 31 specify elements in the second vector).
1991 *
1992 * \param[in] N The shuffle vector SD Node to analyze
1993 * \param[in] IndexOffset Specifies whether to look for even or odd elements
1994 * \param[in] RHSStartValue Specifies the starting index for the righthand input
1995 * vector to the shuffle_vector instruction
1996 * \return true iff this shuffle vector represents an even or odd word merge
1997 */
1998static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1999 unsigned RHSStartValue) {
2000 if (N->getValueType(0) != MVT::v16i8)
2001 return false;
2002
2003 for (unsigned i = 0; i < 2; ++i)
2004 for (unsigned j = 0; j < 4; ++j)
2005 if (!isConstantOrUndef(N->getMaskElt(i*4+j),
2006 i*RHSStartValue+j+IndexOffset) ||
2007 !isConstantOrUndef(N->getMaskElt(i*4+j+8),
2008 i*RHSStartValue+j+IndexOffset+8))
2009 return false;
2010 return true;
2011}
2012
2013/**
2014 * Determine if the specified shuffle mask is suitable for the vmrgew or
2015 * vmrgow instructions.
2016 *
2017 * \param[in] N The shuffle vector SD Node to analyze
2018 * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
2019 * \param[in] ShuffleKind Identify the type of merge:
2020 * - 0 = big-endian merge with two different inputs;
2021 * - 1 = either-endian merge with two identical inputs;
2022 * - 2 = little-endian merge with two different inputs (inputs are swapped for
2023 * little-endian merges).
2024 * \param[in] DAG The current SelectionDAG
2025 * \return true iff this shuffle mask
2026 */
2028 unsigned ShuffleKind, SelectionDAG &DAG) {
2029 if (DAG.getDataLayout().isLittleEndian()) {
2030 unsigned indexOffset = CheckEven ? 4 : 0;
2031 if (ShuffleKind == 1) // Unary
2032 return isVMerge(N, indexOffset, 0);
2033 else if (ShuffleKind == 2) // swapped
2034 return isVMerge(N, indexOffset, 16);
2035 else
2036 return false;
2037 }
2038 else {
2039 unsigned indexOffset = CheckEven ? 0 : 4;
2040 if (ShuffleKind == 1) // Unary
2041 return isVMerge(N, indexOffset, 0);
2042 else if (ShuffleKind == 0) // Normal
2043 return isVMerge(N, indexOffset, 16);
2044 else
2045 return false;
2046 }
2047 return false;
2048}
2049
2050/// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
2051/// amount, otherwise return -1.
2052/// The ShuffleKind distinguishes between big-endian operations with two
2053/// different inputs (0), either-endian operations with two identical inputs
2054/// (1), and little-endian operations with two different inputs (2). For the
2055/// latter, the input operands are swapped (see PPCInstrAltivec.td).
2056int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
2057 SelectionDAG &DAG) {
2058 if (N->getValueType(0) != MVT::v16i8)
2059 return -1;
2060
2062
2063 // Find the first non-undef value in the shuffle mask.
2064 unsigned i;
2065 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
2066 /*search*/;
2067
2068 if (i == 16) return -1; // all undef.
2069
2070 // Otherwise, check to see if the rest of the elements are consecutively
2071 // numbered from this value.
2072 unsigned ShiftAmt = SVOp->getMaskElt(i);
2073 if (ShiftAmt < i) return -1;
2074
2075 ShiftAmt -= i;
2076 bool isLE = DAG.getDataLayout().isLittleEndian();
2077
2078 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
2079 // Check the rest of the elements to see if they are consecutive.
2080 for (++i; i != 16; ++i)
2081 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2082 return -1;
2083 } else if (ShuffleKind == 1) {
2084 // Check the rest of the elements to see if they are consecutive.
2085 for (++i; i != 16; ++i)
2086 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
2087 return -1;
2088 } else
2089 return -1;
2090
2091 if (isLE)
2092 ShiftAmt = 16 - ShiftAmt;
2093
2094 return ShiftAmt;
2095}
2096
2097/// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
2098/// specifies a splat of a single element that is suitable for input to
2099/// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
2101 EVT VT = N->getValueType(0);
2102 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2103 return EltSize == 8 && N->getMaskElt(0) == N->getMaskElt(1);
2104
2105 assert(VT == MVT::v16i8 && isPowerOf2_32(EltSize) &&
2106 EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
2107
2108 // The consecutive indices need to specify an element, not part of two
2109 // different elements. So abandon ship early if this isn't the case.
2110 if (N->getMaskElt(0) % EltSize != 0)
2111 return false;
2112
2113 // This is a splat operation if each element of the permute is the same, and
2114 // if the value doesn't reference the second vector.
2115 unsigned ElementBase = N->getMaskElt(0);
2116
2117 // FIXME: Handle UNDEF elements too!
2118 if (ElementBase >= 16)
2119 return false;
2120
2121 // Check that the indices are consecutive, in the case of a multi-byte element
2122 // splatted with a v16i8 mask.
2123 for (unsigned i = 1; i != EltSize; ++i)
2124 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
2125 return false;
2126
2127 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
2128 // An UNDEF element is a sequence of UNDEF bytes.
2129 if (N->getMaskElt(i) < 0) {
2130 for (unsigned j = 1; j != EltSize; ++j)
2131 if (N->getMaskElt(i + j) >= 0)
2132 return false;
2133 } else
2134 for (unsigned j = 0; j != EltSize; ++j)
2135 if (N->getMaskElt(i + j) != N->getMaskElt(j))
2136 return false;
2137 }
2138 return true;
2139}
2140
2141/// Check that the mask is shuffling N byte elements. Within each N byte
2142/// element of the mask, the indices could be either in increasing or
2143/// decreasing order as long as they are consecutive.
2144/// \param[in] N the shuffle vector SD Node to analyze
2145/// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
2146/// Word/DoubleWord/QuadWord).
2147/// \param[in] StepLen the delta indices number among the N byte element, if
2148/// the mask is in increasing/decreasing order then it is 1/-1.
2149/// \return true iff the mask is shuffling N byte elements.
2150static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
2151 int StepLen) {
2152 assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
2153 "Unexpected element width.");
2154 assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
2155
2156 unsigned NumOfElem = 16 / Width;
2157 unsigned MaskVal[16]; // Width is never greater than 16
2158 for (unsigned i = 0; i < NumOfElem; ++i) {
2159 MaskVal[0] = N->getMaskElt(i * Width);
2160 if ((StepLen == 1) && (MaskVal[0] % Width)) {
2161 return false;
2162 } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
2163 return false;
2164 }
2165
2166 for (unsigned int j = 1; j < Width; ++j) {
2167 MaskVal[j] = N->getMaskElt(i * Width + j);
2168 if (MaskVal[j] != MaskVal[j-1] + StepLen) {
2169 return false;
2170 }
2171 }
2172 }
2173
2174 return true;
2175}
2176
2177bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2178 unsigned &InsertAtByte, bool &Swap, bool IsLE) {
2179 if (!isNByteElemShuffleMask(N, 4, 1))
2180 return false;
2181
2182 // Now we look at mask elements 0,4,8,12
2183 unsigned M0 = N->getMaskElt(0) / 4;
2184 unsigned M1 = N->getMaskElt(4) / 4;
2185 unsigned M2 = N->getMaskElt(8) / 4;
2186 unsigned M3 = N->getMaskElt(12) / 4;
2187 unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
2188 unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
2189
2190 // Below, let H and L be arbitrary elements of the shuffle mask
2191 // where H is in the range [4,7] and L is in the range [0,3].
2192 // H, 1, 2, 3 or L, 5, 6, 7
2193 if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
2194 (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
2195 ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
2196 InsertAtByte = IsLE ? 12 : 0;
2197 Swap = M0 < 4;
2198 return true;
2199 }
2200 // 0, H, 2, 3 or 4, L, 6, 7
2201 if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
2202 (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
2203 ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
2204 InsertAtByte = IsLE ? 8 : 4;
2205 Swap = M1 < 4;
2206 return true;
2207 }
2208 // 0, 1, H, 3 or 4, 5, L, 7
2209 if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
2210 (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
2211 ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
2212 InsertAtByte = IsLE ? 4 : 8;
2213 Swap = M2 < 4;
2214 return true;
2215 }
2216 // 0, 1, 2, H or 4, 5, 6, L
2217 if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
2218 (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
2219 ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
2220 InsertAtByte = IsLE ? 0 : 12;
2221 Swap = M3 < 4;
2222 return true;
2223 }
2224
2225 // If both vector operands for the shuffle are the same vector, the mask will
2226 // contain only elements from the first one and the second one will be undef.
2227 if (N->getOperand(1).isUndef()) {
2228 ShiftElts = 0;
2229 Swap = true;
2230 unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
2231 if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
2232 InsertAtByte = IsLE ? 12 : 0;
2233 return true;
2234 }
2235 if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
2236 InsertAtByte = IsLE ? 8 : 4;
2237 return true;
2238 }
2239 if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
2240 InsertAtByte = IsLE ? 4 : 8;
2241 return true;
2242 }
2243 if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
2244 InsertAtByte = IsLE ? 0 : 12;
2245 return true;
2246 }
2247 }
2248
2249 return false;
2250}
2251
2253 bool &Swap, bool IsLE) {
2254 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2255 // Ensure each byte index of the word is consecutive.
2256 if (!isNByteElemShuffleMask(N, 4, 1))
2257 return false;
2258
2259 // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2260 unsigned M0 = N->getMaskElt(0) / 4;
2261 unsigned M1 = N->getMaskElt(4) / 4;
2262 unsigned M2 = N->getMaskElt(8) / 4;
2263 unsigned M3 = N->getMaskElt(12) / 4;
2264
2265 // If both vector operands for the shuffle are the same vector, the mask will
2266 // contain only elements from the first one and the second one will be undef.
2267 if (N->getOperand(1).isUndef()) {
2268 assert(M0 < 4 && "Indexing into an undef vector?");
2269 if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2270 return false;
2271
2272 ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2273 Swap = false;
2274 return true;
2275 }
2276
2277 // Ensure each word index of the ShuffleVector Mask is consecutive.
2278 if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2279 return false;
2280
2281 if (IsLE) {
2282 if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2283 // Input vectors don't need to be swapped if the leading element
2284 // of the result is one of the 3 left elements of the second vector
2285 // (or if there is no shift to be done at all).
2286 Swap = false;
2287 ShiftElts = (8 - M0) % 8;
2288 } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2289 // Input vectors need to be swapped if the leading element
2290 // of the result is one of the 3 left elements of the first vector
2291 // (or if we're shifting by 4 - thereby simply swapping the vectors).
2292 Swap = true;
2293 ShiftElts = (4 - M0) % 4;
2294 }
2295
2296 return true;
2297 } else { // BE
2298 if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2299 // Input vectors don't need to be swapped if the leading element
2300 // of the result is one of the 4 elements of the first vector.
2301 Swap = false;
2302 ShiftElts = M0;
2303 } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2304 // Input vectors need to be swapped if the leading element
2305 // of the result is one of the 4 elements of the right vector.
2306 Swap = true;
2307 ShiftElts = M0 - 4;
2308 }
2309
2310 return true;
2311 }
2312}
2313
2315 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2316
2317 if (!isNByteElemShuffleMask(N, Width, -1))
2318 return false;
2319
2320 for (int i = 0; i < 16; i += Width)
2321 if (N->getMaskElt(i) != i + Width - 1)
2322 return false;
2323
2324 return true;
2325}
2326
2330
2334
2338
2342
2343/// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2344/// if the inputs to the instruction should be swapped and set \p DM to the
2345/// value for the immediate.
2346/// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2347/// AND element 0 of the result comes from the first input (LE) or second input
2348/// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2349/// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2350/// mask.
2352 bool &Swap, bool IsLE) {
2353 assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2354
2355 // Ensure each byte index of the double word is consecutive.
2356 if (!isNByteElemShuffleMask(N, 8, 1))
2357 return false;
2358
2359 unsigned M0 = N->getMaskElt(0) / 8;
2360 unsigned M1 = N->getMaskElt(8) / 8;
2361 assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2362
2363 // If both vector operands for the shuffle are the same vector, the mask will
2364 // contain only elements from the first one and the second one will be undef.
2365 if (N->getOperand(1).isUndef()) {
2366 if ((M0 | M1) < 2) {
2367 DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2368 Swap = false;
2369 return true;
2370 } else
2371 return false;
2372 }
2373
2374 if (IsLE) {
2375 if (M0 > 1 && M1 < 2) {
2376 Swap = false;
2377 } else if (M0 < 2 && M1 > 1) {
2378 M0 = (M0 + 2) % 4;
2379 M1 = (M1 + 2) % 4;
2380 Swap = true;
2381 } else
2382 return false;
2383
2384 // Note: if control flow comes here that means Swap is already set above
2385 DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2386 return true;
2387 } else { // BE
2388 if (M0 < 2 && M1 > 1) {
2389 Swap = false;
2390 } else if (M0 > 1 && M1 < 2) {
2391 M0 = (M0 + 2) % 4;
2392 M1 = (M1 + 2) % 4;
2393 Swap = true;
2394 } else
2395 return false;
2396
2397 // Note: if control flow comes here that means Swap is already set above
2398 DM = (M0 << 1) + (M1 & 1);
2399 return true;
2400 }
2401}
2402
2403
2404/// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2405/// appropriate for PPC mnemonics (which have a big endian bias - namely
2406/// elements are counted from the left of the vector register).
2407unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2408 SelectionDAG &DAG) {
2410 assert(isSplatShuffleMask(SVOp, EltSize));
2411 EVT VT = SVOp->getValueType(0);
2412
2413 if (VT == MVT::v2i64 || VT == MVT::v2f64)
2414 return DAG.getDataLayout().isLittleEndian() ? 1 - SVOp->getMaskElt(0)
2415 : SVOp->getMaskElt(0);
2416
2417 if (DAG.getDataLayout().isLittleEndian())
2418 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2419 else
2420 return SVOp->getMaskElt(0) / EltSize;
2421}
2422
2423/// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2424/// by using a vspltis[bhw] instruction of the specified element size, return
2425/// the constant being splatted. The ByteSize field indicates the number of
2426/// bytes of each element [124] -> [bhw].
2428 SDValue OpVal;
2429
2430 // If ByteSize of the splat is bigger than the element size of the
2431 // build_vector, then we have a case where we are checking for a splat where
2432 // multiple elements of the buildvector are folded together into a single
2433 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2434 unsigned EltSize = 16/N->getNumOperands();
2435 if (EltSize < ByteSize) {
2436 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
2437 SDValue UniquedVals[4];
2438 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2439
2440 // See if all of the elements in the buildvector agree across.
2441 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2442 if (N->getOperand(i).isUndef()) continue;
2443 // If the element isn't a constant, bail fully out.
2444 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2445
2446 if (!UniquedVals[i&(Multiple-1)].getNode())
2447 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2448 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2449 return SDValue(); // no match.
2450 }
2451
2452 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2453 // either constant or undef values that are identical for each chunk. See
2454 // if these chunks can form into a larger vspltis*.
2455
2456 // Check to see if all of the leading entries are either 0 or -1. If
2457 // neither, then this won't fit into the immediate field.
2458 bool LeadingZero = true;
2459 bool LeadingOnes = true;
2460 for (unsigned i = 0; i != Multiple-1; ++i) {
2461 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
2462
2463 LeadingZero &= isNullConstant(UniquedVals[i]);
2464 LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2465 }
2466 // Finally, check the least significant entry.
2467 if (LeadingZero) {
2468 if (!UniquedVals[Multiple-1].getNode())
2469 return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef
2470 int Val = UniquedVals[Multiple - 1]->getAsZExtVal();
2471 if (Val < 16) // 0,0,0,4 -> vspltisw(4)
2472 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2473 }
2474 if (LeadingOnes) {
2475 if (!UniquedVals[Multiple-1].getNode())
2476 return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2477 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2478 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
2479 return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2480 }
2481
2482 return SDValue();
2483 }
2484
2485 // Check to see if this buildvec has a single non-undef value in its elements.
2486 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2487 if (N->getOperand(i).isUndef()) continue;
2488 if (!OpVal.getNode())
2489 OpVal = N->getOperand(i);
2490 else if (OpVal != N->getOperand(i))
2491 return SDValue();
2492 }
2493
2494 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
2495
2496 unsigned ValSizeInBytes = EltSize;
2497 uint64_t Value = 0;
2498 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2499 Value = CN->getZExtValue();
2500 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2501 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2502 Value = llvm::bit_cast<uint32_t>(CN->getValueAPF().convertToFloat());
2503 }
2504
2505 // If the splat value is larger than the element value, then we can never do
2506 // this splat. The only case that we could fit the replicated bits into our
2507 // immediate field for would be zero, and we prefer to use vxor for it.
2508 if (ValSizeInBytes < ByteSize) return SDValue();
2509
2510 // If the element value is larger than the splat value, check if it consists
2511 // of a repeated bit pattern of size ByteSize.
2512 if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2513 return SDValue();
2514
2515 // Properly sign extend the value.
2516 int MaskVal = SignExtend32(Value, ByteSize * 8);
2517
2518 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2519 if (MaskVal == 0) return SDValue();
2520
2521 // Finally, if this value fits in a 5 bit sext field, return it
2522 if (SignExtend32<5>(MaskVal) == MaskVal)
2523 return DAG.getSignedTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2524 return SDValue();
2525}
2526
2527//===----------------------------------------------------------------------===//
2528// Addressing Mode Selection
2529//===----------------------------------------------------------------------===//
2530
2531/// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2532/// or 64-bit immediate, and if the value can be accurately represented as a
2533/// sign extension from a 16-bit value. If so, this returns true and the
2534/// immediate.
2536 if (!isa<ConstantSDNode>(N))
2537 return false;
2538
2539 Imm = (int16_t)N->getAsZExtVal();
2540 if (N->getValueType(0) == MVT::i32)
2541 return Imm == (int32_t)N->getAsZExtVal();
2542 else
2543 return Imm == (int64_t)N->getAsZExtVal();
2544}
2546 return isIntS16Immediate(Op.getNode(), Imm);
2547}
2548
2549/// Used when computing address flags for selecting loads and stores.
2550/// If we have an OR, check if the LHS and RHS are provably disjoint.
2551/// An OR of two provably disjoint values is equivalent to an ADD.
2552/// Most PPC load/store instructions compute the effective address as a sum,
2553/// so doing this conversion is useful.
2554static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N) {
2555 if (N.getOpcode() != ISD::OR)
2556 return false;
2557 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2558 if (!LHSKnown.Zero.getBoolValue())
2559 return false;
2560 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2561 return (~(LHSKnown.Zero | RHSKnown.Zero) == 0);
2562}
2563
2564/// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2565/// be represented as an indexed [r+r] operation.
2567 SDValue &Index,
2568 SelectionDAG &DAG) const {
2569 for (SDNode *U : N->users()) {
2570 if (MemSDNode *Memop = dyn_cast<MemSDNode>(U)) {
2571 if (Memop->getMemoryVT() == MVT::f64) {
2572 Base = N.getOperand(0);
2573 Index = N.getOperand(1);
2574 return true;
2575 }
2576 }
2577 }
2578 return false;
2579}
2580
2581/// isIntS34Immediate - This method tests if value of node given can be
2582/// accurately represented as a sign extension from a 34-bit value. If so,
2583/// this returns true and the immediate.
2585 if (!isa<ConstantSDNode>(N))
2586 return false;
2587
2588 Imm = cast<ConstantSDNode>(N)->getSExtValue();
2589 return isInt<34>(Imm);
2590}
2592 return isIntS34Immediate(Op.getNode(), Imm);
2593}
2594
2595/// SelectAddressRegReg - Given the specified addressed, check to see if it
2596/// can be represented as an indexed [r+r] operation. Returns false if it
2597/// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2598/// non-zero and N can be represented by a base register plus a signed 16-bit
2599/// displacement, make a more precise judgement by checking (displacement % \p
2600/// EncodingAlignment).
2602 SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2603 MaybeAlign EncodingAlignment) const {
2604 // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2605 // a [pc+imm].
2607 return false;
2608
2609 int16_t Imm = 0;
2610 if (N.getOpcode() == ISD::ADD) {
2611 // Is there any SPE load/store (f64), which can't handle 16bit offset?
2612 // SPE load/store can only handle 8-bit offsets.
2613 if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2614 return true;
2615 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2616 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2617 return false; // r+i
2618 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2619 return false; // r+i
2620
2621 Base = N.getOperand(0);
2622 Index = N.getOperand(1);
2623 return true;
2624 } else if (N.getOpcode() == ISD::OR) {
2625 if (isIntS16Immediate(N.getOperand(1), Imm) &&
2626 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2627 return false; // r+i can fold it if we can.
2628
2629 // If this is an or of disjoint bitfields, we can codegen this as an add
2630 // (for better address arithmetic) if the LHS and RHS of the OR are provably
2631 // disjoint.
2632 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2633
2634 if (LHSKnown.Zero.getBoolValue()) {
2635 KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2636 // If all of the bits are known zero on the LHS or RHS, the add won't
2637 // carry.
2638 if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2639 Base = N.getOperand(0);
2640 Index = N.getOperand(1);
2641 return true;
2642 }
2643 }
2644 }
2645
2646 return false;
2647}
2648
2649// If we happen to be doing an i64 load or store into a stack slot that has
2650// less than a 4-byte alignment, then the frame-index elimination may need to
2651// use an indexed load or store instruction (because the offset may not be a
2652// multiple of 4). The extra register needed to hold the offset comes from the
2653// register scavenger, and it is possible that the scavenger will need to use
2654// an emergency spill slot. As a result, we need to make sure that a spill slot
2655// is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2656// stack slot.
2657static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2658 // FIXME: This does not handle the LWA case.
2659 if (VT != MVT::i64)
2660 return;
2661
2662 // NOTE: We'll exclude negative FIs here, which come from argument
2663 // lowering, because there are no known test cases triggering this problem
2664 // using packed structures (or similar). We can remove this exclusion if
2665 // we find such a test case. The reason why this is so test-case driven is
2666 // because this entire 'fixup' is only to prevent crashes (from the
2667 // register scavenger) on not-really-valid inputs. For example, if we have:
2668 // %a = alloca i1
2669 // %b = bitcast i1* %a to i64*
2670 // store i64* a, i64 b
2671 // then the store should really be marked as 'align 1', but is not. If it
2672 // were marked as 'align 1' then the indexed form would have been
2673 // instruction-selected initially, and the problem this 'fixup' is preventing
2674 // won't happen regardless.
2675 if (FrameIdx < 0)
2676 return;
2677
2679 MachineFrameInfo &MFI = MF.getFrameInfo();
2680
2681 if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2682 return;
2683
2684 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2685 FuncInfo->setHasNonRISpills();
2686}
2687
2688/// Returns true if the address N can be represented by a base register plus
2689/// a signed 16-bit displacement [r+imm], and if it is not better
2690/// represented as reg+reg. If \p EncodingAlignment is non-zero, only accept
2691/// displacements that are multiples of that value.
2693 SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2694 MaybeAlign EncodingAlignment) const {
2695 // FIXME dl should come from parent load or store, not from address
2696 SDLoc dl(N);
2697
2698 // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2699 // a [pc+imm].
2701 return false;
2702
2703 // If this can be more profitably realized as r+r, fail.
2704 if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2705 return false;
2706
2707 if (N.getOpcode() == ISD::ADD) {
2708 int16_t imm = 0;
2709 if (isIntS16Immediate(N.getOperand(1), imm) &&
2710 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2711 Disp = DAG.getSignedTargetConstant(imm, dl, N.getValueType());
2712 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2713 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2714 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2715 } else {
2716 Base = N.getOperand(0);
2717 }
2718 return true; // [r+i]
2719 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2720 // Match LOAD (ADD (X, Lo(G))).
2721 assert(!N.getOperand(1).getConstantOperandVal(1) &&
2722 "Cannot handle constant offsets yet!");
2723 Disp = N.getOperand(1).getOperand(0); // The global address.
2728 Base = N.getOperand(0);
2729 return true; // [&g+r]
2730 }
2731 } else if (N.getOpcode() == ISD::OR) {
2732 int16_t imm = 0;
2733 if (isIntS16Immediate(N.getOperand(1), imm) &&
2734 (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2735 // If this is an or of disjoint bitfields, we can codegen this as an add
2736 // (for better address arithmetic) if the LHS and RHS of the OR are
2737 // provably disjoint.
2738 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2739
2740 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2741 // If all of the bits are known zero on the LHS or RHS, the add won't
2742 // carry.
2743 if (FrameIndexSDNode *FI =
2744 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2745 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2746 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2747 } else {
2748 Base = N.getOperand(0);
2749 }
2750 Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2751 return true;
2752 }
2753 }
2754 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2755 // Loading from a constant address.
2756
2757 // If this address fits entirely in a 16-bit sext immediate field, codegen
2758 // this as "d, 0"
2759 int16_t Imm;
2760 if (isIntS16Immediate(CN, Imm) &&
2761 (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2762 Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2763 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2764 CN->getValueType(0));
2765 return true;
2766 }
2767
2768 // Handle 32-bit sext immediates with LIS + addr mode.
2769 if ((CN->getValueType(0) == MVT::i32 ||
2770 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2771 (!EncodingAlignment ||
2772 isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2773 int Addr = (int)CN->getZExtValue();
2774
2775 // Otherwise, break this down into an LIS + disp.
2776 Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2777
2778 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2779 MVT::i32);
2780 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2781 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2782 return true;
2783 }
2784 }
2785
2786 Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2788 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2789 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2790 } else
2791 Base = N;
2792 return true; // [r+0]
2793}
2794
2795/// Similar to the 16-bit case but for instructions that take a 34-bit
2796/// displacement field (prefixed loads/stores).
2798 SDValue &Base,
2799 SelectionDAG &DAG) const {
2800 // Only on 64-bit targets.
2801 if (N.getValueType() != MVT::i64)
2802 return false;
2803
2804 SDLoc dl(N);
2805 int64_t Imm = 0;
2806
2807 if (N.getOpcode() == ISD::ADD) {
2808 if (!isIntS34Immediate(N.getOperand(1), Imm))
2809 return false;
2810 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2811 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2812 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2813 else
2814 Base = N.getOperand(0);
2815 return true;
2816 }
2817
2818 if (N.getOpcode() == ISD::OR) {
2819 if (!isIntS34Immediate(N.getOperand(1), Imm))
2820 return false;
2821 // If this is an or of disjoint bitfields, we can codegen this as an add
2822 // (for better address arithmetic) if the LHS and RHS of the OR are
2823 // provably disjoint.
2824 KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2825 if ((LHSKnown.Zero.getZExtValue() | ~(uint64_t)Imm) != ~0ULL)
2826 return false;
2827 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
2828 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2829 else
2830 Base = N.getOperand(0);
2831 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2832 return true;
2833 }
2834
2835 if (isIntS34Immediate(N, Imm)) { // If the address is a 34-bit const.
2836 Disp = DAG.getSignedTargetConstant(Imm, dl, N.getValueType());
2837 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
2838 return true;
2839 }
2840
2841 return false;
2842}
2843
2844/// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2845/// represented as an indexed [r+r] operation.
2847 SDValue &Index,
2848 SelectionDAG &DAG) const {
2849 // Check to see if we can easily represent this as an [r+r] address. This
2850 // will fail if it thinks that the address is more profitably represented as
2851 // reg+imm, e.g. where imm = 0.
2852 if (SelectAddressRegReg(N, Base, Index, DAG))
2853 return true;
2854
2855 // If the address is the result of an add, we will utilize the fact that the
2856 // address calculation includes an implicit add. However, we can reduce
2857 // register pressure if we do not materialize a constant just for use as the
2858 // index register. We only get rid of the add if it is not an add of a
2859 // value and a 16-bit signed constant and both have a single use.
2860 int16_t imm = 0;
2861 if (N.getOpcode() == ISD::ADD &&
2862 (!isIntS16Immediate(N.getOperand(1), imm) ||
2863 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2864 Base = N.getOperand(0);
2865 Index = N.getOperand(1);
2866 return true;
2867 }
2868
2869 // Otherwise, do it the hard way, using R0 as the base register.
2870 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2871 N.getValueType());
2872 Index = N;
2873 return true;
2874}
2875
2876template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2877 Ty *PCRelCand = dyn_cast<Ty>(N);
2878 return PCRelCand && (PPCInstrInfo::hasPCRelFlag(PCRelCand->getTargetFlags()));
2879}
2880
2881/// Returns true if this address is a PC Relative address.
2882/// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2883/// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2885 // This is a materialize PC Relative node. Always select this as PC Relative.
2886 Base = N;
2887 if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2888 return true;
2893 return true;
2894 return false;
2895}
2896
2897/// Returns true if we should use a direct load into vector instruction
2898/// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2899static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2900
2901 // If there are any other uses other than scalar to vector, then we should
2902 // keep it as a scalar load -> direct move pattern to prevent multiple
2903 // loads.
2905 if (!LD)
2906 return false;
2907
2908 EVT MemVT = LD->getMemoryVT();
2909 if (!MemVT.isSimple())
2910 return false;
2911 switch(MemVT.getSimpleVT().SimpleTy) {
2912 case MVT::i64:
2913 break;
2914 case MVT::i32:
2915 if (!ST.hasP8Vector())
2916 return false;
2917 break;
2918 case MVT::i16:
2919 case MVT::i8:
2920 if (!ST.hasP9Vector())
2921 return false;
2922 break;
2923 default:
2924 return false;
2925 }
2926
2927 SDValue LoadedVal(N, 0);
2928 if (!LoadedVal.hasOneUse())
2929 return false;
2930
2931 for (SDUse &Use : LD->uses())
2932 if (Use.getResNo() == 0 &&
2933 Use.getUser()->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2934 Use.getUser()->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2935 return false;
2936
2937 return true;
2938}
2939
2940/// getPreIndexedAddressParts - returns true by value, base pointer and
2941/// offset pointer and addressing mode by reference if the node's address
2942/// can be legally represented as pre-indexed load / store address.
2944 SDValue &Offset,
2946 SelectionDAG &DAG) const {
2947 if (!EnablePPCPreinc)
2948 return false;
2949
2950 bool isLoad = true;
2951 SDValue Ptr;
2952 EVT VT;
2953 Align Alignment;
2954 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2955 Ptr = LD->getBasePtr();
2956 VT = LD->getMemoryVT();
2957 Alignment = LD->getAlign();
2958 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2959 Ptr = ST->getBasePtr();
2960 VT = ST->getMemoryVT();
2961 Alignment = ST->getAlign();
2962 isLoad = false;
2963 } else
2964 return false;
2965
2966 // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2967 // instructions because we can fold these into a more efficient instruction
2968 // instead, (such as LXSD).
2969 if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2970 return false;
2971 }
2972
2973 // PowerPC doesn't have preinc load/store instructions for vectors
2974 if (VT.isVector())
2975 return false;
2976
2977 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2978 // Common code will reject creating a pre-inc form if the base pointer
2979 // is a frame index, or if N is a store and the base pointer is either
2980 // the same as or a predecessor of the value being stored. Check for
2981 // those situations here, and try with swapped Base/Offset instead.
2982 bool Swap = false;
2983
2985 Swap = true;
2986 else if (!isLoad) {
2987 SDValue Val = cast<StoreSDNode>(N)->getValue();
2988 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2989 Swap = true;
2990 }
2991
2992 if (Swap)
2994
2995 AM = ISD::PRE_INC;
2996 return true;
2997 }
2998
2999 // LDU/STU can only handle immediates that are a multiple of 4.
3000 if (VT != MVT::i64) {
3001 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, std::nullopt))
3002 return false;
3003 } else {
3004 // LDU/STU need an address with at least 4-byte alignment.
3005 if (Alignment < Align(4))
3006 return false;
3007
3008 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
3009 return false;
3010 }
3011
3012 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3013 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
3014 // sext i32 to i64 when addr mode is r+i.
3015 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
3016 LD->getExtensionType() == ISD::SEXTLOAD &&
3018 return false;
3019 }
3020
3021 AM = ISD::PRE_INC;
3022 return true;
3023}
3024
3025//===----------------------------------------------------------------------===//
3026// LowerOperation implementation
3027//===----------------------------------------------------------------------===//
3028
3029/// Return true if we should reference labels using a PICBase, set the HiOpFlags
3030/// and LoOpFlags to the target MO flags.
3031static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
3032 unsigned &HiOpFlags, unsigned &LoOpFlags,
3033 const GlobalValue *GV = nullptr) {
3034 HiOpFlags = PPCII::MO_HA;
3035 LoOpFlags = PPCII::MO_LO;
3036
3037 // Don't use the pic base if not in PIC relocation model.
3038 if (IsPIC) {
3039 HiOpFlags = PPCII::MO_PIC_HA_FLAG;
3040 LoOpFlags = PPCII::MO_PIC_LO_FLAG;
3041 }
3042}
3043
3044static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
3045 SelectionDAG &DAG) {
3046 SDLoc DL(HiPart);
3047 EVT PtrVT = HiPart.getValueType();
3048 SDValue Zero = DAG.getConstant(0, DL, PtrVT);
3049
3050 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
3051 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
3052
3053 // With PIC, the first instruction is actually "GR+hi(&G)".
3054 if (isPIC)
3055 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
3056 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
3057
3058 // Generate non-pic code that has direct accesses to the constant pool.
3059 // The address of the global is just (hi(&g)+lo(&g)).
3060 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
3061}
3062
3064 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3065 FuncInfo->setUsesTOCBasePtr();
3066}
3067
3071
3072SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
3073 SDValue GA) const {
3074 EVT VT = Subtarget.getScalarIntVT();
3075 SDValue Reg = Subtarget.isPPC64() ? DAG.getRegister(PPC::X2, VT)
3076 : Subtarget.isAIXABI()
3077 ? DAG.getRegister(PPC::R2, VT)
3078 : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
3079 SDValue Ops[] = { GA, Reg };
3080 return DAG.getMemIntrinsicNode(
3081 PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
3084}
3085
3086SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
3087 SelectionDAG &DAG) const {
3088 EVT PtrVT = Op.getValueType();
3089 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3090 const Constant *C = CP->getConstVal();
3091
3092 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3093 // The actual address of the GlobalValue is stored in the TOC.
3094 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3095 if (Subtarget.isUsingPCRelativeCalls()) {
3096 SDLoc DL(CP);
3097 EVT Ty = getPointerTy(DAG.getDataLayout());
3098 SDValue ConstPool = DAG.getTargetConstantPool(
3099 C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
3100 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
3101 }
3102 setUsesTOCBasePtr(DAG);
3103 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
3104 return getTOCEntry(DAG, SDLoc(CP), GA);
3105 }
3106
3107 unsigned MOHiFlag, MOLoFlag;
3108 bool IsPIC = isPositionIndependent();
3109 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3110
3111 if (IsPIC && Subtarget.isSVR4ABI()) {
3112 SDValue GA =
3114 return getTOCEntry(DAG, SDLoc(CP), GA);
3115 }
3116
3117 SDValue CPIHi =
3118 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
3119 SDValue CPILo =
3120 DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
3121 return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
3122}
3123
3124// For 64-bit PowerPC, prefer the more compact relative encodings.
3125// This trades 32 bits per jump table entry for one or two instructions
3126// on the jump site.
3133
3136 return false;
3137 if (Subtarget.isPPC64() || Subtarget.isAIXABI())
3138 return true;
3140}
3141
3143 SelectionDAG &DAG) const {
3144 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3146
3147 switch (getTargetMachine().getCodeModel()) {
3148 case CodeModel::Small:
3149 case CodeModel::Medium:
3151 default:
3152 return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
3154 }
3155}
3156
3157const MCExpr *
3159 unsigned JTI,
3160 MCContext &Ctx) const {
3161 if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
3163
3164 switch (getTargetMachine().getCodeModel()) {
3165 case CodeModel::Small:
3166 case CodeModel::Medium:
3168 default:
3169 return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
3170 }
3171}
3172
3173SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
3174 EVT PtrVT = Op.getValueType();
3176
3177 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3178 if (Subtarget.isUsingPCRelativeCalls()) {
3179 SDLoc DL(JT);
3180 EVT Ty = getPointerTy(DAG.getDataLayout());
3181 SDValue GA =
3183 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3184 return MatAddr;
3185 }
3186
3187 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3188 // The actual address of the GlobalValue is stored in the TOC.
3189 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3190 setUsesTOCBasePtr(DAG);
3191 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
3192 return getTOCEntry(DAG, SDLoc(JT), GA);
3193 }
3194
3195 unsigned MOHiFlag, MOLoFlag;
3196 bool IsPIC = isPositionIndependent();
3197 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3198
3199 if (IsPIC && Subtarget.isSVR4ABI()) {
3200 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3202 return getTOCEntry(DAG, SDLoc(GA), GA);
3203 }
3204
3205 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
3206 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
3207 return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
3208}
3209
3210SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
3211 SelectionDAG &DAG) const {
3212 EVT PtrVT = Op.getValueType();
3213 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
3214 const BlockAddress *BA = BASDN->getBlockAddress();
3215
3216 // isUsingPCRelativeCalls() returns true when PCRelative is enabled
3217 if (Subtarget.isUsingPCRelativeCalls()) {
3218 SDLoc DL(BASDN);
3219 EVT Ty = getPointerTy(DAG.getDataLayout());
3220 SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
3222 SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3223 return MatAddr;
3224 }
3225
3226 // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
3227 // The actual BlockAddress is stored in the TOC.
3228 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3229 setUsesTOCBasePtr(DAG);
3230 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
3231 return getTOCEntry(DAG, SDLoc(BASDN), GA);
3232 }
3233
3234 // 32-bit position-independent ELF stores the BlockAddress in the .got.
3235 if (Subtarget.is32BitELFABI() && isPositionIndependent())
3236 return getTOCEntry(
3237 DAG, SDLoc(BASDN),
3238 DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
3239
3240 unsigned MOHiFlag, MOLoFlag;
3241 bool IsPIC = isPositionIndependent();
3242 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
3243 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
3244 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
3245 return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
3246}
3247
3248SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
3249 SelectionDAG &DAG) const {
3250 if (Subtarget.isAIXABI())
3251 return LowerGlobalTLSAddressAIX(Op, DAG);
3252
3253 return LowerGlobalTLSAddressLinux(Op, DAG);
3254}
3255
3256/// updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings,
3257/// and then apply the update.
3259 SelectionDAG &DAG,
3260 const TargetMachine &TM) {
3261 // Initialize TLS model opt setting lazily:
3262 // (1) Use initial-exec for single TLS var references within current function.
3263 // (2) Use local-dynamic for multiple TLS var references within current
3264 // function.
3265 PPCFunctionInfo *FuncInfo =
3267 if (!FuncInfo->isAIXFuncTLSModelOptInitDone()) {
3269 // Iterate over all instructions within current function, collect all TLS
3270 // global variables (global variables taken as the first parameter to
3271 // Intrinsic::threadlocal_address).
3272 const Function &Func = DAG.getMachineFunction().getFunction();
3273 for (const BasicBlock &BB : Func)
3274 for (const Instruction &I : BB)
3275 if (I.getOpcode() == Instruction::Call)
3276 if (const CallInst *CI = dyn_cast<const CallInst>(&I))
3277 if (Function *CF = CI->getCalledFunction())
3278 if (CF->isDeclaration() &&
3279 CF->getIntrinsicID() == Intrinsic::threadlocal_address)
3280 if (const GlobalValue *GV =
3281 dyn_cast<GlobalValue>(I.getOperand(0))) {
3282 TLSModel::Model GVModel = TM.getTLSModel(GV);
3283 if (GVModel == TLSModel::LocalDynamic)
3284 TLSGV.insert(GV);
3285 }
3286
3287 unsigned TLSGVCnt = TLSGV.size();
3288 LLVM_DEBUG(dbgs() << format("LocalDynamic TLSGV count:%d\n", TLSGVCnt));
3289 if (TLSGVCnt <= PPCAIXTLSModelOptUseIEForLDLimit)
3290 FuncInfo->setAIXFuncUseTLSIEForLD();
3292 }
3293
3294 if (FuncInfo->isAIXFuncUseTLSIEForLD()) {
3295 LLVM_DEBUG(
3296 dbgs() << DAG.getMachineFunction().getName()
3297 << " function is using the TLS-IE model for TLS-LD access.\n");
3298 Model = TLSModel::InitialExec;
3299 }
3300}
3301
3302SDValue PPCTargetLowering::LowerGlobalTLSAddressAIX(SDValue Op,
3303 SelectionDAG &DAG) const {
3304 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3305
3306 if (DAG.getTarget().useEmulatedTLS())
3307 report_fatal_error("Emulated TLS is not yet supported on AIX");
3308
3309 SDLoc dl(GA);
3310 const GlobalValue *GV = GA->getGlobal();
3311 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3312 bool Is64Bit = Subtarget.isPPC64();
3314
3315 // Apply update to the TLS model.
3316 if (Subtarget.hasAIXShLibTLSModelOpt())
3318
3319 // TLS variables are accessed through TOC entries.
3320 // To support this, set the DAG to use the TOC base pointer.
3321 setUsesTOCBasePtr(DAG);
3322
3323 bool IsTLSLocalExecModel = Model == TLSModel::LocalExec;
3324
3325 if (IsTLSLocalExecModel || Model == TLSModel::InitialExec) {
3326 bool HasAIXSmallLocalExecTLS = Subtarget.hasAIXSmallLocalExecTLS();
3327 bool HasAIXSmallTLSGlobalAttr = false;
3328 SDValue VariableOffsetTGA =
3329 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_FLAG);
3330 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3331 SDValue TLSReg;
3332
3333 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
3334 if (GVar->hasAttribute("aix-small-tls"))
3335 HasAIXSmallTLSGlobalAttr = true;
3336
3337 if (Is64Bit) {
3338 // For local-exec and initial-exec on AIX (64-bit), the sequence generated
3339 // involves a load of the variable offset (from the TOC), followed by an
3340 // add of the loaded variable offset to R13 (the thread pointer).
3341 // This code sequence looks like:
3342 // ld reg1,var[TC](2)
3343 // add reg2, reg1, r13 // r13 contains the thread pointer
3344 TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3345
3346 // With the -maix-small-local-exec-tls option, or with the "aix-small-tls"
3347 // global variable attribute, produce a faster access sequence for
3348 // local-exec TLS variables where the offset from the TLS base is encoded
3349 // as an immediate operand.
3350 //
3351 // We only utilize the faster local-exec access sequence when the TLS
3352 // variable has a size within the policy limit. We treat types that are
3353 // not sized or are empty as being over the policy size limit.
3354 if ((HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr) &&
3355 IsTLSLocalExecModel) {
3356 Type *GVType = GV->getValueType();
3357 if (GVType->isSized() && !GVType->isEmptyTy() &&
3358 GV->getDataLayout().getTypeAllocSize(GVType) <=
3360 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA, TLSReg);
3361 }
3362 } else {
3363 // For local-exec and initial-exec on AIX (32-bit), the sequence generated
3364 // involves loading the variable offset from the TOC, generating a call to
3365 // .__get_tpointer to get the thread pointer (which will be in R3), and
3366 // adding the two together:
3367 // lwz reg1,var[TC](2)
3368 // bla .__get_tpointer
3369 // add reg2, reg1, r3
3370 TLSReg = DAG.getNode(PPCISD::GET_TPOINTER, dl, PtrVT);
3371
3372 // We do not implement the 32-bit version of the faster access sequence
3373 // for local-exec that is controlled by the -maix-small-local-exec-tls
3374 // option, or the "aix-small-tls" global variable attribute.
3375 if (HasAIXSmallLocalExecTLS || HasAIXSmallTLSGlobalAttr)
3376 report_fatal_error("The small-local-exec TLS access sequence is "
3377 "currently only supported on AIX (64-bit mode).");
3378 }
3379 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, VariableOffset);
3380 }
3381
3382 if (Model == TLSModel::LocalDynamic) {
3383 bool HasAIXSmallLocalDynamicTLS = Subtarget.hasAIXSmallLocalDynamicTLS();
3384
3385 // We do not implement the 32-bit version of the faster access sequence
3386 // for local-dynamic that is controlled by -maix-small-local-dynamic-tls.
3387 if (!Is64Bit && HasAIXSmallLocalDynamicTLS)
3388 report_fatal_error("The small-local-dynamic TLS access sequence is "
3389 "currently only supported on AIX (64-bit mode).");
3390
3391 // For local-dynamic on AIX, we need to generate one TOC entry for each
3392 // variable offset, and a single module-handle TOC entry for the entire
3393 // file.
3394
3395 SDValue VariableOffsetTGA =
3396 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSLD_FLAG);
3397 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3398
3400 GlobalVariable *TLSGV =
3401 dyn_cast_or_null<GlobalVariable>(M->getOrInsertGlobal(
3402 StringRef("_$TLSML"), PointerType::getUnqual(*DAG.getContext())));
3404 assert(TLSGV && "Not able to create GV for _$TLSML.");
3405 SDValue ModuleHandleTGA =
3406 DAG.getTargetGlobalAddress(TLSGV, dl, PtrVT, 0, PPCII::MO_TLSLDM_FLAG);
3407 SDValue ModuleHandleTOC = getTOCEntry(DAG, dl, ModuleHandleTGA);
3408 SDValue ModuleHandle =
3409 DAG.getNode(PPCISD::TLSLD_AIX, dl, PtrVT, ModuleHandleTOC);
3410
3411 // With the -maix-small-local-dynamic-tls option, produce a faster access
3412 // sequence for local-dynamic TLS variables where the offset from the
3413 // module-handle is encoded as an immediate operand.
3414 //
3415 // We only utilize the faster local-dynamic access sequence when the TLS
3416 // variable has a size within the policy limit. We treat types that are
3417 // not sized or are empty as being over the policy size limit.
3418 if (HasAIXSmallLocalDynamicTLS) {
3419 Type *GVType = GV->getValueType();
3420 if (GVType->isSized() && !GVType->isEmptyTy() &&
3421 GV->getDataLayout().getTypeAllocSize(GVType) <=
3423 return DAG.getNode(PPCISD::Lo, dl, PtrVT, VariableOffsetTGA,
3424 ModuleHandle);
3425 }
3426
3427 return DAG.getNode(ISD::ADD, dl, PtrVT, ModuleHandle, VariableOffset);
3428 }
3429
3430 // If Local- or Initial-exec or Local-dynamic is not possible or specified,
3431 // all GlobalTLSAddress nodes are lowered using the general-dynamic model. We
3432 // need to generate two TOC entries, one for the variable offset, one for the
3433 // region handle. The global address for the TOC entry of the region handle is
3434 // created with the MO_TLSGDM_FLAG flag and the global address for the TOC
3435 // entry of the variable offset is created with MO_TLSGD_FLAG.
3436 SDValue VariableOffsetTGA =
3437 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGD_FLAG);
3438 SDValue RegionHandleTGA =
3439 DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLSGDM_FLAG);
3440 SDValue VariableOffset = getTOCEntry(DAG, dl, VariableOffsetTGA);
3441 SDValue RegionHandle = getTOCEntry(DAG, dl, RegionHandleTGA);
3442 return DAG.getNode(PPCISD::TLSGD_AIX, dl, PtrVT, VariableOffset,
3443 RegionHandle);
3444}
3445
3446SDValue PPCTargetLowering::LowerGlobalTLSAddressLinux(SDValue Op,
3447 SelectionDAG &DAG) const {
3448 // FIXME: TLS addresses currently use medium model code sequences,
3449 // which is the most useful form. Eventually support for small and
3450 // large models could be added if users need it, at the cost of
3451 // additional complexity.
3452 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3453 if (DAG.getTarget().useEmulatedTLS())
3454 return LowerToTLSEmulatedModel(GA, DAG);
3455
3456 SDLoc dl(GA);
3457 const GlobalValue *GV = GA->getGlobal();
3458 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3459 bool is64bit = Subtarget.isPPC64();
3460 const Module *M = DAG.getMachineFunction().getFunction().getParent();
3461 PICLevel::Level picLevel = M->getPICLevel();
3462
3463 const TargetMachine &TM = getTargetMachine();
3464 TLSModel::Model Model = TM.getTLSModel(GV);
3465
3466 if (Model == TLSModel::LocalExec) {
3467 if (Subtarget.isUsingPCRelativeCalls()) {
3468 SDValue TLSReg = DAG.getRegister(PPC::X13, MVT::i64);
3469 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3471 SDValue MatAddr =
3472 DAG.getNode(PPCISD::TLS_LOCAL_EXEC_MAT_ADDR, dl, PtrVT, TGA);
3473 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TLSReg, MatAddr);
3474 }
3475
3476 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3478 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3480 SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
3481 : DAG.getRegister(PPC::R2, MVT::i32);
3482
3483 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
3484 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
3485 }
3486
3487 if (Model == TLSModel::InitialExec) {
3488 bool IsPCRel = Subtarget.isUsingPCRelativeCalls();
3489 SDValue TGA = DAG.getTargetGlobalAddress(
3490 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_GOT_TPREL_PCREL_FLAG : 0);
3491 SDValue TGATLS = DAG.getTargetGlobalAddress(
3492 GV, dl, PtrVT, 0, IsPCRel ? PPCII::MO_TLS_PCREL_FLAG : PPCII::MO_TLS);
3493 SDValue TPOffset;
3494 if (IsPCRel) {
3495 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, dl, PtrVT, TGA);
3496 TPOffset = DAG.getLoad(MVT::i64, dl, DAG.getEntryNode(), MatPCRel,
3497 MachinePointerInfo());
3498 } else {
3499 SDValue GOTPtr;
3500 if (is64bit) {
3501 setUsesTOCBasePtr(DAG);
3502 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3503 GOTPtr =
3504 DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA);
3505 } else {
3506 if (!TM.isPositionIndependent())
3507 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
3508 else if (picLevel == PICLevel::SmallPIC)
3509 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3510 else
3511 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3512 }
3513 TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr);
3514 }
3515 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3516 }
3517
3518 if (Model == TLSModel::GeneralDynamic) {
3519 if (Subtarget.isUsingPCRelativeCalls()) {
3520 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3522 return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3523 }
3524
3525 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3526 SDValue GOTPtr;
3527 if (is64bit) {
3528 setUsesTOCBasePtr(DAG);
3529 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3530 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3531 GOTReg, TGA);
3532 } else {
3533 if (picLevel == PICLevel::SmallPIC)
3534 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3535 else
3536 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3537 }
3538 return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3539 GOTPtr, TGA, TGA);
3540 }
3541
3542 if (Model == TLSModel::LocalDynamic) {
3543 if (Subtarget.isUsingPCRelativeCalls()) {
3544 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3546 SDValue MatPCRel =
3547 DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3548 return DAG.getNode(PPCISD::PADDI_DTPREL, dl, PtrVT, MatPCRel, TGA);
3549 }
3550
3551 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3552 SDValue GOTPtr;
3553 if (is64bit) {
3554 setUsesTOCBasePtr(DAG);
3555 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3556 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3557 GOTReg, TGA);
3558 } else {
3559 if (picLevel == PICLevel::SmallPIC)
3560 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3561 else
3562 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3563 }
3564 SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3565 PtrVT, GOTPtr, TGA, TGA);
3566 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3567 PtrVT, TLSAddr, TGA);
3568 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3569 }
3570
3571 llvm_unreachable("Unknown TLS model!");
3572}
3573
3574SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3575 SelectionDAG &DAG) const {
3576 EVT PtrVT = Op.getValueType();
3577 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3578 SDLoc DL(GSDN);
3579 const GlobalValue *GV = GSDN->getGlobal();
3580
3581 // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3582 // The actual address of the GlobalValue is stored in the TOC.
3583 if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3584 if (Subtarget.isUsingPCRelativeCalls()) {
3585 EVT Ty = getPointerTy(DAG.getDataLayout());
3587 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3589 SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3590 SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3591 MachinePointerInfo());
3592 return Load;
3593 } else {
3594 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3596 return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3597 }
3598 }
3599 setUsesTOCBasePtr(DAG);
3600 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3601 return getTOCEntry(DAG, DL, GA);
3602 }
3603
3604 unsigned MOHiFlag, MOLoFlag;
3605 bool IsPIC = isPositionIndependent();
3606 getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3607
3608 if (IsPIC && Subtarget.isSVR4ABI()) {
3609 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3610 GSDN->getOffset(),
3612 return getTOCEntry(DAG, DL, GA);
3613 }
3614
3615 SDValue GAHi =
3616 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3617 SDValue GALo =
3618 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3619
3620 return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3621}
3622
3623SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3624 bool IsStrict = Op->isStrictFPOpcode();
3625 const SDNodeFlags Flags = Op.getNode()->getFlags();
3627 cast<CondCodeSDNode>(Op.getOperand(IsStrict ? 3 : 2))->get();
3628 SDValue LHS = Op.getOperand(IsStrict ? 1 : 0);
3629 SDValue RHS = Op.getOperand(IsStrict ? 2 : 1);
3630 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
3631 EVT LHSVT = LHS.getValueType();
3632 SDLoc dl(Op);
3633
3634 // Soften the setcc with libcall if it is fp128 or it is SPE and fp32/fp64.
3635 if (LHSVT == MVT::f128 ||
3636 (Subtarget.hasSPE() && (LHSVT == MVT::f32 || LHSVT == MVT::f64) &&
3637 (!Flags.hasNoNaNs() || !Flags.hasNoInfs()))) {
3638 assert(!Subtarget.hasP9Vector() &&
3639 "SETCC for f128 is already legal under Power9!");
3640 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS, Chain,
3641 Op->getOpcode() == ISD::STRICT_FSETCCS);
3642 if (RHS.getNode())
3643 LHS = DAG.getNode(ISD::SETCC, dl, Op.getValueType(), LHS, RHS,
3644 DAG.getCondCode(CC));
3645 if (IsStrict)
3646 return DAG.getMergeValues({LHS, Chain}, dl);
3647 return LHS;
3648 } else if (LHSVT == MVT::f32 || LHSVT == MVT::f64) {
3649 return Op;
3650 }
3651
3652 assert(!IsStrict && "Don't know how to handle STRICT_FSETCC!");
3653
3654 if (Op.getValueType() == MVT::v2i64) {
3655 // When the operands themselves are v2i64 values, we need to do something
3656 // special because VSX has no underlying comparison operations for these.
3657 if (LHS.getValueType() == MVT::v2i64) {
3658 // Equality can be handled by casting to the legal type for Altivec
3659 // comparisons, everything else needs to be expanded.
3660 if (CC != ISD::SETEQ && CC != ISD::SETNE)
3661 return SDValue();
3662 SDValue SetCC32 = DAG.getSetCC(
3663 dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, LHS),
3664 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, RHS), CC);
3665 int ShuffV[] = {1, 0, 3, 2};
3666 SDValue Shuff =
3667 DAG.getVectorShuffle(MVT::v4i32, dl, SetCC32, SetCC32, ShuffV);
3668 return DAG.getBitcast(MVT::v2i64,
3670 dl, MVT::v4i32, Shuff, SetCC32));
3671 }
3672
3673 // We handle most of these in the usual way.
3674 return Op;
3675 }
3676
3677 // If we're comparing for equality to zero, expose the fact that this is
3678 // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3679 // fold the new nodes.
3680 if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3681 return V;
3682
3683 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
3684 // Leave comparisons against 0 and -1 alone for now, since they're usually
3685 // optimized. FIXME: revisit this when we can custom lower all setcc
3686 // optimizations.
3687 if (C->isAllOnes() || C->isZero())
3688 return SDValue();
3689 }
3690
3691 // If we have an integer seteq/setne, turn it into a compare against zero
3692 // by xor'ing the rhs with the lhs, which is faster than setting a
3693 // condition register, reading it back out, and masking the correct bit. The
3694 // normal approach here uses sub to do this instead of xor. Using xor exposes
3695 // the result to other bit-twiddling opportunities.
3696 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3697 EVT VT = Op.getValueType();
3698 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, LHS, RHS);
3699 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3700 }
3701 return SDValue();
3702}
3703
3704SDValue PPCTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3705 const SDNodeFlags Flags = Op->getFlags();
3706 SDValue Chain = Op.getOperand(0);
3707 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3708 SDValue LHS = Op.getOperand(2);
3709 SDValue RHS = Op.getOperand(3);
3710 SDValue Dest = Op.getOperand(4);
3711 EVT LHSVT = LHS.getValueType();
3712 SDLoc dl(Op);
3713
3714 assert(Subtarget.hasSPE() && "LowerBR_CC used only for targets with SPE");
3715
3716 if ((LHSVT == MVT::f32 || LHSVT == MVT::f64) && Flags.hasNoNaNs() &&
3717 Flags.hasNoInfs())
3718 return Op;
3719
3720 softenSetCCOperands(DAG, LHSVT, LHS, RHS, CC, dl, LHS, RHS);
3721
3722 // If softenSetCCOperands returned a scalar, we need to compare the result
3723 // against zero to select between true and false values.
3724 if (!RHS) {
3725 RHS = DAG.getConstant(0, dl, LHSVT);
3726 CC = ISD::SETNE;
3727 }
3728
3729 return DAG.getNode(ISD::BR_CC, dl, Op.getValueType(), Chain,
3730 DAG.getCondCode(CC), LHS, RHS, Dest);
3731}
3732
3733SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3734 SDNode *Node = Op.getNode();
3735 EVT VT = Node->getValueType(0);
3736 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3737 SDValue InChain = Node->getOperand(0);
3738 SDValue VAListPtr = Node->getOperand(1);
3739 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3740 SDLoc dl(Node);
3741
3742 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3743
3744 // gpr_index
3745 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3746 VAListPtr, MachinePointerInfo(SV), MVT::i8);
3747 InChain = GprIndex.getValue(1);
3748
3749 if (VT == MVT::i64) {
3750 // Check if GprIndex is even
3751 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3752 DAG.getConstant(1, dl, MVT::i32));
3753 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3754 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3755 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3756 DAG.getConstant(1, dl, MVT::i32));
3757 // Align GprIndex to be even if it isn't
3758 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3759 GprIndex);
3760 }
3761
3762 // fpr index is 1 byte after gpr
3763 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3764 DAG.getConstant(1, dl, MVT::i32));
3765
3766 // fpr
3767 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3768 FprPtr, MachinePointerInfo(SV), MVT::i8);
3769 InChain = FprIndex.getValue(1);
3770
3771 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3772 DAG.getConstant(8, dl, MVT::i32));
3773
3774 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3775 DAG.getConstant(4, dl, MVT::i32));
3776
3777 // areas
3778 SDValue OverflowArea =
3779 DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3780 InChain = OverflowArea.getValue(1);
3781
3782 SDValue RegSaveArea =
3783 DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3784 InChain = RegSaveArea.getValue(1);
3785
3786 // select overflow_area if index > 8
3787 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3788 DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3789
3790 // adjustment constant gpr_index * 4/8
3791 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3792 VT.isInteger() ? GprIndex : FprIndex,
3793 DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3794 MVT::i32));
3795
3796 // OurReg = RegSaveArea + RegConstant
3797 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3798 RegConstant);
3799
3800 // Floating types are 32 bytes into RegSaveArea
3801 if (VT.isFloatingPoint())
3802 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3803 DAG.getConstant(32, dl, MVT::i32));
3804
3805 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3806 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3807 VT.isInteger() ? GprIndex : FprIndex,
3808 DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3809 MVT::i32));
3810
3811 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3812 VT.isInteger() ? VAListPtr : FprPtr,
3813 MachinePointerInfo(SV), MVT::i8);
3814
3815 // determine if we should load from reg_save_area or overflow_area
3816 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3817
3818 // increase overflow_area by 4/8 if gpr/fpr > 8
3819 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3820 DAG.getConstant(VT.isInteger() ? 4 : 8,
3821 dl, MVT::i32));
3822
3823 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3824 OverflowAreaPlusN);
3825
3826 InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3827 MachinePointerInfo(), MVT::i32);
3828
3829 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3830}
3831
3832SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3833 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3834
3835 // We have to copy the entire va_list struct:
3836 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3837 return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3838 DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3839 Align(8), false, true, /*CI=*/nullptr, std::nullopt,
3840 MachinePointerInfo(), MachinePointerInfo());
3841}
3842
3843SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3844 SelectionDAG &DAG) const {
3845 return Op.getOperand(0);
3846}
3847
3848SDValue PPCTargetLowering::LowerINLINEASM(SDValue Op, SelectionDAG &DAG) const {
3850 PPCFunctionInfo &MFI = *MF.getInfo<PPCFunctionInfo>();
3851
3852 assert((Op.getOpcode() == ISD::INLINEASM ||
3853 Op.getOpcode() == ISD::INLINEASM_BR) &&
3854 "Expecting Inline ASM node.");
3855
3856 // If an LR store is already known to be required then there is not point in
3857 // checking this ASM as well.
3858 if (MFI.isLRStoreRequired())
3859 return Op;
3860
3861 // Inline ASM nodes have an optional last operand that is an incoming Flag of
3862 // type MVT::Glue. We want to ignore this last operand if that is the case.
3863 unsigned NumOps = Op.getNumOperands();
3864 if (Op.getOperand(NumOps - 1).getValueType() == MVT::Glue)
3865 --NumOps;
3866
3867 // Check all operands that may contain the LR.
3868 for (unsigned i = InlineAsm::Op_FirstOperand; i != NumOps;) {
3869 const InlineAsm::Flag Flags(Op.getConstantOperandVal(i));
3870 unsigned NumVals = Flags.getNumOperandRegisters();
3871 ++i; // Skip the ID value.
3872
3873 switch (Flags.getKind()) {
3874 default:
3875 llvm_unreachable("Bad flags!");
3879 i += NumVals;
3880 break;
3884 for (; NumVals; --NumVals, ++i) {
3885 Register Reg = cast<RegisterSDNode>(Op.getOperand(i))->getReg();
3886 if (Reg != PPC::LR && Reg != PPC::LR8)
3887 continue;
3888 MFI.setLRStoreRequired();
3889 return Op;
3890 }
3891 break;
3892 }
3893 }
3894 }
3895
3896 return Op;
3897}
3898
3899SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3900 SelectionDAG &DAG) const {
3901 SDValue Chain = Op.getOperand(0);
3902 SDValue Trmp = Op.getOperand(1); // trampoline
3903 SDValue FPtr = Op.getOperand(2); // nested function
3904 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3905 SDLoc dl(Op);
3906
3907 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3908
3909 if (Subtarget.isAIXABI()) {
3910 // On AIX we create a trampoline descriptor by combining the
3911 // entry point and TOC from the global descriptor (FPtr) with the
3912 // nest argument as the environment pointer.
3913 uint64_t PointerSize = Subtarget.isPPC64() ? 8 : 4;
3914 MaybeAlign PointerAlign(PointerSize);
3915 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
3918 : MachineMemOperand::MONone;
3919
3920 uint64_t TOCPointerOffset = 1 * PointerSize;
3921 uint64_t EnvPointerOffset = 2 * PointerSize;
3922 SDValue SDTOCPtrOffset = DAG.getConstant(TOCPointerOffset, dl, PtrVT);
3923 SDValue SDEnvPtrOffset = DAG.getConstant(EnvPointerOffset, dl, PtrVT);
3924
3925 const Value *TrampolineAddr =
3926 cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3927 const Function *Func =
3928 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
3929
3930 SDValue OutChains[3];
3931
3932 // Copy the entry point address from the global descriptor to the
3933 // trampoline buffer.
3934 SDValue LoadEntryPoint =
3935 DAG.getLoad(PtrVT, dl, Chain, FPtr, MachinePointerInfo(Func, 0),
3936 PointerAlign, MMOFlags);
3937 SDValue EPLoadChain = LoadEntryPoint.getValue(1);
3938 OutChains[0] = DAG.getStore(EPLoadChain, dl, LoadEntryPoint, Trmp,
3939 MachinePointerInfo(TrampolineAddr, 0));
3940
3941 // Copy the TOC pointer from the global descriptor to the trampoline
3942 // buffer.
3943 SDValue TOCFromDescriptorPtr =
3944 DAG.getNode(ISD::ADD, dl, PtrVT, FPtr, SDTOCPtrOffset);
3945 SDValue TOCReg = DAG.getLoad(PtrVT, dl, Chain, TOCFromDescriptorPtr,
3946 MachinePointerInfo(Func, TOCPointerOffset),
3947 PointerAlign, MMOFlags);
3948 SDValue TrampolineTOCPointer =
3949 DAG.getNode(ISD::ADD, dl, PtrVT, Trmp, SDTOCPtrOffset);
3950 SDValue TOCLoadChain = TOCReg.getValue(1);
3951 OutChains[1] =
3952 DAG.getStore(TOCLoadChain, dl, TOCReg, TrampolineTOCPointer,
3953 MachinePointerInfo(TrampolineAddr, TOCPointerOffset));
3954
3955 // Store the nest argument into the environment pointer in the trampoline
3956 // buffer.
3957 SDValue EnvPointer = DAG.getNode(ISD::ADD, dl, PtrVT, Trmp, SDEnvPtrOffset);
3958 OutChains[2] =
3959 DAG.getStore(Chain, dl, Nest, EnvPointer,
3960 MachinePointerInfo(TrampolineAddr, EnvPointerOffset));
3961
3962 SDValue TokenFactor =
3963 DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
3964 return TokenFactor;
3965 }
3966
3967 bool isPPC64 = (PtrVT == MVT::i64);
3969
3971 Args.emplace_back(Trmp, IntPtrTy);
3972 // TrampSize == (isPPC64 ? 48 : 40);
3973 Args.emplace_back(
3974 DAG.getConstant(isPPC64 ? 48 : 40, dl, Subtarget.getScalarIntVT()),
3975 IntPtrTy);
3976 Args.emplace_back(FPtr, IntPtrTy);
3977 Args.emplace_back(Nest, IntPtrTy);
3978
3979 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3980 TargetLowering::CallLoweringInfo CLI(DAG);
3981 CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3983 DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3984
3985 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3986 return CallResult.second;
3987}
3988
3989SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3991 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3992 EVT PtrVT = getPointerTy(MF.getDataLayout());
3993
3994 SDLoc dl(Op);
3995
3996 if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3997 // vastart just stores the address of the VarArgsFrameIndex slot into the
3998 // memory location argument.
3999 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4000 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4001 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4002 MachinePointerInfo(SV));
4003 }
4004
4005 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
4006 // We suppose the given va_list is already allocated.
4007 //
4008 // typedef struct {
4009 // char gpr; /* index into the array of 8 GPRs
4010 // * stored in the register save area
4011 // * gpr=0 corresponds to r3,
4012 // * gpr=1 to r4, etc.
4013 // */
4014 // char fpr; /* index into the array of 8 FPRs
4015 // * stored in the register save area
4016 // * fpr=0 corresponds to f1,
4017 // * fpr=1 to f2, etc.
4018 // */
4019 // char *overflow_arg_area;
4020 // /* location on stack that holds
4021 // * the next overflow argument
4022 // */
4023 // char *reg_save_area;
4024 // /* where r3:r10 and f1:f8 (if saved)
4025 // * are stored
4026 // */
4027 // } va_list[1];
4028
4029 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
4030 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
4031 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
4032 PtrVT);
4033 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4034 PtrVT);
4035
4036 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
4037 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
4038
4039 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
4040 SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
4041
4042 uint64_t FPROffset = 1;
4043 SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
4044
4045 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4046
4047 // Store first byte : number of int regs
4048 SDValue firstStore =
4049 DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
4050 MachinePointerInfo(SV), MVT::i8);
4051 uint64_t nextOffset = FPROffset;
4052 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
4053 ConstFPROffset);
4054
4055 // Store second byte : number of float regs
4056 SDValue secondStore =
4057 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
4058 MachinePointerInfo(SV, nextOffset), MVT::i8);
4059 nextOffset += StackOffset;
4060 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
4061
4062 // Store second word : arguments given on stack
4063 SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
4064 MachinePointerInfo(SV, nextOffset));
4065 nextOffset += FrameOffset;
4066 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
4067
4068 // Store third word : arguments given in registers
4069 return DAG.getStore(thirdStore, dl, FR, nextPtr,
4070 MachinePointerInfo(SV, nextOffset));
4071}
4072
4073/// FPR - The set of FP registers that should be allocated for arguments
4074/// on Darwin and AIX.
4075static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5,
4076 PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10,
4077 PPC::F11, PPC::F12, PPC::F13};
4078
4079/// CalculateStackSlotSize - Calculates the size reserved for this argument on
4080/// the stack.
4081static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
4082 unsigned PtrByteSize) {
4083 unsigned ArgSize = ArgVT.getStoreSize();
4084 if (Flags.isByVal())
4085 ArgSize = Flags.getByValSize();
4086
4087 // Round up to multiples of the pointer size, except for array members,
4088 // which are always packed.
4089 if (!Flags.isInConsecutiveRegs())
4090 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4091
4092 return ArgSize;
4093}
4094
4095/// CalculateStackSlotAlignment - Calculates the alignment of this argument
4096/// on the stack.
4098 ISD::ArgFlagsTy Flags,
4099 unsigned PtrByteSize) {
4100 Align Alignment(PtrByteSize);
4101
4102 // Altivec parameters are padded to a 16 byte boundary.
4103 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4104 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4105 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
4106 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
4107 Alignment = Align(16);
4108
4109 // ByVal parameters are aligned as requested.
4110 if (Flags.isByVal()) {
4111 auto BVAlign = Flags.getNonZeroByValAlign();
4112 if (BVAlign > PtrByteSize) {
4113 if (BVAlign.value() % PtrByteSize != 0)
4115 "ByVal alignment is not a multiple of the pointer size");
4116
4117 Alignment = BVAlign;
4118 }
4119 }
4120
4121 // Array members are always packed to their original alignment.
4122 if (Flags.isInConsecutiveRegs()) {
4123 // If the array member was split into multiple registers, the first
4124 // needs to be aligned to the size of the full type. (Except for
4125 // ppcf128, which is only aligned as its f64 components.)
4126 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
4127 Alignment = Align(OrigVT.getStoreSize());
4128 else
4129 Alignment = Align(ArgVT.getStoreSize());
4130 }
4131
4132 return Alignment;
4133}
4134
4135/// CalculateStackSlotUsed - Return whether this argument will use its
4136/// stack slot (instead of being passed in registers). ArgOffset,
4137/// AvailableFPRs, and AvailableVRs must hold the current argument
4138/// position, and will be updated to account for this argument.
4139static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
4140 unsigned PtrByteSize, unsigned LinkageSize,
4141 unsigned ParamAreaSize, unsigned &ArgOffset,
4142 unsigned &AvailableFPRs,
4143 unsigned &AvailableVRs) {
4144 bool UseMemory = false;
4145
4146 // Respect alignment of argument on the stack.
4147 Align Alignment =
4148 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4149 ArgOffset = alignTo(ArgOffset, Alignment);
4150 // If there's no space left in the argument save area, we must
4151 // use memory (this check also catches zero-sized arguments).
4152 if (ArgOffset >= LinkageSize + ParamAreaSize)
4153 UseMemory = true;
4154
4155 // Allocate argument on the stack.
4156 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4157 if (Flags.isInConsecutiveRegsLast())
4158 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4159 // If we overran the argument save area, we must use memory
4160 // (this check catches arguments passed partially in memory)
4161 if (ArgOffset > LinkageSize + ParamAreaSize)
4162 UseMemory = true;
4163
4164 // However, if the argument is actually passed in an FPR or a VR,
4165 // we don't use memory after all.
4166 if (!Flags.isByVal()) {
4167 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
4168 if (AvailableFPRs > 0) {
4169 --AvailableFPRs;
4170 return false;
4171 }
4172 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4173 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4174 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
4175 ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
4176 if (AvailableVRs > 0) {
4177 --AvailableVRs;
4178 return false;
4179 }
4180 }
4181
4182 return UseMemory;
4183}
4184
4185/// EnsureStackAlignment - Round stack frame size up from NumBytes to
4186/// ensure minimum alignment required for target.
4188 unsigned NumBytes) {
4189 return alignTo(NumBytes, Lowering->getStackAlign());
4190}
4191
4192SDValue PPCTargetLowering::LowerFormalArguments(
4193 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4194 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4195 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4196 if (Subtarget.isAIXABI())
4197 return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
4198 InVals);
4199 if (Subtarget.is64BitELFABI())
4200 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4201 InVals);
4202 assert(Subtarget.is32BitELFABI());
4203 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
4204 InVals);
4205}
4206
4207SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
4208 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4209 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4210 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4211
4212 // 32-bit SVR4 ABI Stack Frame Layout:
4213 // +-----------------------------------+
4214 // +--> | Back chain |
4215 // | +-----------------------------------+
4216 // | | Floating-point register save area |
4217 // | +-----------------------------------+
4218 // | | General register save area |
4219 // | +-----------------------------------+
4220 // | | CR save word |
4221 // | +-----------------------------------+
4222 // | | VRSAVE save word |
4223 // | +-----------------------------------+
4224 // | | Alignment padding |
4225 // | +-----------------------------------+
4226 // | | Vector register save area |
4227 // | +-----------------------------------+
4228 // | | Local variable space |
4229 // | +-----------------------------------+
4230 // | | Parameter list area |
4231 // | +-----------------------------------+
4232 // | | LR save word |
4233 // | +-----------------------------------+
4234 // SP--> +--- | Back chain |
4235 // +-----------------------------------+
4236 //
4237 // Specifications:
4238 // System V Application Binary Interface PowerPC Processor Supplement
4239 // AltiVec Technology Programming Interface Manual
4240
4242 MachineFrameInfo &MFI = MF.getFrameInfo();
4243 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4244
4245 EVT PtrVT = getPointerTy(MF.getDataLayout());
4246 // Potential tail calls could cause overwriting of argument stack slots.
4247 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4248 (CallConv == CallingConv::Fast));
4249 const Align PtrAlign(4);
4250
4251 // Assign locations to all of the incoming arguments.
4253 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4254 *DAG.getContext());
4255
4256 // Reserve space for the linkage area on the stack.
4257 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4258 CCInfo.AllocateStack(LinkageSize, PtrAlign);
4259 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
4260
4261 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4262 CCValAssign &VA = ArgLocs[i];
4263
4264 // Arguments stored in registers.
4265 if (VA.isRegLoc()) {
4266 const TargetRegisterClass *RC;
4267 EVT ValVT = VA.getValVT();
4268
4269 switch (ValVT.getSimpleVT().SimpleTy) {
4270 default:
4271 llvm_unreachable("ValVT not supported by formal arguments Lowering");
4272 case MVT::i1:
4273 case MVT::i32:
4274 RC = &PPC::GPRCRegClass;
4275 break;
4276 case MVT::f32:
4277 if (Subtarget.hasP8Vector())
4278 RC = &PPC::VSSRCRegClass;
4279 else if (Subtarget.hasSPE())
4280 RC = &PPC::GPRCRegClass;
4281 else
4282 RC = &PPC::F4RCRegClass;
4283 break;
4284 case MVT::f64:
4285 if (Subtarget.hasVSX())
4286 RC = &PPC::VSFRCRegClass;
4287 else if (Subtarget.hasSPE())
4288 // SPE passes doubles in GPR pairs.
4289 RC = &PPC::GPRCRegClass;
4290 else
4291 RC = &PPC::F8RCRegClass;
4292 break;
4293 case MVT::v16i8:
4294 case MVT::v8i16:
4295 case MVT::v4i32:
4296 case MVT::v4f32:
4297 case MVT::v2f64:
4298 case MVT::v2i64:
4299 case MVT::f128:
4300 RC = &PPC::VRRCRegClass;
4301 break;
4302 }
4303
4304 SDValue ArgValue;
4305 // Transform the arguments stored in physical registers into
4306 // virtual ones.
4307 if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
4308 assert(i + 1 < e && "No second half of double precision argument");
4309 Register RegLo = MF.addLiveIn(VA.getLocReg(), RC);
4310 Register RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
4311 SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
4312 SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
4313 if (!Subtarget.isLittleEndian())
4314 std::swap (ArgValueLo, ArgValueHi);
4315 ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
4316 ArgValueHi);
4317 } else {
4318 Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
4319 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
4320 ValVT == MVT::i1 ? MVT::i32 : ValVT);
4321 if (ValVT == MVT::i1)
4322 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
4323 }
4324
4325 InVals.push_back(ArgValue);
4326 } else {
4327 // Argument stored in memory.
4328 assert(VA.isMemLoc());
4329
4330 // Get the extended size of the argument type in stack
4331 unsigned ArgSize = VA.getLocVT().getStoreSize();
4332 // Get the actual size of the argument type
4333 unsigned ObjSize = VA.getValVT().getStoreSize();
4334 unsigned ArgOffset = VA.getLocMemOffset();
4335 // Stack objects in PPC32 are right justified.
4336 ArgOffset += ArgSize - ObjSize;
4337 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
4338
4339 // Create load nodes to retrieve arguments from the stack.
4340 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4341 InVals.push_back(
4342 DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
4343 }
4344 }
4345
4346 // Assign locations to all of the incoming aggregate by value arguments.
4347 // Aggregates passed by value are stored in the local variable space of the
4348 // caller's stack frame, right above the parameter list area.
4349 SmallVector<CCValAssign, 16> ByValArgLocs;
4350 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4351 ByValArgLocs, *DAG.getContext());
4352
4353 // Reserve stack space for the allocations in CCInfo.
4354 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
4355
4356 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
4357
4358 // Area that is at least reserved in the caller of this function.
4359 unsigned MinReservedArea = CCByValInfo.getStackSize();
4360 MinReservedArea = std::max(MinReservedArea, LinkageSize);
4361
4362 // Set the size that is at least reserved in caller of this function. Tail
4363 // call optimized function's reserved stack space needs to be aligned so that
4364 // taking the difference between two stack areas will result in an aligned
4365 // stack.
4366 MinReservedArea =
4367 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4368 FuncInfo->setMinReservedArea(MinReservedArea);
4369
4371
4372 // If the function takes variable number of arguments, make a frame index for
4373 // the start of the first vararg value... for expansion of llvm.va_start.
4374 if (isVarArg) {
4375 static const MCPhysReg GPArgRegs[] = {
4376 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4377 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4378 };
4379 const unsigned NumGPArgRegs = std::size(GPArgRegs);
4380
4381 static const MCPhysReg FPArgRegs[] = {
4382 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
4383 PPC::F8
4384 };
4385 unsigned NumFPArgRegs = std::size(FPArgRegs);
4386
4387 if (useSoftFloat() || hasSPE())
4388 NumFPArgRegs = 0;
4389
4390 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
4391 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
4392
4393 // Make room for NumGPArgRegs and NumFPArgRegs.
4394 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
4395 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
4396
4398 PtrVT.getSizeInBits() / 8, CCInfo.getStackSize(), true));
4399
4400 FuncInfo->setVarArgsFrameIndex(
4401 MFI.CreateStackObject(Depth, Align(8), false));
4402 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4403
4404 // The fixed integer arguments of a variadic function are stored to the
4405 // VarArgsFrameIndex on the stack so that they may be loaded by
4406 // dereferencing the result of va_next.
4407 for (MCPhysReg GPArgReg : GPArgRegs) {
4408 // Get an existing live-in vreg, or add a new one.
4409 Register VReg = MF.getRegInfo().getLiveInVirtReg(GPArgReg);
4410 if (!VReg)
4411 VReg = MF.addLiveIn(GPArgReg, &PPC::GPRCRegClass);
4412
4413 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4414 SDValue Store =
4415 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4416 MemOps.push_back(Store);
4417 // Increment the address by four for the next argument to store
4418 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4419 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4420 }
4421
4422 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
4423 // is set.
4424 // The double arguments are stored to the VarArgsFrameIndex
4425 // on the stack.
4426 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
4427 // Get an existing live-in vreg, or add a new one.
4428 Register VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
4429 if (!VReg)
4430 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
4431
4432 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
4433 SDValue Store =
4434 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4435 MemOps.push_back(Store);
4436 // Increment the address by eight for the next argument to store
4437 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
4438 PtrVT);
4439 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4440 }
4441 }
4442
4443 if (!MemOps.empty())
4444 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4445
4446 return Chain;
4447}
4448
4449// PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4450// value to MVT::i64 and then truncate to the correct register size.
4451SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
4452 EVT ObjectVT, SelectionDAG &DAG,
4453 SDValue ArgVal,
4454 const SDLoc &dl) const {
4455 if (Flags.isSExt())
4456 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
4457 DAG.getValueType(ObjectVT));
4458 else if (Flags.isZExt())
4459 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
4460 DAG.getValueType(ObjectVT));
4461
4462 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
4463}
4464
4465SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
4466 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4467 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4468 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4469 // TODO: add description of PPC stack frame format, or at least some docs.
4470 //
4471 bool isELFv2ABI = Subtarget.isELFv2ABI();
4472 bool isLittleEndian = Subtarget.isLittleEndian();
4474 MachineFrameInfo &MFI = MF.getFrameInfo();
4475 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4476
4477 assert(!(CallConv == CallingConv::Fast && isVarArg) &&
4478 "fastcc not supported on varargs functions");
4479
4480 EVT PtrVT = getPointerTy(MF.getDataLayout());
4481 // Potential tail calls could cause overwriting of argument stack slots.
4482 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4483 (CallConv == CallingConv::Fast));
4484 unsigned PtrByteSize = 8;
4485 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4486
4487 static const MCPhysReg GPR[] = {
4488 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4489 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4490 };
4491 static const MCPhysReg VR[] = {
4492 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4493 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4494 };
4495
4496 const unsigned Num_GPR_Regs = std::size(GPR);
4497 const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4498 const unsigned Num_VR_Regs = std::size(VR);
4499
4500 // Do a first pass over the arguments to determine whether the ABI
4501 // guarantees that our caller has allocated the parameter save area
4502 // on its stack frame. In the ELFv1 ABI, this is always the case;
4503 // in the ELFv2 ABI, it is true if this is a vararg function or if
4504 // any parameter is located in a stack slot.
4505
4506 bool HasParameterArea = !isELFv2ABI || isVarArg;
4507 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
4508 unsigned NumBytes = LinkageSize;
4509 unsigned AvailableFPRs = Num_FPR_Regs;
4510 unsigned AvailableVRs = Num_VR_Regs;
4511 for (const ISD::InputArg &In : Ins) {
4512 if (In.Flags.isNest())
4513 continue;
4514
4515 if (CalculateStackSlotUsed(In.VT, In.ArgVT, In.Flags, PtrByteSize,
4516 LinkageSize, ParamAreaSize, NumBytes,
4517 AvailableFPRs, AvailableVRs))
4518 HasParameterArea = true;
4519 }
4520
4521 // Add DAG nodes to load the arguments or copy them out of registers. On
4522 // entry to a function on PPC, the arguments start after the linkage area,
4523 // although the first ones are often in registers.
4524
4525 unsigned ArgOffset = LinkageSize;
4526 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4529 unsigned CurArgIdx = 0;
4530 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4531 SDValue ArgVal;
4532 bool needsLoad = false;
4533 EVT ObjectVT = Ins[ArgNo].VT;
4534 EVT OrigVT = Ins[ArgNo].ArgVT;
4535 unsigned ObjSize = ObjectVT.getStoreSize();
4536 unsigned ArgSize = ObjSize;
4537 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4538 if (Ins[ArgNo].isOrigArg()) {
4539 std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4540 CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4541 }
4542 // We re-align the argument offset for each argument, except when using the
4543 // fast calling convention, when we need to make sure we do that only when
4544 // we'll actually use a stack slot.
4545 unsigned CurArgOffset;
4547 auto ComputeArgOffset = [&]() {
4548 /* Respect alignment of argument on the stack. */
4549 Alignment =
4550 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
4551 ArgOffset = alignTo(ArgOffset, Alignment);
4552 CurArgOffset = ArgOffset;
4553 };
4554
4555 if (CallConv != CallingConv::Fast) {
4556 ComputeArgOffset();
4557
4558 /* Compute GPR index associated with argument offset. */
4559 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4560 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
4561 }
4562
4563 // FIXME the codegen can be much improved in some cases.
4564 // We do not have to keep everything in memory.
4565 if (Flags.isByVal()) {
4566 assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4567
4568 if (CallConv == CallingConv::Fast)
4569 ComputeArgOffset();
4570
4571 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4572 ObjSize = Flags.getByValSize();
4573 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4574 // Empty aggregate parameters do not take up registers. Examples:
4575 // struct { } a;
4576 // union { } b;
4577 // int c[0];
4578 // etc. However, we have to provide a place-holder in InVals, so
4579 // pretend we have an 8-byte item at the current address for that
4580 // purpose.
4581 if (!ObjSize) {
4582 int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4583 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4584 InVals.push_back(FIN);
4585 continue;
4586 }
4587
4588 // Create a stack object covering all stack doublewords occupied
4589 // by the argument. If the argument is (fully or partially) on
4590 // the stack, or if the argument is fully in registers but the
4591 // caller has allocated the parameter save anyway, we can refer
4592 // directly to the caller's stack frame. Otherwise, create a
4593 // local copy in our own frame.
4594 int FI;
4595 if (HasParameterArea ||
4596 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
4597 FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
4598 else
4599 FI = MFI.CreateStackObject(ArgSize, Alignment, false);
4600 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4601
4602 // Handle aggregates smaller than 8 bytes.
4603 if (ObjSize < PtrByteSize) {
4604 // The value of the object is its address, which differs from the
4605 // address of the enclosing doubleword on big-endian systems.
4606 SDValue Arg = FIN;
4607 if (!isLittleEndian) {
4608 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
4609 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
4610 }
4611 InVals.push_back(Arg);
4612
4613 if (GPR_idx != Num_GPR_Regs) {
4614 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4615 FuncInfo->addLiveInAttr(VReg, Flags);
4616 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4617 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), ObjSize * 8);
4618 SDValue Store =
4619 DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
4620 MachinePointerInfo(&*FuncArg), ObjType);
4621 MemOps.push_back(Store);
4622 }
4623 // Whether we copied from a register or not, advance the offset
4624 // into the parameter save area by a full doubleword.
4625 ArgOffset += PtrByteSize;
4626 continue;
4627 }
4628
4629 // The value of the object is its address, which is the address of
4630 // its first stack doubleword.
4631 InVals.push_back(FIN);
4632
4633 // Store whatever pieces of the object are in registers to memory.
4634 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4635 if (GPR_idx == Num_GPR_Regs)
4636 break;
4637
4638 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4639 FuncInfo->addLiveInAttr(VReg, Flags);
4640 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4641 SDValue Addr = FIN;
4642 if (j) {
4643 SDValue Off = DAG.getConstant(j, dl, PtrVT);
4644 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
4645 }
4646 unsigned StoreSizeInBits = std::min(PtrByteSize, (ObjSize - j)) * 8;
4647 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), StoreSizeInBits);
4648 SDValue Store =
4649 DAG.getTruncStore(Val.getValue(1), dl, Val, Addr,
4650 MachinePointerInfo(&*FuncArg, j), ObjType);
4651 MemOps.push_back(Store);
4652 ++GPR_idx;
4653 }
4654 ArgOffset += ArgSize;
4655 continue;
4656 }
4657
4658 switch (ObjectVT.getSimpleVT().SimpleTy) {
4659 default: llvm_unreachable("Unhandled argument type!");
4660 case MVT::i1:
4661 case MVT::i32:
4662 case MVT::i64:
4663 if (Flags.isNest()) {
4664 // The 'nest' parameter, if any, is passed in R11.
4665 Register VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4666 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4667
4668 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4669 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4670
4671 break;
4672 }
4673
4674 // These can be scalar arguments or elements of an integer array type
4675 // passed directly. Clang may use those instead of "byval" aggregate
4676 // types to avoid forcing arguments to memory unnecessarily.
4677 if (GPR_idx != Num_GPR_Regs) {
4678 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4679 FuncInfo->addLiveInAttr(VReg, Flags);
4680 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4681
4682 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4683 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4684 // value to MVT::i64 and then truncate to the correct register size.
4685 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4686 } else {
4687 if (CallConv == CallingConv::Fast)
4688 ComputeArgOffset();
4689
4690 needsLoad = true;
4691 ArgSize = PtrByteSize;
4692 }
4693 if (CallConv != CallingConv::Fast || needsLoad)
4694 ArgOffset += 8;
4695 break;
4696
4697 case MVT::f32:
4698 case MVT::f64:
4699 // These can be scalar arguments or elements of a float array type
4700 // passed directly. The latter are used to implement ELFv2 homogenous
4701 // float aggregates.
4702 if (FPR_idx != Num_FPR_Regs) {
4703 unsigned VReg;
4704
4705 if (ObjectVT == MVT::f32)
4706 VReg = MF.addLiveIn(FPR[FPR_idx],
4707 Subtarget.hasP8Vector()
4708 ? &PPC::VSSRCRegClass
4709 : &PPC::F4RCRegClass);
4710 else
4711 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4712 ? &PPC::VSFRCRegClass
4713 : &PPC::F8RCRegClass);
4714
4715 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4716 ++FPR_idx;
4717 } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4718 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4719 // once we support fp <-> gpr moves.
4720
4721 // This can only ever happen in the presence of f32 array types,
4722 // since otherwise we never run out of FPRs before running out
4723 // of GPRs.
4724 Register VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4725 FuncInfo->addLiveInAttr(VReg, Flags);
4726 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4727
4728 if (ObjectVT == MVT::f32) {
4729 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4730 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4731 DAG.getConstant(32, dl, MVT::i32));
4732 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4733 }
4734
4735 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4736 } else {
4737 if (CallConv == CallingConv::Fast)
4738 ComputeArgOffset();
4739
4740 needsLoad = true;
4741 }
4742
4743 // When passing an array of floats, the array occupies consecutive
4744 // space in the argument area; only round up to the next doubleword
4745 // at the end of the array. Otherwise, each float takes 8 bytes.
4746 if (CallConv != CallingConv::Fast || needsLoad) {
4747 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4748 ArgOffset += ArgSize;
4749 if (Flags.isInConsecutiveRegsLast())
4750 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4751 }
4752 break;
4753 case MVT::v4f32:
4754 case MVT::v4i32:
4755 case MVT::v8i16:
4756 case MVT::v16i8:
4757 case MVT::v2f64:
4758 case MVT::v2i64:
4759 case MVT::v1i128:
4760 case MVT::f128:
4761 // These can be scalar arguments or elements of a vector array type
4762 // passed directly. The latter are used to implement ELFv2 homogenous
4763 // vector aggregates.
4764 if (VR_idx != Num_VR_Regs) {
4765 Register VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4766 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4767 ++VR_idx;
4768 } else {
4769 if (CallConv == CallingConv::Fast)
4770 ComputeArgOffset();
4771 needsLoad = true;
4772 }
4773 if (CallConv != CallingConv::Fast || needsLoad)
4774 ArgOffset += 16;
4775 break;
4776 }
4777
4778 // We need to load the argument to a virtual register if we determined
4779 // above that we ran out of physical registers of the appropriate type.
4780 if (needsLoad) {
4781 if (ObjSize < ArgSize && !isLittleEndian)
4782 CurArgOffset += ArgSize - ObjSize;
4783 int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4784 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4785 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4786 }
4787
4788 InVals.push_back(ArgVal);
4789 }
4790
4791 // Area that is at least reserved in the caller of this function.
4792 unsigned MinReservedArea;
4793 if (HasParameterArea)
4794 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4795 else
4796 MinReservedArea = LinkageSize;
4797
4798 // Set the size that is at least reserved in caller of this function. Tail
4799 // call optimized functions' reserved stack space needs to be aligned so that
4800 // taking the difference between two stack areas will result in an aligned
4801 // stack.
4802 MinReservedArea =
4803 EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4804 FuncInfo->setMinReservedArea(MinReservedArea);
4805
4806 // If the function takes variable number of arguments, make a frame index for
4807 // the start of the first vararg value... for expansion of llvm.va_start.
4808 // On ELFv2ABI spec, it writes:
4809 // C programs that are intended to be *portable* across different compilers
4810 // and architectures must use the header file <stdarg.h> to deal with variable
4811 // argument lists.
4812 if (isVarArg && MFI.hasVAStart()) {
4813 int Depth = ArgOffset;
4814
4815 FuncInfo->setVarArgsFrameIndex(
4816 MFI.CreateFixedObject(PtrByteSize, Depth, true));
4817 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4818
4819 // If this function is vararg, store any remaining integer argument regs
4820 // to their spots on the stack so that they may be loaded by dereferencing
4821 // the result of va_next.
4822 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4823 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4824 Register VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4825 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4826 SDValue Store =
4827 DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4828 MemOps.push_back(Store);
4829 // Increment the address by four for the next argument to store
4830 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4831 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4832 }
4833 }
4834
4835 if (!MemOps.empty())
4836 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4837
4838 return Chain;
4839}
4840
4841/// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4842/// adjusted to accommodate the arguments for the tailcall.
4843static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4844 unsigned ParamSize) {
4845
4846 if (!isTailCall) return 0;
4847
4849 unsigned CallerMinReservedArea = FI->getMinReservedArea();
4850 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4851 // Remember only if the new adjustment is bigger.
4852 if (SPDiff < FI->getTailCallSPDelta())
4853 FI->setTailCallSPDelta(SPDiff);
4854
4855 return SPDiff;
4856}
4857
4858static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV);
4859
4860static bool callsShareTOCBase(const Function *Caller,
4861 const GlobalValue *CalleeGV,
4862 const TargetMachine &TM) {
4863 // It does not make sense to call callsShareTOCBase() with a caller that
4864 // is PC Relative since PC Relative callers do not have a TOC.
4865#ifndef NDEBUG
4866 const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4867 assert(!STICaller->isUsingPCRelativeCalls() &&
4868 "PC Relative callers do not have a TOC and cannot share a TOC Base");
4869#endif
4870
4871 // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4872 // don't have enough information to determine if the caller and callee share
4873 // the same TOC base, so we have to pessimistically assume they don't for
4874 // correctness.
4875 if (!CalleeGV)
4876 return false;
4877
4878 // If the callee is preemptable, then the static linker will use a plt-stub
4879 // which saves the toc to the stack, and needs a nop after the call
4880 // instruction to convert to a toc-restore.
4881 if (!TM.shouldAssumeDSOLocal(CalleeGV))
4882 return false;
4883
4884 // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4885 // We may need a TOC restore in the situation where the caller requires a
4886 // valid TOC but the callee is PC Relative and does not.
4887 const Function *F = dyn_cast<Function>(CalleeGV);
4888 const GlobalAlias *Alias = dyn_cast<GlobalAlias>(CalleeGV);
4889
4890 // If we have an Alias we can try to get the function from there.
4891 if (Alias) {
4892 const GlobalObject *GlobalObj = Alias->getAliaseeObject();
4893 F = dyn_cast<Function>(GlobalObj);
4894 }
4895
4896 // If we still have no valid function pointer we do not have enough
4897 // information to determine if the callee uses PC Relative calls so we must
4898 // assume that it does.
4899 if (!F)
4900 return false;
4901
4902 // If the callee uses PC Relative we cannot guarantee that the callee won't
4903 // clobber the TOC of the caller and so we must assume that the two
4904 // functions do not share a TOC base.
4905 const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4906 if (STICallee->isUsingPCRelativeCalls())
4907 return false;
4908
4909 // If the GV is not a strong definition then we need to assume it can be
4910 // replaced by another function at link time. The function that replaces
4911 // it may not share the same TOC as the caller since the callee may be
4912 // replaced by a PC Relative version of the same function.
4913 if (!CalleeGV->isStrongDefinitionForLinker())
4914 return false;
4915
4916 // The medium and large code models are expected to provide a sufficiently
4917 // large TOC to provide all data addressing needs of a module with a
4918 // single TOC.
4919 if (CodeModel::Medium == TM.getCodeModel() ||
4921 return true;
4922
4923 // Any explicitly-specified sections and section prefixes must also match.
4924 // Also, if we're using -ffunction-sections, then each function is always in
4925 // a different section (the same is true for COMDAT functions).
4926 if (TM.getFunctionSections() || CalleeGV->hasComdat() ||
4927 Caller->hasComdat() || CalleeGV->getSection() != Caller->getSection())
4928 return false;
4929 if (const auto *F = dyn_cast<Function>(CalleeGV)) {
4930 if (F->getSectionPrefix() != Caller->getSectionPrefix())
4931 return false;
4932 }
4933
4934 return true;
4935}
4936
4937static bool
4939 const SmallVectorImpl<ISD::OutputArg> &Outs) {
4940 assert(Subtarget.is64BitELFABI());
4941
4942 const unsigned PtrByteSize = 8;
4943 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4944
4945 static const MCPhysReg GPR[] = {
4946 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4947 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4948 };
4949 static const MCPhysReg VR[] = {
4950 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4951 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4952 };
4953
4954 const unsigned NumGPRs = std::size(GPR);
4955 const unsigned NumFPRs = 13;
4956 const unsigned NumVRs = std::size(VR);
4957 const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4958
4959 unsigned NumBytes = LinkageSize;
4960 unsigned AvailableFPRs = NumFPRs;
4961 unsigned AvailableVRs = NumVRs;
4962
4963 for (const ISD::OutputArg& Param : Outs) {
4964 if (Param.Flags.isNest()) continue;
4965
4966 if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4967 LinkageSize, ParamAreaSize, NumBytes,
4968 AvailableFPRs, AvailableVRs))
4969 return true;
4970 }
4971 return false;
4972}
4973
4974static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4975 if (CB.arg_size() != CallerFn->arg_size())
4976 return false;
4977
4978 auto CalleeArgIter = CB.arg_begin();
4979 auto CalleeArgEnd = CB.arg_end();
4980 Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4981
4982 for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4983 const Value* CalleeArg = *CalleeArgIter;
4984 const Value* CallerArg = &(*CallerArgIter);
4985 if (CalleeArg == CallerArg)
4986 continue;
4987
4988 // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4989 // tail call @callee([4 x i64] undef, [4 x i64] %b)
4990 // }
4991 // 1st argument of callee is undef and has the same type as caller.
4992 if (CalleeArg->getType() == CallerArg->getType() &&
4993 isa<UndefValue>(CalleeArg))
4994 continue;
4995
4996 return false;
4997 }
4998
4999 return true;
5000}
5001
5002// Returns true if TCO is possible between the callers and callees
5003// calling conventions.
5004static bool
5006 CallingConv::ID CalleeCC) {
5007 // Tail calls are possible with fastcc and ccc.
5008 auto isTailCallableCC = [] (CallingConv::ID CC){
5009 return CC == CallingConv::C || CC == CallingConv::Fast;
5010 };
5011 if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
5012 return false;
5013
5014 // We can safely tail call both fastcc and ccc callees from a c calling
5015 // convention caller. If the caller is fastcc, we may have less stack space
5016 // than a non-fastcc caller with the same signature so disable tail-calls in
5017 // that case.
5018 return CallerCC == CallingConv::C || CallerCC == CalleeCC;
5019}
5020
5021bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
5022 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5023 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5025 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5026 bool isCalleeExternalSymbol) const {
5027 bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
5028
5029 if (!EnableSCO && !TailCallOpt)
5030 return false;
5031
5032 // Variadic argument functions are not supported.
5033 if (isVarArg) return false;
5034
5035 // Check that the calling conventions are compatible for tco.
5036 if (!areCallingConvEligibleForTCO_64SVR4(CallerCC, CalleeCC))
5037 return false;
5038
5039 // Caller contains any byval parameter is not supported.
5040 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5041 return false;
5042
5043 // Callee contains any byval parameter is not supported, too.
5044 // Note: This is a quick work around, because in some cases, e.g.
5045 // caller's stack size > callee's stack size, we are still able to apply
5046 // sibling call optimization. For example, gcc is able to do SCO for caller1
5047 // in the following example, but not for caller2.
5048 // struct test {
5049 // long int a;
5050 // char ary[56];
5051 // } gTest;
5052 // __attribute__((noinline)) int callee(struct test v, struct test *b) {
5053 // b->a = v.a;
5054 // return 0;
5055 // }
5056 // void caller1(struct test a, struct test c, struct test *b) {
5057 // callee(gTest, b); }
5058 // void caller2(struct test *b) { callee(gTest, b); }
5059 if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
5060 return false;
5061
5062 // If callee and caller use different calling conventions, we cannot pass
5063 // parameters on stack since offsets for the parameter area may be different.
5064 if (CallerCC != CalleeCC && needStackSlotPassParameters(Subtarget, Outs))
5065 return false;
5066
5067 // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
5068 // the caller and callee share the same TOC for TCO/SCO. If the caller and
5069 // callee potentially have different TOC bases then we cannot tail call since
5070 // we need to restore the TOC pointer after the call.
5071 // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
5072 // We cannot guarantee this for indirect calls or calls to external functions.
5073 // When PC-Relative addressing is used, the concept of the TOC is no longer
5074 // applicable so this check is not required.
5075 // Check first for indirect calls.
5076 if (!Subtarget.isUsingPCRelativeCalls() &&
5077 !isFunctionGlobalAddress(CalleeGV) && !isCalleeExternalSymbol)
5078 return false;
5079
5080 // Check if we share the TOC base.
5081 if (!Subtarget.isUsingPCRelativeCalls() &&
5082 !callsShareTOCBase(CallerFunc, CalleeGV, getTargetMachine()))
5083 return false;
5084
5085 // TCO allows altering callee ABI, so we don't have to check further.
5086 if (CalleeCC == CallingConv::Fast && TailCallOpt)
5087 return true;
5088
5089 if (!EnableSCO)
5090 return false;
5091
5092 // If callee use the same argument list that caller is using, then we can
5093 // apply SCO on this case. If it is not, then we need to check if callee needs
5094 // stack for passing arguments.
5095 // PC Relative tail calls may not have a CallBase.
5096 // If there is no CallBase we cannot verify if we have the same argument
5097 // list so assume that we don't have the same argument list.
5098 if (CB && !hasSameArgumentList(CallerFunc, *CB) &&
5099 needStackSlotPassParameters(Subtarget, Outs))
5100 return false;
5101 else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
5102 return false;
5103
5104 return true;
5105}
5106
5107/// IsEligibleForTailCallOptimization - Check whether the call is eligible
5108/// for tail call optimization. Targets which want to do tail call
5109/// optimization should implement this function.
5110bool PPCTargetLowering::IsEligibleForTailCallOptimization(
5111 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5112 CallingConv::ID CallerCC, bool isVarArg,
5113 const SmallVectorImpl<ISD::InputArg> &Ins) const {
5114 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5115 return false;
5116
5117 // Variable argument functions are not supported.
5118 if (isVarArg)
5119 return false;
5120
5121 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
5122 // Functions containing by val parameters are not supported.
5123 if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
5124 return false;
5125
5126 // Non-PIC/GOT tail calls are supported.
5127 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
5128 return true;
5129
5130 // At the moment we can only do local tail calls (in same module, hidden
5131 // or protected) if we are generating PIC.
5132 if (CalleeGV)
5133 return CalleeGV->hasHiddenVisibility() ||
5134 CalleeGV->hasProtectedVisibility();
5135 }
5136
5137 return false;
5138}
5139
5140/// isCallCompatibleAddress - Return the immediate to use if the specified
5141/// 32-bit value is representable in the immediate field of a BxA instruction.
5144 if (!C) return nullptr;
5145
5146 int Addr = C->getZExtValue();
5147 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
5148 SignExtend32<26>(Addr) != Addr)
5149 return nullptr; // Top 6 bits have to be sext of immediate.
5150
5151 return DAG
5153 (int)C->getZExtValue() >> 2, SDLoc(Op),
5155 .getNode();
5156}
5157
5158namespace {
5159
5160struct TailCallArgumentInfo {
5161 SDValue Arg;
5162 SDValue FrameIdxOp;
5163 int FrameIdx = 0;
5164
5165 TailCallArgumentInfo() = default;
5166};
5167
5168} // end anonymous namespace
5169
5170/// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
5172 SelectionDAG &DAG, SDValue Chain,
5173 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
5174 SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
5175 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
5176 SDValue Arg = TailCallArgs[i].Arg;
5177 SDValue FIN = TailCallArgs[i].FrameIdxOp;
5178 int FI = TailCallArgs[i].FrameIdx;
5179 // Store relative to framepointer.
5180 MemOpChains.push_back(DAG.getStore(
5181 Chain, dl, Arg, FIN,
5183 }
5184}
5185
5186/// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
5187/// the appropriate stack slot for the tail call optimized function call.
5189 SDValue OldRetAddr, SDValue OldFP,
5190 int SPDiff, const SDLoc &dl) {
5191 if (SPDiff) {
5192 // Calculate the new stack slot for the return address.
5194 const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
5195 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
5196 int SlotSize = Subtarget.isPPC64() ? 8 : 4;
5197 int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
5198 int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
5199 NewRetAddrLoc, true);
5200 SDValue NewRetAddrFrIdx =
5201 DAG.getFrameIndex(NewRetAddr, Subtarget.getScalarIntVT());
5202 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
5203 MachinePointerInfo::getFixedStack(MF, NewRetAddr));
5204 }
5205 return Chain;
5206}
5207
5208/// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
5209/// the position of the argument.
5211 SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg,
5212 int SPDiff, unsigned ArgOffset,
5213 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5214 int Offset = ArgOffset + SPDiff;
5215 uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
5216 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
5217 EVT VT = IsPPC64 ? MVT::i64 : MVT::i32;
5218 SDValue FIN = DAG.getFrameIndex(FI, VT);
5219 TailCallArgumentInfo Info;
5220 Info.Arg = Arg;
5221 Info.FrameIdxOp = FIN;
5222 Info.FrameIdx = FI;
5223 TailCallArguments.push_back(Info);
5224}
5225
5226/// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
5227/// stack slot. Returns the chain as result and the loaded frame pointers in
5228/// LROpOut/FPOpout. Used when tail calling.
5229SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
5230 SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
5231 SDValue &FPOpOut, const SDLoc &dl) const {
5232 if (SPDiff) {
5233 // Load the LR and FP stack slot for later adjusting.
5234 LROpOut = getReturnAddrFrameIndex(DAG);
5235 LROpOut = DAG.getLoad(Subtarget.getScalarIntVT(), dl, Chain, LROpOut,
5236 MachinePointerInfo());
5237 Chain = SDValue(LROpOut.getNode(), 1);
5238 }
5239 return Chain;
5240}
5241
5242/// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
5243/// by "Src" to address "Dst" of size "Size". Alignment information is
5244/// specified by the specific parameter attribute. The copy will be passed as
5245/// a byval function parameter.
5246/// Sometimes what we are copying is the end of a larger object, the part that
5247/// does not fit in registers.
5249 SDValue Chain, ISD::ArgFlagsTy Flags,
5250 SelectionDAG &DAG, const SDLoc &dl) {
5251 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
5252 Align Alignment = Flags.getNonZeroByValAlign();
5253 return DAG.getMemcpy(
5254 Chain, dl, Dst, Src, SizeNode, Alignment, Alignment, false, false,
5255 /*CI=*/nullptr, std::nullopt, MachinePointerInfo(), MachinePointerInfo());
5256}
5257
5258/// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
5259/// tail calls.
5261 SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
5262 SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
5263 bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
5264 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
5266 if (!isTailCall) {
5267 if (isVector) {
5268 SDValue StackPtr;
5269 if (isPPC64)
5270 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5271 else
5272 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5273 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5274 DAG.getConstant(ArgOffset, dl, PtrVT));
5275 }
5276 MemOpChains.push_back(
5277 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5278 // Calculate and remember argument location.
5279 } else
5280 CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
5281 TailCallArguments);
5282}
5283
5284static void
5286 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
5287 SDValue FPOp,
5288 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
5289 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
5290 // might overwrite each other in case of tail call optimization.
5291 SmallVector<SDValue, 8> MemOpChains2;
5292 // Do not flag preceding copytoreg stuff together with the following stuff.
5293 InGlue = SDValue();
5294 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5295 MemOpChains2, dl);
5296 if (!MemOpChains2.empty())
5297 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5298
5299 // Store the return address to the appropriate stack slot.
5300 Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5301
5302 // Emit callseq_end just before tailcall node.
5303 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, InGlue, dl);
5304 InGlue = Chain.getValue(1);
5305}
5306
5307// Is this global address that of a function that can be called by name? (as
5308// opposed to something that must hold a descriptor for an indirect call).
5309static bool isFunctionGlobalAddress(const GlobalValue *GV) {
5310 if (GV) {
5311 if (GV->isThreadLocal())
5312 return false;
5313
5314 return GV->getValueType()->isFunctionTy();
5315 }
5316
5317 return false;
5318}
5319
5320SDValue PPCTargetLowering::LowerCallResult(
5321 SDValue Chain, SDValue InGlue, CallingConv::ID CallConv, bool isVarArg,
5322 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5323 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5325 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5326 *DAG.getContext());
5327
5328 CCRetInfo.AnalyzeCallResult(
5329 Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5331 : RetCC_PPC);
5332
5333 // Copy all of the result registers out of their specified physreg.
5334 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5335 CCValAssign &VA = RVLocs[i];
5336 assert(VA.isRegLoc() && "Can only return in registers!");
5337
5338 SDValue Val;
5339
5340 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5341 SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5342 InGlue);
5343 Chain = Lo.getValue(1);
5344 InGlue = Lo.getValue(2);
5345 VA = RVLocs[++i]; // skip ahead to next loc
5346 SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5347 InGlue);
5348 Chain = Hi.getValue(1);
5349 InGlue = Hi.getValue(2);
5350 if (!Subtarget.isLittleEndian())
5351 std::swap (Lo, Hi);
5352 Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5353 } else {
5354 Val = DAG.getCopyFromReg(Chain, dl,
5355 VA.getLocReg(), VA.getLocVT(), InGlue);
5356 Chain = Val.getValue(1);
5357 InGlue = Val.getValue(2);
5358 }
5359
5360 switch (VA.getLocInfo()) {
5361 default: llvm_unreachable("Unknown loc info!");
5362 case CCValAssign::Full: break;
5363 case CCValAssign::AExt:
5364 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5365 break;
5366 case CCValAssign::ZExt:
5367 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5368 DAG.getValueType(VA.getValVT()));
5369 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5370 break;
5371 case CCValAssign::SExt:
5372 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5373 DAG.getValueType(VA.getValVT()));
5374 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5375 break;
5376 }
5377
5378 InVals.push_back(Val);
5379 }
5380
5381 return Chain;
5382}
5383
5384static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5385 const PPCSubtarget &Subtarget, bool isPatchPoint) {
5386 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5387 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5388
5389 // PatchPoint calls are not indirect.
5390 if (isPatchPoint)
5391 return false;
5392
5394 return false;
5395
5396 // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5397 // becuase the immediate function pointer points to a descriptor instead of
5398 // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5399 // pointer immediate points to the global entry point, while the BLA would
5400 // need to jump to the local entry point (see rL211174).
5401 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5402 isBLACompatibleAddress(Callee, DAG))
5403 return false;
5404
5405 return true;
5406}
5407
5408// AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5409static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5410 return Subtarget.isAIXABI() ||
5411 (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5412}
5413
5415 const Function &Caller, const SDValue &Callee,
5416 const PPCSubtarget &Subtarget,
5417 const TargetMachine &TM,
5418 bool IsStrictFPCall = false) {
5419 if (CFlags.IsTailCall)
5420 return PPCISD::TC_RETURN;
5421
5422 unsigned RetOpc = 0;
5423 // This is a call through a function pointer.
5424 if (CFlags.IsIndirect) {
5425 // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5426 // indirect calls. The save of the caller's TOC pointer to the stack will be
5427 // inserted into the DAG as part of call lowering. The restore of the TOC
5428 // pointer is modeled by using a pseudo instruction for the call opcode that
5429 // represents the 2 instruction sequence of an indirect branch and link,
5430 // immediately followed by a load of the TOC pointer from the stack save
5431 // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5432 // as it is not saved or used.
5433 if (Subtarget.usePointerGlueHelper())
5434 RetOpc = PPCISD::BL_LOAD_TOC;
5435 else
5436 RetOpc = isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5437 : PPCISD::BCTRL;
5438 } else if (Subtarget.isUsingPCRelativeCalls()) {
5439 assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5440 RetOpc = PPCISD::CALL_NOTOC;
5441 } else if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI()) {
5442 // The ABIs that maintain a TOC pointer accross calls need to have a nop
5443 // immediately following the call instruction if the caller and callee may
5444 // have different TOC bases. At link time if the linker determines the calls
5445 // may not share a TOC base, the call is redirected to a trampoline inserted
5446 // by the linker. The trampoline will (among other things) save the callers
5447 // TOC pointer at an ABI designated offset in the linkage area and the
5448 // linker will rewrite the nop to be a load of the TOC pointer from the
5449 // linkage area into gpr2.
5450 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5451 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5452 RetOpc =
5453 callsShareTOCBase(&Caller, GV, TM) ? PPCISD::CALL : PPCISD::CALL_NOP;
5454 } else
5455 RetOpc = PPCISD::CALL;
5456 if (IsStrictFPCall) {
5457 switch (RetOpc) {
5458 default:
5459 llvm_unreachable("Unknown call opcode");
5460 case PPCISD::BCTRL_LOAD_TOC:
5461 RetOpc = PPCISD::BCTRL_LOAD_TOC_RM;
5462 break;
5463 case PPCISD::BCTRL:
5464 RetOpc = PPCISD::BCTRL_RM;
5465 break;
5466 case PPCISD::BL_LOAD_TOC:
5467 RetOpc = PPCISD::BL_LOAD_TOC_RM;
5468 break;
5469 case PPCISD::CALL_NOTOC:
5470 RetOpc = PPCISD::CALL_NOTOC_RM;
5471 break;
5472 case PPCISD::CALL:
5473 RetOpc = PPCISD::CALL_RM;
5474 break;
5475 case PPCISD::CALL_NOP:
5476 RetOpc = PPCISD::CALL_NOP_RM;
5477 break;
5478 }
5479 }
5480 return RetOpc;
5481}
5482
5483static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5484 const SDLoc &dl, const PPCSubtarget &Subtarget) {
5485 if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5486 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5487 return SDValue(Dest, 0);
5488
5489 // Returns true if the callee is local, and false otherwise.
5490 auto isLocalCallee = [&]() {
5492 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5493
5494 return DAG.getTarget().shouldAssumeDSOLocal(GV) &&
5496 };
5497
5498 // The PLT is only used in 32-bit ELF PIC mode. Attempting to use the PLT in
5499 // a static relocation model causes some versions of GNU LD (2.17.50, at
5500 // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5501 // built with secure-PLT.
5502 bool UsePlt =
5503 Subtarget.is32BitELFABI() && !isLocalCallee() &&
5505
5506 const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5507 const TargetMachine &TM = Subtarget.getTargetMachine();
5509 auto *S =
5510 static_cast<MCSymbolXCOFF *>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5511
5513 return DAG.getMCSymbol(S, PtrVT);
5514 };
5515
5516 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5517 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5518 if (isFunctionGlobalAddress(GV)) {
5519 const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5520
5521 if (Subtarget.isAIXABI()) {
5522 return getAIXFuncEntryPointSymbolSDNode(GV);
5523 }
5524 return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5525 UsePlt ? PPCII::MO_PLT : 0);
5526 }
5527
5529 const char *SymName = S->getSymbol();
5530 if (Subtarget.isAIXABI()) {
5531 // If there exists a user-declared function whose name is the same as the
5532 // ExternalSymbol's, then we pick up the user-declared version.
5534 if (const Function *F =
5535 dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5536 return getAIXFuncEntryPointSymbolSDNode(F);
5537
5538 // On AIX, direct function calls reference the symbol for the function's
5539 // entry point, which is named by prepending a "." before the function's
5540 // C-linkage name. A Qualname is returned here because an external
5541 // function entry point is a csect with XTY_ER property.
5542 const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5543 auto &Context = DAG.getMachineFunction().getContext();
5544 MCSectionXCOFF *Sec = Context.getXCOFFSection(
5545 (Twine(".") + Twine(SymName)).str(), SectionKind::getMetadata(),
5547 return Sec->getQualNameSymbol();
5548 };
5549
5550 SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5551 }
5552 return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5553 UsePlt ? PPCII::MO_PLT : 0);
5554 }
5555
5556 // No transformation needed.
5557 assert(Callee.getNode() && "What no callee?");
5558 return Callee;
5559}
5560
5562 assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5563 "Expected a CALLSEQ_STARTSDNode.");
5564
5565 // The last operand is the chain, except when the node has glue. If the node
5566 // has glue, then the last operand is the glue, and the chain is the second
5567 // last operand.
5568 SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5569 if (LastValue.getValueType() != MVT::Glue)
5570 return LastValue;
5571
5572 return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5573}
5574
5575// Creates the node that moves a functions address into the count register
5576// to prepare for an indirect call instruction.
5577static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5578 SDValue &Glue, SDValue &Chain,
5579 const SDLoc &dl) {
5580 SDValue MTCTROps[] = {Chain, Callee, Glue};
5581 EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5582 Chain = DAG.getNode(PPCISD::MTCTR, dl, ReturnTypes,
5583 ArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5584 // The glue is the second value produced.
5585 Glue = Chain.getValue(1);
5586}
5587
5589 SDValue &Glue, SDValue &Chain,
5590 SDValue CallSeqStart,
5591 const CallBase *CB, const SDLoc &dl,
5592 bool hasNest,
5593 const PPCSubtarget &Subtarget) {
5594 // Function pointers in the 64-bit SVR4 ABI do not point to the function
5595 // entry point, but to the function descriptor (the function entry point
5596 // address is part of the function descriptor though).
5597 // The function descriptor is a three doubleword structure with the
5598 // following fields: function entry point, TOC base address and
5599 // environment pointer.
5600 // Thus for a call through a function pointer, the following actions need
5601 // to be performed:
5602 // 1. Save the TOC of the caller in the TOC save area of its stack
5603 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5604 // 2. Load the address of the function entry point from the function
5605 // descriptor.
5606 // 3. Load the TOC of the callee from the function descriptor into r2.
5607 // 4. Load the environment pointer from the function descriptor into
5608 // r11.
5609 // 5. Branch to the function entry point address.
5610 // 6. On return of the callee, the TOC of the caller needs to be
5611 // restored (this is done in FinishCall()).
5612 //
5613 // The loads are scheduled at the beginning of the call sequence, and the
5614 // register copies are flagged together to ensure that no other
5615 // operations can be scheduled in between. E.g. without flagging the
5616 // copies together, a TOC access in the caller could be scheduled between
5617 // the assignment of the callee TOC and the branch to the callee, which leads
5618 // to incorrect code.
5619
5620 // Start by loading the function address from the descriptor.
5621 SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5622 auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5626
5627 MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5628
5629 // Registers used in building the DAG.
5630 const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5631 const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5632
5633 // Offsets of descriptor members.
5634 const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5635 const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5636
5637 const MVT RegVT = Subtarget.getScalarIntVT();
5638 const Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
5639
5640 // One load for the functions entry point address.
5641 SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5642 Alignment, MMOFlags);
5643
5644 // One for loading the TOC anchor for the module that contains the called
5645 // function.
5646 SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5647 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5648 SDValue TOCPtr =
5649 DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5650 MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5651
5652 // One for loading the environment pointer.
5653 SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5654 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5655 SDValue LoadEnvPtr =
5656 DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5657 MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5658
5659
5660 // Then copy the newly loaded TOC anchor to the TOC pointer.
5661 SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5662 Chain = TOCVal.getValue(0);
5663 Glue = TOCVal.getValue(1);
5664
5665 // If the function call has an explicit 'nest' parameter, it takes the
5666 // place of the environment pointer.
5667 assert((!hasNest || !Subtarget.isAIXABI()) &&
5668 "Nest parameter is not supported on AIX.");
5669 if (!hasNest) {
5670 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5671 Chain = EnvVal.getValue(0);
5672 Glue = EnvVal.getValue(1);
5673 }
5674
5675 // The rest of the indirect call sequence is the same as the non-descriptor
5676 // DAG.
5677 prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5678}
5679
5681 SDValue &Glue, SDValue &Chain,
5682 SDValue CallSeqStart, const CallBase *CB,
5683 const SDLoc &dl, bool hasNest,
5684 const PPCSubtarget &Subtarget) {
5685 // On AIX there is a feature ("out of line glue code") which uses a special
5686 // trampoline function ._ptrgl to do the indirect call. If this option is
5687 // enabled we instead simply load the address of the descriptor into gpr11,
5688 // with the arguments in the 'normal' registers and branch to the ._ptrgl
5689 // stub.
5690 const MCRegister PtrGlueReg = Subtarget.getGlueCodeDescriptorRegister();
5691 SDValue MoveToPhysicalReg =
5692 DAG.getCopyToReg(Chain, dl, PtrGlueReg, Callee, Glue);
5693 Chain = MoveToPhysicalReg.getValue(0);
5694 Glue = MoveToPhysicalReg.getValue(1);
5695}
5696
5697static void
5699 PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5700 SelectionDAG &DAG,
5701 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5702 SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5703 const PPCSubtarget &Subtarget) {
5704 const bool IsPPC64 = Subtarget.isPPC64();
5705 // MVT for a general purpose register.
5706 const MVT RegVT = Subtarget.getScalarIntVT();
5707
5708 // First operand is always the chain.
5709 Ops.push_back(Chain);
5710
5711 // If it's a direct call pass the callee as the second operand.
5712 if (!CFlags.IsIndirect)
5713 Ops.push_back(Callee);
5714 else if (Subtarget.usePointerGlueHelper()) {
5715 Ops.push_back(Callee);
5716 // Add the register used to pass the descriptor address.
5717 Ops.push_back(
5718 DAG.getRegister(Subtarget.getGlueCodeDescriptorRegister(), RegVT));
5719 } else {
5720 assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5721
5722 // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5723 // on the stack (this would have been done in `LowerCall_64SVR4` or
5724 // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5725 // represents both the indirect branch and a load that restores the TOC
5726 // pointer from the linkage area. The operand for the TOC restore is an add
5727 // of the TOC save offset to the stack pointer. This must be the second
5728 // operand: after the chain input but before any other variadic arguments.
5729 // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5730 // saved or used.
5731 if (isTOCSaveRestoreRequired(Subtarget)) {
5732 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5733
5734 SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5735 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5736 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5737 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5738 Ops.push_back(AddTOC);
5739 }
5740
5741 // Add the register used for the environment pointer.
5742 if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5743 Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5744 RegVT));
5745
5746
5747 // Add CTR register as callee so a bctr can be emitted later.
5748 if (CFlags.IsTailCall)
5749 Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5750 }
5751
5752 // If this is a tail call add stack pointer delta.
5753 if (CFlags.IsTailCall)
5754 Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5755
5756 // Add argument registers to the end of the list so that they are known live
5757 // into the call.
5758 for (const auto &[Reg, N] : RegsToPass)
5759 Ops.push_back(DAG.getRegister(Reg, N.getValueType()));
5760
5761 // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5762 // no way to mark dependencies as implicit here.
5763 // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5764 if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5765 !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5766 Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5767
5768 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5769 if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5770 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5771
5772 // Add a register mask operand representing the call-preserved registers.
5773 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5774 const uint32_t *Mask =
5775 TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5776 assert(Mask && "Missing call preserved mask for calling convention");
5777 Ops.push_back(DAG.getRegisterMask(Mask));
5778
5779 // If the glue is valid, it is the last operand.
5780 if (Glue.getNode())
5781 Ops.push_back(Glue);
5782}
5783
5784SDValue PPCTargetLowering::FinishCall(
5785 CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5786 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5787 SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5788 unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5789 SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5790
5791 if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5792 Subtarget.isAIXABI())
5793 setUsesTOCBasePtr(DAG);
5794
5795 unsigned CallOpc =
5796 getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5797 Subtarget, DAG.getTarget(), CB ? CB->isStrictFP() : false);
5798
5799 if (!CFlags.IsIndirect)
5800 Callee = transformCallee(Callee, DAG, dl, Subtarget);
5801 else if (Subtarget.usesFunctionDescriptors()) {
5802 if (Subtarget.usePointerGlueHelper()) {
5803 prepareOutOfLineGlueCall(DAG, Callee, Glue, Chain, CallSeqStart, CB, dl,
5804 CFlags.HasNest, Subtarget);
5805 SDValue PtrGlueCallee =
5806 DAG.getExternalSymbol("_ptrgl", getPointerTy(DAG.getDataLayout()));
5807 Callee = transformCallee(PtrGlueCallee, DAG, dl, Subtarget);
5808 } else {
5809 prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5810 dl, CFlags.HasNest, Subtarget);
5811 }
5812 } else {
5813 prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5814 }
5815
5816 // Build the operand list for the call instruction.
5818 buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5819 SPDiff, Subtarget);
5820
5821 // Emit tail call.
5822 if (CFlags.IsTailCall) {
5823 // Indirect tail call when using PC Relative calls do not have the same
5824 // constraints.
5825 assert(((Callee.getOpcode() == ISD::Register &&
5826 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5827 Callee.getOpcode() == ISD::TargetExternalSymbol ||
5828 Callee.getOpcode() == ISD::TargetGlobalAddress ||
5829 isa<ConstantSDNode>(Callee) ||
5830 (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5831 "Expecting a global address, external symbol, absolute value, "
5832 "register or an indirect tail call when PC Relative calls are "
5833 "used.");
5834 // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5835 assert(CallOpc == PPCISD::TC_RETURN &&
5836 "Unexpected call opcode for a tail call.");
5838 SDValue Ret = DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5839 DAG.addNoMergeSiteInfo(Ret.getNode(), CFlags.NoMerge);
5840 return Ret;
5841 }
5842
5843 std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5844 Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5845 DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5846 Glue = Chain.getValue(1);
5847
5848 // When performing tail call optimization the callee pops its arguments off
5849 // the stack. Account for this here so these bytes can be pushed back on in
5850 // PPCFrameLowering::eliminateCallFramePseudoInstr.
5851 int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5853 ? NumBytes
5854 : 0;
5855
5856 Chain = DAG.getCALLSEQ_END(Chain, NumBytes, BytesCalleePops, Glue, dl);
5857 Glue = Chain.getValue(1);
5858
5859 return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5860 DAG, InVals);
5861}
5862
5864 CallingConv::ID CalleeCC = CB->getCallingConv();
5865 const Function *CallerFunc = CB->getCaller();
5866 CallingConv::ID CallerCC = CallerFunc->getCallingConv();
5867 const Function *CalleeFunc = CB->getCalledFunction();
5868 if (!CalleeFunc)
5869 return false;
5870 const GlobalValue *CalleeGV = dyn_cast<GlobalValue>(CalleeFunc);
5871
5874
5875 GetReturnInfo(CalleeCC, CalleeFunc->getReturnType(),
5876 CalleeFunc->getAttributes(), Outs, *this,
5877 CalleeFunc->getDataLayout());
5878
5879 return isEligibleForTCO(CalleeGV, CalleeCC, CallerCC, CB,
5880 CalleeFunc->isVarArg(), Outs, Ins, CallerFunc,
5881 false /*isCalleeExternalSymbol*/);
5882}
5883
5884bool PPCTargetLowering::isEligibleForTCO(
5885 const GlobalValue *CalleeGV, CallingConv::ID CalleeCC,
5886 CallingConv::ID CallerCC, const CallBase *CB, bool isVarArg,
5888 const SmallVectorImpl<ISD::InputArg> &Ins, const Function *CallerFunc,
5889 bool isCalleeExternalSymbol) const {
5890 if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5891 return false;
5892
5893 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5894 return IsEligibleForTailCallOptimization_64SVR4(
5895 CalleeGV, CalleeCC, CallerCC, CB, isVarArg, Outs, Ins, CallerFunc,
5896 isCalleeExternalSymbol);
5897 else
5898 return IsEligibleForTailCallOptimization(CalleeGV, CalleeCC, CallerCC,
5899 isVarArg, Ins);
5900}
5901
5902SDValue
5903PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5904 SmallVectorImpl<SDValue> &InVals) const {
5905 SelectionDAG &DAG = CLI.DAG;
5906 SDLoc &dl = CLI.DL;
5908 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
5910 SDValue Chain = CLI.Chain;
5911 SDValue Callee = CLI.Callee;
5912 bool &isTailCall = CLI.IsTailCall;
5913 CallingConv::ID CallConv = CLI.CallConv;
5914 bool isVarArg = CLI.IsVarArg;
5915 bool isPatchPoint = CLI.IsPatchPoint;
5916 const CallBase *CB = CLI.CB;
5917
5918 if (isTailCall) {
5920 CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
5921 auto *G = dyn_cast<GlobalAddressSDNode>(Callee);
5922 const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5923 bool IsCalleeExternalSymbol = isa<ExternalSymbolSDNode>(Callee);
5924
5925 isTailCall =
5926 isEligibleForTCO(GV, CallConv, CallerCC, CB, isVarArg, Outs, Ins,
5927 &(MF.getFunction()), IsCalleeExternalSymbol);
5928 if (isTailCall) {
5929 ++NumTailCalls;
5930 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5931 ++NumSiblingCalls;
5932
5933 // PC Relative calls no longer guarantee that the callee is a Global
5934 // Address Node. The callee could be an indirect tail call in which
5935 // case the SDValue for the callee could be a load (to load the address
5936 // of a function pointer) or it may be a register copy (to move the
5937 // address of the callee from a function parameter into a virtual
5938 // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5939 assert((Subtarget.isUsingPCRelativeCalls() ||
5940 isa<GlobalAddressSDNode>(Callee)) &&
5941 "Callee should be an llvm::Function object.");
5942
5943 LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5944 << "\nTCO callee: ");
5945 LLVM_DEBUG(Callee.dump());
5946 }
5947 }
5948
5949 if (!isTailCall && CB && CB->isMustTailCall())
5950 report_fatal_error("failed to perform tail call elimination on a call "
5951 "site marked musttail");
5952
5953 // When long calls (i.e. indirect calls) are always used, calls are always
5954 // made via function pointer. If we have a function name, first translate it
5955 // into a pointer.
5956 if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5957 !isTailCall)
5958 Callee = LowerGlobalAddress(Callee, DAG);
5959
5960 CallFlags CFlags(
5961 CallConv, isTailCall, isVarArg, isPatchPoint,
5962 isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5963 // hasNest
5964 Subtarget.is64BitELFABI() &&
5965 any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5966 CLI.NoMerge);
5967
5968 if (Subtarget.isAIXABI())
5969 return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5970 InVals, CB);
5971
5972 assert(Subtarget.isSVR4ABI());
5973 if (Subtarget.isPPC64())
5974 return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5975 InVals, CB);
5976 return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5977 InVals, CB);
5978}
5979
5980SDValue PPCTargetLowering::LowerCall_32SVR4(
5981 SDValue Chain, SDValue Callee, CallFlags CFlags,
5983 const SmallVectorImpl<SDValue> &OutVals,
5984 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5986 const CallBase *CB) const {
5987 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5988 // of the 32-bit SVR4 ABI stack frame layout.
5989
5990 const CallingConv::ID CallConv = CFlags.CallConv;
5991 const bool IsVarArg = CFlags.IsVarArg;
5992 const bool IsTailCall = CFlags.IsTailCall;
5993
5994 assert((CallConv == CallingConv::C ||
5995 CallConv == CallingConv::Cold ||
5996 CallConv == CallingConv::Fast) && "Unknown calling convention!");
5997
5998 const Align PtrAlign(4);
5999
6001
6002 // Mark this function as potentially containing a function that contains a
6003 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6004 // and restoring the callers stack pointer in this functions epilog. This is
6005 // done because by tail calling the called function might overwrite the value
6006 // in this function's (MF) stack pointer stack slot 0(SP).
6007 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6008 CallConv == CallingConv::Fast)
6009 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6010
6011 // Count how many bytes are to be pushed on the stack, including the linkage
6012 // area, parameter list area and the part of the local variable space which
6013 // contains copies of aggregates which are passed by value.
6014
6015 // Assign locations to all of the outgoing arguments.
6017 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
6018
6019 // Reserve space for the linkage area on the stack.
6020 CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
6021 PtrAlign);
6022
6023 if (IsVarArg) {
6024 // Handle fixed and variable vector arguments differently.
6025 // Fixed vector arguments go into registers as long as registers are
6026 // available. Variable vector arguments always go into memory.
6027 unsigned NumArgs = Outs.size();
6028
6029 for (unsigned i = 0; i != NumArgs; ++i) {
6030 MVT ArgVT = Outs[i].VT;
6031 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
6032 bool Result;
6033
6034 if (!ArgFlags.isVarArg()) {
6035 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
6036 Outs[i].OrigTy, CCInfo);
6037 } else {
6039 ArgFlags, Outs[i].OrigTy, CCInfo);
6040 }
6041
6042 if (Result) {
6043#ifndef NDEBUG
6044 errs() << "Call operand #" << i << " has unhandled type "
6045 << ArgVT << "\n";
6046#endif
6047 llvm_unreachable(nullptr);
6048 }
6049 }
6050 } else {
6051 // All arguments are treated the same.
6052 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
6053 }
6054
6055 // Assign locations to all of the outgoing aggregate by value arguments.
6056 SmallVector<CCValAssign, 16> ByValArgLocs;
6057 CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
6058
6059 // Reserve stack space for the allocations in CCInfo.
6060 CCByValInfo.AllocateStack(CCInfo.getStackSize(), PtrAlign);
6061
6062 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
6063
6064 // Size of the linkage area, parameter list area and the part of the local
6065 // space variable where copies of aggregates which are passed by value are
6066 // stored.
6067 unsigned NumBytes = CCByValInfo.getStackSize();
6068
6069 // Calculate by how many bytes the stack has to be adjusted in case of tail
6070 // call optimization.
6071 int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
6072
6073 // Adjust the stack pointer for the new arguments...
6074 // These operations are automatically eliminated by the prolog/epilog pass
6075 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6076 SDValue CallSeqStart = Chain;
6077
6078 // Load the return address and frame pointer so it can be moved somewhere else
6079 // later.
6080 SDValue LROp, FPOp;
6081 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6082
6083 // Set up a copy of the stack pointer for use loading and storing any
6084 // arguments that may not fit in the registers available for argument
6085 // passing.
6086 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6087
6089 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6090 SmallVector<SDValue, 8> MemOpChains;
6091
6092 bool seenFloatArg = false;
6093 // Walk the register/memloc assignments, inserting copies/loads.
6094 // i - Tracks the index into the list of registers allocated for the call
6095 // RealArgIdx - Tracks the index into the list of actual function arguments
6096 // j - Tracks the index into the list of byval arguments
6097 for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
6098 i != e;
6099 ++i, ++RealArgIdx) {
6100 CCValAssign &VA = ArgLocs[i];
6101 SDValue Arg = OutVals[RealArgIdx];
6102 ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
6103
6104 if (Flags.isByVal()) {
6105 // Argument is an aggregate which is passed by value, thus we need to
6106 // create a copy of it in the local variable space of the current stack
6107 // frame (which is the stack frame of the caller) and pass the address of
6108 // this copy to the callee.
6109 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
6110 CCValAssign &ByValVA = ByValArgLocs[j++];
6111 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
6112
6113 // Memory reserved in the local variable space of the callers stack frame.
6114 unsigned LocMemOffset = ByValVA.getLocMemOffset();
6115
6116 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6117 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6118 StackPtr, PtrOff);
6119
6120 // Create a copy of the argument in the local area of the current
6121 // stack frame.
6122 SDValue MemcpyCall =
6123 CreateCopyOfByValArgument(Arg, PtrOff,
6124 CallSeqStart.getNode()->getOperand(0),
6125 Flags, DAG, dl);
6126
6127 // This must go outside the CALLSEQ_START..END.
6128 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
6129 SDLoc(MemcpyCall));
6130 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6131 NewCallSeqStart.getNode());
6132 Chain = CallSeqStart = NewCallSeqStart;
6133
6134 // Pass the address of the aggregate copy on the stack either in a
6135 // physical register or in the parameter list area of the current stack
6136 // frame to the callee.
6137 Arg = PtrOff;
6138 }
6139
6140 // When useCRBits() is true, there can be i1 arguments.
6141 // It is because getRegisterType(MVT::i1) => MVT::i1,
6142 // and for other integer types getRegisterType() => MVT::i32.
6143 // Extend i1 and ensure callee will get i32.
6144 if (Arg.getValueType() == MVT::i1)
6145 Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6146 dl, MVT::i32, Arg);
6147
6148 if (VA.isRegLoc()) {
6149 seenFloatArg |= VA.getLocVT().isFloatingPoint();
6150 // Put argument in a physical register.
6151 if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
6152 bool IsLE = Subtarget.isLittleEndian();
6153 SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6154 DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
6155 RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
6156 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
6157 DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
6158 RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
6159 SVal.getValue(0)));
6160 } else
6161 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
6162 } else {
6163 // Put argument in the parameter list area of the current stack frame.
6164 assert(VA.isMemLoc());
6165 unsigned LocMemOffset = VA.getLocMemOffset();
6166
6167 if (!IsTailCall) {
6168 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
6169 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
6170 StackPtr, PtrOff);
6171
6172 MemOpChains.push_back(
6173 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
6174 } else {
6175 // Calculate and remember argument location.
6176 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
6177 TailCallArguments);
6178 }
6179 }
6180 }
6181
6182 if (!MemOpChains.empty())
6183 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6184
6185 // Build a sequence of copy-to-reg nodes chained together with token chain
6186 // and flag operands which copy the outgoing args into the appropriate regs.
6187 SDValue InGlue;
6188 for (const auto &[Reg, N] : RegsToPass) {
6189 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6190 InGlue = Chain.getValue(1);
6191 }
6192
6193 // Set CR bit 6 to true if this is a vararg call with floating args passed in
6194 // registers.
6195 if (IsVarArg) {
6196 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
6197 SDValue Ops[] = { Chain, InGlue };
6198
6199 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl,
6200 VTs, ArrayRef(Ops, InGlue.getNode() ? 2 : 1));
6201
6202 InGlue = Chain.getValue(1);
6203 }
6204
6205 if (IsTailCall)
6206 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6207 TailCallArguments);
6208
6209 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6210 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6211}
6212
6213// Copy an argument into memory, being careful to do this outside the
6214// call sequence for the call to which the argument belongs.
6215SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
6216 SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
6217 SelectionDAG &DAG, const SDLoc &dl) const {
6218 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
6219 CallSeqStart.getNode()->getOperand(0),
6220 Flags, DAG, dl);
6221 // The MEMCPY must go outside the CALLSEQ_START..END.
6222 int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
6223 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
6224 SDLoc(MemcpyCall));
6225 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
6226 NewCallSeqStart.getNode());
6227 return NewCallSeqStart;
6228}
6229
6230SDValue PPCTargetLowering::LowerCall_64SVR4(
6231 SDValue Chain, SDValue Callee, CallFlags CFlags,
6233 const SmallVectorImpl<SDValue> &OutVals,
6234 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6236 const CallBase *CB) const {
6237 bool isELFv2ABI = Subtarget.isELFv2ABI();
6238 bool isLittleEndian = Subtarget.isLittleEndian();
6239 unsigned NumOps = Outs.size();
6240 bool IsSibCall = false;
6241 bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
6242
6243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
6244 unsigned PtrByteSize = 8;
6245
6247
6248 if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
6249 IsSibCall = true;
6250
6251 // Mark this function as potentially containing a function that contains a
6252 // tail call. As a consequence the frame pointer will be used for dynamicalloc
6253 // and restoring the callers stack pointer in this functions epilog. This is
6254 // done because by tail calling the called function might overwrite the value
6255 // in this function's (MF) stack pointer stack slot 0(SP).
6256 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6257 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6258
6259 assert(!(IsFastCall && CFlags.IsVarArg) &&
6260 "fastcc not supported on varargs functions");
6261
6262 // Count how many bytes are to be pushed on the stack, including the linkage
6263 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
6264 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
6265 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
6266 unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6267 unsigned NumBytes = LinkageSize;
6268 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6269
6270 static const MCPhysReg GPR[] = {
6271 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6272 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6273 };
6274 static const MCPhysReg VR[] = {
6275 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6276 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6277 };
6278
6279 const unsigned NumGPRs = std::size(GPR);
6280 const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
6281 const unsigned NumVRs = std::size(VR);
6282
6283 // On ELFv2, we can avoid allocating the parameter area if all the arguments
6284 // can be passed to the callee in registers.
6285 // For the fast calling convention, there is another check below.
6286 // Note: We should keep consistent with LowerFormalArguments_64SVR4()
6287 bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
6288 if (!HasParameterArea) {
6289 unsigned ParamAreaSize = NumGPRs * PtrByteSize;
6290 unsigned AvailableFPRs = NumFPRs;
6291 unsigned AvailableVRs = NumVRs;
6292 unsigned NumBytesTmp = NumBytes;
6293 for (unsigned i = 0; i != NumOps; ++i) {
6294 if (Outs[i].Flags.isNest()) continue;
6295 if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
6296 PtrByteSize, LinkageSize, ParamAreaSize,
6297 NumBytesTmp, AvailableFPRs, AvailableVRs))
6298 HasParameterArea = true;
6299 }
6300 }
6301
6302 // When using the fast calling convention, we don't provide backing for
6303 // arguments that will be in registers.
6304 unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
6305
6306 // Avoid allocating parameter area for fastcc functions if all the arguments
6307 // can be passed in the registers.
6308 if (IsFastCall)
6309 HasParameterArea = false;
6310
6311 // Add up all the space actually used.
6312 for (unsigned i = 0; i != NumOps; ++i) {
6313 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6314 EVT ArgVT = Outs[i].VT;
6315 EVT OrigVT = Outs[i].ArgVT;
6316
6317 if (Flags.isNest())
6318 continue;
6319
6320 if (IsFastCall) {
6321 if (Flags.isByVal()) {
6322 NumGPRsUsed += (Flags.getByValSize()+7)/8;
6323 if (NumGPRsUsed > NumGPRs)
6324 HasParameterArea = true;
6325 } else {
6326 switch (ArgVT.getSimpleVT().SimpleTy) {
6327 default: llvm_unreachable("Unexpected ValueType for argument!");
6328 case MVT::i1:
6329 case MVT::i32:
6330 case MVT::i64:
6331 if (++NumGPRsUsed <= NumGPRs)
6332 continue;
6333 break;
6334 case MVT::v4i32:
6335 case MVT::v8i16:
6336 case MVT::v16i8:
6337 case MVT::v2f64:
6338 case MVT::v2i64:
6339 case MVT::v1i128:
6340 case MVT::f128:
6341 if (++NumVRsUsed <= NumVRs)
6342 continue;
6343 break;
6344 case MVT::v4f32:
6345 if (++NumVRsUsed <= NumVRs)
6346 continue;
6347 break;
6348 case MVT::f32:
6349 case MVT::f64:
6350 if (++NumFPRsUsed <= NumFPRs)
6351 continue;
6352 break;
6353 }
6354 HasParameterArea = true;
6355 }
6356 }
6357
6358 /* Respect alignment of argument on the stack. */
6359 auto Alignement =
6360 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6361 NumBytes = alignTo(NumBytes, Alignement);
6362
6363 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6364 if (Flags.isInConsecutiveRegsLast())
6365 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6366 }
6367
6368 unsigned NumBytesActuallyUsed = NumBytes;
6369
6370 // In the old ELFv1 ABI,
6371 // the prolog code of the callee may store up to 8 GPR argument registers to
6372 // the stack, allowing va_start to index over them in memory if its varargs.
6373 // Because we cannot tell if this is needed on the caller side, we have to
6374 // conservatively assume that it is needed. As such, make sure we have at
6375 // least enough stack space for the caller to store the 8 GPRs.
6376 // In the ELFv2 ABI, we allocate the parameter area iff a callee
6377 // really requires memory operands, e.g. a vararg function.
6378 if (HasParameterArea)
6379 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6380 else
6381 NumBytes = LinkageSize;
6382
6383 // Tail call needs the stack to be aligned.
6384 if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6385 NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6386
6387 int SPDiff = 0;
6388
6389 // Calculate by how many bytes the stack has to be adjusted in case of tail
6390 // call optimization.
6391 if (!IsSibCall)
6392 SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6393
6394 // To protect arguments on the stack from being clobbered in a tail call,
6395 // force all the loads to happen before doing any other lowering.
6396 if (CFlags.IsTailCall)
6397 Chain = DAG.getStackArgumentTokenFactor(Chain);
6398
6399 // Adjust the stack pointer for the new arguments...
6400 // These operations are automatically eliminated by the prolog/epilog pass
6401 if (!IsSibCall)
6402 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6403 SDValue CallSeqStart = Chain;
6404
6405 // Load the return address and frame pointer so it can be move somewhere else
6406 // later.
6407 SDValue LROp, FPOp;
6408 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6409
6410 // Set up a copy of the stack pointer for use loading and storing any
6411 // arguments that may not fit in the registers available for argument
6412 // passing.
6413 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6414
6415 // Figure out which arguments are going to go in registers, and which in
6416 // memory. Also, if this is a vararg function, floating point operations
6417 // must be stored to our stack, and loaded into integer regs as well, if
6418 // any integer regs are available for argument passing.
6419 unsigned ArgOffset = LinkageSize;
6420
6422 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6423
6424 SmallVector<SDValue, 8> MemOpChains;
6425 for (unsigned i = 0; i != NumOps; ++i) {
6426 SDValue Arg = OutVals[i];
6427 ISD::ArgFlagsTy Flags = Outs[i].Flags;
6428 EVT ArgVT = Outs[i].VT;
6429 EVT OrigVT = Outs[i].ArgVT;
6430
6431 // PtrOff will be used to store the current argument to the stack if a
6432 // register cannot be found for it.
6433 SDValue PtrOff;
6434
6435 // We re-align the argument offset for each argument, except when using the
6436 // fast calling convention, when we need to make sure we do that only when
6437 // we'll actually use a stack slot.
6438 auto ComputePtrOff = [&]() {
6439 /* Respect alignment of argument on the stack. */
6440 auto Alignment =
6441 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6442 ArgOffset = alignTo(ArgOffset, Alignment);
6443
6444 PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6445
6446 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6447 };
6448
6449 if (!IsFastCall) {
6450 ComputePtrOff();
6451
6452 /* Compute GPR index associated with argument offset. */
6453 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6454 GPR_idx = std::min(GPR_idx, NumGPRs);
6455 }
6456
6457 // Promote integers to 64-bit values.
6458 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6459 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6460 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6461 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6462 }
6463
6464 // FIXME memcpy is used way more than necessary. Correctness first.
6465 // Note: "by value" is code for passing a structure by value, not
6466 // basic types.
6467 if (Flags.isByVal()) {
6468 // Note: Size includes alignment padding, so
6469 // struct x { short a; char b; }
6470 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
6471 // These are the proper values we need for right-justifying the
6472 // aggregate in a parameter register.
6473 unsigned Size = Flags.getByValSize();
6474
6475 // An empty aggregate parameter takes up no storage and no
6476 // registers.
6477 if (Size == 0)
6478 continue;
6479
6480 if (IsFastCall)
6481 ComputePtrOff();
6482
6483 // All aggregates smaller than 8 bytes must be passed right-justified.
6484 if (Size==1 || Size==2 || Size==4) {
6485 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6486 if (GPR_idx != NumGPRs) {
6487 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6488 MachinePointerInfo(), VT);
6489 MemOpChains.push_back(Load.getValue(1));
6490 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6491
6492 ArgOffset += PtrByteSize;
6493 continue;
6494 }
6495 }
6496
6497 if (GPR_idx == NumGPRs && Size < 8) {
6498 SDValue AddPtr = PtrOff;
6499 if (!isLittleEndian) {
6500 SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6501 PtrOff.getValueType());
6502 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6503 }
6504 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6505 CallSeqStart,
6506 Flags, DAG, dl);
6507 ArgOffset += PtrByteSize;
6508 continue;
6509 }
6510 // Copy the object to parameter save area if it can not be entirely passed
6511 // by registers.
6512 // FIXME: we only need to copy the parts which need to be passed in
6513 // parameter save area. For the parts passed by registers, we don't need
6514 // to copy them to the stack although we need to allocate space for them
6515 // in parameter save area.
6516 if ((NumGPRs - GPR_idx) * PtrByteSize < Size)
6517 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6518 CallSeqStart,
6519 Flags, DAG, dl);
6520
6521 // When a register is available, pass a small aggregate right-justified.
6522 if (Size < 8 && GPR_idx != NumGPRs) {
6523 // The easiest way to get this right-justified in a register
6524 // is to copy the structure into the rightmost portion of a
6525 // local variable slot, then load the whole slot into the
6526 // register.
6527 // FIXME: The memcpy seems to produce pretty awful code for
6528 // small aggregates, particularly for packed ones.
6529 // FIXME: It would be preferable to use the slot in the
6530 // parameter save area instead of a new local variable.
6531 SDValue AddPtr = PtrOff;
6532 if (!isLittleEndian) {
6533 SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6534 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6535 }
6536 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6537 CallSeqStart,
6538 Flags, DAG, dl);
6539
6540 // Load the slot into the register.
6541 SDValue Load =
6542 DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6543 MemOpChains.push_back(Load.getValue(1));
6544 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6545
6546 // Done with this argument.
6547 ArgOffset += PtrByteSize;
6548 continue;
6549 }
6550
6551 // For aggregates larger than PtrByteSize, copy the pieces of the
6552 // object that fit into registers from the parameter save area.
6553 for (unsigned j=0; j<Size; j+=PtrByteSize) {
6554 SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6555 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6556 if (GPR_idx != NumGPRs) {
6557 unsigned LoadSizeInBits = std::min(PtrByteSize, (Size - j)) * 8;
6558 EVT ObjType = EVT::getIntegerVT(*DAG.getContext(), LoadSizeInBits);
6559 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, AddArg,
6560 MachinePointerInfo(), ObjType);
6561
6562 MemOpChains.push_back(Load.getValue(1));
6563 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6564 ArgOffset += PtrByteSize;
6565 } else {
6566 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6567 break;
6568 }
6569 }
6570 continue;
6571 }
6572
6573 switch (Arg.getSimpleValueType().SimpleTy) {
6574 default: llvm_unreachable("Unexpected ValueType for argument!");
6575 case MVT::i1:
6576 case MVT::i32:
6577 case MVT::i64:
6578 if (Flags.isNest()) {
6579 // The 'nest' parameter, if any, is passed in R11.
6580 RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6581 break;
6582 }
6583
6584 // These can be scalar arguments or elements of an integer array type
6585 // passed directly. Clang may use those instead of "byval" aggregate
6586 // types to avoid forcing arguments to memory unnecessarily.
6587 if (GPR_idx != NumGPRs) {
6588 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6589 } else {
6590 if (IsFastCall)
6591 ComputePtrOff();
6592
6593 assert(HasParameterArea &&
6594 "Parameter area must exist to pass an argument in memory.");
6595 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6596 true, CFlags.IsTailCall, false, MemOpChains,
6597 TailCallArguments, dl);
6598 if (IsFastCall)
6599 ArgOffset += PtrByteSize;
6600 }
6601 if (!IsFastCall)
6602 ArgOffset += PtrByteSize;
6603 break;
6604 case MVT::f32:
6605 case MVT::f64: {
6606 // These can be scalar arguments or elements of a float array type
6607 // passed directly. The latter are used to implement ELFv2 homogenous
6608 // float aggregates.
6609
6610 // Named arguments go into FPRs first, and once they overflow, the
6611 // remaining arguments go into GPRs and then the parameter save area.
6612 // Unnamed arguments for vararg functions always go to GPRs and
6613 // then the parameter save area. For now, put all arguments to vararg
6614 // routines always in both locations (FPR *and* GPR or stack slot).
6615 bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6616 bool NeededLoad = false;
6617
6618 // First load the argument into the next available FPR.
6619 if (FPR_idx != NumFPRs)
6620 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6621
6622 // Next, load the argument into GPR or stack slot if needed.
6623 if (!NeedGPROrStack)
6624 ;
6625 else if (GPR_idx != NumGPRs && !IsFastCall) {
6626 // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6627 // once we support fp <-> gpr moves.
6628
6629 // In the non-vararg case, this can only ever happen in the
6630 // presence of f32 array types, since otherwise we never run
6631 // out of FPRs before running out of GPRs.
6632 SDValue ArgVal;
6633
6634 // Double values are always passed in a single GPR.
6635 if (Arg.getValueType() != MVT::f32) {
6636 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6637
6638 // Non-array float values are extended and passed in a GPR.
6639 } else if (!Flags.isInConsecutiveRegs()) {
6640 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6641 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6642
6643 // If we have an array of floats, we collect every odd element
6644 // together with its predecessor into one GPR.
6645 } else if (ArgOffset % PtrByteSize != 0) {
6646 SDValue Lo, Hi;
6647 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6648 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6649 if (!isLittleEndian)
6650 std::swap(Lo, Hi);
6651 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6652
6653 // The final element, if even, goes into the first half of a GPR.
6654 } else if (Flags.isInConsecutiveRegsLast()) {
6655 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6656 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6657 if (!isLittleEndian)
6658 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6659 DAG.getConstant(32, dl, MVT::i32));
6660
6661 // Non-final even elements are skipped; they will be handled
6662 // together the with subsequent argument on the next go-around.
6663 } else
6664 ArgVal = SDValue();
6665
6666 if (ArgVal.getNode())
6667 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6668 } else {
6669 if (IsFastCall)
6670 ComputePtrOff();
6671
6672 // Single-precision floating-point values are mapped to the
6673 // second (rightmost) word of the stack doubleword.
6674 if (Arg.getValueType() == MVT::f32 &&
6675 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6676 SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6677 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6678 }
6679
6680 assert(HasParameterArea &&
6681 "Parameter area must exist to pass an argument in memory.");
6682 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6683 true, CFlags.IsTailCall, false, MemOpChains,
6684 TailCallArguments, dl);
6685
6686 NeededLoad = true;
6687 }
6688 // When passing an array of floats, the array occupies consecutive
6689 // space in the argument area; only round up to the next doubleword
6690 // at the end of the array. Otherwise, each float takes 8 bytes.
6691 if (!IsFastCall || NeededLoad) {
6692 ArgOffset += (Arg.getValueType() == MVT::f32 &&
6693 Flags.isInConsecutiveRegs()) ? 4 : 8;
6694 if (Flags.isInConsecutiveRegsLast())
6695 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6696 }
6697 break;
6698 }
6699 case MVT::v4f32:
6700 case MVT::v4i32:
6701 case MVT::v8i16:
6702 case MVT::v16i8:
6703 case MVT::v2f64:
6704 case MVT::v2i64:
6705 case MVT::v1i128:
6706 case MVT::f128:
6707 // These can be scalar arguments or elements of a vector array type
6708 // passed directly. The latter are used to implement ELFv2 homogenous
6709 // vector aggregates.
6710
6711 // For a varargs call, named arguments go into VRs or on the stack as
6712 // usual; unnamed arguments always go to the stack or the corresponding
6713 // GPRs when within range. For now, we always put the value in both
6714 // locations (or even all three).
6715 if (CFlags.IsVarArg) {
6716 assert(HasParameterArea &&
6717 "Parameter area must exist if we have a varargs call.");
6718 // We could elide this store in the case where the object fits
6719 // entirely in R registers. Maybe later.
6720 SDValue Store =
6721 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6722 MemOpChains.push_back(Store);
6723 if (VR_idx != NumVRs) {
6724 SDValue Load =
6725 DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6726 MemOpChains.push_back(Load.getValue(1));
6727 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6728 }
6729 ArgOffset += 16;
6730 for (unsigned i=0; i<16; i+=PtrByteSize) {
6731 if (GPR_idx == NumGPRs)
6732 break;
6733 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6734 DAG.getConstant(i, dl, PtrVT));
6735 SDValue Load =
6736 DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6737 MemOpChains.push_back(Load.getValue(1));
6738 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6739 }
6740 break;
6741 }
6742
6743 // Non-varargs Altivec params go into VRs or on the stack.
6744 if (VR_idx != NumVRs) {
6745 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6746 } else {
6747 if (IsFastCall)
6748 ComputePtrOff();
6749
6750 assert(HasParameterArea &&
6751 "Parameter area must exist to pass an argument in memory.");
6752 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6753 true, CFlags.IsTailCall, true, MemOpChains,
6754 TailCallArguments, dl);
6755 if (IsFastCall)
6756 ArgOffset += 16;
6757 }
6758
6759 if (!IsFastCall)
6760 ArgOffset += 16;
6761 break;
6762 }
6763 }
6764
6765 assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6766 "mismatch in size of parameter area");
6767 (void)NumBytesActuallyUsed;
6768
6769 if (!MemOpChains.empty())
6770 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6771
6772 // Check if this is an indirect call (MTCTR/BCTRL).
6773 // See prepareDescriptorIndirectCall and buildCallOperands for more
6774 // information about calls through function pointers in the 64-bit SVR4 ABI.
6775 if (CFlags.IsIndirect) {
6776 // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6777 // caller in the TOC save area.
6778 if (isTOCSaveRestoreRequired(Subtarget)) {
6779 assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6780 // Load r2 into a virtual register and store it to the TOC save area.
6781 setUsesTOCBasePtr(DAG);
6782 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6783 // TOC save area offset.
6784 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6785 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6786 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6787 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6789 DAG.getMachineFunction(), TOCSaveOffset));
6790 }
6791 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6792 // This does not mean the MTCTR instruction must use R12; it's easier
6793 // to model this as an extra parameter, so do that.
6794 if (isELFv2ABI && !CFlags.IsPatchPoint)
6795 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6796 }
6797
6798 // Build a sequence of copy-to-reg nodes chained together with token chain
6799 // and flag operands which copy the outgoing args into the appropriate regs.
6800 SDValue InGlue;
6801 for (const auto &[Reg, N] : RegsToPass) {
6802 Chain = DAG.getCopyToReg(Chain, dl, Reg, N, InGlue);
6803 InGlue = Chain.getValue(1);
6804 }
6805
6806 if (CFlags.IsTailCall && !IsSibCall)
6807 PrepareTailCall(DAG, InGlue, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6808 TailCallArguments);
6809
6810 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
6811 Callee, SPDiff, NumBytes, Ins, InVals, CB);
6812}
6813
6814// Returns true when the shadow of a general purpose argument register
6815// in the parameter save area is aligned to at least 'RequiredAlign'.
6816static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign) {
6817 assert(RequiredAlign.value() <= 16 &&
6818 "Required alignment greater than stack alignment.");
6819 switch (Reg) {
6820 default:
6821 report_fatal_error("called on invalid register.");
6822 case PPC::R5:
6823 case PPC::R9:
6824 case PPC::X3:
6825 case PPC::X5:
6826 case PPC::X7:
6827 case PPC::X9:
6828 // These registers are 16 byte aligned which is the most strict aligment
6829 // we can support.
6830 return true;
6831 case PPC::R3:
6832 case PPC::R7:
6833 case PPC::X4:
6834 case PPC::X6:
6835 case PPC::X8:
6836 case PPC::X10:
6837 // The shadow of these registers in the PSA is 8 byte aligned.
6838 return RequiredAlign <= 8;
6839 case PPC::R4:
6840 case PPC::R6:
6841 case PPC::R8:
6842 case PPC::R10:
6843 return RequiredAlign <= 4;
6844 }
6845}
6846
6847static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6848 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6849 Type *OrigTy, CCState &State) {
6850 const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6851 State.getMachineFunction().getSubtarget());
6852 const bool IsPPC64 = Subtarget.isPPC64();
6853 const unsigned PtrSize = IsPPC64 ? 8 : 4;
6854 const Align PtrAlign(PtrSize);
6855 const Align StackAlign(16);
6856 const MVT RegVT = Subtarget.getScalarIntVT();
6857
6858 if (ValVT == MVT::f128)
6859 report_fatal_error("f128 is unimplemented on AIX.");
6860
6861 static const MCPhysReg GPR_32[] = {// 32-bit registers.
6862 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6863 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6864 static const MCPhysReg GPR_64[] = {// 64-bit registers.
6865 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6866 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6867
6868 static const MCPhysReg VR[] = {// Vector registers.
6869 PPC::V2, PPC::V3, PPC::V4, PPC::V5,
6870 PPC::V6, PPC::V7, PPC::V8, PPC::V9,
6871 PPC::V10, PPC::V11, PPC::V12, PPC::V13};
6872
6873 const ArrayRef<MCPhysReg> GPRs = IsPPC64 ? GPR_64 : GPR_32;
6874
6875 if (ArgFlags.isNest()) {
6876 MCRegister EnvReg = State.AllocateReg(IsPPC64 ? PPC::X11 : PPC::R11);
6877 if (!EnvReg)
6878 report_fatal_error("More then one nest argument.");
6879 State.addLoc(CCValAssign::getReg(ValNo, ValVT, EnvReg, RegVT, LocInfo));
6880 return false;
6881 }
6882
6883 if (ArgFlags.isByVal()) {
6884 const Align ByValAlign(ArgFlags.getNonZeroByValAlign());
6885 if (ByValAlign > StackAlign)
6886 report_fatal_error("Pass-by-value arguments with alignment greater than "
6887 "16 are not supported.");
6888
6889 const unsigned ByValSize = ArgFlags.getByValSize();
6890 const Align ObjAlign = ByValAlign > PtrAlign ? ByValAlign : PtrAlign;
6891
6892 // An empty aggregate parameter takes up no storage and no registers,
6893 // but needs a MemLoc for a stack slot for the formal arguments side.
6894 if (ByValSize == 0) {
6896 State.getStackSize(), RegVT, LocInfo));
6897 return false;
6898 }
6899
6900 // Shadow allocate any registers that are not properly aligned.
6901 unsigned NextReg = State.getFirstUnallocated(GPRs);
6902 while (NextReg != GPRs.size() &&
6903 !isGPRShadowAligned(GPRs[NextReg], ObjAlign)) {
6904 // Shadow allocate next registers since its aligment is not strict enough.
6905 MCRegister Reg = State.AllocateReg(GPRs);
6906 // Allocate the stack space shadowed by said register.
6907 State.AllocateStack(PtrSize, PtrAlign);
6908 assert(Reg && "Alocating register unexpectedly failed.");
6909 (void)Reg;
6910 NextReg = State.getFirstUnallocated(GPRs);
6911 }
6912
6913 const unsigned StackSize = alignTo(ByValSize, ObjAlign);
6914 unsigned Offset = State.AllocateStack(StackSize, ObjAlign);
6915 for (const unsigned E = Offset + StackSize; Offset < E; Offset += PtrSize) {
6916 if (MCRegister Reg = State.AllocateReg(GPRs))
6917 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6918 else {
6921 LocInfo));
6922 break;
6923 }
6924 }
6925 return false;
6926 }
6927
6928 // Arguments always reserve parameter save area.
6929 switch (ValVT.SimpleTy) {
6930 default:
6931 report_fatal_error("Unhandled value type for argument.");
6932 case MVT::i64:
6933 // i64 arguments should have been split to i32 for PPC32.
6934 assert(IsPPC64 && "PPC32 should have split i64 values.");
6935 [[fallthrough]];
6936 case MVT::i1:
6937 case MVT::i32: {
6938 const unsigned Offset = State.AllocateStack(PtrSize, PtrAlign);
6939 // AIX integer arguments are always passed in register width.
6940 if (ValVT.getFixedSizeInBits() < RegVT.getFixedSizeInBits())
6941 LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6943 if (MCRegister Reg = State.AllocateReg(GPRs))
6944 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6945 else
6946 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6947
6948 return false;
6949 }
6950 case MVT::f32:
6951 case MVT::f64: {
6952 // Parameter save area (PSA) is reserved even if the float passes in fpr.
6953 const unsigned StoreSize = LocVT.getStoreSize();
6954 // Floats are always 4-byte aligned in the PSA on AIX.
6955 // This includes f64 in 64-bit mode for ABI compatibility.
6956 const unsigned Offset =
6957 State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6958 MCRegister FReg = State.AllocateReg(FPR);
6959 if (FReg)
6960 State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6961
6962 // Reserve and initialize GPRs or initialize the PSA as required.
6963 for (unsigned I = 0; I < StoreSize; I += PtrSize) {
6964 if (MCRegister Reg = State.AllocateReg(GPRs)) {
6965 assert(FReg && "An FPR should be available when a GPR is reserved.");
6966 if (State.isVarArg()) {
6967 // Successfully reserved GPRs are only initialized for vararg calls.
6968 // Custom handling is required for:
6969 // f64 in PPC32 needs to be split into 2 GPRs.
6970 // f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6971 State.addLoc(
6972 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6973 }
6974 } else {
6975 // If there are insufficient GPRs, the PSA needs to be initialized.
6976 // Initialization occurs even if an FPR was initialized for
6977 // compatibility with the AIX XL compiler. The full memory for the
6978 // argument will be initialized even if a prior word is saved in GPR.
6979 // A custom memLoc is used when the argument also passes in FPR so
6980 // that the callee handling can skip over it easily.
6981 State.addLoc(
6982 FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6983 LocInfo)
6984 : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6985 break;
6986 }
6987 }
6988
6989 return false;
6990 }
6991 case MVT::v4f32:
6992 case MVT::v4i32:
6993 case MVT::v8i16:
6994 case MVT::v16i8:
6995 case MVT::v2i64:
6996 case MVT::v2f64:
6997 case MVT::v1i128: {
6998 const unsigned VecSize = 16;
6999 const Align VecAlign(VecSize);
7000
7001 if (!State.isVarArg()) {
7002 // If there are vector registers remaining we don't consume any stack
7003 // space.
7004 if (MCRegister VReg = State.AllocateReg(VR)) {
7005 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7006 return false;
7007 }
7008 // Vectors passed on the stack do not shadow GPRs or FPRs even though they
7009 // might be allocated in the portion of the PSA that is shadowed by the
7010 // GPRs.
7011 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7012 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7013 return false;
7014 }
7015
7016 unsigned NextRegIndex = State.getFirstUnallocated(GPRs);
7017 // Burn any underaligned registers and their shadowed stack space until
7018 // we reach the required alignment.
7019 while (NextRegIndex != GPRs.size() &&
7020 !isGPRShadowAligned(GPRs[NextRegIndex], VecAlign)) {
7021 // Shadow allocate register and its stack shadow.
7022 MCRegister Reg = State.AllocateReg(GPRs);
7023 State.AllocateStack(PtrSize, PtrAlign);
7024 assert(Reg && "Allocating register unexpectedly failed.");
7025 (void)Reg;
7026 NextRegIndex = State.getFirstUnallocated(GPRs);
7027 }
7028
7029 // Vectors that are passed as fixed arguments are handled differently.
7030 // They are passed in VRs if any are available (unlike arguments passed
7031 // through ellipses) and shadow GPRs (unlike arguments to non-vaarg
7032 // functions)
7033 if (!ArgFlags.isVarArg()) {
7034 if (MCRegister VReg = State.AllocateReg(VR)) {
7035 State.addLoc(CCValAssign::getReg(ValNo, ValVT, VReg, LocVT, LocInfo));
7036 // Shadow allocate GPRs and stack space even though we pass in a VR.
7037 for (unsigned I = 0; I != VecSize; I += PtrSize)
7038 State.AllocateReg(GPRs);
7039 State.AllocateStack(VecSize, VecAlign);
7040 return false;
7041 }
7042 // No vector registers remain so pass on the stack.
7043 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7044 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7045 return false;
7046 }
7047
7048 // If all GPRS are consumed then we pass the argument fully on the stack.
7049 if (NextRegIndex == GPRs.size()) {
7050 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7051 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7052 return false;
7053 }
7054
7055 // Corner case for 32-bit codegen. We have 2 registers to pass the first
7056 // half of the argument, and then need to pass the remaining half on the
7057 // stack.
7058 if (GPRs[NextRegIndex] == PPC::R9) {
7059 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7060 State.addLoc(
7061 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7062
7063 const MCRegister FirstReg = State.AllocateReg(PPC::R9);
7064 const MCRegister SecondReg = State.AllocateReg(PPC::R10);
7065 assert(FirstReg && SecondReg &&
7066 "Allocating R9 or R10 unexpectedly failed.");
7067 State.addLoc(
7068 CCValAssign::getCustomReg(ValNo, ValVT, FirstReg, RegVT, LocInfo));
7069 State.addLoc(
7070 CCValAssign::getCustomReg(ValNo, ValVT, SecondReg, RegVT, LocInfo));
7071 return false;
7072 }
7073
7074 // We have enough GPRs to fully pass the vector argument, and we have
7075 // already consumed any underaligned registers. Start with the custom
7076 // MemLoc and then the custom RegLocs.
7077 const unsigned Offset = State.AllocateStack(VecSize, VecAlign);
7078 State.addLoc(
7079 CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT, LocInfo));
7080 for (unsigned I = 0; I != VecSize; I += PtrSize) {
7081 const MCRegister Reg = State.AllocateReg(GPRs);
7082 assert(Reg && "Failed to allocated register for vararg vector argument");
7083 State.addLoc(
7084 CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
7085 }
7086 return false;
7087 }
7088 }
7089 return true;
7090}
7091
7092// So far, this function is only used by LowerFormalArguments_AIX()
7094 bool IsPPC64,
7095 bool HasP8Vector,
7096 bool HasVSX) {
7097 assert((IsPPC64 || SVT != MVT::i64) &&
7098 "i64 should have been split for 32-bit codegen.");
7099
7100 switch (SVT) {
7101 default:
7102 report_fatal_error("Unexpected value type for formal argument");
7103 case MVT::i1:
7104 case MVT::i32:
7105 case MVT::i64:
7106 return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7107 case MVT::f32:
7108 return HasP8Vector ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass;
7109 case MVT::f64:
7110 return HasVSX ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass;
7111 case MVT::v4f32:
7112 case MVT::v4i32:
7113 case MVT::v8i16:
7114 case MVT::v16i8:
7115 case MVT::v2i64:
7116 case MVT::v2f64:
7117 case MVT::v1i128:
7118 return &PPC::VRRCRegClass;
7119 }
7120}
7121
7123 SelectionDAG &DAG, SDValue ArgValue,
7124 MVT LocVT, const SDLoc &dl) {
7125 assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
7126 assert(ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits());
7127
7128 if (Flags.isSExt())
7129 ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
7130 DAG.getValueType(ValVT));
7131 else if (Flags.isZExt())
7132 ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
7133 DAG.getValueType(ValVT));
7134
7135 return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
7136}
7137
7138static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
7139 const unsigned LASize = FL->getLinkageSize();
7140
7141 if (PPC::GPRCRegClass.contains(Reg)) {
7142 assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
7143 "Reg must be a valid argument register!");
7144 return LASize + 4 * (Reg - PPC::R3);
7145 }
7146
7147 if (PPC::G8RCRegClass.contains(Reg)) {
7148 assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
7149 "Reg must be a valid argument register!");
7150 return LASize + 8 * (Reg - PPC::X3);
7151 }
7152
7153 llvm_unreachable("Only general purpose registers expected.");
7154}
7155
7156// AIX ABI Stack Frame Layout:
7157//
7158// Low Memory +--------------------------------------------+
7159// SP +---> | Back chain | ---+
7160// | +--------------------------------------------+ |
7161// | | Saved Condition Register | |
7162// | +--------------------------------------------+ |
7163// | | Saved Linkage Register | |
7164// | +--------------------------------------------+ | Linkage Area
7165// | | Reserved for compilers | |
7166// | +--------------------------------------------+ |
7167// | | Reserved for binders | |
7168// | +--------------------------------------------+ |
7169// | | Saved TOC pointer | ---+
7170// | +--------------------------------------------+
7171// | | Parameter save area |
7172// | +--------------------------------------------+
7173// | | Alloca space |
7174// | +--------------------------------------------+
7175// | | Local variable space |
7176// | +--------------------------------------------+
7177// | | Float/int conversion temporary |
7178// | +--------------------------------------------+
7179// | | Save area for AltiVec registers |
7180// | +--------------------------------------------+
7181// | | AltiVec alignment padding |
7182// | +--------------------------------------------+
7183// | | Save area for VRSAVE register |
7184// | +--------------------------------------------+
7185// | | Save area for General Purpose registers |
7186// | +--------------------------------------------+
7187// | | Save area for Floating Point registers |
7188// | +--------------------------------------------+
7189// +---- | Back chain |
7190// High Memory +--------------------------------------------+
7191//
7192// Specifications:
7193// AIX 7.2 Assembler Language Reference
7194// Subroutine linkage convention
7195
7196SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7197 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7198 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7199 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7200
7201 assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7202 CallConv == CallingConv::Fast) &&
7203 "Unexpected calling convention!");
7204
7205 if (getTargetMachine().Options.GuaranteedTailCallOpt)
7206 report_fatal_error("Tail call support is unimplemented on AIX.");
7207
7208 if (useSoftFloat())
7209 report_fatal_error("Soft float support is unimplemented on AIX.");
7210
7211 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7212
7213 const bool IsPPC64 = Subtarget.isPPC64();
7214 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7215
7216 // Assign locations to all of the incoming arguments.
7219 MachineFrameInfo &MFI = MF.getFrameInfo();
7220 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7221 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7222
7223 const EVT PtrVT = getPointerTy(MF.getDataLayout());
7224 // Reserve space for the linkage area on the stack.
7225 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7226 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7227 uint64_t SaveStackPos = CCInfo.getStackSize();
7228 bool SaveParams = MF.getFunction().hasFnAttribute("save-reg-params");
7229 CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7230
7232
7233 for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7234 CCValAssign &VA = ArgLocs[I++];
7235 MVT LocVT = VA.getLocVT();
7236 MVT ValVT = VA.getValVT();
7237 ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7238
7239 EVT ArgVT = Ins[VA.getValNo()].ArgVT;
7240 bool ArgSignExt = Ins[VA.getValNo()].Flags.isSExt();
7241 // For compatibility with the AIX XL compiler, the float args in the
7242 // parameter save area are initialized even if the argument is available
7243 // in register. The caller is required to initialize both the register
7244 // and memory, however, the callee can choose to expect it in either.
7245 // The memloc is dismissed here because the argument is retrieved from
7246 // the register.
7247 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isFloatingPoint())
7248 continue;
7249
7250 if (SaveParams && VA.isRegLoc() && !Flags.isByVal() && !VA.needsCustom()) {
7251 const TargetRegisterClass *RegClass = getRegClassForSVT(
7252 LocVT.SimpleTy, IsPPC64, Subtarget.hasP8Vector(), Subtarget.hasVSX());
7253 // On PPC64, debugger assumes extended 8-byte values are stored from GPR.
7254 MVT SaveVT = RegClass == &PPC::G8RCRegClass ? MVT::i64 : LocVT;
7255 const Register VReg = MF.addLiveIn(VA.getLocReg(), RegClass);
7256 SDValue Parm = DAG.getCopyFromReg(Chain, dl, VReg, SaveVT);
7257 int FI = MFI.CreateFixedObject(SaveVT.getStoreSize(), SaveStackPos, true);
7258 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7259 SDValue StoreReg = DAG.getStore(Chain, dl, Parm, FIN,
7260 MachinePointerInfo(), Align(PtrByteSize));
7261 SaveStackPos = alignTo(SaveStackPos + SaveVT.getStoreSize(), PtrByteSize);
7262 MemOps.push_back(StoreReg);
7263 }
7264
7265 if (SaveParams && (VA.isMemLoc() || Flags.isByVal()) && !VA.needsCustom()) {
7266 unsigned StoreSize =
7267 Flags.isByVal() ? Flags.getByValSize() : LocVT.getStoreSize();
7268 SaveStackPos = alignTo(SaveStackPos + StoreSize, PtrByteSize);
7269 }
7270
7271 auto HandleMemLoc = [&]() {
7272 const unsigned LocSize = LocVT.getStoreSize();
7273 const unsigned ValSize = ValVT.getStoreSize();
7274 assert((ValSize <= LocSize) &&
7275 "Object size is larger than size of MemLoc");
7276 int CurArgOffset = VA.getLocMemOffset();
7277 // Objects are right-justified because AIX is big-endian.
7278 if (LocSize > ValSize)
7279 CurArgOffset += LocSize - ValSize;
7280 // Potential tail calls could cause overwriting of argument stack slots.
7281 const bool IsImmutable =
7283 (CallConv == CallingConv::Fast));
7284 int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7285 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7286 SDValue ArgValue =
7287 DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7288
7289 // While the ABI specifies the argument type is (sign or zero) extended
7290 // out to register width, not all code is compliant. We truncate and
7291 // re-extend to be more forgiving of these callers when the argument type
7292 // is smaller than register width.
7293 if (!ArgVT.isVector() && !ValVT.isVector() && ArgVT.isInteger() &&
7294 ValVT.isInteger() &&
7295 ArgVT.getScalarSizeInBits() < ValVT.getScalarSizeInBits()) {
7296 // It is possible to have either real integer values
7297 // or integers that were not originally integers.
7298 // In the latter case, these could have came from structs,
7299 // and these integers would not have an extend on the parameter.
7300 // Since these types of integers do not have an extend specified
7301 // in the first place, the type of extend that we do should not matter.
7302 EVT TruncatedArgVT = ArgVT.isSimple() && ArgVT.getSimpleVT() == MVT::i1
7303 ? MVT::i8
7304 : ArgVT;
7305 SDValue ArgValueTrunc =
7306 DAG.getNode(ISD::TRUNCATE, dl, TruncatedArgVT, ArgValue);
7307 SDValue ArgValueExt =
7308 ArgSignExt ? DAG.getSExtOrTrunc(ArgValueTrunc, dl, ValVT)
7309 : DAG.getZExtOrTrunc(ArgValueTrunc, dl, ValVT);
7310 InVals.push_back(ArgValueExt);
7311 } else {
7312 InVals.push_back(ArgValue);
7313 }
7314 };
7315
7316 // Vector arguments to VaArg functions are passed both on the stack, and
7317 // in any available GPRs. Load the value from the stack and add the GPRs
7318 // as live ins.
7319 if (VA.isMemLoc() && VA.needsCustom()) {
7320 assert(ValVT.isVector() && "Unexpected Custom MemLoc type.");
7321 assert(isVarArg && "Only use custom memloc for vararg.");
7322 // ValNo of the custom MemLoc, so we can compare it to the ValNo of the
7323 // matching custom RegLocs.
7324 const unsigned OriginalValNo = VA.getValNo();
7325 (void)OriginalValNo;
7326
7327 auto HandleCustomVecRegLoc = [&]() {
7328 assert(I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7329 "Missing custom RegLoc.");
7330 VA = ArgLocs[I++];
7331 assert(VA.getValVT().isVector() &&
7332 "Unexpected Val type for custom RegLoc.");
7333 assert(VA.getValNo() == OriginalValNo &&
7334 "ValNo mismatch between custom MemLoc and RegLoc.");
7336 MF.addLiveIn(VA.getLocReg(),
7337 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7338 Subtarget.hasVSX()));
7339 };
7340
7341 HandleMemLoc();
7342 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7343 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7344 // R10.
7345 HandleCustomVecRegLoc();
7346 HandleCustomVecRegLoc();
7347
7348 // If we are targeting 32-bit, there might be 2 extra custom RegLocs if
7349 // we passed the vector in R5, R6, R7 and R8.
7350 if (I != End && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom()) {
7351 assert(!IsPPC64 &&
7352 "Only 2 custom RegLocs expected for 64-bit codegen.");
7353 HandleCustomVecRegLoc();
7354 HandleCustomVecRegLoc();
7355 }
7356
7357 continue;
7358 }
7359
7360 if (VA.isRegLoc()) {
7361 if (VA.getValVT().isScalarInteger())
7363 else if (VA.getValVT().isFloatingPoint() && !VA.getValVT().isVector()) {
7364 switch (VA.getValVT().SimpleTy) {
7365 default:
7366 report_fatal_error("Unhandled value type for argument.");
7367 case MVT::f32:
7369 break;
7370 case MVT::f64:
7372 break;
7373 }
7374 } else if (VA.getValVT().isVector()) {
7375 switch (VA.getValVT().SimpleTy) {
7376 default:
7377 report_fatal_error("Unhandled value type for argument.");
7378 case MVT::v16i8:
7380 break;
7381 case MVT::v8i16:
7383 break;
7384 case MVT::v4i32:
7385 case MVT::v2i64:
7386 case MVT::v1i128:
7388 break;
7389 case MVT::v4f32:
7390 case MVT::v2f64:
7392 break;
7393 }
7394 }
7395 }
7396
7397 if (Flags.isByVal() && VA.isMemLoc()) {
7398 const unsigned Size =
7399 alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7400 PtrByteSize);
7401 const int FI = MF.getFrameInfo().CreateFixedObject(
7402 Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7403 /* IsAliased */ true);
7404 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7405 InVals.push_back(FIN);
7406
7407 continue;
7408 }
7409
7410 if (Flags.isByVal()) {
7411 assert(VA.isRegLoc() && "MemLocs should already be handled.");
7412
7413 const MCPhysReg ArgReg = VA.getLocReg();
7414 const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7415
7416 const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7417 const int FI = MF.getFrameInfo().CreateFixedObject(
7418 StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7419 /* IsAliased */ true);
7420 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7421 InVals.push_back(FIN);
7422
7423 // Add live ins for all the RegLocs for the same ByVal.
7424 const TargetRegisterClass *RegClass =
7425 IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7426
7427 auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7428 unsigned Offset) {
7429 const Register VReg = MF.addLiveIn(PhysReg, RegClass);
7430 // Since the callers side has left justified the aggregate in the
7431 // register, we can simply store the entire register into the stack
7432 // slot.
7433 SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7434 // The store to the fixedstack object is needed becuase accessing a
7435 // field of the ByVal will use a gep and load. Ideally we will optimize
7436 // to extracting the value from the register directly, and elide the
7437 // stores when the arguments address is not taken, but that will need to
7438 // be future work.
7439 SDValue Store = DAG.getStore(
7440 CopyFrom.getValue(1), dl, CopyFrom,
7443
7444 MemOps.push_back(Store);
7445 };
7446
7447 unsigned Offset = 0;
7448 HandleRegLoc(VA.getLocReg(), Offset);
7449 Offset += PtrByteSize;
7450 for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7451 Offset += PtrByteSize) {
7452 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7453 "RegLocs should be for ByVal argument.");
7454
7455 const CCValAssign RL = ArgLocs[I++];
7456 HandleRegLoc(RL.getLocReg(), Offset);
7458 }
7459
7460 if (Offset != StackSize) {
7461 assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7462 "Expected MemLoc for remaining bytes.");
7463 assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7464 // Consume the MemLoc.The InVal has already been emitted, so nothing
7465 // more needs to be done.
7466 ++I;
7467 }
7468
7469 continue;
7470 }
7471
7472 if (VA.isRegLoc() && !VA.needsCustom()) {
7473 MVT::SimpleValueType SVT = ValVT.SimpleTy;
7474 Register VReg =
7475 MF.addLiveIn(VA.getLocReg(),
7476 getRegClassForSVT(SVT, IsPPC64, Subtarget.hasP8Vector(),
7477 Subtarget.hasVSX()));
7478 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7479 if (ValVT.isScalarInteger() &&
7480 (ValVT.getFixedSizeInBits() < LocVT.getFixedSizeInBits())) {
7481 ArgValue =
7482 truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7483 }
7484 InVals.push_back(ArgValue);
7485 continue;
7486 }
7487 if (VA.isMemLoc()) {
7488 HandleMemLoc();
7489 continue;
7490 }
7491 }
7492
7493 // On AIX a minimum of 8 words is saved to the parameter save area.
7494 const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7495 // Area that is at least reserved in the caller of this function.
7496 unsigned CallerReservedArea = std::max<unsigned>(
7497 CCInfo.getStackSize(), LinkageSize + MinParameterSaveArea);
7498
7499 // Set the size that is at least reserved in caller of this function. Tail
7500 // call optimized function's reserved stack space needs to be aligned so
7501 // that taking the difference between two stack areas will result in an
7502 // aligned stack.
7503 CallerReservedArea =
7504 EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7505 FuncInfo->setMinReservedArea(CallerReservedArea);
7506
7507 if (isVarArg) {
7508 int VAListIndex = 0;
7509 // If any of the optional arguments are passed in register then the fixed
7510 // stack object we spill into is not immutable. Create a fixed stack object
7511 // that overlaps the remainder of the parameter save area.
7512 if (CCInfo.getStackSize() < (LinkageSize + MinParameterSaveArea)) {
7513 unsigned FixedStackSize =
7514 LinkageSize + MinParameterSaveArea - CCInfo.getStackSize();
7515 VAListIndex =
7516 MFI.CreateFixedObject(FixedStackSize, CCInfo.getStackSize(),
7517 /* IsImmutable */ false, /* IsAliased */ true);
7518 } else {
7519 // All the arguments passed through ellipses are on the stack. Create a
7520 // dummy fixed stack object the same size as a pointer since we don't
7521 // know the actual size.
7522 VAListIndex =
7523 MFI.CreateFixedObject(PtrByteSize, CCInfo.getStackSize(),
7524 /* IsImmutable */ true, /* IsAliased */ true);
7525 }
7526
7527 FuncInfo->setVarArgsFrameIndex(VAListIndex);
7528 SDValue FIN = DAG.getFrameIndex(VAListIndex, PtrVT);
7529
7530 static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7531 PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7532
7533 static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7534 PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7535 const unsigned NumGPArgRegs = std::size(IsPPC64 ? GPR_64 : GPR_32);
7536
7537 // The fixed integer arguments of a variadic function are stored to the
7538 // VarArgsFrameIndex on the stack so that they may be loaded by
7539 // dereferencing the result of va_next.
7540 for (unsigned
7541 GPRIndex = (CCInfo.getStackSize() - LinkageSize) / PtrByteSize,
7542 Offset = 0;
7543 GPRIndex < NumGPArgRegs; ++GPRIndex, Offset += PtrByteSize) {
7544
7545 const Register VReg =
7546 IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7547 : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7548
7549 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7550 MachinePointerInfo MPI =
7551 MachinePointerInfo::getFixedStack(MF, VAListIndex, Offset);
7552 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MPI);
7553 MemOps.push_back(Store);
7554 // Increment the address for the next argument to store.
7555 SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7556 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7557 }
7558 }
7559
7560 if (!MemOps.empty())
7561 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7562
7563 return Chain;
7564}
7565
7566SDValue PPCTargetLowering::LowerCall_AIX(
7567 SDValue Chain, SDValue Callee, CallFlags CFlags,
7569 const SmallVectorImpl<SDValue> &OutVals,
7570 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7572 const CallBase *CB) const {
7573 // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7574 // AIX ABI stack frame layout.
7575
7576 assert((CFlags.CallConv == CallingConv::C ||
7577 CFlags.CallConv == CallingConv::Cold ||
7578 CFlags.CallConv == CallingConv::Fast) &&
7579 "Unexpected calling convention!");
7580
7581 if (CFlags.IsPatchPoint)
7582 report_fatal_error("This call type is unimplemented on AIX.");
7583
7584 const PPCSubtarget &Subtarget = DAG.getSubtarget<PPCSubtarget>();
7585
7588 CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7589 *DAG.getContext());
7590
7591 // Reserve space for the linkage save area (LSA) on the stack.
7592 // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7593 // [SP][CR][LR][2 x reserved][TOC].
7594 // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7595 const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7596 const bool IsPPC64 = Subtarget.isPPC64();
7597 const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7598 const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7599 CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7600 CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7601
7602 // The prolog code of the callee may store up to 8 GPR argument registers to
7603 // the stack, allowing va_start to index over them in memory if the callee
7604 // is variadic.
7605 // Because we cannot tell if this is needed on the caller side, we have to
7606 // conservatively assume that it is needed. As such, make sure we have at
7607 // least enough stack space for the caller to store the 8 GPRs.
7608 const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7609 const unsigned NumBytes = std::max<unsigned>(
7610 LinkageSize + MinParameterSaveAreaSize, CCInfo.getStackSize());
7611
7612 // Adjust the stack pointer for the new arguments...
7613 // These operations are automatically eliminated by the prolog/epilog pass.
7614 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7615 SDValue CallSeqStart = Chain;
7616
7618 SmallVector<SDValue, 8> MemOpChains;
7619
7620 // Set up a copy of the stack pointer for loading and storing any
7621 // arguments that may not fit in the registers available for argument
7622 // passing.
7623 const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7624 : DAG.getRegister(PPC::R1, MVT::i32);
7625
7626 for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7627 const unsigned ValNo = ArgLocs[I].getValNo();
7628 SDValue Arg = OutVals[ValNo];
7629 ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7630
7631 if (Flags.isByVal()) {
7632 const unsigned ByValSize = Flags.getByValSize();
7633
7634 // Nothing to do for zero-sized ByVals on the caller side.
7635 if (!ByValSize) {
7636 ++I;
7637 continue;
7638 }
7639
7640 auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7641 return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7642 (LoadOffset != 0)
7643 ? DAG.getObjectPtrOffset(
7644 dl, Arg, TypeSize::getFixed(LoadOffset))
7645 : Arg,
7646 MachinePointerInfo(), VT);
7647 };
7648
7649 unsigned LoadOffset = 0;
7650
7651 // Initialize registers, which are fully occupied by the by-val argument.
7652 while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7653 SDValue Load = GetLoad(PtrVT, LoadOffset);
7654 MemOpChains.push_back(Load.getValue(1));
7655 LoadOffset += PtrByteSize;
7656 const CCValAssign &ByValVA = ArgLocs[I++];
7657 assert(ByValVA.getValNo() == ValNo &&
7658 "Unexpected location for pass-by-value argument.");
7659 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7660 }
7661
7662 if (LoadOffset == ByValSize)
7663 continue;
7664
7665 // There must be one more loc to handle the remainder.
7666 assert(ArgLocs[I].getValNo() == ValNo &&
7667 "Expected additional location for by-value argument.");
7668
7669 if (ArgLocs[I].isMemLoc()) {
7670 assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7671 const CCValAssign &ByValVA = ArgLocs[I++];
7672 ISD::ArgFlagsTy MemcpyFlags = Flags;
7673 // Only memcpy the bytes that don't pass in register.
7674 MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7675 Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7676 (LoadOffset != 0) ? DAG.getObjectPtrOffset(
7677 dl, Arg, TypeSize::getFixed(LoadOffset))
7678 : Arg,
7680 dl, StackPtr, TypeSize::getFixed(ByValVA.getLocMemOffset())),
7681 CallSeqStart, MemcpyFlags, DAG, dl);
7682 continue;
7683 }
7684
7685 // Initialize the final register residue.
7686 // Any residue that occupies the final by-val arg register must be
7687 // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7688 // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7689 // 2 and 1 byte loads.
7690 const unsigned ResidueBytes = ByValSize % PtrByteSize;
7691 assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7692 "Unexpected register residue for by-value argument.");
7693 SDValue ResidueVal;
7694 for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7695 const unsigned N = llvm::bit_floor(ResidueBytes - Bytes);
7696 const MVT VT =
7697 N == 1 ? MVT::i8
7698 : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7699 SDValue Load = GetLoad(VT, LoadOffset);
7700 MemOpChains.push_back(Load.getValue(1));
7701 LoadOffset += N;
7702 Bytes += N;
7703
7704 // By-val arguments are passed left-justfied in register.
7705 // Every load here needs to be shifted, otherwise a full register load
7706 // should have been used.
7707 assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7708 "Unexpected load emitted during handling of pass-by-value "
7709 "argument.");
7710 unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7711 EVT ShiftAmountTy =
7712 getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7713 SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7714 SDValue ShiftedLoad =
7715 DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7716 ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7717 ShiftedLoad)
7718 : ShiftedLoad;
7719 }
7720
7721 const CCValAssign &ByValVA = ArgLocs[I++];
7722 RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7723 continue;
7724 }
7725
7726 CCValAssign &VA = ArgLocs[I++];
7727 const MVT LocVT = VA.getLocVT();
7728 const MVT ValVT = VA.getValVT();
7729
7730 switch (VA.getLocInfo()) {
7731 default:
7732 report_fatal_error("Unexpected argument extension type.");
7733 case CCValAssign::Full:
7734 break;
7735 case CCValAssign::ZExt:
7736 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7737 break;
7738 case CCValAssign::SExt:
7739 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7740 break;
7741 }
7742
7743 if (VA.isRegLoc() && !VA.needsCustom()) {
7744 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7745 continue;
7746 }
7747
7748 // Vector arguments passed to VarArg functions need custom handling when
7749 // they are passed (at least partially) in GPRs.
7750 if (VA.isMemLoc() && VA.needsCustom() && ValVT.isVector()) {
7751 assert(CFlags.IsVarArg && "Custom MemLocs only used for Vector args.");
7752 // Store value to its stack slot.
7753 SDValue PtrOff =
7754 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7755 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7756 SDValue Store =
7757 DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
7758 MemOpChains.push_back(Store);
7759 const unsigned OriginalValNo = VA.getValNo();
7760 // Then load the GPRs from the stack
7761 unsigned LoadOffset = 0;
7762 auto HandleCustomVecRegLoc = [&]() {
7763 assert(I != E && "Unexpected end of CCvalAssigns.");
7764 assert(ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7765 "Expected custom RegLoc.");
7766 CCValAssign RegVA = ArgLocs[I++];
7767 assert(RegVA.getValNo() == OriginalValNo &&
7768 "Custom MemLoc ValNo and custom RegLoc ValNo must match.");
7769 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
7770 DAG.getConstant(LoadOffset, dl, PtrVT));
7771 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Add, MachinePointerInfo());
7772 MemOpChains.push_back(Load.getValue(1));
7773 RegsToPass.push_back(std::make_pair(RegVA.getLocReg(), Load));
7774 LoadOffset += PtrByteSize;
7775 };
7776
7777 // In 64-bit there will be exactly 2 custom RegLocs that follow, and in
7778 // in 32-bit there will be 2 custom RegLocs if we are passing in R9 and
7779 // R10.
7780 HandleCustomVecRegLoc();
7781 HandleCustomVecRegLoc();
7782
7783 if (I != E && ArgLocs[I].isRegLoc() && ArgLocs[I].needsCustom() &&
7784 ArgLocs[I].getValNo() == OriginalValNo) {
7785 assert(!IsPPC64 &&
7786 "Only 2 custom RegLocs expected for 64-bit codegen.");
7787 HandleCustomVecRegLoc();
7788 HandleCustomVecRegLoc();
7789 }
7790
7791 continue;
7792 }
7793
7794 if (VA.isMemLoc()) {
7795 SDValue PtrOff =
7796 DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7797 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7798 MemOpChains.push_back(
7799 DAG.getStore(Chain, dl, Arg, PtrOff,
7801 Subtarget.getFrameLowering()->getStackAlign()));
7802
7803 continue;
7804 }
7805
7806 if (!ValVT.isFloatingPoint())
7808 "Unexpected register handling for calling convention.");
7809
7810 // Custom handling is used for GPR initializations for vararg float
7811 // arguments.
7812 assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7813 LocVT.isInteger() &&
7814 "Custom register handling only expected for VarArg.");
7815
7816 SDValue ArgAsInt =
7817 DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7818
7819 if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7820 // f32 in 32-bit GPR
7821 // f64 in 64-bit GPR
7822 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7823 else if (Arg.getValueType().getFixedSizeInBits() <
7824 LocVT.getFixedSizeInBits())
7825 // f32 in 64-bit GPR.
7826 RegsToPass.push_back(std::make_pair(
7827 VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7828 else {
7829 // f64 in two 32-bit GPRs
7830 // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7831 assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7832 "Unexpected custom register for argument!");
7833 CCValAssign &GPR1 = VA;
7834 SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7835 DAG.getConstant(32, dl, MVT::i8));
7836 RegsToPass.push_back(std::make_pair(
7837 GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7838
7839 if (I != E) {
7840 // If only 1 GPR was available, there will only be one custom GPR and
7841 // the argument will also pass in memory.
7842 CCValAssign &PeekArg = ArgLocs[I];
7843 if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7844 assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7845 CCValAssign &GPR2 = ArgLocs[I++];
7846 RegsToPass.push_back(std::make_pair(
7847 GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7848 }
7849 }
7850 }
7851 }
7852
7853 if (!MemOpChains.empty())
7854 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7855
7856 // For indirect calls, we need to save the TOC base to the stack for
7857 // restoration after the call.
7858 if (CFlags.IsIndirect && !Subtarget.usePointerGlueHelper()) {
7859 assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7860 const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7861 const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7862 const MVT PtrVT = Subtarget.getScalarIntVT();
7863 const unsigned TOCSaveOffset =
7864 Subtarget.getFrameLowering()->getTOCSaveOffset();
7865
7866 setUsesTOCBasePtr(DAG);
7867 SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7868 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7869 SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7870 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7871 Chain = DAG.getStore(
7872 Val.getValue(1), dl, Val, AddPtr,
7873 MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7874 }
7875
7876 // Build a sequence of copy-to-reg nodes chained together with token chain
7877 // and flag operands which copy the outgoing args into the appropriate regs.
7878 SDValue InGlue;
7879 for (auto Reg : RegsToPass) {
7880 Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InGlue);
7881 InGlue = Chain.getValue(1);
7882 }
7883
7884 const int SPDiff = 0;
7885 return FinishCall(CFlags, dl, DAG, RegsToPass, InGlue, Chain, CallSeqStart,
7886 Callee, SPDiff, NumBytes, Ins, InVals, CB);
7887}
7888
7889bool
7890PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7891 MachineFunction &MF, bool isVarArg,
7894 const Type *RetTy) const {
7896 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7897 return CCInfo.CheckReturn(
7898 Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7900 : RetCC_PPC);
7901}
7902
7903SDValue
7904PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7905 bool isVarArg,
7907 const SmallVectorImpl<SDValue> &OutVals,
7908 const SDLoc &dl, SelectionDAG &DAG) const {
7910 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7911 *DAG.getContext());
7912 CCInfo.AnalyzeReturn(Outs,
7913 (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7915 : RetCC_PPC);
7916
7917 SDValue Glue;
7918 SmallVector<SDValue, 4> RetOps(1, Chain);
7919
7920 // Copy the result values into the output registers.
7921 for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7922 CCValAssign &VA = RVLocs[i];
7923 assert(VA.isRegLoc() && "Can only return in registers!");
7924
7925 SDValue Arg = OutVals[RealResIdx];
7926
7927 switch (VA.getLocInfo()) {
7928 default: llvm_unreachable("Unknown loc info!");
7929 case CCValAssign::Full: break;
7930 case CCValAssign::AExt:
7931 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7932 break;
7933 case CCValAssign::ZExt:
7934 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7935 break;
7936 case CCValAssign::SExt:
7937 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7938 break;
7939 }
7940 if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7941 bool isLittleEndian = Subtarget.isLittleEndian();
7942 // Legalize ret f64 -> ret 2 x i32.
7943 SDValue SVal =
7944 DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7945 DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7946 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7947 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7948 SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7949 DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7950 Glue = Chain.getValue(1);
7951 VA = RVLocs[++i]; // skip ahead to next loc
7952 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Glue);
7953 } else
7954 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Glue);
7955 Glue = Chain.getValue(1);
7956 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7957 }
7958
7959 RetOps[0] = Chain; // Update chain.
7960
7961 // Add the glue if we have it.
7962 if (Glue.getNode())
7963 RetOps.push_back(Glue);
7964
7965 return DAG.getNode(PPCISD::RET_GLUE, dl, MVT::Other, RetOps);
7966}
7967
7968SDValue
7969PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7970 SelectionDAG &DAG) const {
7971 SDLoc dl(Op);
7972
7973 // Get the correct type for integers.
7974 EVT IntVT = Op.getValueType();
7975
7976 // Get the inputs.
7977 SDValue Chain = Op.getOperand(0);
7978 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7979 // Build a DYNAREAOFFSET node.
7980 SDValue Ops[2] = {Chain, FPSIdx};
7981 SDVTList VTs = DAG.getVTList(IntVT);
7982 return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7983}
7984
7985SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7986 SelectionDAG &DAG) const {
7987 // When we pop the dynamic allocation we need to restore the SP link.
7988 SDLoc dl(Op);
7989
7990 // Get the correct type for pointers.
7991 EVT PtrVT = getPointerTy(DAG.getDataLayout());
7992
7993 // Construct the stack pointer operand.
7994 bool isPPC64 = Subtarget.isPPC64();
7995 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7996 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7997
7998 // Get the operands for the STACKRESTORE.
7999 SDValue Chain = Op.getOperand(0);
8000 SDValue SaveSP = Op.getOperand(1);
8001
8002 // Load the old link SP.
8003 SDValue LoadLinkSP =
8004 DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
8005
8006 // Restore the stack pointer.
8007 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
8008
8009 // Store the old link SP.
8010 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
8011}
8012
8013SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
8015 bool isPPC64 = Subtarget.isPPC64();
8016 EVT PtrVT = getPointerTy(MF.getDataLayout());
8017
8018 // Get current frame pointer save index. The users of this index will be
8019 // primarily DYNALLOC instructions.
8020 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8021 int RASI = FI->getReturnAddrSaveIndex();
8022
8023 // If the frame pointer save index hasn't been defined yet.
8024 if (!RASI) {
8025 // Find out what the fix offset of the frame pointer save area.
8026 int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
8027 // Allocate the frame index for frame pointer save area.
8028 RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
8029 // Save the result.
8030 FI->setReturnAddrSaveIndex(RASI);
8031 }
8032 return DAG.getFrameIndex(RASI, PtrVT);
8033}
8034
8035SDValue
8036PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
8038 bool isPPC64 = Subtarget.isPPC64();
8039 EVT PtrVT = getPointerTy(MF.getDataLayout());
8040
8041 // Get current frame pointer save index. The users of this index will be
8042 // primarily DYNALLOC instructions.
8043 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
8044 int FPSI = FI->getFramePointerSaveIndex();
8045
8046 // If the frame pointer save index hasn't been defined yet.
8047 if (!FPSI) {
8048 // Find out what the fix offset of the frame pointer save area.
8049 int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
8050 // Allocate the frame index for frame pointer save area.
8051 FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
8052 // Save the result.
8053 FI->setFramePointerSaveIndex(FPSI);
8054 }
8055 return DAG.getFrameIndex(FPSI, PtrVT);
8056}
8057
8058SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
8059 SelectionDAG &DAG) const {
8061 // Get the inputs.
8062 SDValue Chain = Op.getOperand(0);
8063 SDValue Size = Op.getOperand(1);
8064 SDLoc dl(Op);
8065
8066 // Get the correct type for pointers.
8067 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8068 // Negate the size.
8069 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
8070 DAG.getConstant(0, dl, PtrVT), Size);
8071 // Construct a node for the frame pointer save index.
8072 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
8073 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
8074 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
8075 if (hasInlineStackProbe(MF))
8076 return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
8077 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
8078}
8079
8080SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
8081 SelectionDAG &DAG) const {
8083
8084 bool isPPC64 = Subtarget.isPPC64();
8085 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8086
8087 int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
8088 return DAG.getFrameIndex(FI, PtrVT);
8089}
8090
8091SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
8092 SelectionDAG &DAG) const {
8093 SDLoc DL(Op);
8094 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
8095 DAG.getVTList(MVT::i32, MVT::Other),
8096 Op.getOperand(0), Op.getOperand(1));
8097}
8098
8099SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
8100 SelectionDAG &DAG) const {
8101 SDLoc DL(Op);
8102 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
8103 Op.getOperand(0), Op.getOperand(1));
8104}
8105
8106SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
8107 if (Op.getValueType().isVector())
8108 return LowerVectorLoad(Op, DAG);
8109
8110 assert(Op.getValueType() == MVT::i1 &&
8111 "Custom lowering only for i1 loads");
8112
8113 // First, load 8 bits into 32 bits, then truncate to 1 bit.
8114
8115 SDLoc dl(Op);
8116 LoadSDNode *LD = cast<LoadSDNode>(Op);
8117
8118 SDValue Chain = LD->getChain();
8119 SDValue BasePtr = LD->getBasePtr();
8120 MachineMemOperand *MMO = LD->getMemOperand();
8121
8122 SDValue NewLD =
8123 DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
8124 BasePtr, MVT::i8, MMO);
8125 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
8126
8127 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
8128 return DAG.getMergeValues(Ops, dl);
8129}
8130
8131SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8132 if (Op.getOperand(1).getValueType().isVector())
8133 return LowerVectorStore(Op, DAG);
8134
8135 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
8136 "Custom lowering only for i1 stores");
8137
8138 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
8139
8140 SDLoc dl(Op);
8141 StoreSDNode *ST = cast<StoreSDNode>(Op);
8142
8143 SDValue Chain = ST->getChain();
8144 SDValue BasePtr = ST->getBasePtr();
8145 SDValue Value = ST->getValue();
8146 MachineMemOperand *MMO = ST->getMemOperand();
8147
8149 Value);
8150 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
8151}
8152
8153// FIXME: Remove this once the ANDI glue bug is fixed:
8154SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8155 assert(Op.getValueType() == MVT::i1 &&
8156 "Custom lowering only for i1 results");
8157
8158 SDLoc DL(Op);
8159 return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
8160}
8161
8162SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
8163 SelectionDAG &DAG) const {
8164
8165 // Implements a vector truncate that fits in a vector register as a shuffle.
8166 // We want to legalize vector truncates down to where the source fits in
8167 // a vector register (and target is therefore smaller than vector register
8168 // size). At that point legalization will try to custom lower the sub-legal
8169 // result and get here - where we can contain the truncate as a single target
8170 // operation.
8171
8172 // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
8173 // <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
8174 //
8175 // We will implement it for big-endian ordering as this (where x denotes
8176 // undefined):
8177 // < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
8178 // < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
8179 //
8180 // The same operation in little-endian ordering will be:
8181 // <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
8182 // <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
8183
8184 EVT TrgVT = Op.getValueType();
8185 assert(TrgVT.isVector() && "Vector type expected.");
8186 unsigned TrgNumElts = TrgVT.getVectorNumElements();
8187 EVT EltVT = TrgVT.getVectorElementType();
8188 if (!isOperationCustom(Op.getOpcode(), TrgVT) ||
8189 TrgVT.getSizeInBits() > 128 || !isPowerOf2_32(TrgNumElts) ||
8191 return SDValue();
8192
8193 SDValue N1 = Op.getOperand(0);
8194 EVT SrcVT = N1.getValueType();
8195 unsigned SrcSize = SrcVT.getSizeInBits();
8196 if (SrcSize > 256 || !isPowerOf2_32(SrcVT.getVectorNumElements()) ||
8199 return SDValue();
8200 if (SrcSize == 256 && SrcVT.getVectorNumElements() < 2)
8201 return SDValue();
8202
8203 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8204 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8205
8206 SDLoc DL(Op);
8207 SDValue Op1, Op2;
8208 if (SrcSize == 256) {
8209 EVT VecIdxTy = getVectorIdxTy(DAG.getDataLayout());
8210 EVT SplitVT =
8212 unsigned SplitNumElts = SplitVT.getVectorNumElements();
8213 Op1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8214 DAG.getConstant(0, DL, VecIdxTy));
8215 Op2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, N1,
8216 DAG.getConstant(SplitNumElts, DL, VecIdxTy));
8217 }
8218 else {
8219 Op1 = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
8220 Op2 = DAG.getUNDEF(WideVT);
8221 }
8222
8223 // First list the elements we want to keep.
8224 unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
8225 SmallVector<int, 16> ShuffV;
8226 if (Subtarget.isLittleEndian())
8227 for (unsigned i = 0; i < TrgNumElts; ++i)
8228 ShuffV.push_back(i * SizeMult);
8229 else
8230 for (unsigned i = 1; i <= TrgNumElts; ++i)
8231 ShuffV.push_back(i * SizeMult - 1);
8232
8233 // Populate the remaining elements with undefs.
8234 for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
8235 // ShuffV.push_back(i + WideNumElts);
8236 ShuffV.push_back(WideNumElts + 1);
8237
8238 Op1 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op1);
8239 Op2 = DAG.getNode(ISD::BITCAST, DL, WideVT, Op2);
8240 return DAG.getVectorShuffle(WideVT, DL, Op1, Op2, ShuffV);
8241}
8242
8243/// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
8244/// possible.
8245SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
8246 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
8247 EVT ResVT = Op.getValueType();
8248 EVT CmpVT = Op.getOperand(0).getValueType();
8249 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8250 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
8251 SDLoc dl(Op);
8252
8253 // Without power9-vector, we don't have native instruction for f128 comparison.
8254 // Following transformation to libcall is needed for setcc:
8255 // select_cc lhs, rhs, tv, fv, cc -> select_cc (setcc cc, x, y), 0, tv, fv, NE
8256 if (!Subtarget.hasP9Vector() && CmpVT == MVT::f128) {
8257 SDValue Z = DAG.getSetCC(
8258 dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT),
8259 LHS, RHS, CC);
8260 SDValue Zero = DAG.getConstant(0, dl, Z.getValueType());
8261 return DAG.getSelectCC(dl, Z, Zero, TV, FV, ISD::SETNE);
8262 }
8263
8264 // Not FP, or using SPE? Not a fsel.
8265 if (!CmpVT.isFloatingPoint() || !TV.getValueType().isFloatingPoint() ||
8266 Subtarget.hasSPE())
8267 return Op;
8268
8269 SDNodeFlags Flags = Op.getNode()->getFlags();
8270
8271 // We have xsmaxc[dq]p/xsminc[dq]p which are OK to emit even in the
8272 // presence of infinities.
8273 if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
8274 switch (CC) {
8275 default:
8276 break;
8277 case ISD::SETOGT:
8278 case ISD::SETGT:
8279 return DAG.getNode(PPCISD::XSMAXC, dl, Op.getValueType(), LHS, RHS);
8280 case ISD::SETOLT:
8281 case ISD::SETLT:
8282 return DAG.getNode(PPCISD::XSMINC, dl, Op.getValueType(), LHS, RHS);
8283 }
8284 }
8285
8286 // We might be able to do better than this under some circumstances, but in
8287 // general, fsel-based lowering of select is a finite-math-only optimization.
8288 // For more information, see section F.3 of the 2.06 ISA specification.
8289 // With ISA 3.0
8290 if (!Flags.hasNoInfs() || !Flags.hasNoNaNs() || ResVT == MVT::f128)
8291 return Op;
8292
8293 // If the RHS of the comparison is a 0.0, we don't need to do the
8294 // subtraction at all.
8295 SDValue Sel1;
8297 switch (CC) {
8298 default: break; // SETUO etc aren't handled by fsel.
8299 case ISD::SETNE:
8300 std::swap(TV, FV);
8301 [[fallthrough]];
8302 case ISD::SETEQ:
8303 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8304 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8305 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8306 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8307 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
8308 case ISD::SETULT:
8309 case ISD::SETLT:
8310 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8311 [[fallthrough]];
8312 case ISD::SETOGE:
8313 case ISD::SETGE:
8314 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8315 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8316 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
8317 case ISD::SETUGT:
8318 case ISD::SETGT:
8319 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
8320 [[fallthrough]];
8321 case ISD::SETOLE:
8322 case ISD::SETLE:
8323 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
8324 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
8325 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8326 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
8327 }
8328
8329 SDValue Cmp;
8330 switch (CC) {
8331 default: break; // SETUO etc aren't handled by fsel.
8332 case ISD::SETNE:
8333 std::swap(TV, FV);
8334 [[fallthrough]];
8335 case ISD::SETEQ:
8336 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8337 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8338 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8339 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8340 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
8341 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
8342 case ISD::SETULT:
8343 case ISD::SETLT:
8344 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8345 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8346 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8347 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8348 case ISD::SETOGE:
8349 case ISD::SETGE:
8350 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
8351 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8352 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8353 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8354 case ISD::SETUGT:
8355 case ISD::SETGT:
8356 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8357 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8358 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8359 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
8360 case ISD::SETOLE:
8361 case ISD::SETLE:
8362 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
8363 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
8364 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
8365 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
8366 }
8367 return Op;
8368}
8369
8370static unsigned getPPCStrictOpcode(unsigned Opc) {
8371 switch (Opc) {
8372 default:
8373 llvm_unreachable("No strict version of this opcode!");
8374 case PPCISD::FCTIDZ:
8375 return PPCISD::STRICT_FCTIDZ;
8376 case PPCISD::FCTIWZ:
8377 return PPCISD::STRICT_FCTIWZ;
8378 case PPCISD::FCTIDUZ:
8379 return PPCISD::STRICT_FCTIDUZ;
8380 case PPCISD::FCTIWUZ:
8381 return PPCISD::STRICT_FCTIWUZ;
8382 case PPCISD::FCFID:
8383 return PPCISD::STRICT_FCFID;
8384 case PPCISD::FCFIDU:
8385 return PPCISD::STRICT_FCFIDU;
8386 case PPCISD::FCFIDS:
8387 return PPCISD::STRICT_FCFIDS;
8388 case PPCISD::FCFIDUS:
8389 return PPCISD::STRICT_FCFIDUS;
8390 }
8391}
8392
8394 const PPCSubtarget &Subtarget) {
8395 SDLoc dl(Op);
8396 bool IsStrict = Op->isStrictFPOpcode();
8397 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8398 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8399
8400 // TODO: Any other flags to propagate?
8401 SDNodeFlags Flags;
8402 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8403
8404 // For strict nodes, source is the second operand.
8405 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8406 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
8407 MVT DestTy = Op.getSimpleValueType();
8408 assert(Src.getValueType().isFloatingPoint() &&
8409 (DestTy == MVT::i8 || DestTy == MVT::i16 || DestTy == MVT::i32 ||
8410 DestTy == MVT::i64) &&
8411 "Invalid FP_TO_INT types");
8412 if (Src.getValueType() == MVT::f32) {
8413 if (IsStrict) {
8414 Src =
8416 DAG.getVTList(MVT::f64, MVT::Other), {Chain, Src}, Flags);
8417 Chain = Src.getValue(1);
8418 } else
8419 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8420 }
8421 if ((DestTy == MVT::i8 || DestTy == MVT::i16) && Subtarget.hasP9Vector())
8422 DestTy = Subtarget.getScalarIntVT();
8423 unsigned Opc = ISD::DELETED_NODE;
8424 switch (DestTy.SimpleTy) {
8425 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8426 case MVT::i32:
8427 Opc = IsSigned ? PPCISD::FCTIWZ
8428 : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8429 break;
8430 case MVT::i64:
8431 assert((IsSigned || Subtarget.hasFPCVT()) &&
8432 "i64 FP_TO_UINT is supported only with FPCVT");
8433 Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8434 }
8435 EVT ConvTy = Src.getValueType() == MVT::f128 ? MVT::f128 : MVT::f64;
8436 SDValue Conv;
8437 if (IsStrict) {
8439 Conv = DAG.getNode(Opc, dl, DAG.getVTList(ConvTy, MVT::Other), {Chain, Src},
8440 Flags);
8441 } else {
8442 Conv = DAG.getNode(Opc, dl, ConvTy, Src);
8443 }
8444 return Conv;
8445}
8446
8447void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8448 SelectionDAG &DAG,
8449 const SDLoc &dl) const {
8450 SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8451 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8452 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8453 bool IsStrict = Op->isStrictFPOpcode();
8454
8455 // Convert the FP value to an int value through memory.
8456 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8457 (IsSigned || Subtarget.hasFPCVT());
8458 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8459 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8460 MachinePointerInfo MPI =
8462
8463 // Emit a store to the stack slot.
8464 SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8466 if (i32Stack) {
8468 Alignment = Align(4);
8469 MachineMemOperand *MMO =
8470 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8471 SDValue Ops[] = { Chain, Tmp, FIPtr };
8472 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8473 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8474 } else
8475 Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8476
8477 // Result is a load from the stack slot. If loading 4 bytes, make sure to
8478 // add in a bias on big endian.
8479 if (Op.getValueType() == MVT::i32 && !i32Stack &&
8480 !Subtarget.isLittleEndian()) {
8481 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8482 DAG.getConstant(4, dl, FIPtr.getValueType()));
8483 MPI = MPI.getWithOffset(4);
8484 }
8485
8486 RLI.Chain = Chain;
8487 RLI.Ptr = FIPtr;
8488 RLI.MPI = MPI;
8489 RLI.Alignment = Alignment;
8490}
8491
8492/// Custom lowers floating point to integer conversions to use
8493/// the direct move instructions available in ISA 2.07 to avoid the
8494/// need for load/store combinations.
8495SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8496 SelectionDAG &DAG,
8497 const SDLoc &dl) const {
8498 SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8499 SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8500 if (Op->isStrictFPOpcode())
8501 return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8502 else
8503 return Mov;
8504}
8505
8506SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8507 const SDLoc &dl) const {
8508 bool IsStrict = Op->isStrictFPOpcode();
8509 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8510 Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8511 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8512 EVT SrcVT = Src.getValueType();
8513 EVT DstVT = Op.getValueType();
8514
8515 // FP to INT conversions are legal for f128.
8516 if (SrcVT == MVT::f128)
8517 return Subtarget.hasP9Vector() ? Op : SDValue();
8518
8519 // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8520 // PPC (the libcall is not available).
8521 if (SrcVT == MVT::ppcf128) {
8522 if (DstVT == MVT::i32) {
8523 // TODO: Conservatively pass only nofpexcept flag here. Need to check and
8524 // set other fast-math flags to FP operations in both strict and
8525 // non-strict cases. (FP_TO_SINT, FSUB)
8526 SDNodeFlags Flags;
8527 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8528
8529 if (IsSigned) {
8530 SDValue Lo, Hi;
8531 std::tie(Lo, Hi) = DAG.SplitScalar(Src, dl, MVT::f64, MVT::f64);
8532
8533 // Add the two halves of the long double in round-to-zero mode, and use
8534 // a smaller FP_TO_SINT.
8535 if (IsStrict) {
8536 SDValue Res = DAG.getNode(PPCISD::STRICT_FADDRTZ, dl,
8537 DAG.getVTList(MVT::f64, MVT::Other),
8538 {Op.getOperand(0), Lo, Hi}, Flags);
8539 return DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8540 DAG.getVTList(MVT::i32, MVT::Other),
8541 {Res.getValue(1), Res}, Flags);
8542 } else {
8543 SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8544 return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8545 }
8546 } else {
8547 const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8548 APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8549 SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8550 SDValue SignMask = DAG.getConstant(0x80000000, dl, DstVT);
8551 if (IsStrict) {
8552 // Sel = Src < 0x80000000
8553 // FltOfs = select Sel, 0.0, 0x80000000
8554 // IntOfs = select Sel, 0, 0x80000000
8555 // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8556 SDValue Chain = Op.getOperand(0);
8557 EVT SetCCVT =
8558 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8559 EVT DstSetCCVT =
8560 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8561 SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8562 Chain, true);
8563 Chain = Sel.getValue(1);
8564
8565 SDValue FltOfs = DAG.getSelect(
8566 dl, SrcVT, Sel, DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8567 Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8568
8569 SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl,
8570 DAG.getVTList(SrcVT, MVT::Other),
8571 {Chain, Src, FltOfs}, Flags);
8572 Chain = Val.getValue(1);
8573 SDValue SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl,
8574 DAG.getVTList(DstVT, MVT::Other),
8575 {Chain, Val}, Flags);
8576 Chain = SInt.getValue(1);
8577 SDValue IntOfs = DAG.getSelect(
8578 dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT), SignMask);
8579 SDValue Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8580 return DAG.getMergeValues({Result, Chain}, dl);
8581 } else {
8582 // X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8583 // FIXME: generated code sucks.
8584 SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Cst);
8585 True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8586 True = DAG.getNode(ISD::ADD, dl, MVT::i32, True, SignMask);
8587 SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8588 return DAG.getSelectCC(dl, Src, Cst, True, False, ISD::SETGE);
8589 }
8590 }
8591 }
8592
8593 return SDValue();
8594 }
8595
8596 if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8597 return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8598
8599 ReuseLoadInfo RLI;
8600 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8601
8602 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8603 RLI.Alignment, RLI.MMOFlags(),
8604 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8605}
8606
8607// We're trying to insert a regular store, S, and then a load, L. If the
8608// incoming value, O, is a load, we might just be able to have our load use the
8609// address used by O. However, we don't know if anything else will store to
8610// that address before we can load from it. To prevent this situation, we need
8611// to insert our load, L, into the chain as a peer of O. To do this, we give L
8612// the same chain operand as O, we create a token factor from the chain results
8613// of O and L, and we replace all uses of O's chain result with that token
8614// factor (this last part is handled by makeEquivalentMemoryOrdering).
8615bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8616 ReuseLoadInfo &RLI,
8617 SelectionDAG &DAG,
8618 ISD::LoadExtType ET) const {
8619 // Conservatively skip reusing for constrained FP nodes.
8620 if (Op->isStrictFPOpcode())
8621 return false;
8622
8623 SDLoc dl(Op);
8624 bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8625 (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8626 if (ET == ISD::NON_EXTLOAD &&
8627 (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8628 isOperationLegalOrCustom(Op.getOpcode(),
8629 Op.getOperand(0).getValueType())) {
8630
8631 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8632 return true;
8633 }
8634
8635 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8636 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8637 LD->isNonTemporal())
8638 return false;
8639 if (LD->getMemoryVT() != MemVT)
8640 return false;
8641
8642 // If the result of the load is an illegal type, then we can't build a
8643 // valid chain for reuse since the legalised loads and token factor node that
8644 // ties the legalised loads together uses a different output chain then the
8645 // illegal load.
8646 if (!isTypeLegal(LD->getValueType(0)))
8647 return false;
8648
8649 RLI.Ptr = LD->getBasePtr();
8650 if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8651 assert(LD->getAddressingMode() == ISD::PRE_INC &&
8652 "Non-pre-inc AM on PPC?");
8653 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8654 LD->getOffset());
8655 }
8656
8657 RLI.Chain = LD->getChain();
8658 RLI.MPI = LD->getPointerInfo();
8659 RLI.IsDereferenceable = LD->isDereferenceable();
8660 RLI.IsInvariant = LD->isInvariant();
8661 RLI.Alignment = LD->getAlign();
8662 RLI.AAInfo = LD->getAAInfo();
8663 RLI.Ranges = LD->getRanges();
8664
8665 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8666 return true;
8667}
8668
8669/// Analyze profitability of direct move
8670/// prefer float load to int load plus direct move
8671/// when there is no integer use of int load
8672bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8673 SDNode *Origin = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0).getNode();
8674 if (Origin->getOpcode() != ISD::LOAD)
8675 return true;
8676
8677 // If there is no LXSIBZX/LXSIHZX, like Power8,
8678 // prefer direct move if the memory size is 1 or 2 bytes.
8679 MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8680 if (!Subtarget.hasP9Vector() &&
8681 (!MMO->getSize().hasValue() || MMO->getSize().getValue() <= 2))
8682 return true;
8683
8684 for (SDUse &Use : Origin->uses()) {
8685
8686 // Only look at the users of the loaded value.
8687 if (Use.getResNo() != 0)
8688 continue;
8689
8690 SDNode *User = Use.getUser();
8691 if (User->getOpcode() != ISD::SINT_TO_FP &&
8692 User->getOpcode() != ISD::UINT_TO_FP &&
8693 User->getOpcode() != ISD::STRICT_SINT_TO_FP &&
8694 User->getOpcode() != ISD::STRICT_UINT_TO_FP)
8695 return true;
8696 }
8697
8698 return false;
8699}
8700
8702 const PPCSubtarget &Subtarget,
8703 SDValue Chain = SDValue()) {
8704 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8705 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8706 SDLoc dl(Op);
8707
8708 // TODO: Any other flags to propagate?
8709 SDNodeFlags Flags;
8710 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8711
8712 // If we have FCFIDS, then use it when converting to single-precision.
8713 // Otherwise, convert to double-precision and then round.
8714 bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8715 unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8716 : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8717 EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8718 if (Op->isStrictFPOpcode()) {
8719 if (!Chain)
8720 Chain = Op.getOperand(0);
8721 return DAG.getNode(getPPCStrictOpcode(ConvOpc), dl,
8722 DAG.getVTList(ConvTy, MVT::Other), {Chain, Src}, Flags);
8723 } else
8724 return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8725}
8726
8727/// Custom lowers integer to floating point conversions to use
8728/// the direct move instructions available in ISA 2.07 to avoid the
8729/// need for load/store combinations.
8730SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8731 SelectionDAG &DAG,
8732 const SDLoc &dl) const {
8733 assert((Op.getValueType() == MVT::f32 ||
8734 Op.getValueType() == MVT::f64) &&
8735 "Invalid floating point type as target of conversion");
8736 assert(Subtarget.hasFPCVT() &&
8737 "Int to FP conversions with direct moves require FPCVT");
8738 SDValue Src = Op.getOperand(Op->isStrictFPOpcode() ? 1 : 0);
8739 bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8740 bool Signed = Op.getOpcode() == ISD::SINT_TO_FP ||
8741 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8742 unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8743 SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8744 return convertIntToFP(Op, Mov, DAG, Subtarget);
8745}
8746
8747static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8748
8749 EVT VecVT = Vec.getValueType();
8750 assert(VecVT.isVector() && "Expected a vector type.");
8751 assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8752
8753 EVT EltVT = VecVT.getVectorElementType();
8754 unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8755 EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8756
8757 unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8758 SmallVector<SDValue, 16> Ops(NumConcat);
8759 Ops[0] = Vec;
8760 SDValue UndefVec = DAG.getUNDEF(VecVT);
8761 for (unsigned i = 1; i < NumConcat; ++i)
8762 Ops[i] = UndefVec;
8763
8764 return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8765}
8766
8767SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8768 const SDLoc &dl) const {
8769 bool IsStrict = Op->isStrictFPOpcode();
8770 unsigned Opc = Op.getOpcode();
8771 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8774 "Unexpected conversion type");
8775 assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8776 "Supports conversions to v2f64/v4f32 only.");
8777
8778 // TODO: Any other flags to propagate?
8779 SDNodeFlags Flags;
8780 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8781
8782 bool SignedConv = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
8783 bool FourEltRes = Op.getValueType() == MVT::v4f32;
8784
8785 SDValue Wide = widenVec(DAG, Src, dl);
8786 EVT WideVT = Wide.getValueType();
8787 unsigned WideNumElts = WideVT.getVectorNumElements();
8788 MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8789
8790 SmallVector<int, 16> ShuffV;
8791 for (unsigned i = 0; i < WideNumElts; ++i)
8792 ShuffV.push_back(i + WideNumElts);
8793
8794 int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8795 int SaveElts = FourEltRes ? 4 : 2;
8796 if (Subtarget.isLittleEndian())
8797 for (int i = 0; i < SaveElts; i++)
8798 ShuffV[i * Stride] = i;
8799 else
8800 for (int i = 1; i <= SaveElts; i++)
8801 ShuffV[i * Stride - 1] = i - 1;
8802
8803 SDValue ShuffleSrc2 =
8804 SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8805 SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8806
8807 SDValue Extend;
8808 if (SignedConv) {
8809 Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8810 EVT ExtVT = Src.getValueType();
8811 if (Subtarget.hasP9Altivec())
8812 ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8813 IntermediateVT.getVectorNumElements());
8814
8815 Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8816 DAG.getValueType(ExtVT));
8817 } else
8818 Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8819
8820 if (IsStrict)
8821 return DAG.getNode(Opc, dl, DAG.getVTList(Op.getValueType(), MVT::Other),
8822 {Op.getOperand(0), Extend}, Flags);
8823
8824 return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8825}
8826
8827SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8828 SelectionDAG &DAG) const {
8829 SDLoc dl(Op);
8830 bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP ||
8831 Op.getOpcode() == ISD::STRICT_SINT_TO_FP;
8832 bool IsStrict = Op->isStrictFPOpcode();
8833 SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8834 SDValue Chain = IsStrict ? Op.getOperand(0) : DAG.getEntryNode();
8835
8836 // TODO: Any other flags to propagate?
8837 SDNodeFlags Flags;
8838 Flags.setNoFPExcept(Op->getFlags().hasNoFPExcept());
8839
8840 EVT InVT = Src.getValueType();
8841 EVT OutVT = Op.getValueType();
8842 if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8843 isOperationCustom(Op.getOpcode(), InVT))
8844 return LowerINT_TO_FPVector(Op, DAG, dl);
8845
8846 // Conversions to f128 are legal.
8847 if (Op.getValueType() == MVT::f128)
8848 return Subtarget.hasP9Vector() ? Op : SDValue();
8849
8850 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8851 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8852 return SDValue();
8853
8854 if (Src.getValueType() == MVT::i1) {
8855 SDValue Sel = DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8856 DAG.getConstantFP(1.0, dl, Op.getValueType()),
8857 DAG.getConstantFP(0.0, dl, Op.getValueType()));
8858 if (IsStrict)
8859 return DAG.getMergeValues({Sel, Chain}, dl);
8860 else
8861 return Sel;
8862 }
8863
8864 // If we have direct moves, we can do all the conversion, skip the store/load
8865 // however, without FPCVT we can't do most conversions.
8866 if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8867 Subtarget.isPPC64() && Subtarget.hasFPCVT())
8868 return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8869
8870 assert((IsSigned || Subtarget.hasFPCVT()) &&
8871 "UINT_TO_FP is supported only with FPCVT");
8872
8873 if (Src.getValueType() == MVT::i64) {
8874 SDValue SINT = Src;
8875 // When converting to single-precision, we actually need to convert
8876 // to double-precision first and then round to single-precision.
8877 // To avoid double-rounding effects during that operation, we have
8878 // to prepare the input operand. Bits that might be truncated when
8879 // converting to double-precision are replaced by a bit that won't
8880 // be lost at this stage, but is below the single-precision rounding
8881 // position.
8882 //
8883 // However, if afn is in effect, accept double
8884 // rounding to avoid the extra overhead.
8885 // FIXME: Currently INT_TO_FP can't support fast math flags because
8886 // of nneg flag, thus Op->getFlags().hasApproximateFuncs() is always
8887 // false.
8888 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT() &&
8889 !Op->getFlags().hasApproximateFuncs()) {
8890
8891 // Twiddle input to make sure the low 11 bits are zero. (If this
8892 // is the case, we are guaranteed the value will fit into the 53 bit
8893 // mantissa of an IEEE double-precision value without rounding.)
8894 // If any of those low 11 bits were not zero originally, make sure
8895 // bit 12 (value 2048) is set instead, so that the final rounding
8896 // to single-precision gets the correct result.
8897 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8898 SINT, DAG.getConstant(2047, dl, MVT::i64));
8899 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8900 Round, DAG.getConstant(2047, dl, MVT::i64));
8901 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8902 Round = DAG.getNode(ISD::AND, dl, MVT::i64, Round,
8903 DAG.getSignedConstant(-2048, dl, MVT::i64));
8904
8905 // However, we cannot use that value unconditionally: if the magnitude
8906 // of the input value is small, the bit-twiddling we did above might
8907 // end up visibly changing the output. Fortunately, in that case, we
8908 // don't need to twiddle bits since the original input will convert
8909 // exactly to double-precision floating-point already. Therefore,
8910 // construct a conditional to use the original value if the top 11
8911 // bits are all sign-bit copies, and use the rounded value computed
8912 // above otherwise.
8913 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8914 SINT, DAG.getConstant(53, dl, MVT::i32));
8915 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8916 Cond, DAG.getConstant(1, dl, MVT::i64));
8917 Cond = DAG.getSetCC(
8918 dl,
8919 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8920 Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8921
8922 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8923 }
8924
8925 ReuseLoadInfo RLI;
8926 SDValue Bits;
8927
8929 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8930 // Drop range metadata, as this metadata becomes invalid for f64 bit
8931 // reinterpretation of i64 values.
8932 Bits =
8933 DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, RLI.Alignment,
8934 RLI.MMOFlags(), MMOMetadata(RLI.AAInfo));
8935 if (RLI.ResChain)
8936 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8937 } else if (Subtarget.hasLFIWAX() &&
8938 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8939 MachineMemOperand *MMO = MF.getMachineMemOperand(
8940 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8941 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8942 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8943 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8944 DAG.getVTList(MVT::f64, MVT::Other),
8945 Ops, MVT::i32, MMO);
8946 if (RLI.ResChain)
8947 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8948 } else if (Subtarget.hasFPCVT() &&
8949 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8950 MachineMemOperand *MMO = MF.getMachineMemOperand(
8951 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8952 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8953 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8954 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8955 DAG.getVTList(MVT::f64, MVT::Other),
8956 Ops, MVT::i32, MMO);
8957 if (RLI.ResChain)
8958 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
8959 } else if (((Subtarget.hasLFIWAX() &&
8960 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8961 (Subtarget.hasFPCVT() &&
8962 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8963 SINT.getOperand(0).getValueType() == MVT::i32) {
8964 MachineFrameInfo &MFI = MF.getFrameInfo();
8965 EVT PtrVT = getPointerTy(DAG.getDataLayout());
8966
8967 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8968 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8969
8970 SDValue Store = DAG.getStore(Chain, dl, SINT.getOperand(0), FIdx,
8972 DAG.getMachineFunction(), FrameIdx));
8973 Chain = Store;
8974
8975 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8976 "Expected an i32 store");
8977
8978 RLI.Ptr = FIdx;
8979 RLI.Chain = Chain;
8980 RLI.MPI =
8982 RLI.Alignment = Align(4);
8983
8984 MachineMemOperand *MMO = MF.getMachineMemOperand(
8985 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
8986 MMOMetadata(RLI.AAInfo, RLI.Ranges));
8987 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8989 PPCISD::LFIWZX : PPCISD::LFIWAX,
8990 dl, DAG.getVTList(MVT::f64, MVT::Other),
8991 Ops, MVT::i32, MMO);
8992 Chain = Bits.getValue(1);
8993 } else
8994 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8995
8996 SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget, Chain);
8997 if (IsStrict)
8998 Chain = FP.getValue(1);
8999
9000 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9001 if (IsStrict)
9002 FP = DAG.getNode(
9003 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
9004 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)},
9005 Flags);
9006 else
9007 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
9008 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
9009 }
9010 return FP;
9011 }
9012
9013 assert(Src.getValueType() == MVT::i32 &&
9014 "Unhandled INT_TO_FP type in custom expander!");
9015 // Since we only generate this in 64-bit mode, we can take advantage of
9016 // 64-bit registers. In particular, sign extend the input value into the
9017 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
9018 // then lfd it and fcfid it.
9020 MachineFrameInfo &MFI = MF.getFrameInfo();
9021 EVT PtrVT = getPointerTy(MF.getDataLayout());
9022
9023 SDValue Ld;
9024 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
9025 ReuseLoadInfo RLI;
9026 bool ReusingLoad;
9027 if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
9028 int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
9029 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9030
9031 SDValue Store = DAG.getStore(Chain, dl, Src, FIdx,
9033 DAG.getMachineFunction(), FrameIdx));
9034 Chain = Store;
9035
9036 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
9037 "Expected an i32 store");
9038
9039 RLI.Ptr = FIdx;
9040 RLI.Chain = Chain;
9041 RLI.MPI =
9043 RLI.Alignment = Align(4);
9044 }
9045
9046 MachineMemOperand *MMO = MF.getMachineMemOperand(
9047 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
9048 MMOMetadata(RLI.AAInfo, RLI.Ranges));
9049 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
9050 Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
9051 DAG.getVTList(MVT::f64, MVT::Other), Ops,
9052 MVT::i32, MMO);
9053 Chain = Ld.getValue(1);
9054 if (ReusingLoad && RLI.ResChain) {
9055 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Ld.getValue(1));
9056 }
9057 } else {
9058 assert(Subtarget.isPPC64() &&
9059 "i32->FP without LFIWAX supported only on PPC64");
9060
9061 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
9062 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9063
9064 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
9065
9066 // STD the extended value into the stack slot.
9067 SDValue Store = DAG.getStore(
9068 Chain, dl, Ext64, FIdx,
9070 Chain = Store;
9071
9072 // Load the value as a double.
9073 Ld = DAG.getLoad(
9074 MVT::f64, dl, Chain, FIdx,
9076 Chain = Ld.getValue(1);
9077 }
9078
9079 // FCFID it and return it.
9080 SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget, Chain);
9081 if (IsStrict)
9082 Chain = FP.getValue(1);
9083 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
9084 if (IsStrict)
9085 FP = DAG.getNode(
9086 ISD::STRICT_FP_ROUND, dl, DAG.getVTList(MVT::f32, MVT::Other),
9087 {Chain, FP, DAG.getIntPtrConstant(0, dl, /*isTarget=*/true)}, Flags);
9088 else
9089 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
9090 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
9091 }
9092 return FP;
9093}
9094
9095SDValue PPCTargetLowering::LowerSET_ROUNDING(SDValue Op,
9096 SelectionDAG &DAG) const {
9097 SDLoc Dl(Op);
9099 EVT PtrVT = getPointerTy(MF.getDataLayout());
9100 SDValue Chain = Op.getOperand(0);
9101
9102 // If requested mode is constant, just use simpler mtfsb/mffscrni
9103 if (auto *CVal = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9104 uint64_t Mode = CVal->getZExtValue();
9105 assert(Mode < 4 && "Unsupported rounding mode!");
9106 unsigned InternalRnd = Mode ^ (~(Mode >> 1) & 1);
9107 if (Subtarget.isISA3_0())
9108 return SDValue(
9109 DAG.getMachineNode(
9110 PPC::MFFSCRNI, Dl, {MVT::f64, MVT::Other},
9111 {DAG.getConstant(InternalRnd, Dl, MVT::i32, true), Chain}),
9112 1);
9113 SDNode *SetHi = DAG.getMachineNode(
9114 (InternalRnd & 2) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9115 {DAG.getConstant(30, Dl, MVT::i32, true), Chain});
9116 SDNode *SetLo = DAG.getMachineNode(
9117 (InternalRnd & 1) ? PPC::MTFSB1 : PPC::MTFSB0, Dl, MVT::Other,
9118 {DAG.getConstant(31, Dl, MVT::i32, true), SDValue(SetHi, 0)});
9119 return SDValue(SetLo, 0);
9120 }
9121
9122 // Use x ^ (~(x >> 1) & 1) to transform LLVM rounding mode to Power format.
9123 SDValue One = DAG.getConstant(1, Dl, MVT::i32);
9124 SDValue SrcFlag = DAG.getNode(ISD::AND, Dl, MVT::i32, Op.getOperand(1),
9125 DAG.getConstant(3, Dl, MVT::i32));
9126 SDValue DstFlag = DAG.getNode(
9127 ISD::XOR, Dl, MVT::i32, SrcFlag,
9128 DAG.getNode(ISD::AND, Dl, MVT::i32,
9129 DAG.getNOT(Dl,
9130 DAG.getNode(ISD::SRL, Dl, MVT::i32, SrcFlag, One),
9131 MVT::i32),
9132 One));
9133 // For Power9, there's faster mffscrn, and we don't need to read FPSCR
9134 SDValue MFFS;
9135 if (!Subtarget.isISA3_0()) {
9136 MFFS = DAG.getNode(PPCISD::MFFS, Dl, {MVT::f64, MVT::Other}, Chain);
9137 Chain = MFFS.getValue(1);
9138 }
9139 SDValue NewFPSCR;
9140 if (Subtarget.isPPC64()) {
9141 if (Subtarget.isISA3_0()) {
9142 NewFPSCR = DAG.getAnyExtOrTrunc(DstFlag, Dl, MVT::i64);
9143 } else {
9144 // Set the last two bits (rounding mode) of bitcasted FPSCR.
9145 SDNode *InsertRN = DAG.getMachineNode(
9146 PPC::RLDIMI, Dl, MVT::i64,
9147 {DAG.getNode(ISD::BITCAST, Dl, MVT::i64, MFFS),
9148 DAG.getNode(ISD::ZERO_EXTEND, Dl, MVT::i64, DstFlag),
9149 DAG.getTargetConstant(0, Dl, MVT::i32),
9150 DAG.getTargetConstant(62, Dl, MVT::i32)});
9151 NewFPSCR = SDValue(InsertRN, 0);
9152 }
9153 NewFPSCR = DAG.getNode(ISD::BITCAST, Dl, MVT::f64, NewFPSCR);
9154 } else {
9155 // In 32-bit mode, store f64, load and update the lower half.
9156 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9157 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9158 SDValue Addr = Subtarget.isLittleEndian()
9159 ? StackSlot
9160 : DAG.getNode(ISD::ADD, Dl, PtrVT, StackSlot,
9161 DAG.getConstant(4, Dl, PtrVT));
9162 if (Subtarget.isISA3_0()) {
9163 Chain = DAG.getStore(Chain, Dl, DstFlag, Addr, MachinePointerInfo());
9164 } else {
9165 Chain = DAG.getStore(Chain, Dl, MFFS, StackSlot, MachinePointerInfo());
9166 SDValue Tmp =
9167 DAG.getLoad(MVT::i32, Dl, Chain, Addr, MachinePointerInfo());
9168 Chain = Tmp.getValue(1);
9169 Tmp = SDValue(DAG.getMachineNode(
9170 PPC::RLWIMI, Dl, MVT::i32,
9171 {Tmp, DstFlag, DAG.getTargetConstant(0, Dl, MVT::i32),
9172 DAG.getTargetConstant(30, Dl, MVT::i32),
9173 DAG.getTargetConstant(31, Dl, MVT::i32)}),
9174 0);
9175 Chain = DAG.getStore(Chain, Dl, Tmp, Addr, MachinePointerInfo());
9176 }
9177 NewFPSCR =
9178 DAG.getLoad(MVT::f64, Dl, Chain, StackSlot, MachinePointerInfo());
9179 Chain = NewFPSCR.getValue(1);
9180 }
9181 if (Subtarget.isISA3_0())
9182 return SDValue(DAG.getMachineNode(PPC::MFFSCRN, Dl, {MVT::f64, MVT::Other},
9183 {NewFPSCR, Chain}),
9184 1);
9185 SDValue Zero = DAG.getConstant(0, Dl, MVT::i32, true);
9186 SDNode *MTFSF = DAG.getMachineNode(
9187 PPC::MTFSF, Dl, MVT::Other,
9188 {DAG.getConstant(255, Dl, MVT::i32, true), NewFPSCR, Zero, Zero, Chain});
9189 return SDValue(MTFSF, 0);
9190}
9191
9192SDValue PPCTargetLowering::LowerGET_ROUNDING(SDValue Op,
9193 SelectionDAG &DAG) const {
9194 SDLoc dl(Op);
9195 /*
9196 The rounding mode is in bits 30:31 of FPSR, and has the following
9197 settings:
9198 00 Round to nearest
9199 01 Round to 0
9200 10 Round to +inf
9201 11 Round to -inf
9202
9203 GET_ROUNDING, on the other hand, expects the following:
9204 -1 Undefined
9205 0 Round to 0
9206 1 Round to nearest
9207 2 Round to +inf
9208 3 Round to -inf
9209
9210 To perform the conversion, we do:
9211 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
9212 */
9213
9215 EVT VT = Op.getValueType();
9216 EVT PtrVT = getPointerTy(MF.getDataLayout());
9217
9218 // Save FP Control Word to register
9219 SDValue Chain = Op.getOperand(0);
9220 SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
9221 Chain = MFFS.getValue(1);
9222
9223 SDValue CWD;
9224 if (isTypeLegal(MVT::i64)) {
9225 CWD = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
9226 DAG.getNode(ISD::BITCAST, dl, MVT::i64, MFFS));
9227 } else {
9228 // Save FP register to stack slot
9229 int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
9230 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
9231 Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
9232
9233 // Load FP Control Word from low 32 bits of stack slot.
9235 "Stack slot adjustment is valid only on big endian subtargets!");
9236 SDValue Four = DAG.getConstant(4, dl, PtrVT);
9237 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
9238 CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
9239 Chain = CWD.getValue(1);
9240 }
9241
9242 // Transform as necessary
9243 SDValue CWD1 =
9244 DAG.getNode(ISD::AND, dl, MVT::i32,
9245 CWD, DAG.getConstant(3, dl, MVT::i32));
9246 SDValue CWD2 =
9247 DAG.getNode(ISD::SRL, dl, MVT::i32,
9248 DAG.getNode(ISD::AND, dl, MVT::i32,
9249 DAG.getNode(ISD::XOR, dl, MVT::i32,
9250 CWD, DAG.getConstant(3, dl, MVT::i32)),
9251 DAG.getConstant(3, dl, MVT::i32)),
9252 DAG.getConstant(1, dl, MVT::i32));
9253
9254 SDValue RetVal =
9255 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
9256
9257 RetVal =
9259 dl, VT, RetVal);
9260
9261 return DAG.getMergeValues({RetVal, Chain}, dl);
9262}
9263
9264SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9265 EVT VT = Op.getValueType();
9267 SDLoc dl(Op);
9268 assert(Op.getNumOperands() == 3 &&
9269 VT == Op.getOperand(1).getValueType() &&
9270 "Unexpected SHL!");
9271
9272 // Expand into a bunch of logical ops. Note that these ops
9273 // depend on the PPC behavior for oversized shift amounts.
9274 SDValue Lo = Op.getOperand(0);
9275 SDValue Hi = Op.getOperand(1);
9276 SDValue Amt = Op.getOperand(2);
9277 EVT AmtVT = Amt.getValueType();
9278
9279 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9280 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9281 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
9282 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
9283 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
9284 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9285 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9286 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
9287 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9288 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
9289 SDValue OutOps[] = { OutLo, OutHi };
9290 return DAG.getMergeValues(OutOps, dl);
9291}
9292
9293SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
9294 EVT VT = Op.getValueType();
9295 SDLoc dl(Op);
9297 assert(Op.getNumOperands() == 3 &&
9298 VT == Op.getOperand(1).getValueType() &&
9299 "Unexpected SRL!");
9300
9301 // Expand into a bunch of logical ops. Note that these ops
9302 // depend on the PPC behavior for oversized shift amounts.
9303 SDValue Lo = Op.getOperand(0);
9304 SDValue Hi = Op.getOperand(1);
9305 SDValue Amt = Op.getOperand(2);
9306 EVT AmtVT = Amt.getValueType();
9307
9308 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9309 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9310 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9311 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9312 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9313 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9314 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9315 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
9316 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
9317 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
9318 SDValue OutOps[] = { OutLo, OutHi };
9319 return DAG.getMergeValues(OutOps, dl);
9320}
9321
9322SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
9323 SDLoc dl(Op);
9324 EVT VT = Op.getValueType();
9326 assert(Op.getNumOperands() == 3 &&
9327 VT == Op.getOperand(1).getValueType() &&
9328 "Unexpected SRA!");
9329
9330 // Expand into a bunch of logical ops, followed by a select_cc.
9331 SDValue Lo = Op.getOperand(0);
9332 SDValue Hi = Op.getOperand(1);
9333 SDValue Amt = Op.getOperand(2);
9334 EVT AmtVT = Amt.getValueType();
9335
9336 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
9337 DAG.getConstant(BitWidth, dl, AmtVT), Amt);
9338 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
9339 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
9340 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9341 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
9342 DAG.getSignedConstant(-BitWidth, dl, AmtVT));
9343 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
9344 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
9345 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
9346 Tmp4, Tmp6, ISD::SETLE);
9347 SDValue OutOps[] = { OutLo, OutHi };
9348 return DAG.getMergeValues(OutOps, dl);
9349}
9350
9351SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
9352 SelectionDAG &DAG) const {
9353 SDLoc dl(Op);
9354 EVT VT = Op.getValueType();
9355 unsigned BitWidth = VT.getSizeInBits();
9356
9357 bool IsFSHL = Op.getOpcode() == ISD::FSHL;
9358 SDValue X = Op.getOperand(0);
9359 SDValue Y = Op.getOperand(1);
9360 SDValue Z = Op.getOperand(2);
9361 EVT AmtVT = Z.getValueType();
9362
9363 // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
9364 // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
9365 // This is simpler than TargetLowering::expandFunnelShift because we can rely
9366 // on PowerPC shift by BW being well defined.
9367 Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
9368 DAG.getConstant(BitWidth - 1, dl, AmtVT));
9369 SDValue SubZ =
9370 DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
9371 X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
9372 Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
9373 return DAG.getNode(ISD::OR, dl, VT, X, Y);
9374}
9375
9376//===----------------------------------------------------------------------===//
9377// Vector related lowering.
9378//
9379
9380/// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
9381/// element size of SplatSize. Cast the result to VT.
9382static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
9383 SelectionDAG &DAG, const SDLoc &dl) {
9384 static const MVT VTys[] = { // canonical VT to use for each size.
9385 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
9386 };
9387
9388 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
9389
9390 // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
9391 if (Val == ((1LLU << (SplatSize * 8)) - 1)) {
9392 SplatSize = 1;
9393 Val = 0xFF;
9394 }
9395
9396 EVT CanonicalVT = VTys[SplatSize-1];
9397
9398 // Build a canonical splat for this value.
9399 // Explicitly truncate APInt here, as this API is used with a mix of
9400 // signed and unsigned values.
9401 return DAG.getBitcast(
9402 ReqVT,
9403 DAG.getConstant(APInt(64, Val).trunc(SplatSize * 8), dl, CanonicalVT));
9404}
9405
9406/// BuildIntrinsicOp - Return a unary operator intrinsic node with the
9407/// specified intrinsic ID.
9409 const SDLoc &dl, EVT DestVT = MVT::Other) {
9410 if (DestVT == MVT::Other) DestVT = Op.getValueType();
9411 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9412 DAG.getConstant(IID, dl, MVT::i32), Op);
9413}
9414
9415/// BuildIntrinsicOp - Return a binary operator intrinsic node with the
9416/// specified intrinsic ID.
9418 SelectionDAG &DAG, const SDLoc &dl,
9419 EVT DestVT = MVT::Other) {
9420 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
9421 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9422 DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
9423}
9424
9425/// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
9426/// specified intrinsic ID.
9427static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
9428 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
9429 EVT DestVT = MVT::Other) {
9430 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
9431 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
9432 DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
9433}
9434
9435/// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
9436/// amount. The result has the specified value type.
9437static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
9438 SelectionDAG &DAG, const SDLoc &dl) {
9439 // Force LHS/RHS to be the right type.
9440 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
9441 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
9442
9443 int Ops[16];
9444 for (unsigned i = 0; i != 16; ++i)
9445 Ops[i] = i + Amt;
9446 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
9447 return DAG.getNode(ISD::BITCAST, dl, VT, T);
9448}
9449
9450/// Do we have an efficient pattern in a .td file for this node?
9451///
9452/// \param V - pointer to the BuildVectorSDNode being matched
9453/// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
9454///
9455/// There are some patterns where it is beneficial to keep a BUILD_VECTOR
9456/// node as a BUILD_VECTOR node rather than expanding it. The patterns where
9457/// the opposite is true (expansion is beneficial) are:
9458/// - The node builds a vector out of integers that are not 32 or 64-bits
9459/// - The node builds a vector out of constants
9460/// - The node is a "load-and-splat"
9461/// In all other cases, we will choose to keep the BUILD_VECTOR.
9463 bool HasDirectMove,
9464 bool HasP8Vector) {
9465 EVT VecVT = V->getValueType(0);
9466 bool RightType = VecVT == MVT::v2f64 ||
9467 (HasP8Vector && VecVT == MVT::v4f32) ||
9468 (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
9469 if (!RightType)
9470 return false;
9471
9472 bool IsSplat = true;
9473 bool IsLoad = false;
9474 SDValue Op0 = V->getOperand(0);
9475
9476 // This function is called in a block that confirms the node is not a constant
9477 // splat. So a constant BUILD_VECTOR here means the vector is built out of
9478 // different constants.
9479 if (V->isConstant())
9480 return false;
9481 for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
9482 if (V->getOperand(i).isUndef())
9483 return false;
9484 // We want to expand nodes that represent load-and-splat even if the
9485 // loaded value is a floating point truncation or conversion to int.
9486 if (V->getOperand(i).getOpcode() == ISD::LOAD ||
9487 (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
9488 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9489 (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
9490 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
9491 (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
9492 V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
9493 IsLoad = true;
9494 // If the operands are different or the input is not a load and has more
9495 // uses than just this BV node, then it isn't a splat.
9496 if (V->getOperand(i) != Op0 ||
9497 (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
9498 IsSplat = false;
9499 }
9500 return !(IsSplat && IsLoad);
9501}
9502
9503// Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
9504SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
9505
9506 SDLoc dl(Op);
9507 SDValue Op0 = Op->getOperand(0);
9508
9509 if (!Subtarget.isPPC64() || (Op0.getOpcode() != ISD::BUILD_PAIR) ||
9510 (Op.getValueType() != MVT::f128))
9511 return SDValue();
9512
9513 SDValue Lo = Op0.getOperand(0);
9514 SDValue Hi = Op0.getOperand(1);
9515 if ((Lo.getValueType() != MVT::i64) || (Hi.getValueType() != MVT::i64))
9516 return SDValue();
9517
9518 if (!Subtarget.isLittleEndian())
9519 std::swap(Lo, Hi);
9520
9521 return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Lo, Hi);
9522}
9523
9524// Look through bitcasts and scalar_to_vector ops to find the input load.
9525// If any of the nodes in the chain have multiple uses, stop searching as
9526// the input load won't be removable (due to the other uses).
9527static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
9528 const SDValue *InputLoad = &Op;
9529 while (InputLoad->getOpcode() == ISD::BITCAST) {
9530 if (!InputLoad->hasOneUse())
9531 return nullptr;
9532 InputLoad = &InputLoad->getOperand(0);
9533 }
9534 if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
9535 InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
9536 if (!InputLoad->hasOneUse())
9537 return nullptr;
9538 IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
9539 InputLoad = &InputLoad->getOperand(0);
9540 }
9541 if (InputLoad->getOpcode() != ISD::LOAD)
9542 return nullptr;
9543 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9544 return (ISD::isNormalLoad(LD) && LD->hasOneUse()) ? InputLoad : nullptr;
9545}
9546
9547// Convert the argument APFloat to a single precision APFloat if there is no
9548// loss in information during the conversion to single precision APFloat and the
9549// resulting number is not a denormal number. Return true if successful.
9551 APFloat APFloatToConvert = ArgAPFloat;
9552 bool LosesInfo = true;
9554 &LosesInfo);
9555 bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
9556 if (Success)
9557 ArgAPFloat = APFloatToConvert;
9558 return Success;
9559}
9560
9561// Bitcast the argument APInt to a double and convert it to a single precision
9562// APFloat, bitcast the APFloat to an APInt and assign it to the original
9563// argument if there is no loss in information during the conversion from
9564// double to single precision APFloat and the resulting number is not a denormal
9565// number. Return true if successful.
9567 double DpValue = ArgAPInt.bitsToDouble();
9568 APFloat APFloatDp(DpValue);
9569 bool Success = convertToNonDenormSingle(APFloatDp);
9570 if (Success)
9571 ArgAPInt = APFloatDp.bitcastToAPInt();
9572 return Success;
9573}
9574
9575// Nondestructive check for convertTonNonDenormSingle.
9577 // Only convert if it loses info, since XXSPLTIDP should
9578 // handle the other case.
9579 APFloat APFloatToConvert = ArgAPFloat;
9580 bool LosesInfo = true;
9582 &LosesInfo);
9583
9584 return (!LosesInfo && !APFloatToConvert.isDenormal());
9585}
9586
9587static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op,
9588 unsigned &Opcode) {
9589 LoadSDNode *InputNode = dyn_cast<LoadSDNode>(Op.getOperand(0));
9590 if (!InputNode || !Subtarget.hasVSX() || !ISD::isUNINDEXEDLoad(InputNode))
9591 return false;
9592
9593 EVT Ty = Op->getValueType(0);
9594 // For v2f64, v4f32 and v4i32 types, we require the load to be non-extending
9595 // as we cannot handle extending loads for these types.
9596 if ((Ty == MVT::v2f64 || Ty == MVT::v4f32 || Ty == MVT::v4i32) &&
9597 ISD::isNON_EXTLoad(InputNode))
9598 return true;
9599
9600 EVT MemVT = InputNode->getMemoryVT();
9601 // For v8i16 and v16i8 types, extending loads can be handled as long as the
9602 // memory VT is the same vector element VT type.
9603 // The loads feeding into the v8i16 and v16i8 types will be extending because
9604 // scalar i8/i16 are not legal types.
9605 if ((Ty == MVT::v8i16 || Ty == MVT::v16i8) && ISD::isEXTLoad(InputNode) &&
9606 (MemVT == Ty.getVectorElementType()))
9607 return true;
9608
9609 if (Ty == MVT::v2i64) {
9610 // Check the extend type, when the input type is i32, and the output vector
9611 // type is v2i64.
9612 if (MemVT == MVT::i32) {
9613 if (ISD::isZEXTLoad(InputNode))
9614 Opcode = PPCISD::ZEXT_LD_SPLAT;
9615 if (ISD::isSEXTLoad(InputNode))
9616 Opcode = PPCISD::SEXT_LD_SPLAT;
9617 }
9618 return true;
9619 }
9620 return false;
9621}
9622
9624 bool IsLittleEndian) {
9625 assert(BVN.getNumOperands() > 0 && "Unexpected 0-size build vector");
9626
9627 BitMask.clearAllBits();
9628 EVT VT = BVN.getValueType(0);
9629 unsigned VTSize = VT.getSizeInBits();
9630 APInt ConstValue(VTSize, 0);
9631
9632 unsigned EltWidth = VT.getScalarSizeInBits();
9633
9634 unsigned BitPos = 0;
9635 for (auto OpVal : BVN.op_values()) {
9636 auto *CN = dyn_cast<ConstantSDNode>(OpVal);
9637
9638 if (!CN)
9639 return false;
9640 // The elements in a vector register are ordered in reverse byte order
9641 // between little-endian and big-endian modes.
9642 ConstValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth),
9643 IsLittleEndian ? BitPos : VTSize - EltWidth - BitPos);
9644 BitPos += EltWidth;
9645 }
9646
9647 for (unsigned J = 0; J < 16; ++J) {
9648 APInt ExtractValue = ConstValue.extractBits(8, J * 8);
9649 if (ExtractValue != 0x00 && ExtractValue != 0xFF)
9650 return false;
9651 if (ExtractValue == 0xFF)
9652 BitMask.setBit(J);
9653 }
9654 return true;
9655}
9656
9657// If this is a case we can't handle, return null and let the default
9658// expansion code take care of it. If we CAN select this case, and if it
9659// selects to a single instruction, return Op. Otherwise, if we can codegen
9660// this case more efficiently than a constant pool load, lower it to the
9661// sequence of ops that should be used.
9662SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
9663 SelectionDAG &DAG) const {
9664 SDLoc dl(Op);
9665 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9666 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
9667
9668 if (Subtarget.hasP10Vector()) {
9669 APInt BitMask(32, 0);
9670 // If the value of the vector is all zeros or all ones,
9671 // we do not convert it to MTVSRBMI.
9672 // The xxleqv instruction sets a vector with all ones.
9673 // The xxlxor instruction sets a vector with all zeros.
9674 if (isValidMtVsrBmi(BitMask, *BVN, Subtarget.isLittleEndian()) &&
9675 BitMask != 0 && BitMask != 0xffff) {
9676 SDValue SDConstant = DAG.getTargetConstant(BitMask, dl, MVT::i32);
9677 MachineSDNode *MSDNode =
9678 DAG.getMachineNode(PPC::MTVSRBMI, dl, MVT::v16i8, SDConstant);
9679 SDValue SDV = SDValue(MSDNode, 0);
9680 EVT DVT = BVN->getValueType(0);
9681 EVT SVT = SDV.getValueType();
9682 if (SVT != DVT) {
9683 SDV = DAG.getNode(ISD::BITCAST, dl, DVT, SDV);
9684 }
9685 return SDV;
9686 }
9687 // Recognize build vector patterns to emit VSX vector instructions
9688 // instead of loading value from memory.
9689 if (SDValue VecPat = combineBVLoadsSpecialValue(Op, DAG))
9690 return VecPat;
9691 }
9692 // Check if this is a splat of a constant value.
9693 APInt APSplatBits, APSplatUndef;
9694 unsigned SplatBitSize = 0;
9695 bool HasAnyUndefs;
9696 bool BVNIsConstantSplat =
9697 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
9698 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
9699
9700 // If it is a splat of a double, check if we can shrink it to a 32 bit
9701 // non-denormal float which when converted back to double gives us the same
9702 // double. This is to exploit the XXSPLTIDP instruction.
9703 // If we lose precision, we use XXSPLTI32DX.
9704 if (BVNIsConstantSplat && (SplatBitSize == 64) &&
9705 Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
9706 // Check the type first to short-circuit so we don't modify APSplatBits if
9707 // this block isn't executed.
9708 if ((Op->getValueType(0) == MVT::v2f64) &&
9709 convertToNonDenormSingle(APSplatBits)) {
9710 SDValue SplatNode = DAG.getNode(
9711 PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
9712 DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
9713 return DAG.getBitcast(Op.getValueType(), SplatNode);
9714 } else {
9715 // We may lose precision, so we have to use XXSPLTI32DX.
9716
9717 uint32_t Hi = Hi_32(APSplatBits.getZExtValue());
9718 uint32_t Lo = Lo_32(APSplatBits.getZExtValue());
9719 SDValue SplatNode = DAG.getUNDEF(MVT::v2i64);
9720
9721 if (!Hi || !Lo)
9722 // If either load is 0, then we should generate XXLXOR to set to 0.
9723 SplatNode = DAG.getTargetConstant(0, dl, MVT::v2i64);
9724
9725 if (Hi)
9726 SplatNode = DAG.getNode(
9727 PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9728 DAG.getTargetConstant(0, dl, MVT::i32),
9729 DAG.getTargetConstant(Hi, dl, MVT::i32));
9730
9731 if (Lo)
9732 SplatNode =
9733 DAG.getNode(PPCISD::XXSPLTI32DX, dl, MVT::v2i64, SplatNode,
9734 DAG.getTargetConstant(1, dl, MVT::i32),
9735 DAG.getTargetConstant(Lo, dl, MVT::i32));
9736
9737 return DAG.getBitcast(Op.getValueType(), SplatNode);
9738 }
9739 }
9740
9741 if (SDValue V =
9742 LowerVecSplatSmallFP(Op, DAG, BVNIsConstantSplat, SplatBitSize))
9743 return V;
9744
9745 bool IsSplat64 = false;
9746 uint64_t SplatBits = 0;
9747 int32_t SextVal = 0;
9748 if (BVNIsConstantSplat && SplatBitSize <= 64) {
9749 SplatBits = APSplatBits.getZExtValue();
9750 if (SplatBitSize <= 32) {
9751 SextVal = SignExtend32(SplatBits, SplatBitSize);
9752 } else if (SplatBitSize == 64 && Subtarget.hasP8Altivec()) {
9753 int64_t Splat64Val = static_cast<int64_t>(SplatBits);
9754 bool P9Vector = Subtarget.hasP9Vector();
9755 int32_t Hi = P9Vector ? 127 : 15;
9756 int32_t Lo = P9Vector ? -128 : -16;
9757 IsSplat64 = Splat64Val >= Lo && Splat64Val <= Hi;
9758 SextVal = static_cast<int32_t>(SplatBits);
9759 }
9760 }
9761
9762 if (!BVNIsConstantSplat || (SplatBitSize > 32 && !IsSplat64)) {
9763 unsigned NewOpcode = PPCISD::LD_SPLAT;
9764
9765 // Handle load-and-splat patterns as we have instructions that will do this
9766 // in one go.
9767 if (DAG.isSplatValue(Op, true) &&
9768 isValidSplatLoad(Subtarget, Op, NewOpcode)) {
9769 const SDValue *InputLoad = &Op.getOperand(0);
9770 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9771
9772 // If the input load is an extending load, it will be an i32 -> i64
9773 // extending load and isValidSplatLoad() will update NewOpcode.
9774 unsigned MemorySize = LD->getMemoryVT().getScalarSizeInBits();
9775 unsigned ElementSize =
9776 MemorySize * ((NewOpcode == PPCISD::LD_SPLAT) ? 1 : 2);
9777
9778 assert(((ElementSize == 2 * MemorySize)
9779 ? (NewOpcode == PPCISD::ZEXT_LD_SPLAT ||
9780 NewOpcode == PPCISD::SEXT_LD_SPLAT)
9781 : (NewOpcode == PPCISD::LD_SPLAT)) &&
9782 "Unmatched element size and opcode!\n");
9783
9784 // Checking for a single use of this load, we have to check for vector
9785 // width (128 bits) / ElementSize uses (since each operand of the
9786 // BUILD_VECTOR is a separate use of the value.
9787 unsigned NumUsesOfInputLD = 128 / ElementSize;
9788 for (SDValue BVInOp : Op->ops())
9789 if (BVInOp.isUndef())
9790 NumUsesOfInputLD--;
9791
9792 // Exclude somes case where LD_SPLAT is worse than scalar_to_vector:
9793 // Below cases should also happen for "lfiwzx/lfiwax + LE target + index
9794 // 1" and "lxvrhx + BE target + index 7" and "lxvrbx + BE target + index
9795 // 15", but function IsValidSplatLoad() now will only return true when
9796 // the data at index 0 is not nullptr. So we will not get into trouble for
9797 // these cases.
9798 //
9799 // case 1 - lfiwzx/lfiwax
9800 // 1.1: load result is i32 and is sign/zero extend to i64;
9801 // 1.2: build a v2i64 vector type with above loaded value;
9802 // 1.3: the vector has only one value at index 0, others are all undef;
9803 // 1.4: on BE target, so that lfiwzx/lfiwax does not need any permute.
9804 if (NumUsesOfInputLD == 1 &&
9805 (Op->getValueType(0) == MVT::v2i64 && NewOpcode != PPCISD::LD_SPLAT &&
9806 !Subtarget.isLittleEndian() && Subtarget.hasVSX() &&
9807 Subtarget.hasLFIWAX()))
9808 return SDValue();
9809
9810 // case 2 - lxvr[hb]x
9811 // 2.1: load result is at most i16;
9812 // 2.2: build a vector with above loaded value;
9813 // 2.3: the vector has only one value at index 0, others are all undef;
9814 // 2.4: on LE target, so that lxvr[hb]x does not need any permute.
9815 if (NumUsesOfInputLD == 1 && Subtarget.isLittleEndian() &&
9816 Subtarget.isISA3_1() && ElementSize <= 16)
9817 return SDValue();
9818
9819 assert(NumUsesOfInputLD > 0 && "No uses of input LD of a build_vector?");
9820 if (InputLoad->getNode()->hasNUsesOfValue(NumUsesOfInputLD, 0) &&
9821 Subtarget.hasVSX()) {
9822 SDValue Ops[] = {
9823 LD->getChain(), // Chain
9824 LD->getBasePtr(), // Ptr
9825 DAG.getValueType(Op.getValueType()) // VT
9826 };
9827 SDValue LdSplt = DAG.getMemIntrinsicNode(
9828 NewOpcode, dl, DAG.getVTList(Op.getValueType(), MVT::Other), Ops,
9829 LD->getMemoryVT(), LD->getMemOperand());
9830 // Replace all uses of the output chain of the original load with the
9831 // output chain of the new load.
9832 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1),
9833 LdSplt.getValue(1));
9834 return LdSplt;
9835 }
9836 }
9837
9838 // In 64BIT mode BUILD_VECTOR nodes that are not constant splats of up to
9839 // 32-bits can be lowered to VSX instructions under certain conditions.
9840 // Without VSX, there is no pattern more efficient than expanding the node.
9841 if (Subtarget.hasVSX() && Subtarget.isPPC64() &&
9842 haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
9843 Subtarget.hasP8Vector()))
9844 return Op;
9845 return SDValue();
9846 }
9847
9848 uint64_t SplatUndef = APSplatUndef.getZExtValue();
9849 unsigned SplatSize = SplatBitSize / 8;
9850
9851 // First, handle single instruction cases.
9852
9853 // All zeros?
9854 if (SplatBits == 0) {
9855 // Canonicalize all zero vectors to be v4i32.
9856 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9857 SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9858 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9859 }
9860 return Op;
9861 }
9862
9863 // We have XXSPLTIW for constant splats four bytes wide.
9864 // Given vector length is a multiple of 4, 2-byte splats can be replaced
9865 // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9866 // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9867 // turned into a 4-byte splat of 0xABABABAB.
9868 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 2)
9869 return getCanonicalConstSplat(SplatBits | (SplatBits << 16), SplatSize * 2,
9870 Op.getValueType(), DAG, dl);
9871
9872 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector() && SplatSize == 4)
9873 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9874 dl);
9875
9876 // We have XXSPLTIB for constant splats one byte wide.
9877 if (Subtarget.hasP9Vector() && SplatSize == 1)
9878 return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9879 dl);
9880
9881 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9882 // Use VSPLTIW/VUPKLSW for v2i64 in range [-16,15].
9883 if (SextVal >= -16 && SextVal <= 15) {
9884 // SplatSize may be 1, 2, 4, or 8. Use size 4 instead of 8 for the splat to
9885 // generate a splat word with extend for size 8.
9886 unsigned UseSize = SplatSize == 8 ? 4 : SplatSize;
9887 SDValue Res =
9888 getCanonicalConstSplat(SextVal, UseSize, Op.getValueType(), DAG, dl);
9889 if (SplatSize != 8)
9890 return Res;
9891 SDValue IntrinsicOp =
9892 BuildIntrinsicOp(Intrinsic::ppc_altivec_vupklsw,
9893 DAG.getBitcast(MVT::v4i32, Res), DAG, dl, MVT::v2i64);
9894 return DAG.getBitcast(Op.getValueType(), IntrinsicOp);
9895 }
9896
9897 // Two instruction sequences.
9898
9899 if (Subtarget.hasP9Vector() && SextVal >= -128 && SextVal <= 127) {
9900 SDValue C = DAG.getConstant((unsigned char)SextVal, dl, MVT::i32);
9902 SDValue BV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
9903 unsigned IID;
9904 EVT VT;
9905 switch (SplatSize) {
9906 default:
9907 llvm_unreachable("Unexpected type for vector constant.");
9908 case 2:
9909 IID = Intrinsic::ppc_altivec_vupklsb;
9910 VT = MVT::v8i16;
9911 break;
9912 case 4:
9913 IID = Intrinsic::ppc_altivec_vextsb2w;
9914 VT = MVT::v4i32;
9915 break;
9916 case 8:
9917 IID = Intrinsic::ppc_altivec_vextsb2d;
9918 VT = MVT::v2i64;
9919 break;
9920 }
9921 SDValue Extend = BuildIntrinsicOp(IID, BV, DAG, dl, VT);
9922 return DAG.getBitcast(Op->getValueType(0), Extend);
9923 }
9924 assert(!IsSplat64 && "Unhandled 64-bit splat pattern");
9925
9926 // If this value is in the range [-32,30] and is even, use:
9927 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9928 // If this value is in the range [17,31] and is odd, use:
9929 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9930 // If this value is in the range [-31,-17] and is odd, use:
9931 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9932 // Note the last two are three-instruction sequences.
9933 if (SextVal >= -32 && SextVal <= 31) {
9934 // To avoid having these optimizations undone by constant folding,
9935 // we convert to a pseudo that will be expanded later into one of
9936 // the above forms.
9937 SDValue Elt = DAG.getSignedConstant(SextVal, dl, MVT::i32);
9938 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9939 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9940 SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9941 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9942 if (VT == Op.getValueType())
9943 return RetVal;
9944 else
9945 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9946 }
9947
9948 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
9949 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
9950 // for fneg/fabs.
9951 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9952 // Make -1 and vspltisw -1:
9953 SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9954
9955 // Make the VSLW intrinsic, computing 0x8000_0000.
9956 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9957 OnesV, DAG, dl);
9958
9959 // xor by OnesV to invert it.
9960 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9961 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9962 }
9963
9964 // Check to see if this is a wide variety of vsplti*, binop self cases.
9965 static const signed char SplatCsts[] = {
9966 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9967 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9968 };
9969
9970 for (unsigned idx = 0; idx < std::size(SplatCsts); ++idx) {
9971 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9972 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
9973 int i = SplatCsts[idx];
9974
9975 // Figure out what shift amount will be used by altivec if shifted by i in
9976 // this splat size.
9977 unsigned TypeShiftAmt = i & (SplatBitSize-1);
9978
9979 // vsplti + shl self.
9980 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9981 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9982 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9983 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9984 Intrinsic::ppc_altivec_vslw
9985 };
9986 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9987 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9988 }
9989
9990 // vsplti + srl self.
9991 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9992 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9993 static const unsigned IIDs[] = { // Intrinsic to use for each size.
9994 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9995 Intrinsic::ppc_altivec_vsrw
9996 };
9997 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9998 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9999 }
10000
10001 // vsplti + rol self.
10002 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
10003 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
10004 SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
10005 static const unsigned IIDs[] = { // Intrinsic to use for each size.
10006 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
10007 Intrinsic::ppc_altivec_vrlw
10008 };
10009 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
10010 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
10011 }
10012
10013 // t = vsplti c, result = vsldoi t, t, 1
10014 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
10015 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10016 unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
10017 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10018 }
10019 // t = vsplti c, result = vsldoi t, t, 2
10020 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
10021 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10022 unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
10023 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10024 }
10025 // t = vsplti c, result = vsldoi t, t, 3
10026 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
10027 SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
10028 unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
10029 return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
10030 }
10031 }
10032
10033 return SDValue();
10034}
10035
10036/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
10037/// the specified operations to build the shuffle.
10039 SDValue RHS, SelectionDAG &DAG,
10040 const SDLoc &dl) {
10041 unsigned OpNum = (PFEntry >> 26) & 0x0F;
10042 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
10043 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
10044
10045 enum {
10046 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
10047 OP_VMRGHW,
10048 OP_VMRGLW,
10049 OP_VSPLTISW0,
10050 OP_VSPLTISW1,
10051 OP_VSPLTISW2,
10052 OP_VSPLTISW3,
10053 OP_VSLDOI4,
10054 OP_VSLDOI8,
10055 OP_VSLDOI12
10056 };
10057
10058 if (OpNum == OP_COPY) {
10059 if (LHSID == (1*9+2)*9+3) return LHS;
10060 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
10061 return RHS;
10062 }
10063
10064 SDValue OpLHS, OpRHS;
10065 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
10066 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
10067
10068 int ShufIdxs[16];
10069 switch (OpNum) {
10070 default: llvm_unreachable("Unknown i32 permute!");
10071 case OP_VMRGHW:
10072 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
10073 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
10074 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
10075 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
10076 break;
10077 case OP_VMRGLW:
10078 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
10079 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
10080 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
10081 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
10082 break;
10083 case OP_VSPLTISW0:
10084 for (unsigned i = 0; i != 16; ++i)
10085 ShufIdxs[i] = (i&3)+0;
10086 break;
10087 case OP_VSPLTISW1:
10088 for (unsigned i = 0; i != 16; ++i)
10089 ShufIdxs[i] = (i&3)+4;
10090 break;
10091 case OP_VSPLTISW2:
10092 for (unsigned i = 0; i != 16; ++i)
10093 ShufIdxs[i] = (i&3)+8;
10094 break;
10095 case OP_VSPLTISW3:
10096 for (unsigned i = 0; i != 16; ++i)
10097 ShufIdxs[i] = (i&3)+12;
10098 break;
10099 case OP_VSLDOI4:
10100 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
10101 case OP_VSLDOI8:
10102 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
10103 case OP_VSLDOI12:
10104 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
10105 }
10106 EVT VT = OpLHS.getValueType();
10107 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
10108 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
10109 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
10110 return DAG.getNode(ISD::BITCAST, dl, VT, T);
10111}
10112
10113/// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
10114/// by the VINSERTB instruction introduced in ISA 3.0, else just return default
10115/// SDValue.
10116SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
10117 SelectionDAG &DAG) const {
10118 const unsigned BytesInVector = 16;
10119 bool IsLE = Subtarget.isLittleEndian();
10120 SDLoc dl(N);
10121 SDValue V1 = N->getOperand(0);
10122 SDValue V2 = N->getOperand(1);
10123 unsigned ShiftElts = 0, InsertAtByte = 0;
10124 bool Swap = false;
10125
10126 // Shifts required to get the byte we want at element 7.
10127 unsigned LittleEndianShifts[] = {8, 7, 6, 5, 4, 3, 2, 1,
10128 0, 15, 14, 13, 12, 11, 10, 9};
10129 unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
10130 1, 2, 3, 4, 5, 6, 7, 8};
10131
10132 ArrayRef<int> Mask = N->getMask();
10133 int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
10134
10135 // For each mask element, find out if we're just inserting something
10136 // from V2 into V1 or vice versa.
10137 // Possible permutations inserting an element from V2 into V1:
10138 // X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10139 // 0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
10140 // ...
10141 // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
10142 // Inserting from V1 into V2 will be similar, except mask range will be
10143 // [16,31].
10144
10145 bool FoundCandidate = false;
10146 // If both vector operands for the shuffle are the same vector, the mask
10147 // will contain only elements from the first one and the second one will be
10148 // undef.
10149 unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
10150 // Go through the mask of half-words to find an element that's being moved
10151 // from one vector to the other.
10152 for (unsigned i = 0; i < BytesInVector; ++i) {
10153 unsigned CurrentElement = Mask[i];
10154 // If 2nd operand is undefined, we should only look for element 7 in the
10155 // Mask.
10156 if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
10157 continue;
10158
10159 bool OtherElementsInOrder = true;
10160 // Examine the other elements in the Mask to see if they're in original
10161 // order.
10162 for (unsigned j = 0; j < BytesInVector; ++j) {
10163 if (j == i)
10164 continue;
10165 // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
10166 // from V2 [16,31] and vice versa. Unless the 2nd operand is undefined,
10167 // in which we always assume we're always picking from the 1st operand.
10168 int MaskOffset =
10169 (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
10170 if (Mask[j] != OriginalOrder[j] + MaskOffset) {
10171 OtherElementsInOrder = false;
10172 break;
10173 }
10174 }
10175 // If other elements are in original order, we record the number of shifts
10176 // we need to get the element we want into element 7. Also record which byte
10177 // in the vector we should insert into.
10178 if (OtherElementsInOrder) {
10179 // If 2nd operand is undefined, we assume no shifts and no swapping.
10180 if (V2.isUndef()) {
10181 ShiftElts = 0;
10182 Swap = false;
10183 } else {
10184 // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
10185 ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
10186 : BigEndianShifts[CurrentElement & 0xF];
10187 Swap = CurrentElement < BytesInVector;
10188 }
10189 InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
10190 FoundCandidate = true;
10191 break;
10192 }
10193 }
10194
10195 if (!FoundCandidate)
10196 return SDValue();
10197
10198 // Candidate found, construct the proper SDAG sequence with VINSERTB,
10199 // optionally with VECSHL if shift is required.
10200 if (Swap)
10201 std::swap(V1, V2);
10202 if (V2.isUndef())
10203 V2 = V1;
10204 if (ShiftElts) {
10205 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10206 DAG.getConstant(ShiftElts, dl, MVT::i32));
10207 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
10208 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10209 }
10210 return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
10211 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10212}
10213
10214/// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
10215/// by the VINSERTH instruction introduced in ISA 3.0, else just return default
10216/// SDValue.
10217SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
10218 SelectionDAG &DAG) const {
10219 const unsigned NumHalfWords = 8;
10220 const unsigned BytesInVector = NumHalfWords * 2;
10221 // Check that the shuffle is on half-words.
10222 if (!isNByteElemShuffleMask(N, 2, 1))
10223 return SDValue();
10224
10225 bool IsLE = Subtarget.isLittleEndian();
10226 SDLoc dl(N);
10227 SDValue V1 = N->getOperand(0);
10228 SDValue V2 = N->getOperand(1);
10229 unsigned ShiftElts = 0, InsertAtByte = 0;
10230 bool Swap = false;
10231
10232 // Shifts required to get the half-word we want at element 3.
10233 unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
10234 unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
10235
10236 uint32_t Mask = 0;
10237 uint32_t OriginalOrderLow = 0x1234567;
10238 uint32_t OriginalOrderHigh = 0x89ABCDEF;
10239 // Now we look at mask elements 0,2,4,6,8,10,12,14. Pack the mask into a
10240 // 32-bit space, only need 4-bit nibbles per element.
10241 for (unsigned i = 0; i < NumHalfWords; ++i) {
10242 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10243 Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
10244 }
10245
10246 // For each mask element, find out if we're just inserting something
10247 // from V2 into V1 or vice versa. Possible permutations inserting an element
10248 // from V2 into V1:
10249 // X, 1, 2, 3, 4, 5, 6, 7
10250 // 0, X, 2, 3, 4, 5, 6, 7
10251 // 0, 1, X, 3, 4, 5, 6, 7
10252 // 0, 1, 2, X, 4, 5, 6, 7
10253 // 0, 1, 2, 3, X, 5, 6, 7
10254 // 0, 1, 2, 3, 4, X, 6, 7
10255 // 0, 1, 2, 3, 4, 5, X, 7
10256 // 0, 1, 2, 3, 4, 5, 6, X
10257 // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
10258
10259 bool FoundCandidate = false;
10260 // Go through the mask of half-words to find an element that's being moved
10261 // from one vector to the other.
10262 for (unsigned i = 0; i < NumHalfWords; ++i) {
10263 unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
10264 uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
10265 uint32_t MaskOtherElts = ~(0xF << MaskShift);
10266 uint32_t TargetOrder = 0x0;
10267
10268 // If both vector operands for the shuffle are the same vector, the mask
10269 // will contain only elements from the first one and the second one will be
10270 // undef.
10271 if (V2.isUndef()) {
10272 ShiftElts = 0;
10273 unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
10274 TargetOrder = OriginalOrderLow;
10275 Swap = false;
10276 // Skip if not the correct element or mask of other elements don't equal
10277 // to our expected order.
10278 if (MaskOneElt == VINSERTHSrcElem &&
10279 (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10280 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10281 FoundCandidate = true;
10282 break;
10283 }
10284 } else { // If both operands are defined.
10285 // Target order is [8,15] if the current mask is between [0,7].
10286 TargetOrder =
10287 (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
10288 // Skip if mask of other elements don't equal our expected order.
10289 if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
10290 // We only need the last 3 bits for the number of shifts.
10291 ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
10292 : BigEndianShifts[MaskOneElt & 0x7];
10293 InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
10294 Swap = MaskOneElt < NumHalfWords;
10295 FoundCandidate = true;
10296 break;
10297 }
10298 }
10299 }
10300
10301 if (!FoundCandidate)
10302 return SDValue();
10303
10304 // Candidate found, construct the proper SDAG sequence with VINSERTH,
10305 // optionally with VECSHL if shift is required.
10306 if (Swap)
10307 std::swap(V1, V2);
10308 if (V2.isUndef())
10309 V2 = V1;
10310 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10311 if (ShiftElts) {
10312 // Double ShiftElts because we're left shifting on v16i8 type.
10313 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
10314 DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
10315 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
10316 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10317 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10318 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10319 }
10320 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
10321 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
10322 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10323 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10324}
10325
10326/// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
10327/// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
10328/// return the default SDValue.
10329SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
10330 SelectionDAG &DAG) const {
10331 // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
10332 // to v16i8. Peek through the bitcasts to get the actual operands.
10333 SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
10334 SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
10335
10336 auto ShuffleMask = SVN->getMask();
10337 SDValue VecShuffle(SVN, 0);
10338 SDLoc DL(SVN);
10339
10340 // Check that we have a four byte shuffle.
10341 if (!isNByteElemShuffleMask(SVN, 4, 1))
10342 return SDValue();
10343
10344 // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
10345 if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
10346 std::swap(LHS, RHS);
10348 ShuffleVectorSDNode *CommutedSV = dyn_cast<ShuffleVectorSDNode>(VecShuffle);
10349 if (!CommutedSV)
10350 return SDValue();
10351 ShuffleMask = CommutedSV->getMask();
10352 }
10353
10354 // Ensure that the RHS is a vector of constants.
10355 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
10356 if (!BVN)
10357 return SDValue();
10358
10359 // Check if RHS is a splat of 4-bytes (or smaller).
10360 APInt APSplatValue, APSplatUndef;
10361 unsigned SplatBitSize;
10362 bool HasAnyUndefs;
10363 if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
10364 HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
10365 SplatBitSize > 32)
10366 return SDValue();
10367
10368 // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
10369 // The instruction splats a constant C into two words of the source vector
10370 // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
10371 // Thus we check that the shuffle mask is the equivalent of
10372 // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
10373 // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
10374 // within each word are consecutive, so we only need to check the first byte.
10375 SDValue Index;
10376 bool IsLE = Subtarget.isLittleEndian();
10377 if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
10378 (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
10379 ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
10380 Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
10381 else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
10382 (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
10383 ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
10384 Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
10385 else
10386 return SDValue();
10387
10388 // If the splat is narrower than 32-bits, we need to get the 32-bit value
10389 // for XXSPLTI32DX.
10390 unsigned SplatVal = APSplatValue.getZExtValue();
10391 for (; SplatBitSize < 32; SplatBitSize <<= 1)
10392 SplatVal |= (SplatVal << SplatBitSize);
10393
10394 SDValue SplatNode = DAG.getNode(
10395 PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
10396 Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
10397 return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
10398}
10399
10400/// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
10401/// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
10402/// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
10403/// i.e (or (shl x, C1), (srl x, 128-C1)).
10404SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
10405 assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
10406 assert(Op.getValueType() == MVT::v1i128 &&
10407 "Only set v1i128 as custom, other type shouldn't reach here!");
10408 SDLoc dl(Op);
10409 SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
10410 SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
10411 unsigned SHLAmt = N1.getConstantOperandVal(0);
10412 if (SHLAmt % 8 == 0) {
10413 std::array<int, 16> Mask;
10414 std::iota(Mask.begin(), Mask.end(), 0);
10415 std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
10416 if (SDValue Shuffle =
10417 DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
10418 DAG.getUNDEF(MVT::v16i8), Mask))
10419 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
10420 }
10421 SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
10422 SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
10423 DAG.getConstant(SHLAmt, dl, MVT::i32));
10424 SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
10425 DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
10426 SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
10427 return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
10428}
10429
10430/// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
10431/// is a shuffle we can handle in a single instruction, return it. Otherwise,
10432/// return the code it can be lowered into. Worst case, it can always be
10433/// lowered into a vperm.
10434SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
10435 SelectionDAG &DAG) const {
10436 SDLoc dl(Op);
10437 SDValue V1 = Op.getOperand(0);
10438 SDValue V2 = Op.getOperand(1);
10439 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10440
10441 // Any nodes that were combined in the target-independent combiner prior
10442 // to vector legalization will not be sent to the target combine. Try to
10443 // combine it here.
10444 if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
10445 if (!isa<ShuffleVectorSDNode>(NewShuffle))
10446 return NewShuffle;
10447 Op = NewShuffle;
10449 V1 = Op.getOperand(0);
10450 V2 = Op.getOperand(1);
10451 }
10452 EVT VT = Op.getValueType();
10453 bool isLittleEndian = Subtarget.isLittleEndian();
10454
10455 unsigned ShiftElts, InsertAtByte;
10456 bool Swap = false;
10457
10458 // If this is a load-and-splat, we can do that with a single instruction
10459 // in some cases. However if the load has multiple uses, we don't want to
10460 // combine it because that will just produce multiple loads. Since we are
10461 // looking through bitcasts and scalar_to_vector, we must also ensure that
10462 // the intermediate nodes have a single use.
10463 bool IsPermutedLoad = false;
10464 const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
10465 if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
10466 (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8))) {
10467 bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
10468 int SplatIdx =
10469 PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
10470
10471 // The splat index for permuted loads will be in the left half of the vector
10472 // which is strictly wider than the loaded value by 8 bytes. So we need to
10473 // adjust the splat index to point to the correct address in memory.
10474 if (IsPermutedLoad) {
10475 assert((isLittleEndian || IsFourByte) &&
10476 "Unexpected size for permuted load on big endian target");
10477 SplatIdx += IsFourByte ? 2 : 1;
10478 assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
10479 "Splat of a value outside of the loaded memory");
10480 }
10481
10482 LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
10483 // For 4-byte load-and-splat, we need Power9.
10484 if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
10485 uint64_t Offset = 0;
10486 if (IsFourByte)
10487 Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
10488 else
10489 Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
10490
10491 // If the width of the load is the same as the width of the splat,
10492 // loading with an offset would load the wrong memory.
10493 if (LD->getValueType(0).getSizeInBits() == (IsFourByte ? 32 : 64))
10494 Offset = 0;
10495
10496 SDValue BasePtr = LD->getBasePtr();
10497 if (Offset != 0)
10499 BasePtr, DAG.getIntPtrConstant(Offset, dl));
10500 SDValue Ops[] = {
10501 LD->getChain(), // Chain
10502 BasePtr, // BasePtr
10503 DAG.getValueType(Op.getValueType()) // VT
10504 };
10505 SDVTList VTL =
10506 DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
10507 SDValue LdSplt =
10508 DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
10509 Ops, LD->getMemoryVT(), LD->getMemOperand());
10510 DAG.ReplaceAllUsesOfValueWith(InputLoad->getValue(1), LdSplt.getValue(1));
10511 if (LdSplt.getValueType() != SVOp->getValueType(0))
10512 LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
10513 return LdSplt;
10514 }
10515 }
10516
10517 // All v2i64 and v2f64 shuffles are legal
10518 if (VT == MVT::v2i64 || VT == MVT::v2f64)
10519 return Op;
10520
10521 if (Subtarget.hasP9Vector() &&
10522 PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
10523 isLittleEndian)) {
10524 if (V2.isUndef())
10525 V2 = V1;
10526 else if (Swap)
10527 std::swap(V1, V2);
10528 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10529 SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
10530 if (ShiftElts) {
10531 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
10532 DAG.getConstant(ShiftElts, dl, MVT::i32));
10533 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
10534 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10535 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10536 }
10537 SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
10538 DAG.getConstant(InsertAtByte, dl, MVT::i32));
10539 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
10540 }
10541
10542 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
10543 SDValue SplatInsertNode;
10544 if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
10545 return SplatInsertNode;
10546 }
10547
10548 if (Subtarget.hasP9Altivec()) {
10549 SDValue NewISDNode;
10550 if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
10551 return NewISDNode;
10552
10553 if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
10554 return NewISDNode;
10555 }
10556
10557 if (Subtarget.hasVSX() &&
10558 PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10559 if (Swap)
10560 std::swap(V1, V2);
10561 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10562 SDValue Conv2 =
10563 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
10564
10565 SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
10566 DAG.getConstant(ShiftElts, dl, MVT::i32));
10567 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
10568 }
10569
10570 if (Subtarget.hasVSX() &&
10571 PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
10572 if (Swap)
10573 std::swap(V1, V2);
10574 SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10575 SDValue Conv2 =
10576 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
10577
10578 SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
10579 DAG.getConstant(ShiftElts, dl, MVT::i32));
10580 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
10581 }
10582
10583 if (Subtarget.hasP9Vector()) {
10584 if (PPC::isXXBRHShuffleMask(SVOp)) {
10585 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10586 SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
10587 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
10588 } else if (PPC::isXXBRWShuffleMask(SVOp)) {
10589 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10590 SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
10591 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
10592 } else if (PPC::isXXBRDShuffleMask(SVOp)) {
10593 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
10594 SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
10595 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
10596 } else if (PPC::isXXBRQShuffleMask(SVOp)) {
10597 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
10598 SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
10599 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
10600 }
10601 }
10602
10603 if (Subtarget.hasVSX()) {
10604 if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
10605 int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
10606
10607 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
10608 SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
10609 DAG.getConstant(SplatIdx, dl, MVT::i32));
10610 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
10611 }
10612
10613 // Left shifts of 8 bytes are actually swaps. Convert accordingly.
10614 if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
10615 SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10616 SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
10617 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
10618 }
10619 }
10620
10621 // Cases that are handled by instructions that take permute immediates
10622 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
10623 // selected by the instruction selector.
10624 if (V2.isUndef()) {
10625 if (PPC::isSplatShuffleMask(SVOp, 1) ||
10626 PPC::isSplatShuffleMask(SVOp, 2) ||
10627 PPC::isSplatShuffleMask(SVOp, 4) ||
10628 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
10629 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
10630 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
10631 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
10632 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
10633 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
10634 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
10635 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
10636 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
10637 (Subtarget.hasP8Altivec() && (
10638 PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
10639 PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
10640 PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
10641 return Op;
10642 }
10643 }
10644
10645 // Altivec has a variety of "shuffle immediates" that take two vector inputs
10646 // and produce a fixed permutation. If any of these match, do not lower to
10647 // VPERM.
10648 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
10649 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10650 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10651 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
10652 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10653 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10654 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10655 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
10656 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
10657 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
10658 (Subtarget.hasP8Altivec() && (
10659 PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
10660 PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
10661 PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
10662 return Op;
10663
10664 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
10665 // perfect shuffle table to emit an optimal matching sequence.
10666 ArrayRef<int> PermMask = SVOp->getMask();
10667
10668 if (EnablePerfectShuffle && !isLittleEndian) {
10669 unsigned PFIndexes[4];
10670 bool isFourElementShuffle = true;
10671 for (unsigned i = 0; i != 4 && isFourElementShuffle;
10672 ++i) { // Element number
10673 unsigned EltNo = 8; // Start out undef.
10674 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
10675 if (PermMask[i * 4 + j] < 0)
10676 continue; // Undef, ignore it.
10677
10678 unsigned ByteSource = PermMask[i * 4 + j];
10679 if ((ByteSource & 3) != j) {
10680 isFourElementShuffle = false;
10681 break;
10682 }
10683
10684 if (EltNo == 8) {
10685 EltNo = ByteSource / 4;
10686 } else if (EltNo != ByteSource / 4) {
10687 isFourElementShuffle = false;
10688 break;
10689 }
10690 }
10691 PFIndexes[i] = EltNo;
10692 }
10693
10694 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
10695 // perfect shuffle vector to determine if it is cost effective to do this as
10696 // discrete instructions, or whether we should use a vperm.
10697 // For now, we skip this for little endian until such time as we have a
10698 // little-endian perfect shuffle table.
10699 if (isFourElementShuffle) {
10700 // Compute the index in the perfect shuffle table.
10701 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
10702 PFIndexes[2] * 9 + PFIndexes[3];
10703
10704 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
10705 unsigned Cost = (PFEntry >> 30);
10706
10707 // Determining when to avoid vperm is tricky. Many things affect the cost
10708 // of vperm, particularly how many times the perm mask needs to be
10709 // computed. For example, if the perm mask can be hoisted out of a loop or
10710 // is already used (perhaps because there are multiple permutes with the
10711 // same shuffle mask?) the vperm has a cost of 1. OTOH, hoisting the
10712 // permute mask out of the loop requires an extra register.
10713 //
10714 // As a compromise, we only emit discrete instructions if the shuffle can
10715 // be generated in 3 or fewer operations. When we have loop information
10716 // available, if this block is within a loop, we should avoid using vperm
10717 // for 3-operation perms and use a constant pool load instead.
10718 if (Cost < 3)
10719 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
10720 }
10721 }
10722
10723 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
10724 // vector that will get spilled to the constant pool.
10725 if (V2.isUndef()) V2 = V1;
10726
10727 return LowerVPERM(Op, DAG, PermMask, VT, V1, V2);
10728}
10729
10730SDValue PPCTargetLowering::LowerVPERM(SDValue Op, SelectionDAG &DAG,
10731 ArrayRef<int> PermMask, EVT VT,
10732 SDValue V1, SDValue V2) const {
10733 unsigned Opcode = PPCISD::VPERM;
10734 EVT ValType = V1.getValueType();
10735 SDLoc dl(Op);
10736 bool NeedSwap = false;
10737 bool isLittleEndian = Subtarget.isLittleEndian();
10738 bool isPPC64 = Subtarget.isPPC64();
10739
10740 if (Subtarget.hasVSX() && Subtarget.hasP9Vector() &&
10741 (V1->hasOneUse() || V2->hasOneUse())) {
10742 LLVM_DEBUG(dbgs() << "At least one of two input vectors are dead - using "
10743 "XXPERM instead\n");
10744 Opcode = PPCISD::XXPERM;
10745
10746 // The second input to XXPERM is also an output so if the second input has
10747 // multiple uses then copying is necessary, as a result we want the
10748 // single-use operand to be used as the second input to prevent copying.
10749 if ((!isLittleEndian && !V2->hasOneUse() && V1->hasOneUse()) ||
10750 (isLittleEndian && !V1->hasOneUse() && V2->hasOneUse())) {
10751 std::swap(V1, V2);
10752 NeedSwap = !NeedSwap;
10753 }
10754 }
10755
10756 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
10757 // that it is in input element units, not in bytes. Convert now.
10758
10759 // For little endian, the order of the input vectors is reversed, and
10760 // the permutation mask is complemented with respect to 31. This is
10761 // necessary to produce proper semantics with the big-endian-based vperm
10762 // instruction.
10763 EVT EltVT = V1.getValueType().getVectorElementType();
10764 unsigned BytesPerElement = EltVT.getSizeInBits() / 8;
10765
10766 bool V1HasXXSWAPD = V1->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10767 bool V2HasXXSWAPD = V2->getOperand(0)->getOpcode() == PPCISD::XXSWAPD;
10768
10769 /*
10770 Vectors will be appended like so: [ V1 | v2 ]
10771 XXSWAPD on V1:
10772 [ A | B | C | D ] -> [ C | D | A | B ]
10773 0-3 4-7 8-11 12-15 0-3 4-7 8-11 12-15
10774 i.e. index of A, B += 8, and index of C, D -= 8.
10775 XXSWAPD on V2:
10776 [ E | F | G | H ] -> [ G | H | E | F ]
10777 16-19 20-23 24-27 28-31 16-19 20-23 24-27 28-31
10778 i.e. index of E, F += 8, index of G, H -= 8
10779 Swap V1 and V2:
10780 [ V1 | V2 ] -> [ V2 | V1 ]
10781 0-15 16-31 0-15 16-31
10782 i.e. index of V1 += 16, index of V2 -= 16
10783 */
10784
10785 SmallVector<SDValue, 16> ResultMask;
10786 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
10787 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
10788
10789 if (V1HasXXSWAPD) {
10790 if (SrcElt < 8)
10791 SrcElt += 8;
10792 else if (SrcElt < 16)
10793 SrcElt -= 8;
10794 }
10795 if (V2HasXXSWAPD) {
10796 if (SrcElt > 23)
10797 SrcElt -= 8;
10798 else if (SrcElt > 15)
10799 SrcElt += 8;
10800 }
10801 if (NeedSwap) {
10802 if (SrcElt < 16)
10803 SrcElt += 16;
10804 else
10805 SrcElt -= 16;
10806 }
10807 for (unsigned j = 0; j != BytesPerElement; ++j)
10808 if (isLittleEndian)
10809 ResultMask.push_back(
10810 DAG.getConstant(31 - (SrcElt * BytesPerElement + j), dl, MVT::i32));
10811 else
10812 ResultMask.push_back(
10813 DAG.getConstant(SrcElt * BytesPerElement + j, dl, MVT::i32));
10814 }
10815
10816 if (V1HasXXSWAPD) {
10817 dl = SDLoc(V1->getOperand(0));
10818 V1 = V1->getOperand(0)->getOperand(1);
10819 }
10820 if (V2HasXXSWAPD) {
10821 dl = SDLoc(V2->getOperand(0));
10822 V2 = V2->getOperand(0)->getOperand(1);
10823 }
10824
10825 if (isPPC64 && (V1HasXXSWAPD || V2HasXXSWAPD)) {
10826 if (ValType != MVT::v2f64)
10827 V1 = DAG.getBitcast(MVT::v2f64, V1);
10828 if (V2.getValueType() != MVT::v2f64)
10829 V2 = DAG.getBitcast(MVT::v2f64, V2);
10830 }
10831
10832 ShufflesHandledWithVPERM++;
10833 SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
10834 LLVM_DEBUG({
10835 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10836 if (Opcode == PPCISD::XXPERM) {
10837 dbgs() << "Emitting a XXPERM for the following shuffle:\n";
10838 } else {
10839 dbgs() << "Emitting a VPERM for the following shuffle:\n";
10840 }
10841 SVOp->dump();
10842 dbgs() << "With the following permute control vector:\n";
10843 VPermMask.dump();
10844 });
10845
10846 if (Opcode == PPCISD::XXPERM)
10847 VPermMask = DAG.getBitcast(MVT::v4i32, VPermMask);
10848
10849 // Only need to place items backwards in LE,
10850 // the mask was properly calculated.
10851 if (isLittleEndian)
10852 std::swap(V1, V2);
10853
10854 SDValue VPERMNode =
10855 DAG.getNode(Opcode, dl, V1.getValueType(), V1, V2, VPermMask);
10856
10857 VPERMNode = DAG.getBitcast(ValType, VPERMNode);
10858 return VPERMNode;
10859}
10860
10861/// getVectorCompareInfo - Given an intrinsic, return false if it is not a
10862/// vector comparison. If it is, return true and fill in Opc/isDot with
10863/// information about the intrinsic.
10864static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
10865 bool &isDot, const PPCSubtarget &Subtarget) {
10866 unsigned IntrinsicID = Intrin.getConstantOperandVal(0);
10867 CompareOpc = -1;
10868 isDot = false;
10869 switch (IntrinsicID) {
10870 default:
10871 return false;
10872 // Comparison predicates.
10873 case Intrinsic::ppc_altivec_vcmpbfp_p:
10874 CompareOpc = 966;
10875 isDot = true;
10876 break;
10877 case Intrinsic::ppc_altivec_vcmpeqfp_p:
10878 CompareOpc = 198;
10879 isDot = true;
10880 break;
10881 case Intrinsic::ppc_altivec_vcmpequb_p:
10882 CompareOpc = 6;
10883 isDot = true;
10884 break;
10885 case Intrinsic::ppc_altivec_vcmpequh_p:
10886 CompareOpc = 70;
10887 isDot = true;
10888 break;
10889 case Intrinsic::ppc_altivec_vcmpequw_p:
10890 CompareOpc = 134;
10891 isDot = true;
10892 break;
10893 case Intrinsic::ppc_altivec_vcmpequd_p:
10894 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10895 CompareOpc = 199;
10896 isDot = true;
10897 } else
10898 return false;
10899 break;
10900 case Intrinsic::ppc_altivec_vcmpneb_p:
10901 case Intrinsic::ppc_altivec_vcmpneh_p:
10902 case Intrinsic::ppc_altivec_vcmpnew_p:
10903 case Intrinsic::ppc_altivec_vcmpnezb_p:
10904 case Intrinsic::ppc_altivec_vcmpnezh_p:
10905 case Intrinsic::ppc_altivec_vcmpnezw_p:
10906 if (Subtarget.hasP9Altivec()) {
10907 switch (IntrinsicID) {
10908 default:
10909 llvm_unreachable("Unknown comparison intrinsic.");
10910 case Intrinsic::ppc_altivec_vcmpneb_p:
10911 CompareOpc = 7;
10912 break;
10913 case Intrinsic::ppc_altivec_vcmpneh_p:
10914 CompareOpc = 71;
10915 break;
10916 case Intrinsic::ppc_altivec_vcmpnew_p:
10917 CompareOpc = 135;
10918 break;
10919 case Intrinsic::ppc_altivec_vcmpnezb_p:
10920 CompareOpc = 263;
10921 break;
10922 case Intrinsic::ppc_altivec_vcmpnezh_p:
10923 CompareOpc = 327;
10924 break;
10925 case Intrinsic::ppc_altivec_vcmpnezw_p:
10926 CompareOpc = 391;
10927 break;
10928 }
10929 isDot = true;
10930 } else
10931 return false;
10932 break;
10933 case Intrinsic::ppc_altivec_vcmpgefp_p:
10934 CompareOpc = 454;
10935 isDot = true;
10936 break;
10937 case Intrinsic::ppc_altivec_vcmpgtfp_p:
10938 CompareOpc = 710;
10939 isDot = true;
10940 break;
10941 case Intrinsic::ppc_altivec_vcmpgtsb_p:
10942 CompareOpc = 774;
10943 isDot = true;
10944 break;
10945 case Intrinsic::ppc_altivec_vcmpgtsh_p:
10946 CompareOpc = 838;
10947 isDot = true;
10948 break;
10949 case Intrinsic::ppc_altivec_vcmpgtsw_p:
10950 CompareOpc = 902;
10951 isDot = true;
10952 break;
10953 case Intrinsic::ppc_altivec_vcmpgtsd_p:
10954 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10955 CompareOpc = 967;
10956 isDot = true;
10957 } else
10958 return false;
10959 break;
10960 case Intrinsic::ppc_altivec_vcmpgtub_p:
10961 CompareOpc = 518;
10962 isDot = true;
10963 break;
10964 case Intrinsic::ppc_altivec_vcmpgtuh_p:
10965 CompareOpc = 582;
10966 isDot = true;
10967 break;
10968 case Intrinsic::ppc_altivec_vcmpgtuw_p:
10969 CompareOpc = 646;
10970 isDot = true;
10971 break;
10972 case Intrinsic::ppc_altivec_vcmpgtud_p:
10973 if (Subtarget.hasVSX() || Subtarget.hasP8Altivec()) {
10974 CompareOpc = 711;
10975 isDot = true;
10976 } else
10977 return false;
10978 break;
10979
10980 case Intrinsic::ppc_altivec_vcmpequq:
10981 case Intrinsic::ppc_altivec_vcmpgtsq:
10982 case Intrinsic::ppc_altivec_vcmpgtuq:
10983 if (!Subtarget.isISA3_1())
10984 return false;
10985 switch (IntrinsicID) {
10986 default:
10987 llvm_unreachable("Unknown comparison intrinsic.");
10988 case Intrinsic::ppc_altivec_vcmpequq:
10989 CompareOpc = 455;
10990 break;
10991 case Intrinsic::ppc_altivec_vcmpgtsq:
10992 CompareOpc = 903;
10993 break;
10994 case Intrinsic::ppc_altivec_vcmpgtuq:
10995 CompareOpc = 647;
10996 break;
10997 }
10998 break;
10999
11000 // VSX predicate comparisons use the same infrastructure
11001 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
11002 case Intrinsic::ppc_vsx_xvcmpgedp_p:
11003 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
11004 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
11005 case Intrinsic::ppc_vsx_xvcmpgesp_p:
11006 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
11007 if (Subtarget.hasVSX()) {
11008 switch (IntrinsicID) {
11009 case Intrinsic::ppc_vsx_xvcmpeqdp_p:
11010 CompareOpc = 99;
11011 break;
11012 case Intrinsic::ppc_vsx_xvcmpgedp_p:
11013 CompareOpc = 115;
11014 break;
11015 case Intrinsic::ppc_vsx_xvcmpgtdp_p:
11016 CompareOpc = 107;
11017 break;
11018 case Intrinsic::ppc_vsx_xvcmpeqsp_p:
11019 CompareOpc = 67;
11020 break;
11021 case Intrinsic::ppc_vsx_xvcmpgesp_p:
11022 CompareOpc = 83;
11023 break;
11024 case Intrinsic::ppc_vsx_xvcmpgtsp_p:
11025 CompareOpc = 75;
11026 break;
11027 }
11028 isDot = true;
11029 } else
11030 return false;
11031 break;
11032
11033 // Normal Comparisons.
11034 case Intrinsic::ppc_altivec_vcmpbfp:
11035 CompareOpc = 966;
11036 break;
11037 case Intrinsic::ppc_altivec_vcmpeqfp:
11038 CompareOpc = 198;
11039 break;
11040 case Intrinsic::ppc_altivec_vcmpequb:
11041 CompareOpc = 6;
11042 break;
11043 case Intrinsic::ppc_altivec_vcmpequh:
11044 CompareOpc = 70;
11045 break;
11046 case Intrinsic::ppc_altivec_vcmpequw:
11047 CompareOpc = 134;
11048 break;
11049 case Intrinsic::ppc_altivec_vcmpequd:
11050 if (Subtarget.hasP8Altivec())
11051 CompareOpc = 199;
11052 else
11053 return false;
11054 break;
11055 case Intrinsic::ppc_altivec_vcmpneb:
11056 case Intrinsic::ppc_altivec_vcmpneh:
11057 case Intrinsic::ppc_altivec_vcmpnew:
11058 case Intrinsic::ppc_altivec_vcmpnezb:
11059 case Intrinsic::ppc_altivec_vcmpnezh:
11060 case Intrinsic::ppc_altivec_vcmpnezw:
11061 if (Subtarget.hasP9Altivec())
11062 switch (IntrinsicID) {
11063 default:
11064 llvm_unreachable("Unknown comparison intrinsic.");
11065 case Intrinsic::ppc_altivec_vcmpneb:
11066 CompareOpc = 7;
11067 break;
11068 case Intrinsic::ppc_altivec_vcmpneh:
11069 CompareOpc = 71;
11070 break;
11071 case Intrinsic::ppc_altivec_vcmpnew:
11072 CompareOpc = 135;
11073 break;
11074 case Intrinsic::ppc_altivec_vcmpnezb:
11075 CompareOpc = 263;
11076 break;
11077 case Intrinsic::ppc_altivec_vcmpnezh:
11078 CompareOpc = 327;
11079 break;
11080 case Intrinsic::ppc_altivec_vcmpnezw:
11081 CompareOpc = 391;
11082 break;
11083 }
11084 else
11085 return false;
11086 break;
11087 case Intrinsic::ppc_altivec_vcmpgefp:
11088 CompareOpc = 454;
11089 break;
11090 case Intrinsic::ppc_altivec_vcmpgtfp:
11091 CompareOpc = 710;
11092 break;
11093 case Intrinsic::ppc_altivec_vcmpgtsb:
11094 CompareOpc = 774;
11095 break;
11096 case Intrinsic::ppc_altivec_vcmpgtsh:
11097 CompareOpc = 838;
11098 break;
11099 case Intrinsic::ppc_altivec_vcmpgtsw:
11100 CompareOpc = 902;
11101 break;
11102 case Intrinsic::ppc_altivec_vcmpgtsd:
11103 if (Subtarget.hasP8Altivec())
11104 CompareOpc = 967;
11105 else
11106 return false;
11107 break;
11108 case Intrinsic::ppc_altivec_vcmpgtub:
11109 CompareOpc = 518;
11110 break;
11111 case Intrinsic::ppc_altivec_vcmpgtuh:
11112 CompareOpc = 582;
11113 break;
11114 case Intrinsic::ppc_altivec_vcmpgtuw:
11115 CompareOpc = 646;
11116 break;
11117 case Intrinsic::ppc_altivec_vcmpgtud:
11118 if (Subtarget.hasP8Altivec())
11119 CompareOpc = 711;
11120 else
11121 return false;
11122 break;
11123 case Intrinsic::ppc_altivec_vcmpequq_p:
11124 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11125 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11126 if (!Subtarget.isISA3_1())
11127 return false;
11128 switch (IntrinsicID) {
11129 default:
11130 llvm_unreachable("Unknown comparison intrinsic.");
11131 case Intrinsic::ppc_altivec_vcmpequq_p:
11132 CompareOpc = 455;
11133 break;
11134 case Intrinsic::ppc_altivec_vcmpgtsq_p:
11135 CompareOpc = 903;
11136 break;
11137 case Intrinsic::ppc_altivec_vcmpgtuq_p:
11138 CompareOpc = 647;
11139 break;
11140 }
11141 isDot = true;
11142 break;
11143 }
11144 return true;
11145}
11146
11147/// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
11148/// lower, do it, otherwise return null.
11149SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
11150 SelectionDAG &DAG) const {
11151 unsigned IntrinsicID = Op.getConstantOperandVal(0);
11152
11153 SDLoc dl(Op);
11154 // Note: BCD instructions expect the immediate operand in vector form (v4i32),
11155 // but the builtin provides it as a scalar. To satisfy the instruction
11156 // encoding, we splat the scalar across all lanes using SPLAT_VECTOR.
11157 auto MapNodeWithSplatVector =
11158 [&](unsigned Opcode,
11159 std::initializer_list<SDValue> ExtraOps = {}) -> SDValue {
11160 SDValue SplatVal =
11161 DAG.getNode(ISD::SPLAT_VECTOR, dl, MVT::v4i32, Op.getOperand(2));
11162
11163 SmallVector<SDValue, 4> Ops{SplatVal, Op.getOperand(1)};
11164 Ops.append(ExtraOps.begin(), ExtraOps.end());
11165 return DAG.getNode(Opcode, dl, MVT::v16i8, Ops);
11166 };
11167
11168 switch (IntrinsicID) {
11169 case Intrinsic::thread_pointer:
11170 // Reads the thread pointer register, used for __builtin_thread_pointer.
11171 if (Subtarget.isPPC64())
11172 return DAG.getRegister(PPC::X13, MVT::i64);
11173 return DAG.getRegister(PPC::R2, MVT::i32);
11174
11175 case Intrinsic::ppc_rldimi: {
11176 assert(Subtarget.isPPC64() && "rldimi is only available in 64-bit!");
11177 SDValue Src = Op.getOperand(1);
11178 APInt Mask = Op.getConstantOperandAPInt(4);
11179 if (Mask.isZero())
11180 return Op.getOperand(2);
11181 if (Mask.isAllOnes())
11182 return DAG.getNode(ISD::ROTL, dl, MVT::i64, Src, Op.getOperand(3));
11183 uint64_t SH = Op.getConstantOperandVal(3);
11184 unsigned MB = 0, ME = 0;
11185 if (!isRunOfOnes64(Mask.getZExtValue(), MB, ME))
11186 report_fatal_error("invalid rldimi mask!");
11187 // rldimi requires ME=63-SH, otherwise rotation is needed before rldimi.
11188 if (ME < 63 - SH) {
11189 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11190 DAG.getConstant(ME + SH + 1, dl, MVT::i32));
11191 } else if (ME > 63 - SH) {
11192 Src = DAG.getNode(ISD::ROTL, dl, MVT::i64, Src,
11193 DAG.getConstant(ME + SH - 63, dl, MVT::i32));
11194 }
11195 return SDValue(
11196 DAG.getMachineNode(PPC::RLDIMI, dl, MVT::i64,
11197 {Op.getOperand(2), Src,
11198 DAG.getTargetConstant(63 - ME, dl, MVT::i32),
11199 DAG.getTargetConstant(MB, dl, MVT::i32)}),
11200 0);
11201 }
11202
11203 case Intrinsic::ppc_rlwimi: {
11204 APInt Mask = Op.getConstantOperandAPInt(4);
11205 if (Mask.isZero())
11206 return Op.getOperand(2);
11207 if (Mask.isAllOnes())
11208 return DAG.getNode(ISD::ROTL, dl, MVT::i32, Op.getOperand(1),
11209 Op.getOperand(3));
11210 unsigned MB = 0, ME = 0;
11211 if (!isRunOfOnes(Mask.getZExtValue(), MB, ME))
11212 report_fatal_error("invalid rlwimi mask!");
11213 return SDValue(DAG.getMachineNode(
11214 PPC::RLWIMI, dl, MVT::i32,
11215 {Op.getOperand(2), Op.getOperand(1), Op.getOperand(3),
11216 DAG.getTargetConstant(MB, dl, MVT::i32),
11217 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11218 0);
11219 }
11220
11221 case Intrinsic::ppc_bcdshift:
11222 return MapNodeWithSplatVector(PPCISD::BCDSHIFT, {Op.getOperand(3)});
11223 case Intrinsic::ppc_bcdshiftround:
11224 return MapNodeWithSplatVector(PPCISD::BCDSHIFTROUND, {Op.getOperand(3)});
11225 case Intrinsic::ppc_bcdtruncate:
11226 return MapNodeWithSplatVector(PPCISD::BCDTRUNC, {Op.getOperand(3)});
11227 case Intrinsic::ppc_bcdunsignedtruncate:
11228 return MapNodeWithSplatVector(PPCISD::BCDUTRUNC);
11229 case Intrinsic::ppc_bcdunsignedshift:
11230 return MapNodeWithSplatVector(PPCISD::BCDUSHIFT);
11231
11232 case Intrinsic::ppc_rlwnm: {
11233 if (Op.getConstantOperandVal(3) == 0)
11234 return DAG.getConstant(0, dl, MVT::i32);
11235 unsigned MB = 0, ME = 0;
11236 if (!isRunOfOnes(Op.getConstantOperandVal(3), MB, ME))
11237 report_fatal_error("invalid rlwnm mask!");
11238 return SDValue(
11239 DAG.getMachineNode(PPC::RLWNM, dl, MVT::i32,
11240 {Op.getOperand(1), Op.getOperand(2),
11241 DAG.getTargetConstant(MB, dl, MVT::i32),
11242 DAG.getTargetConstant(ME, dl, MVT::i32)}),
11243 0);
11244 }
11245
11246 case Intrinsic::ppc_mma_disassemble_acc: {
11247 if (Subtarget.isISAFuture()) {
11248 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11249 SDValue WideVec =
11250 SDValue(DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes,
11251 Op.getOperand(1)),
11252 0);
11254 SDValue Value = SDValue(WideVec.getNode(), 0);
11255 SDValue Value2 = SDValue(WideVec.getNode(), 1);
11256
11257 SDValue Extract;
11258 Extract = DAG.getNode(
11259 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11260 Subtarget.isLittleEndian() ? Value2 : Value,
11261 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11262 dl, getPointerTy(DAG.getDataLayout())));
11263 RetOps.push_back(Extract);
11264 Extract = DAG.getNode(
11265 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11266 Subtarget.isLittleEndian() ? Value2 : Value,
11267 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11268 dl, getPointerTy(DAG.getDataLayout())));
11269 RetOps.push_back(Extract);
11270 Extract = DAG.getNode(
11271 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11272 Subtarget.isLittleEndian() ? Value : Value2,
11273 DAG.getConstant(Subtarget.isLittleEndian() ? 1 : 0,
11274 dl, getPointerTy(DAG.getDataLayout())));
11275 RetOps.push_back(Extract);
11276 Extract = DAG.getNode(
11277 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
11278 Subtarget.isLittleEndian() ? Value : Value2,
11279 DAG.getConstant(Subtarget.isLittleEndian() ? 0 : 1,
11280 dl, getPointerTy(DAG.getDataLayout())));
11281 RetOps.push_back(Extract);
11282 return DAG.getMergeValues(RetOps, dl);
11283 }
11284 [[fallthrough]];
11285 }
11286 case Intrinsic::ppc_vsx_disassemble_pair: {
11287 int NumVecs = 2;
11288 SDValue WideVec = Op.getOperand(1);
11289 if (IntrinsicID == Intrinsic::ppc_mma_disassemble_acc) {
11290 NumVecs = 4;
11291 WideVec = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, WideVec);
11292 }
11294 for (int VecNo = 0; VecNo < NumVecs; VecNo++) {
11295 SDValue Extract = DAG.getNode(
11296 PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, WideVec,
11297 DAG.getConstant(Subtarget.isLittleEndian() ? NumVecs - 1 - VecNo
11298 : VecNo,
11299 dl, getPointerTy(DAG.getDataLayout())));
11300 RetOps.push_back(Extract);
11301 }
11302 return DAG.getMergeValues(RetOps, dl);
11303 }
11304
11305 case Intrinsic::ppc_build_dmr: {
11308 for (int i = 1; i < 9; i += 2) {
11309 SDValue Hi = Op.getOperand(i);
11310 SDValue Lo = Op.getOperand(i + 1);
11311 if (Hi->getOpcode() == ISD::LOAD)
11312 Chains.push_back(Hi.getValue(1));
11313 if (Lo->getOpcode() == ISD::LOAD)
11314 Chains.push_back(Lo.getValue(1));
11315 Pairs.push_back(
11316 DAG.getNode(PPCISD::PAIR_BUILD, dl, MVT::v256i1, {Hi, Lo}));
11317 }
11318 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11319 SDValue Value = DMFInsert1024(Pairs, SDLoc(Op), DAG);
11320 return DAG.getMergeValues({Value, TF}, dl);
11321 }
11322
11323 case Intrinsic::ppc_mma_dmxxextfdmr512: {
11324 assert(Subtarget.isISAFuture() && "dmxxextfdmr512 requires ISA Future");
11325 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11326 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11327 "Specify P of 0 or 1 for lower or upper 512 bytes");
11328 unsigned HiLo = Idx->getSExtValue();
11329 unsigned Opcode;
11330 unsigned Subx;
11331 if (HiLo == 0) {
11332 Opcode = PPC::DMXXEXTFDMR512;
11333 Subx = PPC::sub_wacc_lo;
11334 } else {
11335 Opcode = PPC::DMXXEXTFDMR512_HI;
11336 Subx = PPC::sub_wacc_hi;
11337 }
11338 SDValue Subreg(
11339 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
11340 Op.getOperand(1),
11341 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11342 0);
11343 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
11344 return SDValue(DAG.getMachineNode(Opcode, dl, ReturnTypes, Subreg), 0);
11345 }
11346
11347 case Intrinsic::ppc_mma_dmxxextfdmr256: {
11348 assert(Subtarget.isISAFuture() && "dmxxextfdmr256 requires ISA Future");
11349 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11350 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11351 "Specify a dmr row pair 0-3");
11352 unsigned IdxVal = Idx->getSExtValue();
11353 unsigned Subx;
11354 switch (IdxVal) {
11355 case 0:
11356 Subx = PPC::sub_dmrrowp0;
11357 break;
11358 case 1:
11359 Subx = PPC::sub_dmrrowp1;
11360 break;
11361 case 2:
11362 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11363 break;
11364 case 3:
11365 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11366 break;
11367 }
11368 SDValue Subreg(
11369 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v256i1,
11370 Op.getOperand(1),
11371 DAG.getTargetConstant(Subx, dl, MVT::i32)),
11372 0);
11373 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11374 return SDValue(
11375 DAG.getMachineNode(PPC::DMXXEXTFDMR256, dl, MVT::v256i1, {Subreg, P}),
11376 0);
11377 }
11378
11379 case Intrinsic::ppc_mma_dmxxinstdmr512: {
11380 assert(Subtarget.isISAFuture() && "dmxxinstdmr512 requires ISA Future");
11381 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4));
11382 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11383 "Specify P of 0 or 1 for lower or upper 512 bytes");
11384 unsigned HiLo = Idx->getSExtValue();
11385 unsigned Opcode;
11386 unsigned Subx;
11387 if (HiLo == 0) {
11388 Opcode = PPCISD::INST512;
11389 Subx = PPC::sub_wacc_lo;
11390 } else {
11391 Opcode = PPCISD::INST512HI;
11392 Subx = PPC::sub_wacc_hi;
11393 }
11394 SDValue Wacc = DAG.getNode(Opcode, dl, MVT::v512i1, Op.getOperand(2),
11395 Op.getOperand(3));
11396 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11397 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11398 Op.getOperand(1), Wacc, SubReg),
11399 0);
11400 }
11401
11402 case Intrinsic::ppc_mma_dmxxinstdmr256: {
11403 assert(Subtarget.isISAFuture() && "dmxxinstdmr256 requires ISA Future");
11404 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3));
11405 assert(Idx && (Idx->getSExtValue() >= 0 || Idx->getSExtValue() <= 3) &&
11406 "Specify a dmr row pair 0-3");
11407 unsigned IdxVal = Idx->getSExtValue();
11408 unsigned Subx;
11409 switch (IdxVal) {
11410 case 0:
11411 Subx = PPC::sub_dmrrowp0;
11412 break;
11413 case 1:
11414 Subx = PPC::sub_dmrrowp1;
11415 break;
11416 case 2:
11417 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp0;
11418 break;
11419 case 3:
11420 Subx = PPC::sub_wacc_hi_then_sub_dmrrowp1;
11421 break;
11422 }
11423 SDValue SubReg = DAG.getTargetConstant(Subx, dl, MVT::i32);
11424 SDValue P = DAG.getTargetConstant(IdxVal, dl, MVT::i32);
11425 SDValue DMRRowp =
11426 DAG.getNode(PPCISD::INST256, dl, MVT::v256i1, Op.getOperand(2), P);
11427 return SDValue(DAG.getMachineNode(PPC::INSERT_SUBREG, dl, MVT::v1024i1,
11428 Op.getOperand(1), DMRRowp, SubReg),
11429 0);
11430 }
11431
11432 case Intrinsic::ppc_mma_xxmfacc:
11433 case Intrinsic::ppc_mma_xxmtacc: {
11434 // Allow pre-isa-future subtargets to lower as normal.
11435 if (!Subtarget.isISAFuture())
11436 return SDValue();
11437 // The intrinsics for xxmtacc and xxmfacc take one argument of
11438 // type v512i1, for future cpu the corresponding wacc instruction
11439 // dmxx[inst|extf]dmr512 is always generated for type v512i1, negating
11440 // the need to produce the xxm[t|f]acc.
11441 SDValue WideVec = Op.getOperand(1);
11442 DAG.ReplaceAllUsesWith(Op, WideVec);
11443 return SDValue();
11444 }
11445
11446 case Intrinsic::ppc_unpack_longdouble: {
11447 auto *Idx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
11448 assert(Idx && (Idx->getSExtValue() == 0 || Idx->getSExtValue() == 1) &&
11449 "Argument of long double unpack must be 0 or 1!");
11450 return DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Op.getOperand(1),
11451 DAG.getConstant(!!(Idx->getSExtValue()), dl,
11452 Idx->getValueType(0)));
11453 }
11454
11455 case Intrinsic::ppc_compare_exp_lt:
11456 case Intrinsic::ppc_compare_exp_gt:
11457 case Intrinsic::ppc_compare_exp_eq:
11458 case Intrinsic::ppc_compare_exp_uo: {
11459 unsigned Pred;
11460 switch (IntrinsicID) {
11461 case Intrinsic::ppc_compare_exp_lt:
11462 Pred = PPC::PRED_LT;
11463 break;
11464 case Intrinsic::ppc_compare_exp_gt:
11465 Pred = PPC::PRED_GT;
11466 break;
11467 case Intrinsic::ppc_compare_exp_eq:
11468 Pred = PPC::PRED_EQ;
11469 break;
11470 case Intrinsic::ppc_compare_exp_uo:
11471 Pred = PPC::PRED_UN;
11472 break;
11473 }
11474 return SDValue(
11475 DAG.getMachineNode(
11476 PPC::SELECT_CC_I4, dl, MVT::i32,
11477 {SDValue(DAG.getMachineNode(PPC::XSCMPEXPDP, dl, MVT::i32,
11478 Op.getOperand(1), Op.getOperand(2)),
11479 0),
11480 DAG.getConstant(1, dl, MVT::i32), DAG.getConstant(0, dl, MVT::i32),
11481 DAG.getTargetConstant(Pred, dl, MVT::i32)}),
11482 0);
11483 }
11484 case Intrinsic::ppc_test_data_class: {
11485 EVT OpVT = Op.getOperand(1).getValueType();
11486 unsigned CmprOpc = OpVT == MVT::f128 ? PPC::XSTSTDCQP
11487 : (OpVT == MVT::f64 ? PPC::XSTSTDCDP
11488 : PPC::XSTSTDCSP);
11489 // Lower __builtin_ppc_test_data_class(value, mask) to XSTSTDC* instruction.
11490 // The XSTSTDC* instructions test if a floating-point value matches any of
11491 // the data classes specified in the mask, setting CR field bits
11492 // accordingly. We need to extract the EQ bit (bit 2) from the CR field and
11493 // convert it to an integer result (1 if match, 0 if no match).
11494 //
11495 // Note: Operands are swapped because XSTSTDC* expects (mask, value) but the
11496 // intrinsic provides (value, mask) as Op.getOperand(1) and
11497 // Op.getOperand(2).
11498 SDValue TestDataClass =
11499 SDValue(DAG.getMachineNode(CmprOpc, dl, MVT::i32,
11500 {Op.getOperand(2), Op.getOperand(1)}),
11501 0);
11502 if (Subtarget.isISA3_1()) {
11503 // ISA 3.1+: Use SETBC instruction to directly convert CR bit to integer.
11504 // This is more efficient than the SELECT_CC approach used in earlier
11505 // ISAs.
11506 SDValue SubRegIdx = DAG.getTargetConstant(PPC::sub_eq, dl, MVT::i32);
11507 SDValue CRBit =
11508 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11509 TestDataClass, SubRegIdx),
11510 0);
11511
11512 return DAG.getNode(PPCISD::SETBC, dl, MVT::i32, CRBit);
11513 }
11514
11515 // Pre-ISA 3.1: Use SELECT_CC to convert CR field to integer (1 or 0).
11516 return SDValue(
11517 DAG.getMachineNode(PPC::SELECT_CC_I4, dl, MVT::i32,
11518 {TestDataClass, DAG.getConstant(1, dl, MVT::i32),
11519 DAG.getConstant(0, dl, MVT::i32),
11520 DAG.getTargetConstant(PPC::PRED_EQ, dl, MVT::i32)}),
11521 0);
11522 }
11523 case Intrinsic::ppc_fnmsub: {
11524 EVT VT = Op.getOperand(1).getValueType();
11525 if (!Subtarget.hasVSX() || (!Subtarget.hasFloat128() && VT == MVT::f128))
11526 return DAG.getNode(
11527 ISD::FNEG, dl, VT,
11528 DAG.getNode(ISD::FMA, dl, VT, Op.getOperand(1), Op.getOperand(2),
11529 DAG.getNode(ISD::FNEG, dl, VT, Op.getOperand(3))));
11530 return DAG.getNode(PPCISD::FNMSUB, dl, VT, Op.getOperand(1),
11531 Op.getOperand(2), Op.getOperand(3));
11532 }
11533 case Intrinsic::ppc_convert_f128_to_ppcf128:
11534 case Intrinsic::ppc_convert_ppcf128_to_f128: {
11535 RTLIB::Libcall LC = IntrinsicID == Intrinsic::ppc_convert_ppcf128_to_f128
11536 ? RTLIB::CONVERT_PPCF128_F128
11537 : RTLIB::CONVERT_F128_PPCF128;
11538 MakeLibCallOptions CallOptions;
11539 std::pair<SDValue, SDValue> Result =
11540 makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(1), CallOptions,
11541 dl, SDValue());
11542 return Result.first;
11543 }
11544 case Intrinsic::ppc_maxfe:
11545 case Intrinsic::ppc_maxfl:
11546 case Intrinsic::ppc_maxfs:
11547 case Intrinsic::ppc_minfe:
11548 case Intrinsic::ppc_minfl:
11549 case Intrinsic::ppc_minfs: {
11550 EVT VT = Op.getValueType();
11551 assert(
11552 all_of(Op->ops().drop_front(4),
11553 [VT](const SDUse &Use) { return Use.getValueType() == VT; }) &&
11554 "ppc_[max|min]f[e|l|s] must have uniform type arguments");
11555 (void)VT;
11557 if (IntrinsicID == Intrinsic::ppc_minfe ||
11558 IntrinsicID == Intrinsic::ppc_minfl ||
11559 IntrinsicID == Intrinsic::ppc_minfs)
11560 CC = ISD::SETLT;
11561 unsigned I = Op.getNumOperands() - 2, Cnt = I;
11562 SDValue Res = Op.getOperand(I);
11563 for (--I; Cnt != 0; --Cnt, I = (--I == 0 ? (Op.getNumOperands() - 1) : I)) {
11564 Res =
11565 DAG.getSelectCC(dl, Res, Op.getOperand(I), Res, Op.getOperand(I), CC);
11566 }
11567 return Res;
11568 }
11569 }
11570
11571 // If this is a lowered altivec predicate compare, CompareOpc is set to the
11572 // opcode number of the comparison.
11573 int CompareOpc;
11574 bool isDot;
11575 if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
11576 return SDValue(); // Don't custom lower most intrinsics.
11577
11578 // If this is a non-dot comparison, make the VCMP node and we are done.
11579 if (!isDot) {
11580 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
11581 Op.getOperand(1), Op.getOperand(2),
11582 DAG.getConstant(CompareOpc, dl, MVT::i32));
11583 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
11584 }
11585
11586 // Create the PPCISD altivec 'dot' comparison node.
11587 SDValue Ops[] = {
11588 Op.getOperand(2), // LHS
11589 Op.getOperand(3), // RHS
11590 DAG.getConstant(CompareOpc, dl, MVT::i32)
11591 };
11592 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
11593 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
11594
11595 // Unpack the result based on how the target uses it.
11596 unsigned BitNo; // Bit # of CR6.
11597 bool InvertBit; // Invert result?
11598 unsigned Bitx;
11599 unsigned SetOp;
11600 switch (Op.getConstantOperandVal(1)) {
11601 default: // Can't happen, don't crash on invalid number though.
11602 case 0: // Return the value of the EQ bit of CR6.
11603 BitNo = 0;
11604 InvertBit = false;
11605 Bitx = PPC::sub_eq;
11606 SetOp = PPCISD::SETBC;
11607 break;
11608 case 1: // Return the inverted value of the EQ bit of CR6.
11609 BitNo = 0;
11610 InvertBit = true;
11611 Bitx = PPC::sub_eq;
11612 SetOp = PPCISD::SETBCR;
11613 break;
11614 case 2: // Return the value of the LT bit of CR6.
11615 BitNo = 2;
11616 InvertBit = false;
11617 Bitx = PPC::sub_lt;
11618 SetOp = PPCISD::SETBC;
11619 break;
11620 case 3: // Return the inverted value of the LT bit of CR6.
11621 BitNo = 2;
11622 InvertBit = true;
11623 Bitx = PPC::sub_lt;
11624 SetOp = PPCISD::SETBCR;
11625 break;
11626 }
11627
11628 SDValue GlueOp = CompNode.getValue(1);
11629 if (Subtarget.isISA3_1()) {
11630 SDValue SubRegIdx = DAG.getTargetConstant(Bitx, dl, MVT::i32);
11631 SDValue CR6Reg = DAG.getRegister(PPC::CR6, MVT::i32);
11632 SDValue CRBit =
11633 SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
11634 CR6Reg, SubRegIdx, GlueOp),
11635 0);
11636 return DAG.getNode(SetOp, dl, MVT::i32, CRBit);
11637 }
11638
11639 // Now that we have the comparison, emit a copy from the CR to a GPR.
11640 // This is flagged to the above dot comparison.
11641 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
11642 DAG.getRegister(PPC::CR6, MVT::i32), GlueOp);
11643
11644 // Shift the bit into the low position.
11645 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
11646 DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
11647 // Isolate the bit.
11648 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
11649 DAG.getConstant(1, dl, MVT::i32));
11650
11651 // If we are supposed to, toggle the bit.
11652 if (InvertBit)
11653 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
11654 DAG.getConstant(1, dl, MVT::i32));
11655 return Flags;
11656}
11657
11658SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
11659 SelectionDAG &DAG) const {
11660 // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
11661 // the beginning of the argument list.
11662 int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
11663 SDLoc DL(Op);
11664 switch (Op.getConstantOperandVal(ArgStart)) {
11665 case Intrinsic::ppc_cfence: {
11666 assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
11667 SDValue Val = Op.getOperand(ArgStart + 1);
11668 EVT Ty = Val.getValueType();
11669 if (Ty == MVT::i128) {
11670 // FIXME: Testing one of two paired registers is sufficient to guarantee
11671 // ordering?
11672 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, Val);
11673 }
11674 unsigned Opcode = Subtarget.isPPC64() ? PPC::CFENCE8 : PPC::CFENCE;
11675 return SDValue(
11676 DAG.getMachineNode(
11677 Opcode, DL, MVT::Other,
11678 DAG.getNode(ISD::ANY_EXTEND, DL, Subtarget.getScalarIntVT(), Val),
11679 Op.getOperand(0)),
11680 0);
11681 }
11682 case Intrinsic::ppc_disassemble_dmr: {
11683 assert(ArgStart == 1 &&
11684 "llvm.ppc.disassemble.dmr must carry a chain argument.");
11685 return DAG.getStore(Op.getOperand(0), DL, Op.getOperand(ArgStart + 2),
11686 Op.getOperand(ArgStart + 1), MachinePointerInfo());
11687 }
11688 default:
11689 break;
11690 }
11691 return SDValue();
11692}
11693
11694// Lower scalar BSWAP64 to xxbrd.
11695SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
11696 SDLoc dl(Op);
11697 if (!Subtarget.isPPC64())
11698 return Op;
11699
11700 if (Subtarget.hasP9Vector()) {
11701 // MTVSRDD
11702 Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
11703 Op.getOperand(0));
11704 // XXBRD
11705 Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
11706 // MFVSRD
11707 int VectorIndex = 0;
11708 if (Subtarget.isLittleEndian())
11709 VectorIndex = 1;
11710 Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
11711 DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
11712 return Op;
11713 }
11714
11715 // For Power8, use parallel rotate instructions for faster bswap64.
11716 SDValue Input = Op.getOperand(0);
11717 // Helper to create rotate-and-insert operations (RLWIMI/RLDIMI).
11718 auto CreateRotateInsert =
11719 [&](unsigned Opcode, MVT VT, SDValue Dest, SDValue Src, unsigned RotAmt,
11720 unsigned MaskBegin,
11721 std::optional<unsigned> MaskEnd = std::nullopt) -> SDValue {
11723 Dest, Src, DAG.getTargetConstant(RotAmt, dl, MVT::i32),
11724 DAG.getTargetConstant(MaskBegin, dl, MVT::i32)};
11725 if (MaskEnd.has_value())
11726 Ops.push_back(DAG.getTargetConstant(*MaskEnd, dl, MVT::i32));
11727
11728 return SDValue(DAG.getMachineNode(Opcode, dl, VT, Ops), 0);
11729 };
11730
11731 // Helper to perform 32-bit byte swap using rotl(8) + 2x rlwimi.
11732 auto Swap32 = [&](SDValue Val32) -> SDValue {
11733 SDValue Rot = DAG.getNode(ISD::ROTL, dl, MVT::i32, Val32,
11734 DAG.getConstant(8, dl, MVT::i32));
11735 // Insert bits [24:31] from Val32 into Rot at position [0:7].
11736 SDValue Swap =
11737 CreateRotateInsert(PPC::RLWIMI, MVT::i32, Rot, Val32, 24, 0, 7);
11738 // Insert bits [16:23] from Val32 into Swap at position [16:23].
11739 return CreateRotateInsert(PPC::RLWIMI, MVT::i32, Swap, Val32, 24, 16, 23);
11740 };
11741 // Extract and swap high and low 32-bit halves independently for parallelism.
11742 SDValue Hi32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
11743 DAG.getNode(ISD::SRL, dl, MVT::i64, Input,
11744 DAG.getConstant(32, dl, MVT::i64)));
11745 SDValue Lo32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Input);
11746
11747 // Combine swapped halves: rotate LoSwap left by 32 bits and insert into
11748 // HiSwap to swap their positions, completing the 64-bit byte reversal.
11749 SDValue HiSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Hi32));
11750 SDValue LoSwap = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Swap32(Lo32));
11751
11752 return CreateRotateInsert(PPC::RLDIMI, MVT::i64, HiSwap, LoSwap, 32, 0);
11753}
11754
11755// ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
11756// compared to a value that is atomically loaded (atomic loads zero-extend).
11757SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
11758 SelectionDAG &DAG) const {
11759 assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
11760 "Expecting an atomic compare-and-swap here.");
11761 SDLoc dl(Op);
11762 auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
11763 EVT MemVT = AtomicNode->getMemoryVT();
11764 if (MemVT.getSizeInBits() >= 32)
11765 return Op;
11766
11767 SDValue CmpOp = Op.getOperand(2);
11768 // If this is already correctly zero-extended, leave it alone.
11769 auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
11770 if (DAG.MaskedValueIsZero(CmpOp, HighBits))
11771 return Op;
11772
11773 // Clear the high bits of the compare operand.
11774 unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
11775 SDValue NewCmpOp =
11776 DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
11777 DAG.getConstant(MaskVal, dl, MVT::i32));
11778
11779 // Replace the existing compare operand with the properly zero-extended one.
11781 for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
11782 Ops.push_back(AtomicNode->getOperand(i));
11783 Ops[2] = NewCmpOp;
11784 MachineMemOperand *MMO = AtomicNode->getMemOperand();
11785 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
11786 auto NodeTy =
11787 (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
11788 return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
11789}
11790
11791SDValue PPCTargetLowering::LowerATOMIC_LOAD_STORE(SDValue Op,
11792 SelectionDAG &DAG) const {
11793 AtomicSDNode *N = cast<AtomicSDNode>(Op.getNode());
11794 EVT MemVT = N->getMemoryVT();
11795 assert(MemVT.getSimpleVT() == MVT::i128 &&
11796 "Expect quadword atomic operations");
11797 SDLoc dl(N);
11798 unsigned Opc = N->getOpcode();
11799 switch (Opc) {
11800 case ISD::ATOMIC_LOAD: {
11801 // Lower quadword atomic load to int_ppc_atomic_load_i128 which will be
11802 // lowered to ppc instructions by pattern matching instruction selector.
11803 SDVTList Tys = DAG.getVTList(MVT::i64, MVT::i64, MVT::Other);
11805 N->getOperand(0),
11806 DAG.getConstant(Intrinsic::ppc_atomic_load_i128, dl, MVT::i32)};
11807 for (int I = 1, E = N->getNumOperands(); I < E; ++I)
11808 Ops.push_back(N->getOperand(I));
11809 SDValue LoadedVal = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, Tys,
11810 Ops, MemVT, N->getMemOperand());
11811 SDValue ValLo = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal);
11812 SDValue ValHi =
11813 DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i128, LoadedVal.getValue(1));
11814 ValHi = DAG.getNode(ISD::SHL, dl, MVT::i128, ValHi,
11815 DAG.getConstant(64, dl, MVT::i32));
11816 SDValue Val =
11817 DAG.getNode(ISD::OR, dl, {MVT::i128, MVT::Other}, {ValLo, ValHi});
11818 return DAG.getNode(ISD::MERGE_VALUES, dl, {MVT::i128, MVT::Other},
11819 {Val, LoadedVal.getValue(2)});
11820 }
11821 case ISD::ATOMIC_STORE: {
11822 // Lower quadword atomic store to int_ppc_atomic_store_i128 which will be
11823 // lowered to ppc instructions by pattern matching instruction selector.
11824 SDVTList Tys = DAG.getVTList(MVT::Other);
11826 N->getOperand(0),
11827 DAG.getConstant(Intrinsic::ppc_atomic_store_i128, dl, MVT::i32)};
11828 SDValue Val = N->getOperand(1);
11829 SDValue ValLo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, Val);
11830 SDValue ValHi = DAG.getNode(ISD::SRL, dl, MVT::i128, Val,
11831 DAG.getConstant(64, dl, MVT::i32));
11832 ValHi = DAG.getNode(ISD::TRUNCATE, dl, MVT::i64, ValHi);
11833 Ops.push_back(ValLo);
11834 Ops.push_back(ValHi);
11835 Ops.push_back(N->getOperand(2));
11836 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops, MemVT,
11837 N->getMemOperand());
11838 }
11839 default:
11840 llvm_unreachable("Unexpected atomic opcode");
11841 }
11842}
11843
11845 SelectionDAG &DAG,
11846 const PPCSubtarget &Subtarget) {
11847 assert(Mask <= fcAllFlags && "Invalid fp_class flags!");
11848
11849 enum DataClassMask {
11850 DC_NAN = 1 << 6,
11851 DC_NEG_INF = 1 << 4,
11852 DC_POS_INF = 1 << 5,
11853 DC_NEG_ZERO = 1 << 2,
11854 DC_POS_ZERO = 1 << 3,
11855 DC_NEG_SUBNORM = 1,
11856 DC_POS_SUBNORM = 1 << 1,
11857 };
11858
11859 EVT VT = Op.getValueType();
11860
11861 unsigned TestOp = VT == MVT::f128 ? PPC::XSTSTDCQP
11862 : VT == MVT::f64 ? PPC::XSTSTDCDP
11863 : PPC::XSTSTDCSP;
11864
11865 if (Mask == fcAllFlags)
11866 return DAG.getBoolConstant(true, Dl, MVT::i1, VT);
11867 if (Mask == 0)
11868 return DAG.getBoolConstant(false, Dl, MVT::i1, VT);
11869
11870 // When it's cheaper or necessary to test reverse flags.
11871 if ((Mask & fcNormal) == fcNormal || Mask == ~fcQNan || Mask == ~fcSNan) {
11872 SDValue Rev = getDataClassTest(Op, ~Mask, Dl, DAG, Subtarget);
11873 return DAG.getNOT(Dl, Rev, MVT::i1);
11874 }
11875
11876 // Power doesn't support testing whether a value is 'normal'. Test the rest
11877 // first, and test if it's 'not not-normal' with expected sign.
11878 if (Mask & fcNormal) {
11879 SDValue Rev(DAG.getMachineNode(
11880 TestOp, Dl, MVT::i32,
11881 DAG.getTargetConstant(DC_NAN | DC_NEG_INF | DC_POS_INF |
11882 DC_NEG_ZERO | DC_POS_ZERO |
11883 DC_NEG_SUBNORM | DC_POS_SUBNORM,
11884 Dl, MVT::i32),
11885 Op),
11886 0);
11887 // Sign are stored in CR bit 0, result are in CR bit 2.
11888 SDValue Sign(
11889 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11890 DAG.getTargetConstant(PPC::sub_lt, Dl, MVT::i32)),
11891 0);
11892 SDValue Normal(DAG.getNOT(
11893 Dl,
11895 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1, Rev,
11896 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11897 0),
11898 MVT::i1));
11899 if (Mask & fcPosNormal)
11900 Sign = DAG.getNOT(Dl, Sign, MVT::i1);
11901 SDValue Result = DAG.getNode(ISD::AND, Dl, MVT::i1, Sign, Normal);
11902 if (Mask == fcPosNormal || Mask == fcNegNormal)
11903 return Result;
11904
11905 return DAG.getNode(
11906 ISD::OR, Dl, MVT::i1,
11907 getDataClassTest(Op, Mask & ~fcNormal, Dl, DAG, Subtarget), Result);
11908 }
11909
11910 // The instruction doesn't differentiate between signaling or quiet NaN. Test
11911 // the rest first, and test if it 'is NaN and is signaling/quiet'.
11912 if ((Mask & fcNan) == fcQNan || (Mask & fcNan) == fcSNan) {
11913 bool IsQuiet = Mask & fcQNan;
11914 SDValue NanCheck = getDataClassTest(Op, fcNan, Dl, DAG, Subtarget);
11915
11916 // Quietness is determined by the first bit in fraction field.
11917 uint64_t QuietMask = 0;
11918 SDValue HighWord;
11919 if (VT == MVT::f128) {
11920 HighWord = DAG.getNode(
11921 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, DAG.getBitcast(MVT::v4i32, Op),
11922 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 3 : 0, Dl));
11923 QuietMask = 0x8000;
11924 } else if (VT == MVT::f64) {
11925 if (Subtarget.isPPC64()) {
11926 HighWord = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i32,
11927 DAG.getBitcast(MVT::i64, Op),
11928 DAG.getConstant(1, Dl, MVT::i32));
11929 } else {
11930 SDValue Vec = DAG.getBitcast(
11931 MVT::v4i32, DAG.getNode(ISD::SCALAR_TO_VECTOR, Dl, MVT::v2f64, Op));
11932 HighWord = DAG.getNode(
11933 ISD::EXTRACT_VECTOR_ELT, Dl, MVT::i32, Vec,
11934 DAG.getVectorIdxConstant(Subtarget.isLittleEndian() ? 1 : 0, Dl));
11935 }
11936 QuietMask = 0x80000;
11937 } else if (VT == MVT::f32) {
11938 HighWord = DAG.getBitcast(MVT::i32, Op);
11939 QuietMask = 0x400000;
11940 }
11941 SDValue NanRes = DAG.getSetCC(
11942 Dl, MVT::i1,
11943 DAG.getNode(ISD::AND, Dl, MVT::i32, HighWord,
11944 DAG.getConstant(QuietMask, Dl, MVT::i32)),
11945 DAG.getConstant(0, Dl, MVT::i32), IsQuiet ? ISD::SETNE : ISD::SETEQ);
11946 NanRes = DAG.getNode(ISD::AND, Dl, MVT::i1, NanCheck, NanRes);
11947 if (Mask == fcQNan || Mask == fcSNan)
11948 return NanRes;
11949
11950 return DAG.getNode(ISD::OR, Dl, MVT::i1,
11951 getDataClassTest(Op, Mask & ~fcNan, Dl, DAG, Subtarget),
11952 NanRes);
11953 }
11954
11955 unsigned NativeMask = 0;
11956 if ((Mask & fcNan) == fcNan)
11957 NativeMask |= DC_NAN;
11958 if (Mask & fcNegInf)
11959 NativeMask |= DC_NEG_INF;
11960 if (Mask & fcPosInf)
11961 NativeMask |= DC_POS_INF;
11962 if (Mask & fcNegZero)
11963 NativeMask |= DC_NEG_ZERO;
11964 if (Mask & fcPosZero)
11965 NativeMask |= DC_POS_ZERO;
11966 if (Mask & fcNegSubnormal)
11967 NativeMask |= DC_NEG_SUBNORM;
11968 if (Mask & fcPosSubnormal)
11969 NativeMask |= DC_POS_SUBNORM;
11970 return SDValue(
11971 DAG.getMachineNode(
11972 TargetOpcode::EXTRACT_SUBREG, Dl, MVT::i1,
11974 TestOp, Dl, MVT::i32,
11975 DAG.getTargetConstant(NativeMask, Dl, MVT::i32), Op),
11976 0),
11977 DAG.getTargetConstant(PPC::sub_eq, Dl, MVT::i32)),
11978 0);
11979}
11980
11981SDValue PPCTargetLowering::LowerIS_FPCLASS(SDValue Op,
11982 SelectionDAG &DAG) const {
11983 assert(Subtarget.hasP9Vector() && "Test data class requires Power9");
11984 SDValue LHS = Op.getOperand(0);
11985 uint64_t RHSC = Op.getConstantOperandVal(1);
11986 SDLoc Dl(Op);
11987 FPClassTest Category = static_cast<FPClassTest>(RHSC);
11988 if (LHS.getValueType() == MVT::ppcf128) {
11989 // The higher part determines the value class.
11990 LHS = DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::f64, LHS,
11991 DAG.getConstant(1, Dl, MVT::i32));
11992 }
11993
11994 return getDataClassTest(LHS, Category, Dl, DAG, Subtarget);
11995}
11996
11997// Adjust the length value for a load/store with length to account for the
11998// instructions requiring a left justified length, and for non-byte element
11999// types requiring scaling by element size.
12000static SDValue AdjustLength(SDValue Val, unsigned Bits, bool Left,
12001 SelectionDAG &DAG) {
12002 SDLoc dl(Val);
12003 EVT VT = Val->getValueType(0);
12004 unsigned LeftAdj = Left ? VT.getSizeInBits() - 8 : 0;
12005 unsigned TypeAdj = llvm::countr_zero<uint32_t>(Bits / 8);
12006 SDValue SHLAmt = DAG.getConstant(LeftAdj + TypeAdj, dl, VT);
12007 return DAG.getNode(ISD::SHL, dl, VT, Val, SHLAmt);
12008}
12009
12010SDValue PPCTargetLowering::LowerVP_LOAD(SDValue Op, SelectionDAG &DAG) const {
12011 auto VPLD = cast<VPLoadSDNode>(Op);
12012 bool Future = Subtarget.isISAFuture();
12013 SDLoc dl(Op);
12014 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(3).getNode(), true) &&
12015 "Mask predication not supported");
12016 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12017 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPLD->getOperand(4));
12018 unsigned IID = Future ? Intrinsic::ppc_vsx_lxvrl : Intrinsic::ppc_vsx_lxvl;
12019 unsigned EltBits = Op->getValueType(0).getScalarType().getSizeInBits();
12020 Len = AdjustLength(Len, EltBits, !Future, DAG);
12021 SDValue Ops[] = {VPLD->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12022 VPLD->getOperand(1), Len};
12023 SDVTList Tys = DAG.getVTList(Op->getValueType(0), MVT::Other);
12024 SDValue VPL =
12026 VPLD->getMemoryVT(), VPLD->getMemOperand());
12027 return VPL;
12028}
12029
12030SDValue PPCTargetLowering::LowerVP_STORE(SDValue Op, SelectionDAG &DAG) const {
12031 auto VPST = cast<VPStoreSDNode>(Op);
12032 assert(ISD::isConstantSplatVectorAllOnes(Op->getOperand(4).getNode(), true) &&
12033 "Mask predication not supported");
12034 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12035 SDLoc dl(Op);
12036 SDValue Len = DAG.getNode(ISD::ANY_EXTEND, dl, PtrVT, VPST->getOperand(5));
12037 unsigned EltBits =
12038 Op->getOperand(1).getValueType().getScalarType().getSizeInBits();
12039 bool Future = Subtarget.isISAFuture();
12040 unsigned IID = Future ? Intrinsic::ppc_vsx_stxvrl : Intrinsic::ppc_vsx_stxvl;
12041 Len = AdjustLength(Len, EltBits, !Future, DAG);
12042 SDValue Ops[] = {
12043 VPST->getChain(), DAG.getConstant(IID, dl, MVT::i32),
12044 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, VPST->getOperand(1)),
12045 VPST->getOperand(2), Len};
12046 SDVTList Tys = DAG.getVTList(MVT::Other);
12047 SDValue VPS =
12049 VPST->getMemoryVT(), VPST->getMemOperand());
12050 return VPS;
12051}
12052
12053SDValue PPCTargetLowering::LowerPartialReduce(SDValue Op,
12054 SelectionDAG &DAG) const {
12055 SDValue Acc = Op.getOperand(0);
12056 SDValue Op1 = Op.getOperand(1);
12057 SDValue Op2 = Op.getOperand(2);
12058
12059 assert(Op.getOpcode() == ISD::PARTIAL_REDUCE_UMLA &&
12060 "Unexpected partial reduction");
12061
12062 if (Acc.getValueType() != MVT::v4i32)
12063 return SDValue();
12064 if (Op1.getValueType() != MVT::v16i32 || Op1.getOpcode() != ISD::SIGN_EXTEND)
12065 return SDValue();
12066 SDValue Op1Input = Op1.getOperand(0);
12067 if (Op1Input.getValueType() != MVT::v16i8 || !llvm::isOneOrOneSplat(Op2))
12068 return SDValue();
12069
12070 SDLoc dl(Op);
12071 SDValue Ones = DAG.getConstant(1, dl, MVT::v16i8);
12072 return DAG.getNode(ISD::PARTIAL_REDUCE_SUMLA, dl, MVT::v4i32, Acc, Op1Input,
12073 Ones);
12074}
12075
12076SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
12077 SelectionDAG &DAG) const {
12078 SDLoc dl(Op);
12079
12081 SDValue Op0 = Op.getOperand(0);
12082 EVT ValVT = Op0.getValueType();
12083 unsigned EltSize = Op.getValueType().getScalarSizeInBits();
12084 if (isa<ConstantSDNode>(Op0) && EltSize <= 32) {
12085 int64_t IntVal = Op.getConstantOperandVal(0);
12086 if (IntVal >= -16 && IntVal <= 15)
12087 return getCanonicalConstSplat(IntVal, EltSize / 8, Op.getValueType(), DAG,
12088 dl);
12089 }
12090
12091 ReuseLoadInfo RLI;
12092 if (Subtarget.hasLFIWAX() && Subtarget.hasVSX() &&
12093 Op.getValueType() == MVT::v4i32 && Op0.getOpcode() == ISD::LOAD &&
12094 Op0.getValueType() == MVT::i32 && Op0.hasOneUse() &&
12095 canReuseLoadAddress(Op0, MVT::i32, RLI, DAG, ISD::NON_EXTLOAD)) {
12096
12097 MachineMemOperand *MMO = MF.getMachineMemOperand(
12098 RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment,
12099 MMOMetadata(RLI.AAInfo, RLI.Ranges));
12100 SDValue Ops[] = {RLI.Chain, RLI.Ptr, DAG.getValueType(Op.getValueType())};
12101 SDValue Bits = DAG.getMemIntrinsicNode(
12102 PPCISD::LD_SPLAT, dl, DAG.getVTList(MVT::v4i32, MVT::Other), Ops,
12103 MVT::i32, MMO);
12104 if (RLI.ResChain)
12105 DAG.makeEquivalentMemoryOrdering(RLI.ResChain, Bits.getValue(1));
12106 return Bits.getValue(0);
12107 }
12108
12109 // Create a stack slot that is 16-byte aligned.
12110 MachineFrameInfo &MFI = MF.getFrameInfo();
12111 int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
12112 EVT PtrVT = getPointerTy(DAG.getDataLayout());
12113 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
12114
12115 SDValue Val = Op0;
12116 // P10 hardware store forwarding requires that a single store contains all
12117 // the data for the load. P10 is able to merge a pair of adjacent stores. Try
12118 // to avoid load hit store on P10 when running binaries compiled for older
12119 // processors by generating two mergeable scalar stores to forward with the
12120 // vector load.
12121 if (EnableP10StoreForward && Subtarget.isPPC64() &&
12122 !Subtarget.isLittleEndian() && ValVT.isInteger() &&
12123 ValVT.getSizeInBits() <= 64) {
12124 Val = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, Val);
12125 EVT ShiftAmountTy = getShiftAmountTy(MVT::i64, DAG.getDataLayout());
12126 SDValue ShiftBy = DAG.getConstant(
12127 64 - Op.getValueType().getScalarSizeInBits(), dl, ShiftAmountTy);
12128 Val = DAG.getNode(ISD::SHL, dl, MVT::i64, Val, ShiftBy);
12129 SDValue Plus8 =
12130 DAG.getNode(ISD::ADD, dl, PtrVT, FIdx, DAG.getConstant(8, dl, PtrVT));
12131 SDValue Store2 =
12132 DAG.getStore(DAG.getEntryNode(), dl, Val, Plus8, MachinePointerInfo());
12133 SDValue Store = DAG.getStore(Store2, dl, Val, FIdx, MachinePointerInfo());
12134 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx,
12135 MachinePointerInfo());
12136 }
12137
12138 // Store the input value into Value#0 of the stack slot.
12139 SDValue Store =
12140 DAG.getStore(DAG.getEntryNode(), dl, Val, FIdx, MachinePointerInfo());
12141 // Load it out.
12142 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
12143}
12144
12145SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
12146 SelectionDAG &DAG) const {
12147 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
12148 "Should only be called for ISD::INSERT_VECTOR_ELT");
12149
12150 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
12151
12152 EVT VT = Op.getValueType();
12153 SDLoc dl(Op);
12154 SDValue V1 = Op.getOperand(0);
12155 SDValue V2 = Op.getOperand(1);
12156
12157 if (VT == MVT::v2f64 && C)
12158 return Op;
12159
12160 if (Subtarget.hasP9Vector()) {
12161 // A f32 load feeding into a v4f32 insert_vector_elt is handled in this way
12162 // because on P10, it allows this specific insert_vector_elt load pattern to
12163 // utilize the refactored load and store infrastructure in order to exploit
12164 // prefixed loads.
12165 // On targets with inexpensive direct moves (Power9 and up), a
12166 // (insert_vector_elt v4f32:$vec, (f32 load)) is always better as an integer
12167 // load since a single precision load will involve conversion to double
12168 // precision on the load followed by another conversion to single precision.
12169 if ((VT == MVT::v4f32) && (V2.getValueType() == MVT::f32) &&
12170 (isa<LoadSDNode>(V2))) {
12171 SDValue BitcastVector = DAG.getBitcast(MVT::v4i32, V1);
12172 SDValue BitcastLoad = DAG.getBitcast(MVT::i32, V2);
12173 SDValue InsVecElt =
12174 DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v4i32, BitcastVector,
12175 BitcastLoad, Op.getOperand(2));
12176 return DAG.getBitcast(MVT::v4f32, InsVecElt);
12177 }
12178 }
12179
12180 if (Subtarget.isISA3_1()) {
12181 if ((VT == MVT::v2i64 || VT == MVT::v2f64) && !Subtarget.isPPC64())
12182 return SDValue();
12183 // On P10, we have legal lowering for constant and variable indices for
12184 // all vectors.
12185 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
12186 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
12187 return Op;
12188 }
12189
12190 // Before P10, we have legal lowering for constant indices but not for
12191 // variable ones.
12192 if (!C)
12193 return SDValue();
12194
12195 // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
12196 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
12197 SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
12198 unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
12199 unsigned InsertAtElement = C->getZExtValue();
12200 unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
12201 if (Subtarget.isLittleEndian()) {
12202 InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
12203 }
12204 return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
12205 DAG.getConstant(InsertAtByte, dl, MVT::i32));
12206 }
12207 return Op;
12208}
12209
12210SDValue PPCTargetLowering::LowerDMFVectorLoad(SDValue Op,
12211 SelectionDAG &DAG) const {
12212 SDLoc dl(Op);
12213 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12214 SDValue LoadChain = LN->getChain();
12215 SDValue BasePtr = LN->getBasePtr();
12216 EVT VT = Op.getValueType();
12217 bool IsV1024i1 = VT == MVT::v1024i1;
12218 bool IsV2048i1 = VT == MVT::v2048i1;
12219
12220 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12221 // Dense Math dmr pair registers, respectively.
12222 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12223 (void)IsV2048i1;
12224 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12225 "Dense Math support required.");
12226 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12227
12229 SmallVector<SDValue, 8> LoadChains;
12230
12231 SDValue IntrinID = DAG.getConstant(Intrinsic::ppc_vsx_lxvp, dl, MVT::i32);
12232 SDValue LoadOps[] = {LoadChain, IntrinID, BasePtr};
12233 MachineMemOperand *MMO = LN->getMemOperand();
12234 unsigned NumVecs = VT.getSizeInBits() / 256;
12235 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12236 MachineMemOperand *NewMMO =
12237 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12238 if (Idx > 0) {
12239 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12240 DAG.getConstant(32, dl, BasePtr.getValueType()));
12241 LoadOps[2] = BasePtr;
12242 }
12243 SDValue Ld = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12244 DAG.getVTList(MVT::v256i1, MVT::Other),
12245 LoadOps, MVT::v256i1, NewMMO);
12246 LoadChains.push_back(Ld.getValue(1));
12247 Loads.push_back(Ld);
12248 }
12249
12250 if (Subtarget.isLittleEndian()) {
12251 std::reverse(Loads.begin(), Loads.end());
12252 std::reverse(LoadChains.begin(), LoadChains.end());
12253 }
12254
12255 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12256 SDValue Value = DMFInsert1024(Loads, dl, DAG);
12257
12258 if (IsV1024i1) {
12259 return DAG.getMergeValues({Value, TF}, dl);
12260 }
12261
12262 // Handle Loads for V2048i1 which represents a dmr pair.
12263 SmallVector<SDValue, 4> MoreLoads{Loads[4], Loads[5], Loads[6], Loads[7]};
12264 SDValue Dmr1Value = DMFInsert1024(MoreLoads, dl, DAG);
12265
12266 SDValue Dmr0Sub = DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32);
12267 SDValue Dmr1Sub = DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32);
12268
12269 SDValue DmrPRC = DAG.getTargetConstant(PPC::DMRpRCRegClassID, dl, MVT::i32);
12270 const SDValue DmrPOps[] = {DmrPRC, Value, Dmr0Sub, Dmr1Value, Dmr1Sub};
12271
12272 SDValue DmrPValue = SDValue(
12273 DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v2048i1, DmrPOps), 0);
12274
12275 return DAG.getMergeValues({DmrPValue, TF}, dl);
12276}
12277
12278SDValue PPCTargetLowering::DMFInsert1024(const SmallVectorImpl<SDValue> &Pairs,
12279 const SDLoc &dl,
12280 SelectionDAG &DAG) const {
12281 SDValue Lo =
12282 DAG.getNode(PPCISD::INST512, dl, MVT::v512i1, Pairs[0], Pairs[1]);
12283 SDValue LoSub = DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32);
12284 SDValue Hi =
12285 DAG.getNode(PPCISD::INST512HI, dl, MVT::v512i1, Pairs[2], Pairs[3]);
12286 SDValue HiSub = DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32);
12287 SDValue RC = DAG.getTargetConstant(PPC::DMRRCRegClassID, dl, MVT::i32);
12288
12289 return SDValue(DAG.getMachineNode(PPC::REG_SEQUENCE, dl, MVT::v1024i1,
12290 {RC, Lo, LoSub, Hi, HiSub}),
12291 0);
12292}
12293
12294SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
12295 SelectionDAG &DAG) const {
12296 SDLoc dl(Op);
12297 LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
12298 SDValue LoadChain = LN->getChain();
12299 SDValue BasePtr = LN->getBasePtr();
12300 EVT VT = Op.getValueType();
12301
12302 if (VT == MVT::v1024i1 || VT == MVT::v2048i1)
12303 return LowerDMFVectorLoad(Op, DAG);
12304
12305 if (VT != MVT::v256i1 && VT != MVT::v512i1)
12306 return Op;
12307
12308 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12309 assert((VT != MVT::v512i1 || Subtarget.hasMMA()) &&
12310 "Type unsupported without MMA");
12311 assert((VT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12312 "Type unsupported without paired vector support");
12313
12314 // For v256i1 on ISA Future, let the load go through to instruction selection
12315 // where it will be matched to lxvp/plxvp by the instruction patterns.
12316 if (VT == MVT::v256i1 && Subtarget.isISAFuture())
12317 return Op;
12318
12319 // For other cases, create 2 or 4 v16i8 loads to load the pair or accumulator
12320 // value in 2 or 4 vsx registers.
12321 Align Alignment = LN->getAlign();
12323 SmallVector<SDValue, 4> LoadChains;
12324 unsigned NumVecs = VT.getSizeInBits() / 128;
12325 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12326 SDValue Load =
12327 DAG.getLoad(MVT::v16i8, dl, LoadChain, BasePtr,
12328 LN->getPointerInfo().getWithOffset(Idx * 16),
12329 commonAlignment(Alignment, Idx * 16),
12330 LN->getMemOperand()->getFlags(), LN->getAAInfo());
12331 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12332 DAG.getConstant(16, dl, BasePtr.getValueType()));
12333 Loads.push_back(Load);
12334 LoadChains.push_back(Load.getValue(1));
12335 }
12336 if (Subtarget.isLittleEndian()) {
12337 std::reverse(Loads.begin(), Loads.end());
12338 std::reverse(LoadChains.begin(), LoadChains.end());
12339 }
12340 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
12341 SDValue Value =
12342 DAG.getNode(VT == MVT::v512i1 ? PPCISD::ACC_BUILD : PPCISD::PAIR_BUILD,
12343 dl, VT, Loads);
12344 SDValue RetOps[] = {Value, TF};
12345 return DAG.getMergeValues(RetOps, dl);
12346}
12347
12348SDValue PPCTargetLowering::LowerDMFVectorStore(SDValue Op,
12349 SelectionDAG &DAG) const {
12350
12351 SDLoc dl(Op);
12352 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12353 SDValue StoreChain = SN->getChain();
12354 SDValue BasePtr = SN->getBasePtr();
12357 EVT VT = SN->getValue().getValueType();
12358 bool IsV1024i1 = VT == MVT::v1024i1;
12359 bool IsV2048i1 = VT == MVT::v2048i1;
12360
12361 // The types v1024i1 and v2048i1 are used for Dense Math dmr registers and
12362 // Dense Math dmr pair registers, respectively.
12363 assert((IsV1024i1 || IsV2048i1) && "Unsupported type.");
12364 (void)IsV2048i1;
12365 assert((Subtarget.hasMMA() && Subtarget.isISAFuture()) &&
12366 "Dense Math support required.");
12367 assert(Subtarget.pairedVectorMemops() && "Vector pair support required.");
12368
12369 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12370 if (IsV1024i1) {
12371 SDValue Lo(DAG.getMachineNode(
12372 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12373 Op.getOperand(1),
12374 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12375 0);
12376 SDValue Hi(DAG.getMachineNode(
12377 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1,
12378 Op.getOperand(1),
12379 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12380 0);
12381 MachineSDNode *ExtNode =
12382 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Lo);
12383 Values.push_back(SDValue(ExtNode, 0));
12384 Values.push_back(SDValue(ExtNode, 1));
12385 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Hi);
12386 Values.push_back(SDValue(ExtNode, 0));
12387 Values.push_back(SDValue(ExtNode, 1));
12388 } else {
12389 // This corresponds to v2048i1 which represents a dmr pair.
12390 SDValue Dmr0(
12391 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12392 Op.getOperand(1),
12393 DAG.getTargetConstant(PPC::sub_dmr0, dl, MVT::i32)),
12394 0);
12395
12396 SDValue Dmr1(
12397 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::v1024i1,
12398 Op.getOperand(1),
12399 DAG.getTargetConstant(PPC::sub_dmr1, dl, MVT::i32)),
12400 0);
12401
12402 SDValue Dmr0Lo(DAG.getMachineNode(
12403 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12404 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12405 0);
12406
12407 SDValue Dmr0Hi(DAG.getMachineNode(
12408 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr0,
12409 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12410 0);
12411
12412 SDValue Dmr1Lo(DAG.getMachineNode(
12413 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12414 DAG.getTargetConstant(PPC::sub_wacc_lo, dl, MVT::i32)),
12415 0);
12416
12417 SDValue Dmr1Hi(DAG.getMachineNode(
12418 TargetOpcode::EXTRACT_SUBREG, dl, MVT::v512i1, Dmr1,
12419 DAG.getTargetConstant(PPC::sub_wacc_hi, dl, MVT::i32)),
12420 0);
12421
12422 MachineSDNode *ExtNode =
12423 DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr0Lo);
12424 Values.push_back(SDValue(ExtNode, 0));
12425 Values.push_back(SDValue(ExtNode, 1));
12426 ExtNode =
12427 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr0Hi);
12428 Values.push_back(SDValue(ExtNode, 0));
12429 Values.push_back(SDValue(ExtNode, 1));
12430 ExtNode = DAG.getMachineNode(PPC::DMXXEXTFDMR512, dl, ReturnTypes, Dmr1Lo);
12431 Values.push_back(SDValue(ExtNode, 0));
12432 Values.push_back(SDValue(ExtNode, 1));
12433 ExtNode =
12434 DAG.getMachineNode(PPC::DMXXEXTFDMR512_HI, dl, ReturnTypes, Dmr1Hi);
12435 Values.push_back(SDValue(ExtNode, 0));
12436 Values.push_back(SDValue(ExtNode, 1));
12437 }
12438
12439 if (Subtarget.isLittleEndian())
12440 std::reverse(Values.begin(), Values.end());
12441
12442 SDVTList Tys = DAG.getVTList(MVT::Other);
12444 StoreChain, DAG.getConstant(Intrinsic::ppc_vsx_stxvp, dl, MVT::i32),
12445 Values[0], BasePtr};
12446 MachineMemOperand *MMO = SN->getMemOperand();
12447 unsigned NumVecs = VT.getSizeInBits() / 256;
12448 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12449 MachineMemOperand *NewMMO =
12450 DAG.getMachineFunction().getMachineMemOperand(MMO, Idx * 32, 32);
12451 if (Idx > 0) {
12452 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12453 DAG.getConstant(32, dl, BasePtr.getValueType()));
12454 Ops[3] = BasePtr;
12455 }
12456 Ops[2] = Values[Idx];
12457 SDValue St = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, Tys, Ops,
12458 MVT::v256i1, NewMMO);
12459 Stores.push_back(St);
12460 }
12461
12462 SDValue TF = DAG.getTokenFactor(dl, Stores);
12463 return TF;
12464}
12465
12466SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
12467 SelectionDAG &DAG) const {
12468 SDLoc dl(Op);
12469 StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
12470 SDValue StoreChain = SN->getChain();
12471 SDValue BasePtr = SN->getBasePtr();
12472 SDValue Value = SN->getValue();
12473 SDValue Value2 = SN->getValue();
12474 EVT StoreVT = Value.getValueType();
12475
12476 if (StoreVT == MVT::v1024i1 || StoreVT == MVT::v2048i1)
12477 return LowerDMFVectorStore(Op, DAG);
12478
12479 if (StoreVT != MVT::v256i1 && StoreVT != MVT::v512i1)
12480 return Op;
12481
12482 // Type v256i1 is used for pairs and v512i1 is used for accumulators.
12483 assert((StoreVT != MVT::v512i1 || Subtarget.hasMMA()) &&
12484 "Type unsupported without MMA");
12485 assert((StoreVT != MVT::v256i1 || Subtarget.pairedVectorMemops()) &&
12486 "Type unsupported without paired vector support");
12487
12488 // For v256i1 on ISA Future, let the store go through to instruction selection
12489 // where it will be matched to stxvp/pstxvp by the instruction patterns.
12490 if (StoreVT == MVT::v256i1 && Subtarget.isISAFuture() &&
12492 return Op;
12493
12494 // For other cases, create 2 or 4 v16i8 stores to store the pair or
12495 // accumulator underlying registers individually.
12496 Align Alignment = SN->getAlign();
12498 unsigned NumVecs = 2;
12499 if (StoreVT == MVT::v512i1) {
12500 if (Subtarget.isISAFuture()) {
12501 EVT ReturnTypes[] = {MVT::v256i1, MVT::v256i1};
12502 MachineSDNode *ExtNode = DAG.getMachineNode(
12503 PPC::DMXXEXTFDMR512, dl, ReturnTypes, Op.getOperand(1));
12504
12505 Value = SDValue(ExtNode, 0);
12506 Value2 = SDValue(ExtNode, 1);
12507 } else
12508 Value = DAG.getNode(PPCISD::XXMFACC, dl, MVT::v512i1, Value);
12509 NumVecs = 4;
12510 }
12511 for (unsigned Idx = 0; Idx < NumVecs; ++Idx) {
12512 unsigned VecNum = Subtarget.isLittleEndian() ? NumVecs - 1 - Idx : Idx;
12513 SDValue Elt;
12514 if (Subtarget.isISAFuture()) {
12515 VecNum = Subtarget.isLittleEndian() ? 1 - (Idx % 2) : (Idx % 2);
12516 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8,
12517 Idx > 1 ? Value2 : Value,
12518 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12519 } else
12520 Elt = DAG.getNode(PPCISD::EXTRACT_VSX_REG, dl, MVT::v16i8, Value,
12521 DAG.getConstant(VecNum, dl, getPointerTy(DAG.getDataLayout())));
12522
12523 SDValue Store =
12524 DAG.getStore(StoreChain, dl, Elt, BasePtr,
12525 SN->getPointerInfo().getWithOffset(Idx * 16),
12526 commonAlignment(Alignment, Idx * 16),
12527 SN->getMemOperand()->getFlags(), SN->getAAInfo());
12528 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12529 DAG.getConstant(16, dl, BasePtr.getValueType()));
12530 Stores.push_back(Store);
12531 }
12532 SDValue TF = DAG.getTokenFactor(dl, Stores);
12533 return TF;
12534}
12535
12536SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
12537 SDLoc dl(Op);
12538 if (Op.getValueType() == MVT::v4i32) {
12539 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12540
12541 SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
12542 // +16 as shift amt.
12543 SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
12544 SDValue RHSSwap = // = vrlw RHS, 16
12545 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
12546
12547 // Shrinkify inputs to v8i16.
12548 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
12549 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
12550 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
12551
12552 // Low parts multiplied together, generating 32-bit results (we ignore the
12553 // top parts).
12554 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
12555 LHS, RHS, DAG, dl, MVT::v4i32);
12556
12557 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
12558 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
12559 // Shift the high parts up 16 bits.
12560 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
12561 Neg16, DAG, dl);
12562 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
12563 } else if (Op.getValueType() == MVT::v16i8) {
12564 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
12565 bool isLittleEndian = Subtarget.isLittleEndian();
12566
12567 // Multiply the even 8-bit parts, producing 16-bit sums.
12568 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
12569 LHS, RHS, DAG, dl, MVT::v8i16);
12570 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
12571
12572 // Multiply the odd 8-bit parts, producing 16-bit sums.
12573 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
12574 LHS, RHS, DAG, dl, MVT::v8i16);
12575 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
12576
12577 // Merge the results together. Because vmuleub and vmuloub are
12578 // instructions with a big-endian bias, we must reverse the
12579 // element numbering and reverse the meaning of "odd" and "even"
12580 // when generating little endian code.
12581 int Ops[16];
12582 for (unsigned i = 0; i != 8; ++i) {
12583 if (isLittleEndian) {
12584 Ops[i*2 ] = 2*i;
12585 Ops[i*2+1] = 2*i+16;
12586 } else {
12587 Ops[i*2 ] = 2*i+1;
12588 Ops[i*2+1] = 2*i+1+16;
12589 }
12590 }
12591 if (isLittleEndian)
12592 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
12593 else
12594 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
12595 } else {
12596 llvm_unreachable("Unknown mul to lower!");
12597 }
12598}
12599
12600SDValue PPCTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12601 bool IsStrict = Op->isStrictFPOpcode();
12602 if (Op.getOperand(IsStrict ? 1 : 0).getValueType() == MVT::f128 &&
12603 !Subtarget.hasP9Vector())
12604 return SDValue();
12605
12606 return Op;
12607}
12608
12609// Custom lowering for fpext vf32 to v2f64
12610SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12611
12612 assert(Op.getOpcode() == ISD::FP_EXTEND &&
12613 "Should only be called for ISD::FP_EXTEND");
12614
12615 // FIXME: handle extends from half precision float vectors on P9.
12616 // We only want to custom lower an extend from v2f32 to v2f64.
12617 if (Op.getValueType() != MVT::v2f64 ||
12618 Op.getOperand(0).getValueType() != MVT::v2f32)
12619 return SDValue();
12620
12621 SDLoc dl(Op);
12622 SDValue Op0 = Op.getOperand(0);
12623
12624 switch (Op0.getOpcode()) {
12625 default:
12626 return SDValue();
12628 assert(Op0.getNumOperands() == 2 &&
12630 "Node should have 2 operands with second one being a constant!");
12631
12632 if (Op0.getOperand(0).getValueType() != MVT::v4f32)
12633 return SDValue();
12634
12635 // Custom lower is only done for high or low doubleword.
12636 int Idx = Op0.getConstantOperandVal(1);
12637 if (Idx % 2 != 0)
12638 return SDValue();
12639
12640 // Since input is v4f32, at this point Idx is either 0 or 2.
12641 // Shift to get the doubleword position we want.
12642 int DWord = Idx >> 1;
12643
12644 // High and low word positions are different on little endian.
12645 if (Subtarget.isLittleEndian())
12646 DWord ^= 0x1;
12647
12648 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
12649 Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
12650 }
12651 case ISD::FADD:
12652 case ISD::FMUL:
12653 case ISD::FSUB: {
12654 SDValue NewLoad[2];
12655 for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
12656 // Ensure both input are loads.
12657 SDValue LdOp = Op0.getOperand(i);
12658 if (LdOp.getOpcode() != ISD::LOAD)
12659 return SDValue();
12660 // Generate new load node.
12661 LoadSDNode *LD = cast<LoadSDNode>(LdOp);
12662 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12663 NewLoad[i] = DAG.getMemIntrinsicNode(
12664 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12665 LD->getMemoryVT(), LD->getMemOperand());
12666 }
12667 SDValue NewOp =
12668 DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
12669 NewLoad[1], Op0.getNode()->getFlags());
12670 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
12671 DAG.getConstant(0, dl, MVT::i32));
12672 }
12673 case ISD::LOAD: {
12674 LoadSDNode *LD = cast<LoadSDNode>(Op0);
12675 SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
12676 SDValue NewLd = DAG.getMemIntrinsicNode(
12677 PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
12678 LD->getMemoryVT(), LD->getMemOperand());
12679 return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
12680 DAG.getConstant(0, dl, MVT::i32));
12681 }
12682 }
12683 llvm_unreachable("ERROR:Should return for all cases within swtich.");
12684}
12685
12687 SelectionDAG &DAG,
12688 const PPCSubtarget &STI) {
12689 SDLoc DL(Value);
12690 if (STI.useCRBits())
12691 Value = DAG.getNode(ISD::SELECT, DL, SumType, Value,
12692 DAG.getConstant(1, DL, SumType),
12693 DAG.getConstant(0, DL, SumType));
12694 else
12695 Value = DAG.getZExtOrTrunc(Value, DL, SumType);
12696 SDValue Sum = DAG.getNode(PPCISD::ADDC, DL, DAG.getVTList(SumType, MVT::i32),
12697 Value, DAG.getAllOnesConstant(DL, SumType));
12698 return Sum.getValue(1);
12699}
12700
12702 EVT CarryType, SelectionDAG &DAG,
12703 const PPCSubtarget &STI) {
12704 SDLoc DL(Flag);
12705 SDValue Zero = DAG.getConstant(0, DL, SumType);
12706 SDValue Carry = DAG.getNode(
12707 PPCISD::ADDE, DL, DAG.getVTList(SumType, MVT::i32), Zero, Zero, Flag);
12708 if (STI.useCRBits())
12709 return DAG.getSetCC(DL, CarryType, Carry, Zero, ISD::SETNE);
12710 return DAG.getZExtOrTrunc(Carry, DL, CarryType);
12711}
12712
12713SDValue PPCTargetLowering::LowerADDSUBO(SDValue Op, SelectionDAG &DAG) const {
12714
12715 SDLoc DL(Op);
12716 SDNode *N = Op.getNode();
12717 EVT VT = N->getValueType(0);
12718 EVT CarryType = N->getValueType(1);
12719 unsigned Opc = N->getOpcode();
12720 bool IsAdd = Opc == ISD::UADDO;
12721 Opc = IsAdd ? PPCISD::ADDC : PPCISD::SUBC;
12722 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12723 N->getOperand(0), N->getOperand(1));
12724 SDValue Carry = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType,
12725 DAG, Subtarget);
12726 if (!IsAdd)
12727 Carry = DAG.getNode(ISD::XOR, DL, CarryType, Carry,
12728 DAG.getConstant(1UL, DL, CarryType));
12729 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, Carry);
12730}
12731
12732SDValue PPCTargetLowering::LowerADDSUBO_CARRY(SDValue Op,
12733 SelectionDAG &DAG) const {
12734 SDLoc DL(Op);
12735 SDNode *N = Op.getNode();
12736 unsigned Opc = N->getOpcode();
12737 EVT VT = N->getValueType(0);
12738 EVT CarryType = N->getValueType(1);
12739 SDValue CarryOp = N->getOperand(2);
12740 bool IsAdd = Opc == ISD::UADDO_CARRY;
12741 Opc = IsAdd ? PPCISD::ADDE : PPCISD::SUBE;
12742 if (!IsAdd)
12743 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12744 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12745 CarryOp = ConvertCarryValueToCarryFlag(VT, CarryOp, DAG, Subtarget);
12746 SDValue Sum = DAG.getNode(Opc, DL, DAG.getVTList(VT, MVT::i32),
12747 Op.getOperand(0), Op.getOperand(1), CarryOp);
12748 CarryOp = ConvertCarryFlagToCarryValue(VT, Sum.getValue(1), CarryType, DAG,
12749 Subtarget);
12750 if (!IsAdd)
12751 CarryOp = DAG.getNode(ISD::XOR, DL, CarryOp.getValueType(), CarryOp,
12752 DAG.getConstant(1UL, DL, CarryOp.getValueType()));
12753 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, CarryOp);
12754}
12755
12756SDValue PPCTargetLowering::LowerSSUBO(SDValue Op, SelectionDAG &DAG) const {
12757
12758 SDLoc dl(Op);
12759 SDValue LHS = Op.getOperand(0);
12760 SDValue RHS = Op.getOperand(1);
12761 EVT VT = Op.getNode()->getValueType(0);
12762
12763 SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12764
12765 SDValue Xor1 = DAG.getNode(ISD::XOR, dl, VT, RHS, LHS);
12766 SDValue Xor2 = DAG.getNode(ISD::XOR, dl, VT, Sub, LHS);
12767
12768 SDValue And = DAG.getNode(ISD::AND, dl, VT, Xor1, Xor2);
12769
12770 SDValue Overflow =
12771 DAG.getNode(ISD::SRL, dl, VT, And,
12772 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12773
12774 SDValue OverflowTrunc =
12775 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12776
12777 return DAG.getMergeValues({Sub, OverflowTrunc}, dl);
12778}
12779
12780/// Implements signed add with overflow detection using the rule:
12781/// (x eqv y) & (sum xor x), where the overflow bit is extracted from the sign
12782SDValue PPCTargetLowering::LowerSADDO(SDValue Op, SelectionDAG &DAG) const {
12783
12784 SDLoc dl(Op);
12785 SDValue LHS = Op.getOperand(0);
12786 SDValue RHS = Op.getOperand(1);
12787 EVT VT = Op.getNode()->getValueType(0);
12788
12789 SDValue Sum = DAG.getNode(ISD::ADD, dl, VT, LHS, RHS);
12790
12791 // Compute ~(x xor y)
12792 SDValue XorXY = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
12793 SDValue EqvXY = DAG.getNOT(dl, XorXY, VT);
12794 // Compute (s xor x)
12795 SDValue SumXorX = DAG.getNode(ISD::XOR, dl, VT, Sum, LHS);
12796
12797 // overflow = (x eqv y) & (s xor x)
12798 SDValue OverflowInSign = DAG.getNode(ISD::AND, dl, VT, EqvXY, SumXorX);
12799
12800 // Shift sign bit down to LSB
12801 SDValue Overflow =
12802 DAG.getNode(ISD::SRL, dl, VT, OverflowInSign,
12803 DAG.getConstant(VT.getSizeInBits() - 1, dl, MVT::i32));
12804 // Truncate to the overflow type (i1)
12805 SDValue OverflowTrunc =
12806 DAG.getNode(ISD::TRUNCATE, dl, Op.getNode()->getValueType(1), Overflow);
12807
12808 return DAG.getMergeValues({Sum, OverflowTrunc}, dl);
12809}
12810
12811/// Lower ABDU with negation pattern using branchless carry arithmetic.
12812/// Recognizes: abdu(a, sub(0, x)) and transforms to:
12813/// a - (0 - x) = a + x (mod 2^n)
12814/// Uses SUBC to compute result without branches.
12815SDValue PPCTargetLowering::LowerABDU(SDValue Op, SelectionDAG &DAG) const {
12816 SDLoc DL(Op);
12817 SDValue LHS = Op.getOperand(0);
12818 SDValue RHS = Op.getOperand(1);
12819 EVT OpVT = LHS.getValueType();
12820 EVT VT = Op.getValueType();
12821 bool IsNonNegative = DAG.SignBitIsZero(LHS) && DAG.SignBitIsZero(RHS);
12822
12823 // If the subtract doesn't overflow then just use abs(sub()).
12824 if (DAG.willNotOverflowSub(IsNonNegative, LHS, RHS))
12825 return DAG.getNode(ISD::ABS, DL, VT,
12826 DAG.getNode(ISD::SUB, DL, VT, LHS, RHS));
12827
12828 if (DAG.willNotOverflowSub(IsNonNegative, RHS, LHS))
12829 return DAG.getNode(ISD::ABS, DL, VT,
12830 DAG.getNode(ISD::SUB, DL, VT, RHS, LHS));
12831
12832 // General path: use SUBC (or ADDC when RHS is 0-X) to get
12833 // subtract-with-flags, then CMOV to select a-b or b-a. ADDC/SUBC produce the
12834 // flags we need.
12835 unsigned Opcode = PPCISD::SUBC;
12836
12837 // Check if RHS is a negation (0 - X). If so, we can use ADDC instead of SUBC:
12838 // a - (0 - x) = a + x (mod 2^n)
12839 // Same semantics as in LowerCMP; apply same safety checks.
12840 if (RHS.getOpcode() == ISD::SUB) {
12841 SDValue SubLHS = RHS.getOperand(0);
12842 SDValue SubRHS = RHS.getOperand(1);
12843
12844 if (isNullConstant(SubLHS) && DAG.isKnownNeverZero(SubRHS)) {
12845 Opcode = PPCISD::ADDC;
12846 RHS = SubRHS;
12847 }
12848 }
12849
12850 // On PPC64, carry ops use the full 64-bit register. Operands are type-legal
12851 // i32 here; widen only for the carry path (fast abs(sub) stays at VT).
12852 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12853 LHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, LHS);
12854 RHS = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RHS);
12855 OpVT = MVT::i64;
12856 }
12857
12858 // Calculate LHS - RHS and capture the carry (CA)
12859 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12860 SDValue Res = DAG.getNode(Opcode, DL, VTs, LHS, RHS);
12861 SDValue CA0 = Res.getValue(1);
12862
12863 // t2 = A - B + CA0 using SUBE.
12864 SDValue ZeroOrNeg1 = DAG.getNode(PPCISD::SUBE, DL, VTs, Res, Res, CA0);
12865
12866 SDValue Xor = DAG.getNode(ISD::XOR, DL, OpVT, Res, ZeroOrNeg1);
12867
12868 Res = DAG.getNode(ISD::SUB, DL, OpVT, Xor, ZeroOrNeg1);
12869
12870 Res = DAG.getNode(ISD::TRUNCATE, DL, VT, Res);
12871 return Res;
12872}
12873
12874// Lower unsigned 3-way compare producing -1/0/1.
12875SDValue PPCTargetLowering::LowerUCMP(SDValue Op, SelectionDAG &DAG) const {
12876 SDLoc DL(Op);
12877 SDValue A = DAG.getFreeze(Op.getOperand(0));
12878 SDValue B = DAG.getFreeze(Op.getOperand(1));
12879 EVT OpVT = A.getValueType();
12880 EVT ResVT = Op.getValueType();
12881
12882 // On PPC64, i32 carries are affected by the upper 32 bits of the registers.
12883 // We must zero-extend to i64 to ensure the carry reflects the 32-bit unsigned
12884 // comparison.
12885 if (Subtarget.isPPC64() && OpVT != MVT::i64) {
12886 A = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, A);
12887 B = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, B);
12888 OpVT = MVT::i64;
12889 }
12890
12891 // First compute diff = A - B.
12892 SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, A, B);
12893
12894 // Generate B - A using SUBC to capture carry.
12895 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
12896 SDValue SubC = DAG.getNode(PPCISD::SUBC, DL, VTs, B, A);
12897 SDValue CA0 = SubC.getValue(1);
12898
12899 // t2 = A - B + CA0 using SUBE.
12900 SDValue SubE1 = DAG.getNode(PPCISD::SUBE, DL, VTs, A, B, CA0);
12901 SDValue CA1 = SubE1.getValue(1);
12902
12903 // res = diff - t2 + CA1 using SUBE (produces desired -1/0/1).
12904 SDValue ResPair = DAG.getNode(PPCISD::SUBE, DL, VTs, Diff, SubE1, CA1);
12905
12906 // Extract the first result and truncate to result type if needed.
12907 return DAG.getSExtOrTrunc(ResPair.getValue(0), DL, ResVT);
12908}
12909
12910// Lower signed 3-way compare producing -1/0/1.
12911// For PowerPC with SETB (P9+), use the default expansion.
12912// For pre-P9, we generate a custom sequence using comparison and bit
12913// extraction.
12914// cmpw cr7, LHS, RHS
12915// mfocrf r, CR7
12916// rlwinm LT, r, 29, 31, 31 (extract LT bit from CR7)
12917// rlwinm GT, r, 30, 31, 31 (extract GT bit from CR7)
12918// subf result, LT, GT (GT - LT = -1/0/1)
12919SDValue PPCTargetLowering::LowerSCMP(SDValue Op, SelectionDAG &DAG) const {
12920 SDLoc DL(Op);
12921 SDValue LHS = Op.getOperand(0);
12922 SDValue RHS = Op.getOperand(1);
12923 EVT VT = LHS.getValueType();
12924 EVT ResVT = Op.getValueType();
12925
12926 // For P9+, use the default expansion which will use SETB instruction
12927 if (Subtarget.isISA3_0())
12928 return SDValue();
12929
12930 // For pre-P9, generate custom sequence without SETB
12931 bool Is64BitCmp = (VT == MVT::i64);
12932
12933 // On PPC64, always use 64-bit operations to avoid extra sign-extension
12934 // Even if result type is i32, it will likely be extended to i64 by calling
12935 // convention
12936 bool Use64BitOps = Subtarget.isPPC64();
12937
12938 // Perform comparison
12939 unsigned CmpOpc = Is64BitCmp ? PPC::CMPD : PPC::CMPW;
12940 SDValue Cmp = SDValue(DAG.getMachineNode(CmpOpc, DL, MVT::i32, LHS, RHS), 0);
12941
12942 // Move comparison result to CR7 to have known bit positions
12943 SDValue CR7Reg = DAG.getRegister(PPC::CR7, MVT::i32);
12944 SDValue InGlue; // Null incoming glue
12945 SDValue CopyToReg =
12946 DAG.getCopyToReg(DAG.getEntryNode(), DL, CR7Reg, Cmp, InGlue);
12947 SDValue Glue = CopyToReg.getValue(1);
12948
12949 // Use MFOCRF to read CR7
12950 unsigned MFOCRFOpc = Use64BitOps ? PPC::MFOCRF8 : PPC::MFOCRF;
12951 EVT MFVT = Use64BitOps ? MVT::i64 : MVT::i32;
12952 SDValue MFOCRF =
12953 SDValue(DAG.getMachineNode(MFOCRFOpc, DL, MFVT, CR7Reg, Glue), 0);
12954
12955 // CR7 bits in the result (after MFOCRF):
12956 // Bit 28: LT
12957 // Bit 29: GT
12958 // Bit 30: EQ
12959 // Bit 31: SO
12960
12961 // Extract LT and GT bits using RLWINM
12962 unsigned RLWinmOpc = Use64BitOps ? PPC::RLWINM8 : PPC::RLWINM;
12963
12964 // Extract LT bit (Bit 28 -> Rotate Left 29 to move to bit 31, then mask)
12965 SDValue LTOps[] = {MFOCRF, DAG.getTargetConstant(29, DL, MVT::i32),
12966 DAG.getTargetConstant(31, DL, MVT::i32),
12967 DAG.getTargetConstant(31, DL, MVT::i32)};
12968 SDValue LTBit = SDValue(DAG.getMachineNode(RLWinmOpc, DL, MFVT, LTOps), 0);
12969
12970 // Extract GT bit (Bit 29 -> Rotate Left 30 to move to bit 31, then mask)
12971 SDValue GTOps[] = {MFOCRF, DAG.getTargetConstant(30, DL, MVT::i32),
12972 DAG.getTargetConstant(31, DL, MVT::i32),
12973 DAG.getTargetConstant(31, DL, MVT::i32)};
12974 SDValue GTBit = SDValue(DAG.getMachineNode(RLWinmOpc, DL, MFVT, GTOps), 0);
12975
12976 // Compute result: GT - LT
12977 // If LT: 0 - 1 = -1
12978 // If GT: 1 - 0 = 1
12979 // If EQ: 0 - 0 = 0
12980 unsigned SubOpc = Use64BitOps ? PPC::SUBF8 : PPC::SUBF;
12981 SDValue Result =
12982 SDValue(DAG.getMachineNode(SubOpc, DL, MFVT, LTBit, GTBit), 0);
12983
12984 if (ResVT == MFVT)
12985 return Result;
12986
12987 // Adjust result to match expected type (sign-extend or truncate as needed)
12988 return DAG.getSExtOrTrunc(Result, DL, ResVT);
12989}
12990
12991/// LowerOperation - Provide custom lowering hooks for some operations.
12992///
12994 switch (Op.getOpcode()) {
12995 default:
12996 llvm_unreachable("Wasn't expecting to be able to lower this!");
12997 case ISD::FPOW: return lowerPow(Op, DAG);
12998 case ISD::FSIN: return lowerSin(Op, DAG);
12999 case ISD::FCOS: return lowerCos(Op, DAG);
13000 case ISD::FLOG: return lowerLog(Op, DAG);
13001 case ISD::FLOG10: return lowerLog10(Op, DAG);
13002 case ISD::FEXP: return lowerExp(Op, DAG);
13003 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
13004 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
13005 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
13006 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
13007 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
13008 case ISD::STRICT_FSETCC:
13010 case ISD::SETCC: return LowerSETCC(Op, DAG);
13011 case ISD::BR_CC: return LowerBR_CC(Op, DAG);
13012 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
13013 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
13014 case ISD::SSUBO:
13015 return LowerSSUBO(Op, DAG);
13016 case ISD::SADDO:
13017 return LowerSADDO(Op, DAG);
13018
13019 case ISD::INLINEASM:
13020 case ISD::INLINEASM_BR: return LowerINLINEASM(Op, DAG);
13021 // Variable argument lowering.
13022 case ISD::VASTART: return LowerVASTART(Op, DAG);
13023 case ISD::VAARG: return LowerVAARG(Op, DAG);
13024 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
13025
13026 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG);
13027 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
13029 return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
13030
13031 // Exception handling lowering.
13032 case ISD::EH_DWARF_CFA: return LowerEH_DWARF_CFA(Op, DAG);
13033 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
13034 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
13035
13036 case ISD::LOAD: return LowerLOAD(Op, DAG);
13037 case ISD::STORE: return LowerSTORE(Op, DAG);
13038 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
13039 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
13042 case ISD::FP_TO_UINT:
13043 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
13046 case ISD::UINT_TO_FP:
13047 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
13048 case ISD::GET_ROUNDING: return LowerGET_ROUNDING(Op, DAG);
13049 case ISD::SET_ROUNDING:
13050 return LowerSET_ROUNDING(Op, DAG);
13051
13052 // Lower 64-bit shifts.
13053 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
13054 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
13055 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
13056
13057 case ISD::FSHL: return LowerFunnelShift(Op, DAG);
13058 case ISD::FSHR: return LowerFunnelShift(Op, DAG);
13059
13060 // Vector-related lowering.
13061 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
13062 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
13063 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
13064 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
13065 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
13066 case ISD::MUL: return LowerMUL(Op, DAG);
13067 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
13069 case ISD::FP_ROUND:
13070 return LowerFP_ROUND(Op, DAG);
13071 case ISD::ROTL: return LowerROTL(Op, DAG);
13072
13073 // For counter-based loop handling.
13075 return SDValue();
13076
13077 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
13078
13079 // Frame & Return address.
13080 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
13081 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
13082
13084 return LowerINTRINSIC_VOID(Op, DAG);
13085 case ISD::BSWAP:
13086 return LowerBSWAP(Op, DAG);
13088 return LowerATOMIC_CMP_SWAP(Op, DAG);
13089 case ISD::ATOMIC_STORE:
13090 return LowerATOMIC_LOAD_STORE(Op, DAG);
13091 case ISD::IS_FPCLASS:
13092 return LowerIS_FPCLASS(Op, DAG);
13093 case ISD::UADDO:
13094 case ISD::USUBO:
13095 return LowerADDSUBO(Op, DAG);
13096 case ISD::UADDO_CARRY:
13097 case ISD::USUBO_CARRY:
13098 return LowerADDSUBO_CARRY(Op, DAG);
13099 case ISD::UCMP:
13100 return LowerUCMP(Op, DAG);
13101 case ISD::ABDU:
13102 return LowerABDU(Op, DAG);
13103 case ISD::SCMP:
13104 return LowerSCMP(Op, DAG);
13105 case ISD::STRICT_LRINT:
13106 case ISD::STRICT_LLRINT:
13107 case ISD::STRICT_LROUND:
13110 if (Op->getFlags().hasNoFPExcept())
13111 return Op;
13112 return SDValue();
13113 case ISD::VP_LOAD:
13114 return LowerVP_LOAD(Op, DAG);
13115 case ISD::VP_STORE:
13116 return LowerVP_STORE(Op, DAG);
13118 return LowerPartialReduce(Op, DAG);
13119 }
13120}
13121
13124 SelectionDAG &DAG) const {
13125 SDLoc dl(N);
13126 switch (N->getOpcode()) {
13127 default:
13128 llvm_unreachable("Do not know how to custom type legalize this operation!");
13129 case ISD::ATOMIC_LOAD: {
13130 SDValue Res = LowerATOMIC_LOAD_STORE(SDValue(N, 0), DAG);
13131 Results.push_back(Res);
13132 Results.push_back(Res.getValue(1));
13133 break;
13134 }
13135 case ISD::READCYCLECOUNTER: {
13136 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
13137 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
13138
13139 Results.push_back(
13140 DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
13141 Results.push_back(RTB.getValue(2));
13142 break;
13143 }
13145 if (N->getConstantOperandVal(1) != Intrinsic::loop_decrement)
13146 break;
13147
13148 assert(N->getValueType(0) == MVT::i1 &&
13149 "Unexpected result type for CTR decrement intrinsic");
13150 EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
13151 N->getValueType(0));
13152 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
13153 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
13154 N->getOperand(1));
13155
13156 Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
13157 Results.push_back(NewInt.getValue(1));
13158 break;
13159 }
13161 switch (N->getConstantOperandVal(0)) {
13162 case Intrinsic::ppc_pack_longdouble:
13163 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
13164 N->getOperand(2), N->getOperand(1)));
13165 break;
13166 case Intrinsic::ppc_maxfe:
13167 case Intrinsic::ppc_minfe:
13168 case Intrinsic::ppc_fnmsub:
13169 case Intrinsic::ppc_convert_f128_to_ppcf128:
13170 Results.push_back(LowerINTRINSIC_WO_CHAIN(SDValue(N, 0), DAG));
13171 break;
13172 }
13173 break;
13174 }
13175 case ISD::VAARG: {
13176 if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
13177 return;
13178
13179 EVT VT = N->getValueType(0);
13180
13181 if (VT == MVT::i64) {
13182 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
13183
13184 Results.push_back(NewNode);
13185 Results.push_back(NewNode.getValue(1));
13186 }
13187 return;
13188 }
13191 case ISD::FP_TO_SINT:
13192 case ISD::FP_TO_UINT: {
13193 // LowerFP_TO_INT() can only handle f32 and f64.
13194 if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
13195 MVT::ppcf128)
13196 return;
13197 SDValue LoweredValue = LowerFP_TO_INT(SDValue(N, 0), DAG, dl);
13198 Results.push_back(LoweredValue);
13199 if (N->isStrictFPOpcode())
13200 Results.push_back(LoweredValue.getValue(1));
13201 return;
13202 }
13203 case ISD::TRUNCATE: {
13204 if (!N->getValueType(0).isVector())
13205 return;
13206 SDValue Lowered = LowerTRUNCATEVector(SDValue(N, 0), DAG);
13207 if (Lowered)
13208 Results.push_back(Lowered);
13209 return;
13210 }
13211 case ISD::SCALAR_TO_VECTOR: {
13212 SDValue Lowered = LowerSCALAR_TO_VECTOR(SDValue(N, 0), DAG);
13213 if (Lowered)
13214 Results.push_back(Lowered);
13215 return;
13216 }
13217 case ISD::FSHL:
13218 case ISD::FSHR:
13219 // Don't handle funnel shifts here.
13220 return;
13221 case ISD::BITCAST:
13222 // Don't handle bitcast here.
13223 return;
13224 case ISD::FP_EXTEND:
13225 SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
13226 if (Lowered)
13227 Results.push_back(Lowered);
13228 return;
13229 }
13230}
13231
13232//===----------------------------------------------------------------------===//
13233// Other Lowering Code
13234//===----------------------------------------------------------------------===//
13235
13237 return Builder.CreateIntrinsicWithoutFolding(Id, {});
13238}
13239
13241 Value *Addr,
13242 AtomicOrdering Ord) const {
13243 unsigned SZ = ValueTy->getPrimitiveSizeInBits();
13244
13245 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13246 "Only 8/16/32/64-bit atomic loads supported");
13247 Intrinsic::ID IntID;
13248 switch (SZ) {
13249 default:
13250 llvm_unreachable("Unexpected PrimitiveSize");
13251 case 8:
13252 IntID = Intrinsic::ppc_lbarx;
13253 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13254 break;
13255 case 16:
13256 IntID = Intrinsic::ppc_lharx;
13257 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13258 break;
13259 case 32:
13260 IntID = Intrinsic::ppc_lwarx;
13261 break;
13262 case 64:
13263 IntID = Intrinsic::ppc_ldarx;
13264 break;
13265 }
13266 Value *Call =
13267 Builder.CreateIntrinsic(IntID, Addr, /*FMFSource=*/nullptr, "larx");
13268
13269 return Builder.CreateTruncOrBitCast(Call, ValueTy);
13270}
13271
13272// Perform a store-conditional operation to Addr. Return the status of the
13273// store. This should be 0 if the store succeeded, non-zero otherwise.
13275 Value *Val, Value *Addr,
13276 AtomicOrdering Ord) const {
13277 Type *Ty = Val->getType();
13278 unsigned SZ = Ty->getPrimitiveSizeInBits();
13279
13280 assert((SZ == 8 || SZ == 16 || SZ == 32 || SZ == 64) &&
13281 "Only 8/16/32/64-bit atomic loads supported");
13282 Intrinsic::ID IntID;
13283 switch (SZ) {
13284 default:
13285 llvm_unreachable("Unexpected PrimitiveSize");
13286 case 8:
13287 IntID = Intrinsic::ppc_stbcx;
13288 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13289 break;
13290 case 16:
13291 IntID = Intrinsic::ppc_sthcx;
13292 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
13293 break;
13294 case 32:
13295 IntID = Intrinsic::ppc_stwcx;
13296 break;
13297 case 64:
13298 IntID = Intrinsic::ppc_stdcx;
13299 break;
13300 }
13301
13302 if (SZ == 8 || SZ == 16)
13303 Val = Builder.CreateZExt(Val, Builder.getInt32Ty());
13304
13305 Value *Call = Builder.CreateIntrinsic(IntID, {Addr, Val},
13306 /*FMFSource=*/nullptr, "stcx");
13307 return Builder.CreateXor(Call, Builder.getInt32(1));
13308}
13309
13310// The mappings for emitLeading/TrailingFence is taken from
13311// http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13313 Instruction *Inst,
13314 AtomicOrdering Ord) const {
13316 return callIntrinsic(Builder, Intrinsic::ppc_sync);
13317 if (isReleaseOrStronger(Ord))
13318 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13319 return nullptr;
13320}
13321
13323 Instruction *Inst,
13324 AtomicOrdering Ord) const {
13325 if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
13326 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
13327 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
13328 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
13329 if (isa<LoadInst>(Inst))
13330 return Builder.CreateIntrinsicWithoutFolding(Intrinsic::ppc_cfence,
13331 {Inst->getType()}, {Inst});
13332 // FIXME: Can use isync for rmw operation.
13333 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
13334 }
13335 return nullptr;
13336}
13337
13339 return !Subtarget.fenceKeepsReservation();
13340}
13341
13344 unsigned BinOpcode,
13345 unsigned CmpOpcode,
13346 unsigned CmpPred) const {
13347 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13348 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13349 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13350 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13351 unsigned AtomicSize = MI.getOperand(3).getImm();
13352
13353 auto LoadMnemonic = PPC::LDARX;
13354 auto StoreMnemonic = PPC::STDCX;
13355 switch (AtomicSize) {
13356 default:
13357 llvm_unreachable("Unexpected size of atomic entity");
13358 case 1:
13359 LoadMnemonic = PPC::LBARX;
13360 StoreMnemonic = PPC::STBCX;
13361 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13362 break;
13363 case 2:
13364 LoadMnemonic = PPC::LHARX;
13365 StoreMnemonic = PPC::STHCX;
13366 assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
13367 break;
13368 case 4:
13369 LoadMnemonic = PPC::LWARX;
13370 StoreMnemonic = PPC::STWCX;
13371 break;
13372 case 8:
13373 LoadMnemonic = PPC::LDARX;
13374 StoreMnemonic = PPC::STDCX;
13375 break;
13376 }
13377
13378 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13379 MachineFunction *F = BB->getParent();
13381
13382 if (CmpOpcode == PPC::CMPW && (AtomicSize == 1 || AtomicSize == 2))
13383 signExtendOperandIfUnknown(MI, BB, 4, /*IsByte=*/AtomicSize == 1, TII);
13384
13385 Register dest = MI.getOperand(0).getReg();
13386 Register ptrA = MI.getOperand(1).getReg();
13387 Register ptrB = MI.getOperand(2).getReg();
13388 Register incr = MI.getOperand(4).getReg();
13389 DebugLoc dl = MI.getDebugLoc();
13390
13391 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13392 MachineBasicBlock *loop2MBB =
13393 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13394 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13395 F->insert(It, loopMBB);
13396 if (CmpOpcode)
13397 F->insert(It, loop2MBB);
13398 F->insert(It, exitMBB);
13399 exitMBB->splice(exitMBB->begin(), BB,
13400 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13402
13403 MachineRegisterInfo &RegInfo = F->getRegInfo();
13404 Register TmpReg = (!BinOpcode) ? incr :
13405 RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
13406 : &PPC::GPRCRegClass);
13407
13408 // thisMBB:
13409 // ...
13410 // fallthrough --> loopMBB
13411 BB->addSuccessor(loopMBB);
13412
13413 // loopMBB:
13414 // l[wd]arx dest, ptr
13415 // add r0, dest, incr
13416 // st[wd]cx. r0, ptr
13417 // bne- loopMBB
13418 // fallthrough --> exitMBB
13419
13420 // For max/min...
13421 // loopMBB:
13422 // l[wd]arx dest, ptr
13423 // cmpl?[wd] dest, incr
13424 // bgt exitMBB
13425 // loop2MBB:
13426 // st[wd]cx. dest, ptr
13427 // bne- loopMBB
13428 // fallthrough --> exitMBB
13429
13430 BB = loopMBB;
13431 BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
13432 .addReg(ptrA).addReg(ptrB);
13433 if (BinOpcode)
13434 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
13435 if (CmpOpcode) {
13436 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13437 // Signed comparisons of byte or halfword values must be sign-extended.
13438 if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
13439 Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13440 BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
13441 ExtReg).addReg(dest);
13442 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ExtReg).addReg(incr);
13443 } else
13444 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(dest).addReg(incr);
13445
13446 BuildMI(BB, dl, TII->get(PPC::BCC))
13447 .addImm(CmpPred)
13448 .addReg(CrReg)
13449 .addMBB(exitMBB);
13450 BB->addSuccessor(loop2MBB);
13451 BB->addSuccessor(exitMBB);
13452 BB = loop2MBB;
13453 }
13454 BuildMI(BB, dl, TII->get(StoreMnemonic))
13455 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
13456 BuildMI(BB, dl, TII->get(PPC::BCC))
13458 .addReg(PPC::CR0)
13459 .addMBB(loopMBB);
13460 BB->addSuccessor(loopMBB);
13461 BB->addSuccessor(exitMBB);
13462
13463 // exitMBB:
13464 // ...
13465 BB = exitMBB;
13466 return BB;
13467}
13468
13470 switch(MI.getOpcode()) {
13471 default:
13472 return false;
13473 case PPC::COPY:
13474 return TII->isSignExtended(MI.getOperand(1).getReg(),
13475 &MI.getMF()->getRegInfo());
13476 case PPC::LHA:
13477 case PPC::LHA8:
13478 case PPC::LHAU:
13479 case PPC::LHAU8:
13480 case PPC::LHAUX:
13481 case PPC::LHAUX8:
13482 case PPC::LHAX:
13483 case PPC::LHAX8:
13484 case PPC::LWA:
13485 case PPC::LWAUX:
13486 case PPC::LWAX:
13487 case PPC::LWAX_32:
13488 case PPC::LWA_32:
13489 case PPC::PLHA:
13490 case PPC::PLHA8:
13491 case PPC::PLHA8pc:
13492 case PPC::PLHApc:
13493 case PPC::PLWA:
13494 case PPC::PLWA8:
13495 case PPC::PLWA8pc:
13496 case PPC::PLWApc:
13497 case PPC::EXTSB:
13498 case PPC::EXTSB8:
13499 case PPC::EXTSB8_32_64:
13500 case PPC::EXTSB8_rec:
13501 case PPC::EXTSB_rec:
13502 case PPC::EXTSH:
13503 case PPC::EXTSH8:
13504 case PPC::EXTSH8_32_64:
13505 case PPC::EXTSH8_rec:
13506 case PPC::EXTSH_rec:
13507 case PPC::EXTSW:
13508 case PPC::EXTSWSLI:
13509 case PPC::EXTSWSLI_32_64:
13510 case PPC::EXTSWSLI_32_64_rec:
13511 case PPC::EXTSWSLI_rec:
13512 case PPC::EXTSW_32:
13513 case PPC::EXTSW_32_64:
13514 case PPC::EXTSW_32_64_rec:
13515 case PPC::EXTSW_rec:
13516 case PPC::SRAW:
13517 case PPC::SRAWI:
13518 case PPC::SRAWI_rec:
13519 case PPC::SRAW_rec:
13520 return true;
13521 }
13522 return false;
13523}
13524
13525// Sign extend operand OpIdx if the value is not known to be sign extended.
13526// Assumes the operand is a register. The flag IsByte controls which instruction
13527// is used for the sign extension.
13529 unsigned OpIdx, bool IsByte,
13530 const PPCInstrInfo *TII) {
13531 MachineFunction *F = MI.getMF();
13532 MachineRegisterInfo &RegInfo = F->getRegInfo();
13533 Register Reg = MI.getOperand(OpIdx).getReg();
13534 bool IsSignExtended =
13535 Reg.isVirtual() && isSignExtended(*RegInfo.getVRegDef(Reg), TII);
13536
13537 if (!IsSignExtended) {
13538 Register ValueReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
13539 BuildMI(*BB, MI, MI.getDebugLoc(),
13540 TII->get(IsByte ? PPC::EXTSB : PPC::EXTSH), ValueReg)
13541 .addReg(Reg);
13542 MI.getOperand(OpIdx).setReg(ValueReg);
13543 }
13544}
13545
13547 MachineInstr &MI, MachineBasicBlock *BB, unsigned BinOpcode,
13548 unsigned CmpOpcode, unsigned CmpPred) const {
13549 // BinOpcode != 0: Handles atomic load with binary operator, e.g. NAND.
13550 // CmpOpcode != 0: Handles atomic load with MIN/MAX etc.
13551 // BinOpcode == 0 && CmpOpcode == 0: Handles ATOMIC_SWAP.
13552 assert(!Subtarget.hasPartwordAtomics() &&
13553 "Assumes that part-word atomics are not available");
13554 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13555
13556 // If this is a signed comparison and the value being compared is not known
13557 // to be sign extended, sign extend it here.
13558 DebugLoc dl = MI.getDebugLoc();
13559 MachineFunction *F = BB->getParent();
13560 MachineRegisterInfo &RegInfo = F->getRegInfo();
13561 const bool is8bit = MI.getOperand(3).getImm() == 1;
13562 if (CmpOpcode == PPC::CMPW)
13563 signExtendOperandIfUnknown(MI, BB, 4, is8bit, TII);
13564 Register incr = MI.getOperand(4).getReg();
13565
13566 // In 64 bit mode we have to use 64 bits for addresses, even though the
13567 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
13568 // registers without caring whether they're 32 or 64, but here we're
13569 // doing actual arithmetic on the addresses.
13570 bool is64bit = Subtarget.isPPC64();
13571 bool isLittleEndian = Subtarget.isLittleEndian();
13572 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
13573
13574 const BasicBlock *LLVM_BB = BB->getBasicBlock();
13576
13577 Register dest = MI.getOperand(0).getReg();
13578 Register ptrA = MI.getOperand(1).getReg();
13579 Register ptrB = MI.getOperand(2).getReg();
13580
13581 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
13582 MachineBasicBlock *loop2MBB =
13583 CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
13584 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
13585 F->insert(It, loopMBB);
13586 if (CmpOpcode)
13587 F->insert(It, loop2MBB);
13588 F->insert(It, exitMBB);
13589 exitMBB->splice(exitMBB->begin(), BB,
13590 std::next(MachineBasicBlock::iterator(MI)), BB->end());
13592
13593 const TargetRegisterClass *RC =
13594 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13595 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
13596
13597 Register PtrReg = RegInfo.createVirtualRegister(RC);
13598 Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
13599 Register ShiftReg =
13600 isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
13601 Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
13602 Register MaskReg = RegInfo.createVirtualRegister(GPRC);
13603 Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
13604 Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
13605 Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
13606 Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
13607 Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
13608 Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
13609 Register SrwDestReg = RegInfo.createVirtualRegister(GPRC);
13610 Register Ptr1Reg;
13611 Register TmpReg =
13612 (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
13613
13614 // thisMBB:
13615 // ...
13616 // fallthrough --> loopMBB
13617 BB->addSuccessor(loopMBB);
13618
13619 // The 4-byte load must be aligned, while a char or short may be
13620 // anywhere in the word. Hence all this nasty bookkeeping code.
13621 // add ptr1, ptrA, ptrB [copy if ptrA==0]
13622 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
13623 // xori shift, shift1, 24 [16]
13624 // rlwinm ptr, ptr1, 0, 0, 29
13625 // slw incr2, incr, shift
13626 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
13627 // slw mask, mask2, shift
13628 // loopMBB:
13629 // lwarx tmpDest, ptr
13630 // add tmp, tmpDest, incr2
13631 // andc tmp2, tmpDest, mask
13632 // and tmp3, tmp, mask
13633 // or tmp4, tmp3, tmp2
13634 // stwcx. tmp4, ptr
13635 // bne- loopMBB
13636 // fallthrough --> exitMBB
13637 // srw SrwDest, tmpDest, shift
13638 // rlwinm SrwDest, SrwDest, 0, 24 [16], 31
13639 if (ptrA != ZeroReg) {
13640 Ptr1Reg = RegInfo.createVirtualRegister(RC);
13641 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
13642 .addReg(ptrA)
13643 .addReg(ptrB);
13644 } else {
13645 Ptr1Reg = ptrB;
13646 }
13647 // We need use 32-bit subregister to avoid mismatch register class in 64-bit
13648 // mode.
13649 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
13650 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
13651 .addImm(3)
13652 .addImm(27)
13653 .addImm(is8bit ? 28 : 27);
13654 if (!isLittleEndian)
13655 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
13656 .addReg(Shift1Reg)
13657 .addImm(is8bit ? 24 : 16);
13658 if (is64bit)
13659 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
13660 .addReg(Ptr1Reg)
13661 .addImm(0)
13662 .addImm(61);
13663 else
13664 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
13665 .addReg(Ptr1Reg)
13666 .addImm(0)
13667 .addImm(0)
13668 .addImm(29);
13669 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
13670 if (is8bit)
13671 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
13672 else {
13673 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
13674 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
13675 .addReg(Mask3Reg)
13676 .addImm(65535);
13677 }
13678 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
13679 .addReg(Mask2Reg)
13680 .addReg(ShiftReg);
13681
13682 BB = loopMBB;
13683 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
13684 .addReg(ZeroReg)
13685 .addReg(PtrReg);
13686 if (BinOpcode)
13687 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
13688 .addReg(Incr2Reg)
13689 .addReg(TmpDestReg);
13690 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
13691 .addReg(TmpDestReg)
13692 .addReg(MaskReg);
13693 BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
13694 if (CmpOpcode) {
13695 // For unsigned comparisons, we can directly compare the shifted values.
13696 // For signed comparisons we shift and sign extend.
13697 Register SReg = RegInfo.createVirtualRegister(GPRC);
13698 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
13699 BuildMI(BB, dl, TII->get(PPC::AND), SReg)
13700 .addReg(TmpDestReg)
13701 .addReg(MaskReg);
13702 unsigned ValueReg = SReg;
13703 unsigned CmpReg = Incr2Reg;
13704 if (CmpOpcode == PPC::CMPW) {
13705 ValueReg = RegInfo.createVirtualRegister(GPRC);
13706 BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
13707 .addReg(SReg)
13708 .addReg(ShiftReg);
13709 Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
13710 BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
13711 .addReg(ValueReg);
13712 ValueReg = ValueSReg;
13713 CmpReg = incr;
13714 }
13715 BuildMI(BB, dl, TII->get(CmpOpcode), CrReg).addReg(ValueReg).addReg(CmpReg);
13716 BuildMI(BB, dl, TII->get(PPC::BCC))
13717 .addImm(CmpPred)
13718 .addReg(CrReg)
13719 .addMBB(exitMBB);
13720 BB->addSuccessor(loop2MBB);
13721 BB->addSuccessor(exitMBB);
13722 BB = loop2MBB;
13723 }
13724 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
13725 BuildMI(BB, dl, TII->get(PPC::STWCX))
13726 .addReg(Tmp4Reg)
13727 .addReg(ZeroReg)
13728 .addReg(PtrReg);
13729 BuildMI(BB, dl, TII->get(PPC::BCC))
13731 .addReg(PPC::CR0)
13732 .addMBB(loopMBB);
13733 BB->addSuccessor(loopMBB);
13734 BB->addSuccessor(exitMBB);
13735
13736 // exitMBB:
13737 // ...
13738 BB = exitMBB;
13739 // Since the shift amount is not a constant, we need to clear
13740 // the upper bits with a separate RLWINM.
13741 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::RLWINM), dest)
13742 .addReg(SrwDestReg)
13743 .addImm(0)
13744 .addImm(is8bit ? 24 : 16)
13745 .addImm(31);
13746 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), SrwDestReg)
13747 .addReg(TmpDestReg)
13748 .addReg(ShiftReg);
13749 return BB;
13750}
13751
13754 MachineBasicBlock *MBB) const {
13755 DebugLoc DL = MI.getDebugLoc();
13756 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13757 const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13758
13759 MachineFunction *MF = MBB->getParent();
13761
13762 const BasicBlock *BB = MBB->getBasicBlock();
13763 MachineFunction::iterator I = ++MBB->getIterator();
13764
13765 Register DstReg = MI.getOperand(0).getReg();
13766 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13767 assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
13768 Register mainDstReg = MRI.createVirtualRegister(RC);
13769 Register restoreDstReg = MRI.createVirtualRegister(RC);
13770
13771 MVT PVT = getPointerTy(MF->getDataLayout());
13772 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13773 "Invalid Pointer Size!");
13774 // For v = setjmp(buf), we generate
13775 //
13776 // thisMBB:
13777 // SjLjSetup mainMBB
13778 // bl mainMBB
13779 // v_restore = 1
13780 // b sinkMBB
13781 //
13782 // mainMBB:
13783 // buf[LabelOffset] = LR
13784 // v_main = 0
13785 //
13786 // sinkMBB:
13787 // v = phi(main, restore)
13788 //
13789
13790 MachineBasicBlock *thisMBB = MBB;
13791 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13792 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13793 MF->insert(I, mainMBB);
13794 MF->insert(I, sinkMBB);
13795
13797
13798 // Transfer the remainder of BB and its successor edges to sinkMBB.
13799 sinkMBB->splice(sinkMBB->begin(), MBB,
13800 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
13802
13803 // Note that the structure of the jmp_buf used here is not compatible
13804 // with that used by libc, and is not designed to be. Specifically, it
13805 // stores only those 'reserved' registers that LLVM does not otherwise
13806 // understand how to spill. Also, by convention, by the time this
13807 // intrinsic is called, Clang has already stored the frame address in the
13808 // first slot of the buffer and stack address in the third. Following the
13809 // X86 target code, we'll store the jump address in the second slot. We also
13810 // need to save the TOC pointer (R2) to handle jumps between shared
13811 // libraries, and that will be stored in the fourth slot. The thread
13812 // identifier (R13) is not affected.
13813
13814 // thisMBB:
13815 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13816 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13817 const int64_t BPOffset = 4 * PVT.getStoreSize();
13818
13819 // Prepare IP either in reg.
13820 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
13821 Register LabelReg = MRI.createVirtualRegister(PtrRC);
13822 Register BufReg = MI.getOperand(1).getReg();
13823
13824 if (Subtarget.is64BitELFABI()) {
13825 setUsesTOCBasePtr(*MBB->getParent());
13826 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
13827 .addReg(PPC::X2)
13828 .addImm(TOCOffset)
13829 .addReg(BufReg)
13830 .cloneMemRefs(MI);
13831 }
13832
13833 // Naked functions never have a base pointer, and so we use r1. For all
13834 // other functions, this decision must be delayed until during PEI.
13835 unsigned BaseReg;
13836 if (MF->getFunction().hasFnAttribute(Attribute::Naked))
13837 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
13838 else
13839 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
13840
13841 MIB = BuildMI(*thisMBB, MI, DL,
13842 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
13843 .addReg(BaseReg)
13844 .addImm(BPOffset)
13845 .addReg(BufReg)
13846 .cloneMemRefs(MI);
13847
13848 // Setup
13849 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
13850 MIB.addRegMask(TRI->getNoPreservedMask());
13851
13852 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
13853
13854 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
13855 .addMBB(mainMBB);
13856 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
13857
13858 thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
13859 thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
13860
13861 // mainMBB:
13862 // mainDstReg = 0
13863 MIB =
13864 BuildMI(mainMBB, DL,
13865 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
13866
13867 // Store IP
13868 if (Subtarget.isPPC64()) {
13869 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
13870 .addReg(LabelReg)
13871 .addImm(LabelOffset)
13872 .addReg(BufReg);
13873 } else {
13874 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
13875 .addReg(LabelReg)
13876 .addImm(LabelOffset)
13877 .addReg(BufReg);
13878 }
13879 MIB.cloneMemRefs(MI);
13880
13881 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
13882 mainMBB->addSuccessor(sinkMBB);
13883
13884 // sinkMBB:
13885 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13886 TII->get(PPC::PHI), DstReg)
13887 .addReg(mainDstReg).addMBB(mainMBB)
13888 .addReg(restoreDstReg).addMBB(thisMBB);
13889
13890 MI.eraseFromParent();
13891 return sinkMBB;
13892}
13893
13896 MachineBasicBlock *MBB) const {
13897 DebugLoc DL = MI.getDebugLoc();
13898 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13899
13900 MachineFunction *MF = MBB->getParent();
13902
13903 MVT PVT = getPointerTy(MF->getDataLayout());
13904 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
13905 "Invalid Pointer Size!");
13906
13907 const TargetRegisterClass *RC =
13908 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
13909 Register Tmp = MRI.createVirtualRegister(RC);
13910 // Since FP is only updated here but NOT referenced, it's treated as GPR.
13911 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
13912 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
13913 unsigned BP =
13914 (PVT == MVT::i64)
13915 ? PPC::X30
13916 : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
13917 : PPC::R30);
13918
13920
13921 const int64_t LabelOffset = 1 * PVT.getStoreSize();
13922 const int64_t SPOffset = 2 * PVT.getStoreSize();
13923 const int64_t TOCOffset = 3 * PVT.getStoreSize();
13924 const int64_t BPOffset = 4 * PVT.getStoreSize();
13925
13926 Register BufReg = MI.getOperand(0).getReg();
13927
13928 // Reload FP (the jumped-to function may not have had a
13929 // frame pointer, and if so, then its r31 will be restored
13930 // as necessary).
13931 if (PVT == MVT::i64) {
13932 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
13933 .addImm(0)
13934 .addReg(BufReg);
13935 } else {
13936 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
13937 .addImm(0)
13938 .addReg(BufReg);
13939 }
13940 MIB.cloneMemRefs(MI);
13941
13942 // Reload IP
13943 if (PVT == MVT::i64) {
13944 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
13945 .addImm(LabelOffset)
13946 .addReg(BufReg);
13947 } else {
13948 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
13949 .addImm(LabelOffset)
13950 .addReg(BufReg);
13951 }
13952 MIB.cloneMemRefs(MI);
13953
13954 // Reload SP
13955 if (PVT == MVT::i64) {
13956 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
13957 .addImm(SPOffset)
13958 .addReg(BufReg);
13959 } else {
13960 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
13961 .addImm(SPOffset)
13962 .addReg(BufReg);
13963 }
13964 MIB.cloneMemRefs(MI);
13965
13966 // Reload BP
13967 if (PVT == MVT::i64) {
13968 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
13969 .addImm(BPOffset)
13970 .addReg(BufReg);
13971 } else {
13972 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
13973 .addImm(BPOffset)
13974 .addReg(BufReg);
13975 }
13976 MIB.cloneMemRefs(MI);
13977
13978 // Reload TOC
13979 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
13980 setUsesTOCBasePtr(*MBB->getParent());
13981 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
13982 .addImm(TOCOffset)
13983 .addReg(BufReg)
13984 .cloneMemRefs(MI);
13985 }
13986
13987 // Jump
13988 BuildMI(*MBB, MI, DL,
13989 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
13990 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
13991
13992 MI.eraseFromParent();
13993 return MBB;
13994}
13995
13997 // If the function specifically requests inline stack probes, emit them.
13998 if (MF.getFunction().hasFnAttribute("probe-stack"))
13999 return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
14000 "inline-asm";
14001 return false;
14002}
14003
14005 const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
14006 unsigned StackAlign = TFI->getStackAlignment();
14007 assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
14008 "Unexpected stack alignment");
14009 // The default stack probe size is 4096 if the function has no
14010 // stack-probe-size attribute.
14011 const Function &Fn = MF.getFunction();
14012 unsigned StackProbeSize =
14013 Fn.getFnAttributeAsParsedInteger("stack-probe-size", 4096);
14014 // Round down to the stack alignment.
14015 StackProbeSize &= ~(StackAlign - 1);
14016 return StackProbeSize ? StackProbeSize : StackAlign;
14017}
14018
14019// Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
14020// into three phases. In the first phase, it uses pseudo instruction
14021// PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
14022// FinalStackPtr. In the second phase, it generates a loop for probing blocks.
14023// At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
14024// MaxCallFrameSize so that it can calculate correct data area pointer.
14027 MachineBasicBlock *MBB) const {
14028 const bool isPPC64 = Subtarget.isPPC64();
14029 MachineFunction *MF = MBB->getParent();
14030 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14031 DebugLoc DL = MI.getDebugLoc();
14032 const unsigned ProbeSize = getStackProbeSize(*MF);
14033 const BasicBlock *ProbedBB = MBB->getBasicBlock();
14035 // The CFG of probing stack looks as
14036 // +-----+
14037 // | MBB |
14038 // +--+--+
14039 // |
14040 // +----v----+
14041 // +--->+ TestMBB +---+
14042 // | +----+----+ |
14043 // | | |
14044 // | +-----v----+ |
14045 // +---+ BlockMBB | |
14046 // +----------+ |
14047 // |
14048 // +---------+ |
14049 // | TailMBB +<--+
14050 // +---------+
14051 // In MBB, calculate previous frame pointer and final stack pointer.
14052 // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
14053 // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
14054 // TailMBB is spliced via \p MI.
14055 MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
14056 MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
14057 MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
14058
14059 MachineFunction::iterator MBBIter = ++MBB->getIterator();
14060 MF->insert(MBBIter, TestMBB);
14061 MF->insert(MBBIter, BlockMBB);
14062 MF->insert(MBBIter, TailMBB);
14063
14064 const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
14065 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
14066
14067 Register DstReg = MI.getOperand(0).getReg();
14068 Register NegSizeReg = MI.getOperand(1).getReg();
14069 Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
14070 Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14071 Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14072 Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14073
14074 // Since value of NegSizeReg might be realigned in prologepilog, insert a
14075 // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
14076 // NegSize.
14077 unsigned ProbeOpc;
14078 if (!MRI.hasOneNonDBGUse(NegSizeReg))
14079 ProbeOpc =
14080 isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
14081 else
14082 // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
14083 // and NegSizeReg will be allocated in the same phyreg to avoid
14084 // redundant copy when NegSizeReg has only one use which is current MI and
14085 // will be replaced by PREPARE_PROBED_ALLOCA then.
14086 ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
14087 : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
14088 BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
14089 .addDef(ActualNegSizeReg)
14090 .addReg(NegSizeReg)
14091 .add(MI.getOperand(2))
14092 .add(MI.getOperand(3));
14093
14094 // Calculate final stack pointer, which equals to SP + ActualNegSize.
14095 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
14096 FinalStackPtr)
14097 .addReg(SPReg)
14098 .addReg(ActualNegSizeReg);
14099
14100 // Materialize a scratch register for update.
14101 int64_t NegProbeSize = -(int64_t)ProbeSize;
14102 assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
14103 Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14104 if (!isInt<16>(NegProbeSize)) {
14105 Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14106 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
14107 .addImm(NegProbeSize >> 16);
14108 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
14109 ScratchReg)
14110 .addReg(TempReg)
14111 .addImm(NegProbeSize & 0xFFFF);
14112 } else
14113 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
14114 .addImm(NegProbeSize);
14115
14116 {
14117 // Probing leading residual part.
14118 Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14119 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
14120 .addReg(ActualNegSizeReg)
14121 .addReg(ScratchReg);
14122 Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14123 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
14124 .addReg(Div)
14125 .addReg(ScratchReg);
14126 Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14127 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
14128 .addReg(Mul)
14129 .addReg(ActualNegSizeReg);
14130 BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14131 .addReg(FramePointer)
14132 .addReg(SPReg)
14133 .addReg(NegMod);
14134 }
14135
14136 {
14137 // Remaining part should be multiple of ProbeSize.
14138 Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
14139 BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
14140 .addReg(SPReg)
14141 .addReg(FinalStackPtr);
14142 BuildMI(TestMBB, DL, TII->get(PPC::BCC))
14144 .addReg(CmpResult)
14145 .addMBB(TailMBB);
14146 TestMBB->addSuccessor(BlockMBB);
14147 TestMBB->addSuccessor(TailMBB);
14148 }
14149
14150 {
14151 // Touch the block.
14152 // |P...|P...|P...
14153 BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
14154 .addReg(FramePointer)
14155 .addReg(SPReg)
14156 .addReg(ScratchReg);
14157 BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
14158 BlockMBB->addSuccessor(TestMBB);
14159 }
14160
14161 // Calculation of MaxCallFrameSize is deferred to prologepilog, use
14162 // DYNAREAOFFSET pseudo instruction to get the future result.
14163 Register MaxCallFrameSizeReg =
14164 MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
14165 BuildMI(TailMBB, DL,
14166 TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
14167 MaxCallFrameSizeReg)
14168 .add(MI.getOperand(2))
14169 .add(MI.getOperand(3));
14170 BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
14171 .addReg(SPReg)
14172 .addReg(MaxCallFrameSizeReg);
14173
14174 // Splice instructions after MI to TailMBB.
14175 TailMBB->splice(TailMBB->end(), MBB,
14176 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
14178 MBB->addSuccessor(TestMBB);
14179
14180 // Delete the pseudo instruction.
14181 MI.eraseFromParent();
14182
14183 ++NumDynamicAllocaProbed;
14184 return TailMBB;
14185}
14186
14187/// Check if the opcode is a SELECT or SELECT_CC variant.
14188/// @param Opcode The opcode to check
14189/// @param CheckOnlyCC If true, only return true for SELECT_CC variants;
14190/// if false, return true for both SELECT and SELECT_CC
14191static bool IsSelect(unsigned Opcode, bool CheckOnlyCC = false) {
14192 switch (Opcode) {
14193 // SELECT_CC variants - always return true
14194 case PPC::SELECT_CC_I4:
14195 case PPC::SELECT_CC_I8:
14196 case PPC::SELECT_CC_F4:
14197 case PPC::SELECT_CC_F8:
14198 case PPC::SELECT_CC_F16:
14199 case PPC::SELECT_CC_VRRC:
14200 case PPC::SELECT_CC_VSFRC:
14201 case PPC::SELECT_CC_VSSRC:
14202 case PPC::SELECT_CC_VSRC:
14203 case PPC::SELECT_CC_SPE4:
14204 case PPC::SELECT_CC_SPE:
14205 return true;
14206 // SELECT variants - only return true if CheckOnlyCC is false
14207 case PPC::SELECT_I4:
14208 case PPC::SELECT_I8:
14209 case PPC::SELECT_F4:
14210 case PPC::SELECT_F8:
14211 case PPC::SELECT_F16:
14212 case PPC::SELECT_SPE:
14213 case PPC::SELECT_SPE4:
14214 case PPC::SELECT_VRRC:
14215 case PPC::SELECT_VSFRC:
14216 case PPC::SELECT_VSSRC:
14217 case PPC::SELECT_VSRC:
14218 return !CheckOnlyCC; // true if checking all SELECTs, false if only CC
14219 default:
14220 return false;
14221 }
14222}
14223static bool IsSelectCC(unsigned Opcode) { return IsSelect(Opcode, true); }
14224
14225/// Emit SELECT instruction, using ISEL if available, otherwise use
14226/// branch-based control flow.
14227///
14228/// For targets with ISEL support (SELECT_CC_I4/I8, SELECT_I4/I8), this
14229/// generates a single ISEL instruction. Otherwise, it creates a
14230/// branch-based control flow pattern with PHI nodes.
14232 const TargetInstrInfo *TII,
14233 const PPCSubtarget &Subtarget) {
14234 assert(IsSelect(MI.getOpcode()) && "Instruction must be a SELECT variant");
14235
14236 // Check if we can use ISEL for this SELECT
14237 if (Subtarget.hasISEL() &&
14238 (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14239 MI.getOpcode() == PPC::SELECT_CC_I8 ||
14240 MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8)) {
14242 if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
14243 MI.getOpcode() == PPC::SELECT_CC_I8)
14244 Cond.push_back(MI.getOperand(4));
14245 else
14247 Cond.push_back(MI.getOperand(1));
14248
14249 DebugLoc dl = MI.getDebugLoc();
14250 TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
14251 MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
14252 MI.eraseFromParent();
14253 return BB;
14254 }
14255
14256 // Fall back to branch-based SELECT implementation
14257 MachineFunction *F = BB->getParent();
14258 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14260 DebugLoc dl = MI.getDebugLoc();
14261
14262 MachineBasicBlock *thisMBB = BB;
14263 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14264 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14265 F->insert(It, copy0MBB);
14266 F->insert(It, sinkMBB);
14267
14268 if (isPhysRegUsedAfter(PPC::CARRY, MI.getIterator())) {
14269 copy0MBB->addLiveIn(PPC::CARRY);
14270 sinkMBB->addLiveIn(PPC::CARRY);
14271 }
14272
14273 // Set the call frame size on entry to the new basic blocks.
14274 unsigned CallFrameSize = TII->getCallFrameSizeAt(MI);
14275 copy0MBB->setCallFrameSize(CallFrameSize);
14276 sinkMBB->setCallFrameSize(CallFrameSize);
14277
14278 // Transfer the remainder of BB and its successor edges to sinkMBB.
14279 sinkMBB->splice(sinkMBB->begin(), BB,
14280 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14282
14283 // Add successors
14284 BB->addSuccessor(copy0MBB);
14285 BB->addSuccessor(sinkMBB);
14286
14287 // Build branch instruction
14288 if (IsSelectCC(MI.getOpcode()))
14289 BuildMI(BB, dl, TII->get(PPC::BCC))
14290 .addImm(MI.getOperand(4).getImm())
14291 .addReg(MI.getOperand(1).getReg())
14292 .addMBB(sinkMBB);
14293 else
14294 BuildMI(BB, dl, TII->get(PPC::BC))
14295 .addReg(MI.getOperand(1).getReg())
14296 .addMBB(sinkMBB);
14297
14298 // copy0MBB: fallthrough to sinkMBB
14299 BB = copy0MBB;
14300 BB->addSuccessor(sinkMBB);
14301
14302 // sinkMBB: PHI instruction
14303 BB = sinkMBB;
14304 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
14305 .addReg(MI.getOperand(3).getReg())
14306 .addMBB(copy0MBB)
14307 .addReg(MI.getOperand(2).getReg())
14308 .addMBB(thisMBB);
14309 MI.eraseFromParent();
14310 return BB;
14311}
14312
14313/// Helper function to create basic blocks for atomic compare-and-swap.
14314/// Creates three basic blocks (loop1MBB, loop2MBB, exitMBB) and sets up
14315/// the control flow structure common to both hardware and software
14316/// implementations of atomic compare-and-swap operations.
14318 MachineBasicBlock *&loop1MBB,
14319 MachineBasicBlock *&loop2MBB,
14320 MachineBasicBlock *&exitMBB,
14323 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14324 loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
14325 loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
14326 exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
14327 F->insert(It, loop1MBB);
14328 F->insert(It, loop2MBB);
14329 F->insert(It, exitMBB);
14330 exitMBB->splice(exitMBB->begin(), BB,
14331 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14333 BB->addSuccessor(loop1MBB);
14334}
14335
14336/// Emit hardware-supported atomic compare-and-swap for I32/I64 and I8/I16
14337/// with partword atomic support.
14338///
14339/// This uses native PowerPC atomic instructions (LBARX/LHARX/LWARX/LDARX for
14340/// load-and-reserve, STBCX/STHCX/STWCX/STDCX for store-conditional) to
14341/// implement atomic compare-and-swap at byte, halfword, word, or doubleword
14342/// granularity.
14343///
14344/// Control flow:
14345/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14346/// | |
14347/// +------------+
14348///
14349/// loop1MBB:
14350/// - Load-and-reserve from memory
14351/// - Compare loaded value with expected old value
14352/// - Branch to exitMBB if not equal (CAS failed)
14353/// loop2MBB:
14354/// - Store-conditional new value to memory
14355/// - Branch back to loop1MBB if store failed (retry)
14356/// - Fall through to exitMBB on success
14357static MachineBasicBlock *
14359 const TargetInstrInfo *TII,
14360 const PPCSubtarget &Subtarget) {
14361 MachineFunction *F = BB->getParent();
14363
14364 bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
14365
14366 unsigned LoadMnemonic = PPC::LDARX;
14367 unsigned StoreMnemonic = PPC::STDCX;
14368 switch (MI.getOpcode()) {
14369 default:
14370 llvm_unreachable("Compare and swap of unknown size");
14371 case PPC::ATOMIC_CMP_SWAP_I8:
14372 LoadMnemonic = PPC::LBARX;
14373 StoreMnemonic = PPC::STBCX;
14374 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14375 break;
14376 case PPC::ATOMIC_CMP_SWAP_I16:
14377 LoadMnemonic = PPC::LHARX;
14378 StoreMnemonic = PPC::STHCX;
14379 assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
14380 break;
14381 case PPC::ATOMIC_CMP_SWAP_I32:
14382 LoadMnemonic = PPC::LWARX;
14383 StoreMnemonic = PPC::STWCX;
14384 break;
14385 case PPC::ATOMIC_CMP_SWAP_I64:
14386 LoadMnemonic = PPC::LDARX;
14387 StoreMnemonic = PPC::STDCX;
14388 break;
14389 }
14390
14391 MachineRegisterInfo &RegInfo = F->getRegInfo();
14392 Register dest = MI.getOperand(0).getReg();
14393 Register ptrA = MI.getOperand(1).getReg();
14394 Register ptrB = MI.getOperand(2).getReg();
14395 Register oldval = MI.getOperand(3).getReg();
14396 Register newval = MI.getOperand(4).getReg();
14397 DebugLoc dl = MI.getDebugLoc();
14398
14399 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14400 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14401
14402 Register CrReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14403
14404 // loop1MBB:
14405 // l[bhwd]arx dest, ptr
14406 // cmp[wd] dest, oldval
14407 // bne- exitBB
14408 BB = loop1MBB;
14409 BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
14410 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), CrReg)
14411 .addReg(dest)
14412 .addReg(oldval);
14413 BuildMI(BB, dl, TII->get(PPC::BCC))
14415 .addReg(CrReg)
14416 .addMBB(exitMBB);
14417 BB->addSuccessor(loop2MBB);
14418 BB->addSuccessor(exitMBB);
14419
14420 // loop2MBB:
14421 // st[bhwd]cx. newval, ptr
14422 // bne- loopMBB
14423 // b exitBB
14424 BB = loop2MBB;
14425 BuildMI(BB, dl, TII->get(StoreMnemonic))
14426 .addReg(newval)
14427 .addReg(ptrA)
14428 .addReg(ptrB);
14429 BuildMI(BB, dl, TII->get(PPC::BCC))
14431 .addReg(PPC::CR0)
14432 .addMBB(loop1MBB);
14433 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14434 BB->addSuccessor(loop1MBB);
14435 BB->addSuccessor(exitMBB);
14436
14437 return exitMBB;
14438}
14439
14440/// Emit software-emulated atomic compare-and-swap for I8/I16 without
14441/// hardware partword atomic support.
14442///
14443/// This emulates byte/halfword atomic operations using word (32-bit) atomic
14444/// instructions. Since PowerPC atomic instructions work at word granularity,
14445/// we must:
14446/// 1. Align the pointer to a word boundary
14447/// 2. Calculate the bit shift for the target byte/halfword within the word
14448/// 3. Create masks to isolate the target byte/halfword
14449/// 4. Shift old/new values into the correct bit position
14450/// 5. Use LWARX/STWCX on the full word
14451/// 6. Mask and merge to preserve other bytes in the word
14452/// 7. Extract and shift the result back
14453///
14454/// Control flow:
14455/// thisMBB -> loop1MBB -> loop2MBB -> exitMBB
14456/// | |
14457/// +------------+
14458///
14459/// loop1MBB:
14460/// - LWARX: Load-and-reserve full word
14461/// - Mask to extract target byte/halfword
14462/// - Compare with expected old value
14463/// - Branch to exitMBB if not equal (CAS failed)
14464/// loop2MBB:
14465/// - Merge new value with other bytes in the word
14466/// - STWCX: Store-conditional full word
14467/// - Branch back to loop1MBB if store failed (retry)
14468/// - Fall through to exitMBB on success
14469/// exitMBB:
14470/// - Extract and return the loaded value
14471static MachineBasicBlock *
14473 const TargetInstrInfo *TII,
14474 const PPCSubtarget &Subtarget) {
14475 MachineFunction *F = BB->getParent();
14477
14478 bool is64bit = Subtarget.isPPC64();
14479 bool isLittleEndian = Subtarget.isLittleEndian();
14480 bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
14481
14482 Register dest = MI.getOperand(0).getReg();
14483 Register ptrA = MI.getOperand(1).getReg();
14484 Register ptrB = MI.getOperand(2).getReg();
14485 Register oldval = MI.getOperand(3).getReg();
14486 Register newval = MI.getOperand(4).getReg();
14487 DebugLoc dl = MI.getDebugLoc();
14488
14489 MachineBasicBlock *loop1MBB, *loop2MBB, *exitMBB;
14490 createAtomicLoopBlocks(F, BB, loop1MBB, loop2MBB, exitMBB, MI, It);
14491
14492 MachineRegisterInfo &RegInfo = F->getRegInfo();
14493 const TargetRegisterClass *RC =
14494 is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
14495 const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
14496
14497 // Lambda to create virtual registers
14498 auto createVReg = [&](const TargetRegisterClass *RC) {
14499 return RegInfo.createVirtualRegister(RC);
14500 };
14501
14502 Register PtrReg = createVReg(RC);
14503 Register Shift1Reg = createVReg(GPRC);
14504 Register ShiftReg = isLittleEndian ? Shift1Reg : createVReg(GPRC);
14505 Register NewVal2Reg = createVReg(GPRC);
14506 Register NewVal3Reg = createVReg(GPRC);
14507 Register OldVal2Reg = createVReg(GPRC);
14508 Register OldVal3Reg = createVReg(GPRC);
14509 Register MaskReg = createVReg(GPRC);
14510 Register Mask2Reg = createVReg(GPRC);
14511 Register Mask3Reg = createVReg(GPRC);
14512 Register Tmp2Reg = createVReg(GPRC);
14513 Register Tmp4Reg = createVReg(GPRC);
14514 Register TmpDestReg = createVReg(GPRC);
14515 Register TmpReg = createVReg(GPRC);
14516 Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
14517 Register CrReg = createVReg(&PPC::CRRCRegClass);
14518
14519 // Compute aligned pointer and shift amount
14520 Register Ptr1Reg;
14521 if (ptrA != ZeroReg) {
14522 Ptr1Reg = createVReg(RC);
14523 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
14524 .addReg(ptrA)
14525 .addReg(ptrB);
14526 } else {
14527 Ptr1Reg = ptrB;
14528 }
14529
14530 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
14531 .addReg(Ptr1Reg, {}, is64bit ? PPC::sub_32 : 0)
14532 .addImm(3)
14533 .addImm(27)
14534 .addImm(is8bit ? 28 : 27);
14535 if (!isLittleEndian)
14536 BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
14537 .addReg(Shift1Reg)
14538 .addImm(is8bit ? 24 : 16);
14539 if (is64bit)
14540 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
14541 .addReg(Ptr1Reg)
14542 .addImm(0)
14543 .addImm(61);
14544 else
14545 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
14546 .addReg(Ptr1Reg)
14547 .addImm(0)
14548 .addImm(0)
14549 .addImm(29);
14550
14551 // Prepare masked values
14552 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
14553 .addReg(newval)
14554 .addReg(ShiftReg);
14555 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
14556 .addReg(oldval)
14557 .addReg(ShiftReg);
14558 if (is8bit)
14559 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
14560 else {
14561 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
14562 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
14563 .addReg(Mask3Reg)
14564 .addImm(65535);
14565 }
14566 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
14567 .addReg(Mask2Reg)
14568 .addReg(ShiftReg);
14569 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
14570 .addReg(NewVal2Reg)
14571 .addReg(MaskReg);
14572 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
14573 .addReg(OldVal2Reg)
14574 .addReg(MaskReg);
14575
14576 // loop1MBB:
14577 // lwarx tmpDest, ptr
14578 // and tmp, tmpDest, mask
14579 // cmpw tmp, oldval3
14580 // bne- exitBB
14581 BB = loop1MBB;
14582 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
14583 .addReg(ZeroReg)
14584 .addReg(PtrReg);
14585 BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
14586 .addReg(TmpDestReg)
14587 .addReg(MaskReg);
14588 BuildMI(BB, dl, TII->get(PPC::CMPW), CrReg).addReg(TmpReg).addReg(OldVal3Reg);
14589 BuildMI(BB, dl, TII->get(PPC::BCC))
14591 .addReg(CrReg)
14592 .addMBB(exitMBB);
14593 BB->addSuccessor(loop2MBB);
14594 BB->addSuccessor(exitMBB);
14595
14596 // loop2MBB:
14597 // andc tmp2, tmpDest, mask
14598 // or tmp4, tmp2, newval3
14599 // stwcx. tmp4, ptr
14600 // bne- loop1MBB
14601 // b exitBB
14602 BB = loop2MBB;
14603 BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
14604 .addReg(TmpDestReg)
14605 .addReg(MaskReg);
14606 BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
14607 .addReg(Tmp2Reg)
14608 .addReg(NewVal3Reg);
14609 BuildMI(BB, dl, TII->get(PPC::STWCX))
14610 .addReg(Tmp4Reg)
14611 .addReg(ZeroReg)
14612 .addReg(PtrReg);
14613 BuildMI(BB, dl, TII->get(PPC::BCC))
14615 .addReg(PPC::CR0)
14616 .addMBB(loop1MBB);
14617 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
14618 BB->addSuccessor(loop1MBB);
14619 BB->addSuccessor(exitMBB);
14620
14621 // exitMBB:
14622 // srw dest, tmpDest, shift
14623 BB = exitMBB;
14624 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
14625 .addReg(TmpReg)
14626 .addReg(ShiftReg);
14627
14628 return BB;
14629}
14630
14633 MachineBasicBlock *BB) const {
14634 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
14635
14636 // To "insert" these instructions we actually have to insert their
14637 // control-flow patterns.
14638 const BasicBlock *LLVM_BB = BB->getBasicBlock();
14640
14641 MachineFunction *F = BB->getParent();
14642 MachineRegisterInfo &MRI = F->getRegInfo();
14643
14644 // Handle SELECT with ISEL support first (before generic SELECT handling)
14645 if (IsSelect(MI.getOpcode()))
14646 return emitSelect(MI, BB, TII, Subtarget);
14647
14648 switch (MI.getOpcode()) {
14649 case TargetOpcode::STACKMAP:
14650 return emitPatchPoint(MI, BB);
14651 case TargetOpcode::PATCHPOINT:
14652 // Call lowering should have added an r2 operand to indicate a dependence
14653 // on the TOC base pointer value. It can't however, because there is no
14654 // way to mark the dependence as implicit there, and so the stackmap code
14655 // will confuse it with a regular operand. Instead, add the dependence
14656 // here.
14657 if (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls())
14658 MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
14659 return emitPatchPoint(MI, BB);
14660
14661 case PPC::EH_SjLj_SetJmp32:
14662 case PPC::EH_SjLj_SetJmp64:
14663 return emitEHSjLjSetJmp(MI, BB);
14664
14665 case PPC::EH_SjLj_LongJmp32:
14666 case PPC::EH_SjLj_LongJmp64:
14667 return emitEHSjLjLongJmp(MI, BB);
14668
14669 case PPC::ReadTB: {
14670 // To read the 64-bit time-base register on a 32-bit target, we read the
14671 // two halves. Should the counter have wrapped while it was being read, we
14672 // need to try again.
14673 // ...
14674 // readLoop:
14675 // mfspr Rx,TBU # load from TBU
14676 // mfspr Ry,TB # load from TB
14677 // mfspr Rz,TBU # load from TBU
14678 // cmpw crX,Rx,Rz # check if 'old'='new'
14679 // bne readLoop # branch if they're not equal
14680 // ...
14681
14682 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
14683 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14684 DebugLoc dl = MI.getDebugLoc();
14685 F->insert(It, readMBB);
14686 F->insert(It, sinkMBB);
14687
14688 // Transfer the remainder of BB and its successor edges to sinkMBB.
14689 sinkMBB->splice(sinkMBB->begin(), BB,
14690 std::next(MachineBasicBlock::iterator(MI)), BB->end());
14692
14693 BB->addSuccessor(readMBB);
14694 BB = readMBB;
14695
14696 MachineRegisterInfo &RegInfo = F->getRegInfo();
14697 Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
14698 Register LoReg = MI.getOperand(0).getReg();
14699 Register HiReg = MI.getOperand(1).getReg();
14700
14701 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
14702 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
14703 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
14704
14705 Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14706
14707 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
14708 .addReg(HiReg)
14709 .addReg(ReadAgainReg);
14710 BuildMI(BB, dl, TII->get(PPC::BCC))
14712 .addReg(CmpReg)
14713 .addMBB(readMBB);
14714
14715 BB->addSuccessor(readMBB);
14716 BB->addSuccessor(sinkMBB);
14717 break;
14718 }
14719 case PPC::ATOMIC_LOAD_ADD_NOWP:
14720 BB = EmitPartwordAtomicBinary(MI, BB, PPC::ADD4);
14721 break;
14722 case PPC::ATOMIC_LOAD_ADD:
14723 BB = EmitAtomicBinary(MI, BB, PPC::ADD4);
14724 break;
14725 case PPC::ATOMIC_LOAD_ADD_I64:
14726 BB = EmitAtomicBinary(MI, BB, PPC::ADD8);
14727 break;
14728 case PPC::ATOMIC_LOAD_AND_NOWP:
14729 BB = EmitPartwordAtomicBinary(MI, BB, PPC::AND);
14730 break;
14731 case PPC::ATOMIC_LOAD_AND:
14732 BB = EmitAtomicBinary(MI, BB, PPC::AND);
14733 break;
14734 case PPC::ATOMIC_LOAD_AND_I64:
14735 BB = EmitAtomicBinary(MI, BB, PPC::AND8);
14736 break;
14737 case PPC::ATOMIC_LOAD_OR_NOWP:
14738 BB = EmitPartwordAtomicBinary(MI, BB, PPC::OR);
14739 break;
14740 case PPC::ATOMIC_LOAD_OR:
14741 BB = EmitAtomicBinary(MI, BB, PPC::OR);
14742 break;
14743 case PPC::ATOMIC_LOAD_OR_I64:
14744 BB = EmitAtomicBinary(MI, BB, PPC::OR8);
14745 break;
14746 case PPC::ATOMIC_LOAD_XOR_NOWP:
14747 BB = EmitPartwordAtomicBinary(MI, BB, PPC::XOR);
14748 break;
14749 case PPC::ATOMIC_LOAD_XOR:
14750 BB = EmitAtomicBinary(MI, BB, PPC::XOR);
14751 break;
14752 case PPC::ATOMIC_LOAD_XOR_I64:
14753 BB = EmitAtomicBinary(MI, BB, PPC::XOR8);
14754 break;
14755 case PPC::ATOMIC_LOAD_NAND_NOWP:
14756 BB = EmitPartwordAtomicBinary(MI, BB, PPC::NAND);
14757 break;
14758 case PPC::ATOMIC_LOAD_NAND:
14759 BB = EmitAtomicBinary(MI, BB, PPC::NAND);
14760 break;
14761 case PPC::ATOMIC_LOAD_NAND_I64:
14762 BB = EmitAtomicBinary(MI, BB, PPC::NAND8);
14763 break;
14764 case PPC::ATOMIC_LOAD_SUB_NOWP:
14765 BB = EmitPartwordAtomicBinary(MI, BB, PPC::SUBF);
14766 break;
14767 case PPC::ATOMIC_LOAD_SUB:
14768 BB = EmitAtomicBinary(MI, BB, PPC::SUBF);
14769 break;
14770 case PPC::ATOMIC_LOAD_SUB_I64:
14771 BB = EmitAtomicBinary(MI, BB, PPC::SUBF8);
14772 break;
14773 case PPC::ATOMIC_LOAD_MIN_NOWP:
14774 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14775 break;
14776 case PPC::ATOMIC_LOAD_MIN:
14777 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_LT);
14778 break;
14779 case PPC::ATOMIC_LOAD_MIN_I64:
14780 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_LT);
14781 break;
14782 case PPC::ATOMIC_LOAD_MAX_NOWP:
14783 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14784 break;
14785 case PPC::ATOMIC_LOAD_MAX:
14786 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPW, PPC::PRED_GT);
14787 break;
14788 case PPC::ATOMIC_LOAD_MAX_I64:
14789 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPD, PPC::PRED_GT);
14790 break;
14791 case PPC::ATOMIC_LOAD_UMIN_NOWP:
14792 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14793 break;
14794 case PPC::ATOMIC_LOAD_UMIN:
14795 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_LT);
14796 break;
14797 case PPC::ATOMIC_LOAD_UMIN_I64:
14798 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_LT);
14799 break;
14800 case PPC::ATOMIC_LOAD_UMAX_NOWP:
14801 BB = EmitPartwordAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14802 break;
14803 case PPC::ATOMIC_LOAD_UMAX:
14804 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLW, PPC::PRED_GT);
14805 break;
14806 case PPC::ATOMIC_LOAD_UMAX_I64:
14807 BB = EmitAtomicBinary(MI, BB, 0, PPC::CMPLD, PPC::PRED_GT);
14808 break;
14809 case PPC::ATOMIC_SWAP_NOWP:
14810 BB = EmitPartwordAtomicBinary(MI, BB, 0);
14811 break;
14812 case PPC::ATOMIC_SWAP:
14813 case PPC::ATOMIC_SWAP_I64:
14814 BB = EmitAtomicBinary(MI, BB, 0);
14815 break;
14816 case PPC::ATOMIC_CMP_SWAP_I32:
14817 case PPC::ATOMIC_CMP_SWAP_I64:
14818 case PPC::ATOMIC_CMP_SWAP_I8:
14819 case PPC::ATOMIC_CMP_SWAP_I16: {
14820 // Use hardware-supported atomic operations if available
14821 bool useHardware = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
14822 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
14823 (Subtarget.hasPartwordAtomics() &&
14824 (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
14825 MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16));
14826
14827 if (useHardware)
14828 BB = emitAtomicCmpSwapHardware(MI, BB, TII, Subtarget);
14829 else
14830 BB = emitAtomicCmpSwapSoftware(MI, BB, TII, Subtarget);
14831 break;
14832 }
14833 case PPC::FADDrtz: {
14834 // This pseudo performs an FADD with rounding mode temporarily forced
14835 // to round-to-zero. We emit this via custom inserter since the FPSCR
14836 // is not modeled at the SelectionDAG level.
14837 Register Dest = MI.getOperand(0).getReg();
14838 Register Src1 = MI.getOperand(1).getReg();
14839 Register Src2 = MI.getOperand(2).getReg();
14840 DebugLoc dl = MI.getDebugLoc();
14841
14842 MachineRegisterInfo &RegInfo = F->getRegInfo();
14843 Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
14844
14845 // Save FPSCR value.
14846 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
14847
14848 // Set rounding mode to round-to-zero.
14849 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
14850 .addImm(31)
14852
14853 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
14854 .addImm(30)
14856
14857 // Perform addition.
14858 auto MIB = BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest)
14859 .addReg(Src1)
14860 .addReg(Src2);
14861 if (MI.getFlag(MachineInstr::NoFPExcept))
14863
14864 // Restore FPSCR value.
14865 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
14866 break;
14867 }
14868 case PPC::ANDI_rec_1_EQ_BIT:
14869 case PPC::ANDI_rec_1_GT_BIT:
14870 case PPC::ANDI_rec_1_EQ_BIT8:
14871 case PPC::ANDI_rec_1_GT_BIT8: {
14872 unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
14873 MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
14874 ? PPC::ANDI8_rec
14875 : PPC::ANDI_rec;
14876 bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
14877 MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
14878
14879 MachineRegisterInfo &RegInfo = F->getRegInfo();
14880 Register Dest = RegInfo.createVirtualRegister(
14881 Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
14882
14883 DebugLoc Dl = MI.getDebugLoc();
14884 BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
14885 .addReg(MI.getOperand(1).getReg())
14886 .addImm(1);
14887 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14888 MI.getOperand(0).getReg())
14889 .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
14890 break;
14891 }
14892 case PPC::TCHECK_RET: {
14893 DebugLoc Dl = MI.getDebugLoc();
14894 MachineRegisterInfo &RegInfo = F->getRegInfo();
14895 Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
14896 BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
14897 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14898 MI.getOperand(0).getReg())
14899 .addReg(CRReg);
14900 break;
14901 }
14902 case PPC::TBEGIN_RET: {
14903 DebugLoc Dl = MI.getDebugLoc();
14904 unsigned Imm = MI.getOperand(1).getImm();
14905 BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
14906 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
14907 MI.getOperand(0).getReg())
14908 .addReg(PPC::CR0EQ);
14909 break;
14910 }
14911 case PPC::SETRNDi: {
14912 DebugLoc dl = MI.getDebugLoc();
14913 Register OldFPSCRReg = MI.getOperand(0).getReg();
14914
14915 // Save FPSCR value.
14916 if (MRI.use_empty(OldFPSCRReg))
14917 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
14918 else
14919 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
14920
14921 // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
14922 // the following settings:
14923 // 00 Round to nearest
14924 // 01 Round to 0
14925 // 10 Round to +inf
14926 // 11 Round to -inf
14927
14928 // When the operand is immediate, using the two least significant bits of
14929 // the immediate to set the bits 62:63 of FPSCR.
14930 unsigned Mode = MI.getOperand(1).getImm();
14931 BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
14932 .addImm(31)
14934
14935 BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
14936 .addImm(30)
14938 break;
14939 }
14940 case PPC::SETRND: {
14941 DebugLoc dl = MI.getDebugLoc();
14942
14943 // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
14944 // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
14945 // If the target doesn't have DirectMove, we should use stack to do the
14946 // conversion, because the target doesn't have the instructions like mtvsrd
14947 // or mfvsrd to do this conversion directly.
14948 auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
14949 if (Subtarget.hasDirectMove()) {
14950 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
14951 .addReg(SrcReg);
14952 } else {
14953 // Use stack to do the register copy.
14954 unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
14955 MachineRegisterInfo &RegInfo = F->getRegInfo();
14956 const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
14957 if (RC == &PPC::F8RCRegClass) {
14958 // Copy register from F8RCRegClass to G8RCRegclass.
14959 assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
14960 "Unsupported RegClass.");
14961
14962 StoreOp = PPC::STFD;
14963 LoadOp = PPC::LD;
14964 } else {
14965 // Copy register from G8RCRegClass to F8RCRegclass.
14966 assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
14967 (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
14968 "Unsupported RegClass.");
14969 }
14970
14971 MachineFrameInfo &MFI = F->getFrameInfo();
14972 int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
14973
14974 MachineMemOperand *MMOStore = F->getMachineMemOperand(
14975 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14977 MFI.getObjectAlign(FrameIdx));
14978
14979 // Store the SrcReg into the stack.
14980 BuildMI(*BB, MI, dl, TII->get(StoreOp))
14981 .addReg(SrcReg)
14982 .addImm(0)
14983 .addFrameIndex(FrameIdx)
14984 .addMemOperand(MMOStore);
14985
14986 MachineMemOperand *MMOLoad = F->getMachineMemOperand(
14987 MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
14989 MFI.getObjectAlign(FrameIdx));
14990
14991 // Load from the stack where SrcReg is stored, and save to DestReg,
14992 // so we have done the RegClass conversion from RegClass::SrcReg to
14993 // RegClass::DestReg.
14994 BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
14995 .addImm(0)
14996 .addFrameIndex(FrameIdx)
14997 .addMemOperand(MMOLoad);
14998 }
14999 };
15000
15001 Register OldFPSCRReg = MI.getOperand(0).getReg();
15002
15003 // Save FPSCR value.
15004 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
15005
15006 // When the operand is gprc register, use two least significant bits of the
15007 // register and mtfsf instruction to set the bits 62:63 of FPSCR.
15008 //
15009 // copy OldFPSCRTmpReg, OldFPSCRReg
15010 // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
15011 // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
15012 // copy NewFPSCRReg, NewFPSCRTmpReg
15013 // mtfsf 255, NewFPSCRReg
15014 MachineOperand SrcOp = MI.getOperand(1);
15015 MachineRegisterInfo &RegInfo = F->getRegInfo();
15016 Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
15017
15018 copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
15019
15020 Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
15021 Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
15022
15023 // The first operand of INSERT_SUBREG should be a register which has
15024 // subregisters, we only care about its RegClass, so we should use an
15025 // IMPLICIT_DEF register.
15026 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
15027 BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
15028 .addReg(ImDefReg)
15029 .add(SrcOp)
15030 .addImm(PPC::sub_32);
15031
15032 Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
15033 BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
15034 .addReg(OldFPSCRTmpReg)
15035 .addReg(ExtSrcReg)
15036 .addImm(0)
15037 .addImm(62);
15038
15039 Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
15040 copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
15041
15042 // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
15043 // bits of FPSCR.
15044 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
15045 .addImm(255)
15046 .addReg(NewFPSCRReg)
15047 .addImm(0)
15048 .addImm(0);
15049 break;
15050 }
15051 case PPC::SETFLM: {
15052 DebugLoc Dl = MI.getDebugLoc();
15053
15054 // Result of setflm is previous FPSCR content, so we need to save it first.
15055 Register OldFPSCRReg = MI.getOperand(0).getReg();
15056 if (MRI.use_empty(OldFPSCRReg))
15057 BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::IMPLICIT_DEF), OldFPSCRReg);
15058 else
15059 BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
15060
15061 // Put bits in 32:63 to FPSCR.
15062 Register NewFPSCRReg = MI.getOperand(1).getReg();
15063 BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
15064 .addImm(255)
15065 .addReg(NewFPSCRReg)
15066 .addImm(0)
15067 .addImm(0);
15068 break;
15069 }
15070 case PPC::PROBED_ALLOCA_32:
15071 case PPC::PROBED_ALLOCA_64:
15072 return emitProbedAlloca(MI, BB);
15073
15074 case PPC::SPLIT_QUADWORD: {
15075 DebugLoc DL = MI.getDebugLoc();
15076 Register Src = MI.getOperand(2).getReg();
15077 Register Lo = MI.getOperand(0).getReg();
15078 Register Hi = MI.getOperand(1).getReg();
15079 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
15080 .addDef(Lo)
15081 .addUse(Src, {}, PPC::sub_gp8_x1);
15082 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::COPY))
15083 .addDef(Hi)
15084 .addUse(Src, {}, PPC::sub_gp8_x0);
15085 break;
15086 }
15087 case PPC::LQX_PSEUDO:
15088 case PPC::STQX_PSEUDO: {
15089 DebugLoc DL = MI.getDebugLoc();
15090 // Ptr is used as the ptr_rc_no_r0 part
15091 // of LQ/STQ's memory operand and adding result of RA and RB,
15092 // so it has to be g8rc_and_g8rc_nox0.
15093 Register Ptr =
15094 F->getRegInfo().createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
15095 Register Val = MI.getOperand(0).getReg();
15096 Register RA = MI.getOperand(1).getReg();
15097 Register RB = MI.getOperand(2).getReg();
15098 BuildMI(*BB, MI, DL, TII->get(PPC::ADD8), Ptr).addReg(RA).addReg(RB);
15099 BuildMI(*BB, MI, DL,
15100 MI.getOpcode() == PPC::LQX_PSEUDO ? TII->get(PPC::LQ)
15101 : TII->get(PPC::STQ))
15102 .addReg(Val, getDefRegState(MI.getOpcode() == PPC::LQX_PSEUDO))
15103 .addImm(0)
15104 .addReg(Ptr);
15105 break;
15106 }
15107 default:
15108 llvm_unreachable("Unexpected instr type to insert");
15109 }
15110
15111 MI.eraseFromParent(); // The pseudo instruction is gone now.
15112 return BB;
15113}
15114
15115//===----------------------------------------------------------------------===//
15116// Target Optimization Hooks
15117//===----------------------------------------------------------------------===//
15118
15119static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
15120 // For the estimates, convergence is quadratic, so we essentially double the
15121 // number of digits correct after every iteration. For both FRE and FRSQRTE,
15122 // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
15123 // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
15124 int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
15125 if (VT.getScalarType() == MVT::f64)
15126 RefinementSteps++;
15127 return RefinementSteps;
15128}
15129
15130SDValue PPCTargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
15131 const DenormalMode &Mode,
15132 SDNodeFlags Flags) const {
15133 // We only have VSX Vector Test for software Square Root.
15134 EVT VT = Op.getValueType();
15135 if (!isTypeLegal(MVT::i1) ||
15136 (VT != MVT::f64 &&
15137 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX())))
15138 return TargetLowering::getSqrtInputTest(Op, DAG, Mode, Flags);
15139
15140 SDLoc DL(Op);
15141 // The output register of FTSQRT is CR field.
15142 SDValue FTSQRT = DAG.getNode(PPCISD::FTSQRT, DL, MVT::i32, Op, Flags);
15143 // ftsqrt BF,FRB
15144 // Let e_b be the unbiased exponent of the double-precision
15145 // floating-point operand in register FRB.
15146 // fe_flag is set to 1 if either of the following conditions occurs.
15147 // - The double-precision floating-point operand in register FRB is a zero,
15148 // a NaN, or an infinity, or a negative value.
15149 // - e_b is less than or equal to -970.
15150 // Otherwise fe_flag is set to 0.
15151 // Both VSX and non-VSX versions would set EQ bit in the CR if the number is
15152 // not eligible for iteration. (zero/negative/infinity/nan or unbiased
15153 // exponent is less than -970)
15154 SDValue SRIdxVal = DAG.getTargetConstant(PPC::sub_eq, DL, MVT::i32);
15155 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::i1,
15156 FTSQRT, SRIdxVal),
15157 0);
15158}
15159
15160SDValue
15161PPCTargetLowering::getSqrtResultForDenormInput(SDValue Op,
15162 SelectionDAG &DAG) const {
15163 // We only have VSX Vector Square Root.
15164 EVT VT = Op.getValueType();
15165 if (VT != MVT::f64 &&
15166 ((VT != MVT::v2f64 && VT != MVT::v4f32) || !Subtarget.hasVSX()))
15168
15169 return DAG.getNode(PPCISD::FSQRT, SDLoc(Op), VT, Op);
15170}
15171
15172SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
15173 int Enabled, int &RefinementSteps,
15174 bool &UseOneConstNR,
15175 bool Reciprocal) const {
15176 EVT VT = Operand.getValueType();
15177 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
15178 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
15179 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15180 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15181 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15182 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15183
15184 // The Newton-Raphson computation with a single constant does not provide
15185 // enough accuracy on some CPUs.
15186 UseOneConstNR = !Subtarget.needsTwoConstNR();
15187 return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
15188 }
15189 return SDValue();
15190}
15191
15192SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
15193 int Enabled,
15194 int &RefinementSteps) const {
15195 EVT VT = Operand.getValueType();
15196 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
15197 (VT == MVT::f64 && Subtarget.hasFRE()) ||
15198 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
15199 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
15200 if (RefinementSteps == ReciprocalEstimate::Unspecified)
15201 RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
15202 return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
15203 }
15204 return SDValue();
15205}
15206
15208 // Note: This functionality is used only when arcp is enabled, and
15209 // on cores with reciprocal estimates (which are used when arcp is
15210 // enabled for division), this functionality is redundant with the default
15211 // combiner logic (once the division -> reciprocal/multiply transformation
15212 // has taken place). As a result, this matters more for older cores than for
15213 // newer ones.
15214
15215 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
15216 // reciprocal if there are two or more FDIVs (for embedded cores with only
15217 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
15218 switch (Subtarget.getCPUDirective()) {
15219 default:
15220 return 3;
15221 case PPC::DIR_440:
15222 case PPC::DIR_A2:
15223 case PPC::DIR_E500:
15224 case PPC::DIR_E500mc:
15225 case PPC::DIR_E5500:
15226 return 2;
15227 }
15228}
15229
15230// isConsecutiveLSLoc needs to work even if all adds have not yet been
15231// collapsed, and so we need to look through chains of them.
15233 int64_t& Offset, SelectionDAG &DAG) {
15234 if (DAG.isBaseWithConstantOffset(Loc)) {
15235 Base = Loc.getOperand(0);
15236 Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
15237
15238 // The base might itself be a base plus an offset, and if so, accumulate
15239 // that as well.
15240 getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
15241 }
15242}
15243
15245 unsigned Bytes, int Dist,
15246 SelectionDAG &DAG) {
15247 if (VT.getSizeInBits() / 8 != Bytes)
15248 return false;
15249
15250 SDValue BaseLoc = Base->getBasePtr();
15251 if (Loc.getOpcode() == ISD::FrameIndex) {
15252 if (BaseLoc.getOpcode() != ISD::FrameIndex)
15253 return false;
15255 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
15256 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
15257 int FS = MFI.getObjectSize(FI);
15258 int BFS = MFI.getObjectSize(BFI);
15259 if (FS != BFS || FS != (int)Bytes) return false;
15260 return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
15261 }
15262
15263 SDValue Base1 = Loc, Base2 = BaseLoc;
15264 int64_t Offset1 = 0, Offset2 = 0;
15265 getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
15266 getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
15267 if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
15268 return true;
15269
15270 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15271 const GlobalValue *GV1 = nullptr;
15272 const GlobalValue *GV2 = nullptr;
15273 Offset1 = 0;
15274 Offset2 = 0;
15275 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
15276 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
15277 if (isGA1 && isGA2 && GV1 == GV2)
15278 return Offset1 == (Offset2 + Dist*Bytes);
15279 return false;
15280}
15281
15282// Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
15283// not enforce equality of the chain operands.
15285 unsigned Bytes, int Dist,
15286 SelectionDAG &DAG) {
15288 EVT VT = LS->getMemoryVT();
15289 SDValue Loc = LS->getBasePtr();
15290 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
15291 }
15292
15293 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
15294 EVT VT;
15295 switch (N->getConstantOperandVal(1)) {
15296 default: return false;
15297 case Intrinsic::ppc_altivec_lvx:
15298 case Intrinsic::ppc_altivec_lvxl:
15299 case Intrinsic::ppc_vsx_lxvw4x:
15300 case Intrinsic::ppc_vsx_lxvw4x_be:
15301 VT = MVT::v4i32;
15302 break;
15303 case Intrinsic::ppc_vsx_lxvd2x:
15304 case Intrinsic::ppc_vsx_lxvd2x_be:
15305 VT = MVT::v2f64;
15306 break;
15307 case Intrinsic::ppc_altivec_lvebx:
15308 VT = MVT::i8;
15309 break;
15310 case Intrinsic::ppc_altivec_lvehx:
15311 VT = MVT::i16;
15312 break;
15313 case Intrinsic::ppc_altivec_lvewx:
15314 VT = MVT::i32;
15315 break;
15316 }
15317
15318 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
15319 }
15320
15321 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
15322 EVT VT;
15323 switch (N->getConstantOperandVal(1)) {
15324 default: return false;
15325 case Intrinsic::ppc_altivec_stvx:
15326 case Intrinsic::ppc_altivec_stvxl:
15327 case Intrinsic::ppc_vsx_stxvw4x:
15328 VT = MVT::v4i32;
15329 break;
15330 case Intrinsic::ppc_vsx_stxvd2x:
15331 VT = MVT::v2f64;
15332 break;
15333 case Intrinsic::ppc_vsx_stxvw4x_be:
15334 VT = MVT::v4i32;
15335 break;
15336 case Intrinsic::ppc_vsx_stxvd2x_be:
15337 VT = MVT::v2f64;
15338 break;
15339 case Intrinsic::ppc_altivec_stvebx:
15340 VT = MVT::i8;
15341 break;
15342 case Intrinsic::ppc_altivec_stvehx:
15343 VT = MVT::i16;
15344 break;
15345 case Intrinsic::ppc_altivec_stvewx:
15346 VT = MVT::i32;
15347 break;
15348 }
15349
15350 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
15351 }
15352
15353 return false;
15354}
15355
15356// Return true is there is a nearyby consecutive load to the one provided
15357// (regardless of alignment). We search up and down the chain, looking though
15358// token factors and other loads (but nothing else). As a result, a true result
15359// indicates that it is safe to create a new consecutive load adjacent to the
15360// load provided.
15362 SDValue Chain = LD->getChain();
15363 EVT VT = LD->getMemoryVT();
15364
15365 SmallPtrSet<SDNode *, 16> LoadRoots;
15366 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
15368
15369 // First, search up the chain, branching to follow all token-factor operands.
15370 // If we find a consecutive load, then we're done, otherwise, record all
15371 // nodes just above the top-level loads and token factors.
15372 while (!Queue.empty()) {
15373 SDNode *ChainNext = Queue.pop_back_val();
15374 if (!Visited.insert(ChainNext).second)
15375 continue;
15376
15377 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
15378 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15379 return true;
15380
15381 if (!Visited.count(ChainLD->getChain().getNode()))
15382 Queue.push_back(ChainLD->getChain().getNode());
15383 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
15384 for (const SDUse &O : ChainNext->ops())
15385 if (!Visited.count(O.getNode()))
15386 Queue.push_back(O.getNode());
15387 } else
15388 LoadRoots.insert(ChainNext);
15389 }
15390
15391 // Second, search down the chain, starting from the top-level nodes recorded
15392 // in the first phase. These top-level nodes are the nodes just above all
15393 // loads and token factors. Starting with their uses, recursively look though
15394 // all loads (just the chain uses) and token factors to find a consecutive
15395 // load.
15396 Visited.clear();
15397 Queue.clear();
15398
15399 for (SDNode *I : LoadRoots) {
15400 Queue.push_back(I);
15401
15402 while (!Queue.empty()) {
15403 SDNode *LoadRoot = Queue.pop_back_val();
15404 if (!Visited.insert(LoadRoot).second)
15405 continue;
15406
15407 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
15408 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
15409 return true;
15410
15411 for (SDNode *U : LoadRoot->users())
15412 if (((isa<MemSDNode>(U) &&
15413 cast<MemSDNode>(U)->getChain().getNode() == LoadRoot) ||
15414 U->getOpcode() == ISD::TokenFactor) &&
15415 !Visited.count(U))
15416 Queue.push_back(U);
15417 }
15418 }
15419
15420 return false;
15421}
15422
15423/// This function is called when we have proved that a SETCC node can be replaced
15424/// by subtraction (and other supporting instructions) so that the result of
15425/// comparison is kept in a GPR instead of CR. This function is purely for
15426/// codegen purposes and has some flags to guide the codegen process.
15427static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
15428 bool Swap, SDLoc &DL, SelectionDAG &DAG) {
15429 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15430
15431 // Zero extend the operands to the largest legal integer. Originally, they
15432 // must be of a strictly smaller size.
15433 auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0));
15434 auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
15435
15436 // Swap if needed. Depends on the condition code.
15437 if (Swap)
15438 std::swap(Op0, Op1);
15439
15440 // Subtract extended integers.
15441 auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
15442
15443 // Move the sign bit to the least significant position and zero out the rest.
15444 // Now the least significant bit carries the result of original comparison.
15445 auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
15446 DAG.getConstant(Size - 1, DL, MVT::i32));
15447 auto Final = Shifted;
15448
15449 // Complement the result if needed. Based on the condition code.
15450 if (Complement)
15451 Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
15452 DAG.getConstant(1, DL, MVT::i64));
15453
15454 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
15455}
15456
15457SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
15458 DAGCombinerInfo &DCI) const {
15459 assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
15460
15461 SelectionDAG &DAG = DCI.DAG;
15462 SDLoc DL(N);
15463
15464 // Size of integers being compared has a critical role in the following
15465 // analysis, so we prefer to do this when all types are legal.
15466 if (!DCI.isAfterLegalizeDAG())
15467 return SDValue();
15468
15469 // If all users of SETCC extend its value to a legal integer type
15470 // then we replace SETCC with a subtraction
15471 for (const SDNode *U : N->users())
15472 if (U->getOpcode() != ISD::ZERO_EXTEND)
15473 return SDValue();
15474
15475 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
15476 auto OpSize = N->getOperand(0).getValueSizeInBits();
15477
15479
15480 if (OpSize < Size) {
15481 switch (CC) {
15482 default: break;
15483 case ISD::SETULT:
15484 return generateEquivalentSub(N, Size, false, false, DL, DAG);
15485 case ISD::SETULE:
15486 return generateEquivalentSub(N, Size, true, true, DL, DAG);
15487 case ISD::SETUGT:
15488 return generateEquivalentSub(N, Size, false, true, DL, DAG);
15489 case ISD::SETUGE:
15490 return generateEquivalentSub(N, Size, true, false, DL, DAG);
15491 }
15492 }
15493
15494 return SDValue();
15495}
15496
15497SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
15498 DAGCombinerInfo &DCI) const {
15499 SelectionDAG &DAG = DCI.DAG;
15500 SDLoc dl(N);
15501
15502 assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
15503 // If we're tracking CR bits, we need to be careful that we don't have:
15504 // trunc(binary-ops(zext(x), zext(y)))
15505 // or
15506 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
15507 // such that we're unnecessarily moving things into GPRs when it would be
15508 // better to keep them in CR bits.
15509
15510 // Note that trunc here can be an actual i1 trunc, or can be the effective
15511 // truncation that comes from a setcc or select_cc.
15512 if (N->getOpcode() == ISD::TRUNCATE &&
15513 N->getValueType(0) != MVT::i1)
15514 return SDValue();
15515
15516 if (N->getOperand(0).getValueType() != MVT::i32 &&
15517 N->getOperand(0).getValueType() != MVT::i64)
15518 return SDValue();
15519
15520 if (N->getOpcode() == ISD::SETCC ||
15521 N->getOpcode() == ISD::SELECT_CC) {
15522 // If we're looking at a comparison, then we need to make sure that the
15523 // high bits (all except for the first) don't matter the result.
15525 cast<CondCodeSDNode>(N->getOperand(
15526 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
15527 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
15528
15530 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
15531 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
15532 return SDValue();
15533 } else if (ISD::isUnsignedIntSetCC(CC)) {
15534 if (!DAG.MaskedValueIsZero(N->getOperand(0),
15535 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
15536 !DAG.MaskedValueIsZero(N->getOperand(1),
15537 APInt::getHighBitsSet(OpBits, OpBits-1)))
15538 return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
15539 : SDValue());
15540 } else {
15541 // This is neither a signed nor an unsigned comparison, just make sure
15542 // that the high bits are equal.
15543 KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
15544 KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
15545
15546 // We don't really care about what is known about the first bit (if
15547 // anything), so pretend that it is known zero for both to ensure they can
15548 // be compared as constants.
15549 Op1Known.Zero.setBit(0); Op1Known.One.clearBit(0);
15550 Op2Known.Zero.setBit(0); Op2Known.One.clearBit(0);
15551
15552 if (!Op1Known.isConstant() || !Op2Known.isConstant() ||
15553 Op1Known.getConstant() != Op2Known.getConstant())
15554 return SDValue();
15555 }
15556 }
15557
15558 // We now know that the higher-order bits are irrelevant, we just need to
15559 // make sure that all of the intermediate operations are bit operations, and
15560 // all inputs are extensions.
15561 if (N->getOperand(0).getOpcode() != ISD::AND &&
15562 N->getOperand(0).getOpcode() != ISD::OR &&
15563 N->getOperand(0).getOpcode() != ISD::XOR &&
15564 N->getOperand(0).getOpcode() != ISD::SELECT &&
15565 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
15566 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
15567 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
15568 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
15569 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
15570 return SDValue();
15571
15572 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
15573 N->getOperand(1).getOpcode() != ISD::AND &&
15574 N->getOperand(1).getOpcode() != ISD::OR &&
15575 N->getOperand(1).getOpcode() != ISD::XOR &&
15576 N->getOperand(1).getOpcode() != ISD::SELECT &&
15577 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
15578 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
15579 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
15580 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
15581 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
15582 return SDValue();
15583
15585 SmallVector<SDValue, 8> BinOps, PromOps;
15586 SmallPtrSet<SDNode *, 16> Visited;
15587
15588 for (unsigned i = 0; i < 2; ++i) {
15589 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15590 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15591 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15592 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15593 isa<ConstantSDNode>(N->getOperand(i)))
15594 Inputs.push_back(N->getOperand(i));
15595 else
15596 BinOps.push_back(N->getOperand(i));
15597
15598 if (N->getOpcode() == ISD::TRUNCATE)
15599 break;
15600 }
15601
15602 // Visit all inputs, collect all binary operations (and, or, xor and
15603 // select) that are all fed by extensions.
15604 while (!BinOps.empty()) {
15605 SDValue BinOp = BinOps.pop_back_val();
15606
15607 if (!Visited.insert(BinOp.getNode()).second)
15608 continue;
15609
15610 PromOps.push_back(BinOp);
15611
15612 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15613 // The condition of the select is not promoted.
15614 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15615 continue;
15616 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15617 continue;
15618
15619 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15620 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15621 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
15622 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
15623 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15624 Inputs.push_back(BinOp.getOperand(i));
15625 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15626 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15627 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15628 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15629 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
15630 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15631 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
15632 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
15633 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
15634 BinOps.push_back(BinOp.getOperand(i));
15635 } else {
15636 // We have an input that is not an extension or another binary
15637 // operation; we'll abort this transformation.
15638 return SDValue();
15639 }
15640 }
15641 }
15642
15643 // Make sure that this is a self-contained cluster of operations (which
15644 // is not quite the same thing as saying that everything has only one
15645 // use).
15646 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15647 if (isa<ConstantSDNode>(Inputs[i]))
15648 continue;
15649
15650 for (const SDNode *User : Inputs[i].getNode()->users()) {
15651 if (User != N && !Visited.count(User))
15652 return SDValue();
15653
15654 // Make sure that we're not going to promote the non-output-value
15655 // operand(s) or SELECT or SELECT_CC.
15656 // FIXME: Although we could sometimes handle this, and it does occur in
15657 // practice that one of the condition inputs to the select is also one of
15658 // the outputs, we currently can't deal with this.
15659 if (User->getOpcode() == ISD::SELECT) {
15660 if (User->getOperand(0) == Inputs[i])
15661 return SDValue();
15662 } else if (User->getOpcode() == ISD::SELECT_CC) {
15663 if (User->getOperand(0) == Inputs[i] ||
15664 User->getOperand(1) == Inputs[i])
15665 return SDValue();
15666 }
15667 }
15668 }
15669
15670 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15671 for (const SDNode *User : PromOps[i].getNode()->users()) {
15672 if (User != N && !Visited.count(User))
15673 return SDValue();
15674
15675 // Make sure that we're not going to promote the non-output-value
15676 // operand(s) or SELECT or SELECT_CC.
15677 // FIXME: Although we could sometimes handle this, and it does occur in
15678 // practice that one of the condition inputs to the select is also one of
15679 // the outputs, we currently can't deal with this.
15680 if (User->getOpcode() == ISD::SELECT) {
15681 if (User->getOperand(0) == PromOps[i])
15682 return SDValue();
15683 } else if (User->getOpcode() == ISD::SELECT_CC) {
15684 if (User->getOperand(0) == PromOps[i] ||
15685 User->getOperand(1) == PromOps[i])
15686 return SDValue();
15687 }
15688 }
15689 }
15690
15691 // Replace all inputs with the extension operand.
15692 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15693 // Constants may have users outside the cluster of to-be-promoted nodes,
15694 // and so we need to replace those as we do the promotions.
15695 if (isa<ConstantSDNode>(Inputs[i]))
15696 continue;
15697 else
15698 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
15699 }
15700
15701 std::list<HandleSDNode> PromOpHandles;
15702 for (auto &PromOp : PromOps)
15703 PromOpHandles.emplace_back(PromOp);
15704
15705 // Replace all operations (these are all the same, but have a different
15706 // (i1) return type). DAG.getNode will validate that the types of
15707 // a binary operator match, so go through the list in reverse so that
15708 // we've likely promoted both operands first. Any intermediate truncations or
15709 // extensions disappear.
15710 while (!PromOpHandles.empty()) {
15711 SDValue PromOp = PromOpHandles.back().getValue();
15712 PromOpHandles.pop_back();
15713
15714 if (PromOp.getOpcode() == ISD::TRUNCATE ||
15715 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
15716 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
15717 PromOp.getOpcode() == ISD::ANY_EXTEND) {
15718 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
15719 PromOp.getOperand(0).getValueType() != MVT::i1) {
15720 // The operand is not yet ready (see comment below).
15721 PromOpHandles.emplace_front(PromOp);
15722 continue;
15723 }
15724
15725 SDValue RepValue = PromOp.getOperand(0);
15726 if (isa<ConstantSDNode>(RepValue))
15727 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
15728
15729 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
15730 continue;
15731 }
15732
15733 unsigned C;
15734 switch (PromOp.getOpcode()) {
15735 default: C = 0; break;
15736 case ISD::SELECT: C = 1; break;
15737 case ISD::SELECT_CC: C = 2; break;
15738 }
15739
15740 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15741 PromOp.getOperand(C).getValueType() != MVT::i1) ||
15742 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15743 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
15744 // The to-be-promoted operands of this node have not yet been
15745 // promoted (this should be rare because we're going through the
15746 // list backward, but if one of the operands has several users in
15747 // this cluster of to-be-promoted nodes, it is possible).
15748 PromOpHandles.emplace_front(PromOp);
15749 continue;
15750 }
15751
15753
15754 // If there are any constant inputs, make sure they're replaced now.
15755 for (unsigned i = 0; i < 2; ++i)
15756 if (isa<ConstantSDNode>(Ops[C+i]))
15757 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
15758
15759 DAG.ReplaceAllUsesOfValueWith(PromOp,
15760 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
15761 }
15762
15763 // Now we're left with the initial truncation itself.
15764 if (N->getOpcode() == ISD::TRUNCATE)
15765 return N->getOperand(0);
15766
15767 // Otherwise, this is a comparison. The operands to be compared have just
15768 // changed type (to i1), but everything else is the same.
15769 return SDValue(N, 0);
15770}
15771
15772SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
15773 DAGCombinerInfo &DCI) const {
15774 SelectionDAG &DAG = DCI.DAG;
15775 SDLoc dl(N);
15776
15777 // If we're tracking CR bits, we need to be careful that we don't have:
15778 // zext(binary-ops(trunc(x), trunc(y)))
15779 // or
15780 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
15781 // such that we're unnecessarily moving things into CR bits that can more
15782 // efficiently stay in GPRs. Note that if we're not certain that the high
15783 // bits are set as required by the final extension, we still may need to do
15784 // some masking to get the proper behavior.
15785
15786 // This same functionality is important on PPC64 when dealing with
15787 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
15788 // the return values of functions. Because it is so similar, it is handled
15789 // here as well.
15790
15791 if (N->getValueType(0) != MVT::i32 &&
15792 N->getValueType(0) != MVT::i64)
15793 return SDValue();
15794
15795 if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
15796 (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
15797 return SDValue();
15798
15799 if (N->getOperand(0).getOpcode() != ISD::AND &&
15800 N->getOperand(0).getOpcode() != ISD::OR &&
15801 N->getOperand(0).getOpcode() != ISD::XOR &&
15802 N->getOperand(0).getOpcode() != ISD::SELECT &&
15803 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
15804 return SDValue();
15805
15807 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
15808 SmallPtrSet<SDNode *, 16> Visited;
15809
15810 // Visit all inputs, collect all binary operations (and, or, xor and
15811 // select) that are all fed by truncations.
15812 while (!BinOps.empty()) {
15813 SDValue BinOp = BinOps.pop_back_val();
15814
15815 if (!Visited.insert(BinOp.getNode()).second)
15816 continue;
15817
15818 PromOps.push_back(BinOp);
15819
15820 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
15821 // The condition of the select is not promoted.
15822 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
15823 continue;
15824 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
15825 continue;
15826
15827 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
15828 isa<ConstantSDNode>(BinOp.getOperand(i))) {
15829 Inputs.push_back(BinOp.getOperand(i));
15830 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
15831 BinOp.getOperand(i).getOpcode() == ISD::OR ||
15832 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
15833 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
15834 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
15835 BinOps.push_back(BinOp.getOperand(i));
15836 } else {
15837 // We have an input that is not a truncation or another binary
15838 // operation; we'll abort this transformation.
15839 return SDValue();
15840 }
15841 }
15842 }
15843
15844 // The operands of a select that must be truncated when the select is
15845 // promoted because the operand is actually part of the to-be-promoted set.
15846 DenseMap<SDNode *, EVT> SelectTruncOp[2];
15847
15848 // Make sure that this is a self-contained cluster of operations (which
15849 // is not quite the same thing as saying that everything has only one
15850 // use).
15851 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15852 if (isa<ConstantSDNode>(Inputs[i]))
15853 continue;
15854
15855 for (SDNode *User : Inputs[i].getNode()->users()) {
15856 if (User != N && !Visited.count(User))
15857 return SDValue();
15858
15859 // If we're going to promote the non-output-value operand(s) or SELECT or
15860 // SELECT_CC, record them for truncation.
15861 if (User->getOpcode() == ISD::SELECT) {
15862 if (User->getOperand(0) == Inputs[i])
15863 SelectTruncOp[0].insert(std::make_pair(User,
15864 User->getOperand(0).getValueType()));
15865 } else if (User->getOpcode() == ISD::SELECT_CC) {
15866 if (User->getOperand(0) == Inputs[i])
15867 SelectTruncOp[0].insert(std::make_pair(User,
15868 User->getOperand(0).getValueType()));
15869 if (User->getOperand(1) == Inputs[i])
15870 SelectTruncOp[1].insert(std::make_pair(User,
15871 User->getOperand(1).getValueType()));
15872 }
15873 }
15874 }
15875
15876 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
15877 for (SDNode *User : PromOps[i].getNode()->users()) {
15878 if (User != N && !Visited.count(User))
15879 return SDValue();
15880
15881 // If we're going to promote the non-output-value operand(s) or SELECT or
15882 // SELECT_CC, record them for truncation.
15883 if (User->getOpcode() == ISD::SELECT) {
15884 if (User->getOperand(0) == PromOps[i])
15885 SelectTruncOp[0].insert(std::make_pair(User,
15886 User->getOperand(0).getValueType()));
15887 } else if (User->getOpcode() == ISD::SELECT_CC) {
15888 if (User->getOperand(0) == PromOps[i])
15889 SelectTruncOp[0].insert(std::make_pair(User,
15890 User->getOperand(0).getValueType()));
15891 if (User->getOperand(1) == PromOps[i])
15892 SelectTruncOp[1].insert(std::make_pair(User,
15893 User->getOperand(1).getValueType()));
15894 }
15895 }
15896 }
15897
15898 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
15899 bool ReallyNeedsExt = false;
15900 if (N->getOpcode() != ISD::ANY_EXTEND) {
15901 // If all of the inputs are not already sign/zero extended, then
15902 // we'll still need to do that at the end.
15903 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15904 if (isa<ConstantSDNode>(Inputs[i]))
15905 continue;
15906
15907 unsigned OpBits =
15908 Inputs[i].getOperand(0).getValueSizeInBits();
15909 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
15910
15911 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
15912 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
15913 APInt::getHighBitsSet(OpBits,
15914 OpBits-PromBits))) ||
15915 (N->getOpcode() == ISD::SIGN_EXTEND &&
15916 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
15917 (OpBits-(PromBits-1)))) {
15918 ReallyNeedsExt = true;
15919 break;
15920 }
15921 }
15922 }
15923
15924 // Convert PromOps to handles before doing any RAUW operations, as these
15925 // may CSE with existing nodes, deleting the originals.
15926 std::list<HandleSDNode> PromOpHandles;
15927 for (auto &PromOp : PromOps)
15928 PromOpHandles.emplace_back(PromOp);
15929
15930 // Replace all inputs, either with the truncation operand, or a
15931 // truncation or extension to the final output type.
15932 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
15933 // Constant inputs need to be replaced with the to-be-promoted nodes that
15934 // use them because they might have users outside of the cluster of
15935 // promoted nodes.
15936 if (isa<ConstantSDNode>(Inputs[i]))
15937 continue;
15938
15939 SDValue InSrc = Inputs[i].getOperand(0);
15940 if (Inputs[i].getValueType() == N->getValueType(0))
15941 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
15942 else if (N->getOpcode() == ISD::SIGN_EXTEND)
15943 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15944 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
15945 else if (N->getOpcode() == ISD::ZERO_EXTEND)
15946 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15947 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
15948 else
15949 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
15950 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
15951 }
15952
15953 // Replace all operations (these are all the same, but have a different
15954 // (promoted) return type). DAG.getNode will validate that the types of
15955 // a binary operator match, so go through the list in reverse so that
15956 // we've likely promoted both operands first.
15957 while (!PromOpHandles.empty()) {
15958 SDValue PromOp = PromOpHandles.back().getValue();
15959 PromOpHandles.pop_back();
15960
15961 unsigned C;
15962 switch (PromOp.getOpcode()) {
15963 default: C = 0; break;
15964 case ISD::SELECT: C = 1; break;
15965 case ISD::SELECT_CC: C = 2; break;
15966 }
15967
15968 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
15969 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
15970 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
15971 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
15972 // The to-be-promoted operands of this node have not yet been
15973 // promoted (this should be rare because we're going through the
15974 // list backward, but if one of the operands has several users in
15975 // this cluster of to-be-promoted nodes, it is possible).
15976 PromOpHandles.emplace_front(PromOp);
15977 continue;
15978 }
15979
15980 // For SELECT and SELECT_CC nodes, we do a similar check for any
15981 // to-be-promoted comparison inputs.
15982 if (PromOp.getOpcode() == ISD::SELECT ||
15983 PromOp.getOpcode() == ISD::SELECT_CC) {
15984 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
15985 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
15986 (SelectTruncOp[1].count(PromOp.getNode()) &&
15987 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
15988 PromOpHandles.emplace_front(PromOp);
15989 continue;
15990 }
15991 }
15992
15994
15995 // If this node has constant inputs, then they'll need to be promoted here.
15996 for (unsigned i = 0; i < 2; ++i) {
15997 if (!isa<ConstantSDNode>(Ops[C+i]))
15998 continue;
15999 if (Ops[C+i].getValueType() == N->getValueType(0))
16000 continue;
16001
16002 if (N->getOpcode() == ISD::SIGN_EXTEND)
16003 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
16004 else if (N->getOpcode() == ISD::ZERO_EXTEND)
16005 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
16006 else
16007 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
16008 }
16009
16010 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
16011 // truncate them again to the original value type.
16012 if (PromOp.getOpcode() == ISD::SELECT ||
16013 PromOp.getOpcode() == ISD::SELECT_CC) {
16014 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
16015 if (SI0 != SelectTruncOp[0].end())
16016 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
16017 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
16018 if (SI1 != SelectTruncOp[1].end())
16019 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
16020 }
16021
16022 DAG.ReplaceAllUsesOfValueWith(PromOp,
16023 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
16024 }
16025
16026 // Now we're left with the initial extension itself.
16027 if (!ReallyNeedsExt)
16028 return N->getOperand(0);
16029
16030 // To zero extend, just mask off everything except for the first bit (in the
16031 // i1 case).
16032 if (N->getOpcode() == ISD::ZERO_EXTEND)
16033 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
16035 N->getValueSizeInBits(0), PromBits),
16036 dl, N->getValueType(0)));
16037
16038 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
16039 "Invalid extension type");
16040 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
16041 SDValue ShiftCst =
16042 DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
16043 return DAG.getNode(
16044 ISD::SRA, dl, N->getValueType(0),
16045 DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
16046 ShiftCst);
16047}
16048
16049// The function check a i128 load can convert to 16i8 load for Vcmpequb.
16050static bool canConvertToVcmpequb(SDValue &LHS, SDValue &RHS, bool IsPPC64) {
16051
16052 auto isValidForConvert = [IsPPC64](SDValue &Operand) {
16053 if (!Operand.hasOneUse())
16054 return false;
16055
16056 if (Operand.getValueType() != MVT::i128)
16057 return false;
16058
16059 if (Operand.getOpcode() == ISD::Constant) {
16060 auto *C = cast<ConstantSDNode>(Operand);
16061 const APInt &Val = C->getAPIntValue();
16062 // On PPC64, comparing an i128 value loaded from memory against a
16063 // constant smaller than 2^16 is usually better left to scalar lowering.
16064 // In that case, the compare can be lowered using xori (since xori has a
16065 // 16-bit immediate field), which is cheaper than materializing a vector
16066 // constant and using vcmpequb.
16067 if (IsPPC64 && Val.ult(1ULL << 16))
16068 return false;
16069 return true;
16070 }
16071
16072 auto *LoadNode = dyn_cast<LoadSDNode>(Operand);
16073 if (!LoadNode)
16074 return false;
16075
16076 // If memory operation is volatile, do not perform any
16077 // optimization or transformation. Volatile operations must be preserved
16078 // as written to ensure correct program behavior, so we return an empty
16079 // SDValue to indicate no action.
16080
16081 if (LoadNode->isVolatile())
16082 return false;
16083
16084 // Only combine loads if both use the unindexed addressing mode.
16085 // PowerPC AltiVec/VMX does not support vector loads or stores with
16086 // pre/post-increment addressing. Indexed modes may imply implicit
16087 // pointer updates, which are not compatible with AltiVec vector
16088 // instructions.
16089 if (LoadNode->getAddressingMode() != ISD::UNINDEXED)
16090 return false;
16091
16092 // Only combine loads if both are non-extending loads
16093 // (ISD::NON_EXTLOAD). Extending loads (such as ISD::ZEXTLOAD or
16094 // ISD::SEXTLOAD) perform zero or sign extension, which may change the
16095 // loaded value's semantics and are not compatible with vector loads.
16096 if (LoadNode->getExtensionType() != ISD::NON_EXTLOAD)
16097 return false;
16098
16099 return true;
16100 };
16101
16102 return (isValidForConvert(LHS) && isValidForConvert(RHS));
16103}
16104
16106 const SDLoc &DL) {
16107
16108 assert(N->getOpcode() == ISD::SETCC && "Should be called with a SETCC node");
16109
16110 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16111 assert((CC == ISD::SETNE || CC == ISD::SETEQ) &&
16112 "CC mus be ISD::SETNE or ISD::SETEQ");
16113
16114 auto getV16i8Load = [&](const SDValue &Operand) {
16115 if (Operand.getOpcode() == ISD::Constant)
16116 return DAG.getBitcast(MVT::v16i8, Operand);
16117
16118 assert(Operand.getOpcode() == ISD::LOAD && "Must be LoadSDNode here.");
16119
16120 auto *LoadNode = cast<LoadSDNode>(Operand);
16121 // Create a new MachineMemOperand without range metadata.
16122 // Range metadata is only valid for integer scalar types, not vectors.
16123 // The original i128 load may have range metadata, but when we convert
16124 // to v16i8, that metadata is no longer semantically valid.
16125 MachineMemOperand *MMO = LoadNode->getMemOperand();
16128 MMO->getPointerInfo(), MMO->getFlags(), MMO->getSize(), MMO->getAlign(),
16129 MMO->getAAInfo(), MMO->getSyncScopeID(), MMO->getSuccessOrdering(),
16130 MMO->getFailureOrdering());
16131 SDValue NewLoad = DAG.getLoad(MVT::v16i8, DL, LoadNode->getChain(),
16132 LoadNode->getBasePtr(), NewMMO);
16133 DAG.ReplaceAllUsesOfValueWith(SDValue(LoadNode, 1), NewLoad.getValue(1));
16134 return NewLoad;
16135 };
16136
16137 // Following code transforms the DAG
16138 // t0: ch,glue = EntryToken
16139 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16140 // t3: i128,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16141 // undef:i64
16142 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16143 // t5: i128,ch =
16144 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64 t6: i1 =
16145 // setcc t3, t5, setne:ch
16146 //
16147 // ---->
16148 //
16149 // t0: ch,glue = EntryToken
16150 // t2: i64,ch = CopyFromReg t0, Register:i64 %0
16151 // t3: v16i8,ch = load<(load (s128) from %ir.a, align 1)> t0, t2,
16152 // undef:i64
16153 // t4: i64,ch = CopyFromReg t0, Register:i64 %1
16154 // t5: v16i8,ch =
16155 // load<(load (s128) from %ir.b, align 1)> t0, t4, undef:i64
16156 // t6: i32 =
16157 // llvm.ppc.altivec.vcmpequb.p TargetConstant:i32<10505>,
16158 // Constant:i32<2>, t3, t5
16159 // t7: i1 = setcc t6, Constant:i32<0>, seteq:ch
16160
16161 // Or transforms the DAG
16162 // t5: i128,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16163 // t8: i1 =
16164 // setcc Constant:i128<237684487579686500932345921536>, t5, setne:ch
16165 //
16166 // --->
16167 //
16168 // t5: v16i8,ch = load<(load (s128) from %ir.X, align 1)> t0, t2, undef:i64
16169 // t6: v16i8 = bitcast Constant:i128<237684487579686500932345921536>
16170 // t7: i32 =
16171 // llvm.ppc.altivec.vcmpequb.p Constant:i32<10962>, Constant:i32<2>, t5, t2
16172
16173 SDValue LHSVec = getV16i8Load(N->getOperand(0));
16174 SDValue RHSVec = getV16i8Load(N->getOperand(1));
16175
16176 SDValue IntrID =
16177 DAG.getConstant(Intrinsic::ppc_altivec_vcmpequb_p, DL, MVT::i32);
16178 SDValue CRSel = DAG.getConstant(2, DL, MVT::i32); // which CR6 predicate field
16179 SDValue PredResult = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
16180 IntrID, CRSel, LHSVec, RHSVec);
16181 // ppc_altivec_vcmpequb_p returns 1 when two vectors are the same,
16182 // so we need to invert the CC opcode.
16183 return DAG.getSetCC(DL, N->getValueType(0), PredResult,
16184 DAG.getConstant(0, DL, MVT::i32),
16186}
16187
16188// Detect whether there is a pattern like (setcc (and X, 1), 0, eq).
16189// If it is , return true; otherwise return false.
16191 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16192
16193 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16194 if (CC != ISD::SETEQ)
16195 return false;
16196
16197 SDValue LHS = N->getOperand(0);
16198 SDValue RHS = N->getOperand(1);
16199
16200 // Check the `SDValue &V` is from `and` with `1`.
16201 auto IsAndWithOne = [](SDValue &V) {
16202 if (V.getOpcode() == ISD::AND) {
16203 for (const SDValue &Op : V->ops())
16204 if (auto *C = dyn_cast<ConstantSDNode>(Op))
16205 if (C->isOne())
16206 return true;
16207 }
16208 return false;
16209 };
16210
16211 // Check whether the SETCC compare with zero.
16212 auto IsCompareWithZero = [](SDValue &V) {
16213 if (auto *C = dyn_cast<ConstantSDNode>(V))
16214 if (C->isZero())
16215 return true;
16216 return false;
16217 };
16218
16219 return (IsAndWithOne(LHS) && IsCompareWithZero(RHS)) ||
16220 (IsAndWithOne(RHS) && IsCompareWithZero(LHS));
16221}
16222
16223// You must check whether the `SDNode* N` can be converted to Xori using
16224// the function `static bool canConvertSETCCToXori(SDNode *N)`
16225// before calling the function; otherwise, it may produce incorrect results.
16227
16228 assert(N->getOpcode() == ISD::SETCC && "Should be SETCC SDNode here.");
16229 SDValue LHS = N->getOperand(0);
16230 SDValue RHS = N->getOperand(1);
16231 SDLoc DL(N);
16232
16233 [[maybe_unused]] ISD::CondCode CC =
16234 cast<CondCodeSDNode>(N->getOperand(2))->get();
16235 assert((CC == ISD::SETEQ) && "CC must be ISD::SETEQ.");
16236 // Rewrite it as XORI (and X, 1), 1.
16237 auto MakeXor1 = [&](SDValue V) {
16238 EVT VT = V.getValueType();
16239 SDValue One = DAG.getConstant(1, DL, VT);
16240 SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, V, One);
16241 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Xor);
16242 };
16243
16244 if (LHS.getOpcode() == ISD::AND && RHS.getOpcode() != ISD::AND)
16245 return MakeXor1(LHS);
16246
16247 if (RHS.getOpcode() == ISD::AND && LHS.getOpcode() != ISD::AND)
16248 return MakeXor1(RHS);
16249
16250 llvm_unreachable("Should not reach here.");
16251}
16252
16253// Match `sext(setcc X, 0, eq)` and turn it into an ADDIC/SUBFE sequence.
16254//
16255// This generates code for:
16256// X == 0 ? -1 : 0
16257//
16258// On pre-ISA 3.1 targets, this is better than the longer CNTLZW/SRWI/NEG
16259// sequence. This is useful for cases like:
16260// uint8_t f(uint8_t x) { return (x == 0) ? -1 : 0; }
16261//
16262// ISA 3.1+ is skipped because those targets can use SETBC.
16263
16264SDValue PPCTargetLowering::combineSignExtendSetCC(SDNode *N,
16265 DAGCombinerInfo &DCI) const {
16266 if (Subtarget.isISA3_1())
16267 return SDValue();
16268
16269 EVT VT = N->getValueType(0);
16270 if (VT != MVT::i32 && (VT != MVT::i64 || !Subtarget.isPPC64()))
16271 return SDValue();
16272
16273 SDValue N0 = N->getOperand(0);
16274 if (N0.getOpcode() != ISD::SETCC)
16275 return SDValue();
16276
16278 SDValue LHS = N0.getOperand(0);
16279 SDValue RHS = N0.getOperand(1);
16280
16281 // Not match: sext (setcc x, 0, eq) or sext (setcc 0, x, eq)
16282 if (CC != ISD::SETEQ || (!isNullConstant(LHS) && !isNullConstant(RHS)))
16283 return SDValue();
16284
16285 SDLoc dl(N);
16286 SelectionDAG &DAG = DCI.DAG;
16287 SDValue X = isNullConstant(LHS) ? RHS : LHS;
16288 EVT XVT = X.getValueType(); // The type of x in the setcc x, 0, eq.
16289
16290 // The type that ADDC/SUBE operate on. Reject larger types and zero-extend
16291 // smaller ones.
16292 MVT OpVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
16293 if (XVT.bitsGT(OpVT))
16294 return SDValue();
16295
16296 if (XVT.bitsLT(OpVT))
16297 X = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, X);
16298
16299 // Generate: SUBFE(ADDC(X, -1)).
16300 SDValue MinusOne = DAG.getAllOnesConstant(dl, OpVT);
16301 SDValue Addc =
16302 DAG.getNode(PPCISD::ADDC, dl, DAG.getVTList(OpVT, MVT::i32), X, MinusOne);
16303 SDValue Carry = Addc.getValue(1);
16304 SDValue Sube = DAG.getNode(PPCISD::SUBE, dl, DAG.getVTList(OpVT, MVT::i32),
16305 Addc, Addc, Carry);
16306
16307 // Truncate back to i32 if we used i64 operations.
16308 if (OpVT == MVT::i64 && VT == MVT::i32)
16309 return DAG.getNode(ISD::TRUNCATE, dl, VT, Sube);
16310
16311 return Sube;
16312}
16313
16314SDValue PPCTargetLowering::combineSetCC(SDNode *N,
16315 DAGCombinerInfo &DCI) const {
16316 assert(N->getOpcode() == ISD::SETCC &&
16317 "Should be called with a SETCC node");
16318
16319 // Check if the pattern (setcc (and X, 1), 0, eq) is present.
16320 // If it is, rewrite it as XORI (and X, 1), 1.
16322 return ConvertSETCCToXori(N, DCI.DAG);
16323
16324 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
16325 if (CC == ISD::SETNE || CC == ISD::SETEQ) {
16326 SDValue LHS = N->getOperand(0);
16327 SDValue RHS = N->getOperand(1);
16328
16329 // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
16330 if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
16331 LHS.hasOneUse())
16332 std::swap(LHS, RHS);
16333
16334 // x == 0-y --> x+y == 0
16335 // x != 0-y --> x+y != 0
16336 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
16337 RHS.hasOneUse()) {
16338 SDLoc DL(N);
16339 SelectionDAG &DAG = DCI.DAG;
16340 EVT VT = N->getValueType(0);
16341 EVT OpVT = LHS.getValueType();
16342 SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
16343 return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
16344 }
16345
16346 // Optimization: Fold i128 equality/inequality compares of two loads into a
16347 // vectorized compare using vcmpequb.p when Altivec is available.
16348 //
16349 // Rationale:
16350 // A scalar i128 SETCC (eq/ne) normally lowers to multiple scalar ops.
16351 // On VSX-capable subtargets, we can instead reinterpret the i128 loads
16352 // as v16i8 vectors and use the Altive vcmpequb.p instruction to
16353 // perform a full 128-bit equality check in a single vector compare.
16354 //
16355 // Example Result:
16356 // This transformation replaces memcmp(a, b, 16) with two vector loads
16357 // and one vector compare instruction.
16358
16359 if (Subtarget.hasAltivec() &&
16360 canConvertToVcmpequb(LHS, RHS, Subtarget.isPPC64()))
16361 return convertTwoLoadsAndCmpToVCMPEQUB(DCI.DAG, N, SDLoc(N));
16362 }
16363
16364 return DAGCombineTruncBoolExt(N, DCI);
16365}
16366
16367// Is this an extending load from an f32 to an f64?
16368static bool isFPExtLoad(SDValue Op) {
16369 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
16370 return LD->getExtensionType() == ISD::EXTLOAD &&
16371 Op.getValueType() == MVT::f64;
16372 return false;
16373}
16374
16375/// Reduces the number of fp-to-int conversion when building a vector.
16376///
16377/// If this vector is built out of floating to integer conversions,
16378/// transform it to a vector built out of floating point values followed by a
16379/// single floating to integer conversion of the vector.
16380/// Namely (build_vector (fptosi $A), (fptosi $B), ...)
16381/// becomes (fptosi (build_vector ($A, $B, ...)))
16382SDValue PPCTargetLowering::
16383combineElementTruncationToVectorTruncation(SDNode *N,
16384 DAGCombinerInfo &DCI) const {
16385 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16386 "Should be called with a BUILD_VECTOR node");
16387
16388 SelectionDAG &DAG = DCI.DAG;
16389 SDLoc dl(N);
16390
16391 SDValue FirstInput = N->getOperand(0);
16392 assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
16393 "The input operand must be an fp-to-int conversion.");
16394
16395 // This combine happens after legalization so the fp_to_[su]i nodes are
16396 // already converted to PPCSISD nodes.
16397 unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
16398 if (FirstConversion == PPCISD::FCTIDZ ||
16399 FirstConversion == PPCISD::FCTIDUZ ||
16400 FirstConversion == PPCISD::FCTIWZ ||
16401 FirstConversion == PPCISD::FCTIWUZ) {
16402 bool IsSplat = true;
16403 bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
16404 FirstConversion == PPCISD::FCTIWUZ;
16405 EVT SrcVT = FirstInput.getOperand(0).getValueType();
16407 EVT TargetVT = N->getValueType(0);
16408 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16409 SDValue NextOp = N->getOperand(i);
16410 if (NextOp.getOpcode() != PPCISD::MFVSR)
16411 return SDValue();
16412 unsigned NextConversion = NextOp.getOperand(0).getOpcode();
16413 if (NextConversion != FirstConversion)
16414 return SDValue();
16415 // If we are converting to 32-bit integers, we need to add an FP_ROUND.
16416 // This is not valid if the input was originally double precision. It is
16417 // also not profitable to do unless this is an extending load in which
16418 // case doing this combine will allow us to combine consecutive loads.
16419 if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
16420 return SDValue();
16421 if (N->getOperand(i) != FirstInput)
16422 IsSplat = false;
16423 }
16424
16425 // If this is a splat, we leave it as-is since there will be only a single
16426 // fp-to-int conversion followed by a splat of the integer. This is better
16427 // for 32-bit and smaller ints and neutral for 64-bit ints.
16428 if (IsSplat)
16429 return SDValue();
16430
16431 // Now that we know we have the right type of node, get its operands
16432 for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
16433 SDValue In = N->getOperand(i).getOperand(0);
16434 if (Is32Bit) {
16435 // For 32-bit values, we need to add an FP_ROUND node (if we made it
16436 // here, we know that all inputs are extending loads so this is safe).
16437 if (In.isUndef())
16438 Ops.push_back(DAG.getUNDEF(SrcVT));
16439 else {
16440 SDValue Trunc =
16441 DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, In.getOperand(0),
16442 DAG.getIntPtrConstant(1, dl, /*isTarget=*/true));
16443 Ops.push_back(Trunc);
16444 }
16445 } else
16446 Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
16447 }
16448
16449 unsigned Opcode;
16450 if (FirstConversion == PPCISD::FCTIDZ ||
16451 FirstConversion == PPCISD::FCTIWZ)
16452 Opcode = ISD::FP_TO_SINT;
16453 else
16454 Opcode = ISD::FP_TO_UINT;
16455
16456 EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
16457 SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
16458 return DAG.getNode(Opcode, dl, TargetVT, BV);
16459 }
16460 return SDValue();
16461}
16462
16463// LXVKQ instruction load VSX vector with a special quadword value
16464// based on an immediate value. This helper method returns the details of the
16465// match as a tuple of {LXVKQ unsigned IMM Value, right_shift_amount}
16466// to help generate the LXVKQ instruction and the subsequent shift instruction
16467// required to match the original build vector pattern.
16468
16469// LXVKQPattern: {LXVKQ unsigned IMM Value, right_shift_amount}
16470using LXVKQPattern = std::tuple<uint32_t, uint8_t>;
16471
16472static std::optional<LXVKQPattern> getPatternInfo(const APInt &FullVal) {
16473
16474 // LXVKQ instruction loads the Quadword value:
16475 // 0x8000_0000_0000_0000_0000_0000_0000_0000 when imm = 0b10000
16476 static const APInt BasePattern = APInt(128, 0x8000000000000000ULL) << 64;
16477 static const uint32_t Uim = 16;
16478
16479 // Check for direct LXVKQ match (no shift needed)
16480 if (FullVal == BasePattern)
16481 return std::make_tuple(Uim, uint8_t{0});
16482
16483 // Check if FullValue is 1 (the result of the base pattern >> 127)
16484 if (FullVal == APInt(128, 1))
16485 return std::make_tuple(Uim, uint8_t{127});
16486
16487 return std::nullopt;
16488}
16489
16490/// Combine vector loads to a single load (using lxvkq) or splat with shift of a
16491/// constant (xxspltib + vsrq) by recognising patterns in the Build Vector.
16492/// LXVKQ instruction load VSX vector with a special quadword value based on an
16493/// immediate value. if UIM=0b10000 then LXVKQ loads VSR[32×TX+T] with value
16494/// 0x8000_0000_0000_0000_0000_0000_0000_0000.
16495/// This can be used to inline the build vector constants that have the
16496/// following patterns:
16497///
16498/// 0x8000_0000_0000_0000_0000_0000_0000_0000 (MSB set pattern)
16499/// 0x0000_0000_0000_0000_0000_0000_0000_0001 (LSB set pattern)
16500/// MSB pattern can directly loaded using LXVKQ while LSB is loaded using a
16501/// combination of splatting and right shift instructions.
16502
16503SDValue PPCTargetLowering::combineBVLoadsSpecialValue(SDValue Op,
16504 SelectionDAG &DAG) const {
16505
16506 assert((Op.getNode() && Op.getOpcode() == ISD::BUILD_VECTOR) &&
16507 "Expected a BuildVectorSDNode in combineBVLoadsSpecialValue");
16508
16509 // This transformation is only supported if we are loading either a byte,
16510 // halfword, word, or doubleword.
16511 EVT VT = Op.getValueType();
16512 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
16513 VT == MVT::v2i64))
16514 return SDValue();
16515
16516 LLVM_DEBUG(llvm::dbgs() << "\ncombineBVLoadsSpecialValue: Build vector ("
16517 << VT << "): ";
16518 Op->dump());
16519
16520 unsigned NumElems = VT.getVectorNumElements();
16521 unsigned ElemBits = VT.getScalarSizeInBits();
16522
16523 bool IsLittleEndian = DAG.getDataLayout().isLittleEndian();
16524
16525 // Check for Non-constant operand in the build vector.
16526 for (const SDValue &Operand : Op.getNode()->op_values()) {
16527 if (!isa<ConstantSDNode>(Operand))
16528 return SDValue();
16529 }
16530
16531 // Assemble build vector operands as a 128-bit register value
16532 // We need to reconstruct what the 128-bit register pattern would be
16533 // that produces this vector when interpreted with the current endianness
16534 APInt FullVal = APInt::getZero(128);
16535
16536 for (unsigned Index = 0; Index < NumElems; ++Index) {
16537 auto *C = cast<ConstantSDNode>(Op.getOperand(Index));
16538
16539 // Get element value as raw bits (zero-extended)
16540 uint64_t ElemValue = C->getZExtValue();
16541
16542 // Mask to element size to ensure we only get the relevant bits
16543 if (ElemBits < 64)
16544 ElemValue &= ((1ULL << ElemBits) - 1);
16545
16546 // Calculate bit position for this element in the 128-bit register
16547 unsigned BitPos =
16548 (IsLittleEndian) ? (Index * ElemBits) : (128 - (Index + 1) * ElemBits);
16549
16550 // Create APInt for the element value and shift it to correct position
16551 APInt ElemAPInt(128, ElemValue);
16552 ElemAPInt <<= BitPos;
16553
16554 // Place the element value at the correct bit position
16555 FullVal |= ElemAPInt;
16556 }
16557
16558 if (FullVal.isZero() || FullVal.isAllOnes())
16559 return SDValue();
16560
16561 if (auto UIMOpt = getPatternInfo(FullVal)) {
16562 const auto &[Uim, ShiftAmount] = *UIMOpt;
16563 SDLoc Dl(Op);
16564
16565 // Generate LXVKQ instruction if the shift amount is zero.
16566 if (ShiftAmount == 0) {
16567 SDValue UimVal = DAG.getTargetConstant(Uim, Dl, MVT::i32);
16568 SDValue LxvkqInstr =
16569 SDValue(DAG.getMachineNode(PPC::LXVKQ, Dl, VT, UimVal), 0);
16571 << "combineBVLoadsSpecialValue: Instruction Emitted ";
16572 LxvkqInstr.dump());
16573 return LxvkqInstr;
16574 }
16575
16576 assert(ShiftAmount == 127 && "Unexpected lxvkq shift amount value");
16577
16578 // The right shifted pattern can be constructed using a combination of
16579 // XXSPLTIB and VSRQ instruction. VSRQ uses the shift amount from the lower
16580 // 7 bits of byte 15. This can be specified using XXSPLTIB with immediate
16581 // value 255.
16582 SDValue ShiftAmountVec =
16583 SDValue(DAG.getMachineNode(PPC::XXSPLTIB, Dl, MVT::v4i32,
16584 DAG.getTargetConstant(255, Dl, MVT::i32)),
16585 0);
16586 // Generate appropriate right shift instruction
16587 SDValue ShiftVec = SDValue(
16588 DAG.getMachineNode(PPC::VSRQ, Dl, VT, ShiftAmountVec, ShiftAmountVec),
16589 0);
16591 << "\n combineBVLoadsSpecialValue: Instruction Emitted ";
16592 ShiftVec.dump());
16593 return ShiftVec;
16594 }
16595 // No patterns matched for build vectors.
16596 return SDValue();
16597}
16598
16599/// Reduce the number of loads when building a vector.
16600///
16601/// Building a vector out of multiple loads can be converted to a load
16602/// of the vector type if the loads are consecutive. If the loads are
16603/// consecutive but in descending order, a shuffle is added at the end
16604/// to reorder the vector.
16606 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16607 "Should be called with a BUILD_VECTOR node");
16608
16609 SDLoc dl(N);
16610
16611 // Return early for non byte-sized type, as they can't be consecutive.
16612 if (!N->getValueType(0).getVectorElementType().isByteSized())
16613 return SDValue();
16614
16615 bool InputsAreConsecutiveLoads = true;
16616 bool InputsAreReverseConsecutive = true;
16617 unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
16618 SDValue FirstInput = N->getOperand(0);
16619 bool IsRoundOfExtLoad = false;
16620 LoadSDNode *FirstLoad = nullptr;
16621
16622 if (FirstInput.getOpcode() == ISD::FP_ROUND &&
16623 FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
16624 FirstLoad = cast<LoadSDNode>(FirstInput.getOperand(0));
16625 IsRoundOfExtLoad = FirstLoad->getExtensionType() == ISD::EXTLOAD;
16626 }
16627 // Not a build vector of (possibly fp_rounded) loads.
16628 if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
16629 N->getNumOperands() == 1)
16630 return SDValue();
16631
16632 if (!IsRoundOfExtLoad)
16633 FirstLoad = cast<LoadSDNode>(FirstInput);
16634
16636 InputLoads.push_back(FirstLoad);
16637 for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
16638 // If any inputs are fp_round(extload), they all must be.
16639 if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
16640 return SDValue();
16641
16642 SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
16643 N->getOperand(i);
16644 if (NextInput.getOpcode() != ISD::LOAD)
16645 return SDValue();
16646
16647 SDValue PreviousInput =
16648 IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
16649 LoadSDNode *LD1 = cast<LoadSDNode>(PreviousInput);
16650 LoadSDNode *LD2 = cast<LoadSDNode>(NextInput);
16651
16652 // If any inputs are fp_round(extload), they all must be.
16653 if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
16654 return SDValue();
16655
16656 // We only care about regular loads. The PPC-specific load intrinsics
16657 // will not lead to a merge opportunity.
16658 if (!DAG.areNonVolatileConsecutiveLoads(LD2, LD1, ElemSize, 1))
16659 InputsAreConsecutiveLoads = false;
16660 if (!DAG.areNonVolatileConsecutiveLoads(LD1, LD2, ElemSize, 1))
16661 InputsAreReverseConsecutive = false;
16662
16663 // Exit early if the loads are neither consecutive nor reverse consecutive.
16664 if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
16665 return SDValue();
16666 InputLoads.push_back(LD2);
16667 }
16668
16669 assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
16670 "The loads cannot be both consecutive and reverse consecutive.");
16671
16672 SDValue WideLoad;
16673 SDValue ReturnSDVal;
16674 if (InputsAreConsecutiveLoads) {
16675 assert(FirstLoad && "Input needs to be a LoadSDNode.");
16676 WideLoad = DAG.getLoad(N->getValueType(0), dl, FirstLoad->getChain(),
16677 FirstLoad->getBasePtr(), FirstLoad->getPointerInfo(),
16678 FirstLoad->getAlign());
16679 ReturnSDVal = WideLoad;
16680 } else if (InputsAreReverseConsecutive) {
16681 LoadSDNode *LastLoad = InputLoads.back();
16682 assert(LastLoad && "Input needs to be a LoadSDNode.");
16683 WideLoad = DAG.getLoad(N->getValueType(0), dl, LastLoad->getChain(),
16684 LastLoad->getBasePtr(), LastLoad->getPointerInfo(),
16685 LastLoad->getAlign());
16687 for (int i = N->getNumOperands() - 1; i >= 0; i--)
16688 Ops.push_back(i);
16689
16690 ReturnSDVal = DAG.getVectorShuffle(N->getValueType(0), dl, WideLoad,
16691 DAG.getUNDEF(N->getValueType(0)), Ops);
16692 } else
16693 return SDValue();
16694
16695 for (auto *LD : InputLoads)
16696 DAG.makeEquivalentMemoryOrdering(LD, WideLoad);
16697 return ReturnSDVal;
16698}
16699
16700// This function adds the required vector_shuffle needed to get
16701// the elements of the vector extract in the correct position
16702// as specified by the CorrectElems encoding.
16704 SDValue Input, uint64_t Elems,
16705 uint64_t CorrectElems) {
16706 SDLoc dl(N);
16707
16708 unsigned NumElems = Input.getValueType().getVectorNumElements();
16709 SmallVector<int, 16> ShuffleMask(NumElems, -1);
16710
16711 // Knowing the element indices being extracted from the original
16712 // vector and the order in which they're being inserted, just put
16713 // them at element indices required for the instruction.
16714 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16715 if (DAG.getDataLayout().isLittleEndian())
16716 ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
16717 else
16718 ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
16719 CorrectElems = CorrectElems >> 8;
16720 Elems = Elems >> 8;
16721 }
16722
16723 SDValue Shuffle =
16724 DAG.getVectorShuffle(Input.getValueType(), dl, Input,
16725 DAG.getUNDEF(Input.getValueType()), ShuffleMask);
16726
16727 EVT VT = N->getValueType(0);
16728 SDValue Conv = DAG.getBitcast(VT, Shuffle);
16729
16730 EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
16731 Input.getValueType().getVectorElementType(),
16733 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
16734 DAG.getValueType(ExtVT));
16735}
16736
16737// Look for build vector patterns where input operands come from sign
16738// extended vector_extract elements of specific indices. If the correct indices
16739// aren't used, add a vector shuffle to fix up the indices and create
16740// SIGN_EXTEND_INREG node which selects the vector sign extend instructions
16741// during instruction selection.
16743 // This array encodes the indices that the vector sign extend instructions
16744 // extract from when extending from one type to another for both BE and LE.
16745 // The right nibble of each byte corresponds to the LE incides.
16746 // and the left nibble of each byte corresponds to the BE incides.
16747 // For example: 0x3074B8FC byte->word
16748 // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
16749 // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
16750 // For example: 0x000070F8 byte->double word
16751 // For LE: the allowed indices are: 0x0,0x8
16752 // For BE: the allowed indices are: 0x7,0xF
16753 uint64_t TargetElems[] = {
16754 0x3074B8FC, // b->w
16755 0x000070F8, // b->d
16756 0x10325476, // h->w
16757 0x00003074, // h->d
16758 0x00001032, // w->d
16759 };
16760
16761 uint64_t Elems = 0;
16762 int Index;
16763 SDValue Input;
16764
16765 auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
16766 if (!Op)
16767 return false;
16768 if (Op.getOpcode() != ISD::SIGN_EXTEND &&
16769 Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
16770 return false;
16771
16772 // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
16773 // of the right width.
16774 SDValue Extract = Op.getOperand(0);
16775 if (Extract.getOpcode() == ISD::ANY_EXTEND)
16776 Extract = Extract.getOperand(0);
16777 if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
16778 return false;
16779
16781 if (!ExtOp)
16782 return false;
16783
16784 Index = ExtOp->getZExtValue();
16785 if (Input && Input != Extract.getOperand(0))
16786 return false;
16787
16788 if (!Input)
16789 Input = Extract.getOperand(0);
16790
16791 Elems = Elems << 8;
16792 Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
16793 Elems |= Index;
16794
16795 return true;
16796 };
16797
16798 // If the build vector operands aren't sign extended vector extracts,
16799 // of the same input vector, then return.
16800 for (unsigned i = 0; i < N->getNumOperands(); i++) {
16801 if (!isSExtOfVecExtract(N->getOperand(i))) {
16802 return SDValue();
16803 }
16804 }
16805
16806 // If the vector extract indices are not correct, add the appropriate
16807 // vector_shuffle.
16808 int TgtElemArrayIdx;
16809 int InputSize = Input.getValueType().getScalarSizeInBits();
16810 int OutputSize = N->getValueType(0).getScalarSizeInBits();
16811 if (InputSize + OutputSize == 40)
16812 TgtElemArrayIdx = 0;
16813 else if (InputSize + OutputSize == 72)
16814 TgtElemArrayIdx = 1;
16815 else if (InputSize + OutputSize == 48)
16816 TgtElemArrayIdx = 2;
16817 else if (InputSize + OutputSize == 80)
16818 TgtElemArrayIdx = 3;
16819 else if (InputSize + OutputSize == 96)
16820 TgtElemArrayIdx = 4;
16821 else
16822 return SDValue();
16823
16824 uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
16825 CorrectElems = DAG.getDataLayout().isLittleEndian()
16826 ? CorrectElems & 0x0F0F0F0F0F0F0F0F
16827 : CorrectElems & 0xF0F0F0F0F0F0F0F0;
16828 if (Elems != CorrectElems) {
16829 return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
16830 }
16831
16832 // Regular lowering will catch cases where a shuffle is not needed.
16833 return SDValue();
16834}
16835
16836// Look for the pattern of a load from a narrow width to i128, feeding
16837// into a BUILD_VECTOR of v1i128. Replace this sequence with a PPCISD node
16838// (LXVRZX). This node represents a zero extending load that will be matched
16839// to the Load VSX Vector Rightmost instructions.
16841 SDLoc DL(N);
16842
16843 // This combine is only eligible for a BUILD_VECTOR of v1i128.
16844 if (N->getValueType(0) != MVT::v1i128)
16845 return SDValue();
16846
16847 SDValue Operand = N->getOperand(0);
16848 // Proceed with the transformation if the operand to the BUILD_VECTOR
16849 // is a load instruction.
16850 if (Operand.getOpcode() != ISD::LOAD)
16851 return SDValue();
16852
16853 auto *LD = cast<LoadSDNode>(Operand);
16854 EVT MemoryType = LD->getMemoryVT();
16855
16856 // This transformation is only valid if the we are loading either a byte,
16857 // halfword, word, or doubleword.
16858 bool ValidLDType = MemoryType == MVT::i8 || MemoryType == MVT::i16 ||
16859 MemoryType == MVT::i32 || MemoryType == MVT::i64;
16860
16861 // Ensure that the load from the narrow width is being zero extended to i128.
16862 if (!ValidLDType ||
16863 (LD->getExtensionType() != ISD::ZEXTLOAD &&
16864 LD->getExtensionType() != ISD::EXTLOAD))
16865 return SDValue();
16866
16867 SDValue LoadOps[] = {
16868 LD->getChain(), LD->getBasePtr(),
16869 DAG.getIntPtrConstant(MemoryType.getScalarSizeInBits(), DL)};
16870
16871 return DAG.getMemIntrinsicNode(PPCISD::LXVRZX, DL,
16872 DAG.getVTList(MVT::v1i128, MVT::Other),
16873 LoadOps, MemoryType, LD->getMemOperand());
16874}
16875
16876SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
16877 DAGCombinerInfo &DCI) const {
16878 assert(N->getOpcode() == ISD::BUILD_VECTOR &&
16879 "Should be called with a BUILD_VECTOR node");
16880
16881 SelectionDAG &DAG = DCI.DAG;
16882 SDLoc dl(N);
16883
16884 if (!Subtarget.hasVSX())
16885 return SDValue();
16886
16887 // The target independent DAG combiner will leave a build_vector of
16888 // float-to-int conversions intact. We can generate MUCH better code for
16889 // a float-to-int conversion of a vector of floats.
16890 SDValue FirstInput = N->getOperand(0);
16891 if (FirstInput.getOpcode() == PPCISD::MFVSR) {
16892 SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
16893 if (Reduced)
16894 return Reduced;
16895 }
16896
16897 // If we're building a vector out of consecutive loads, just load that
16898 // vector type.
16899 SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
16900 if (Reduced)
16901 return Reduced;
16902
16903 // If we're building a vector out of extended elements from another vector
16904 // we have P9 vector integer extend instructions. The code assumes legal
16905 // input types (i.e. it can't handle things like v4i16) so do not run before
16906 // legalization.
16907 if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
16908 Reduced = combineBVOfVecSExt(N, DAG);
16909 if (Reduced)
16910 return Reduced;
16911 }
16912
16913 // On Power10, the Load VSX Vector Rightmost instructions can be utilized
16914 // if this is a BUILD_VECTOR of v1i128, and if the operand to the BUILD_VECTOR
16915 // is a load from <valid narrow width> to i128.
16916 if (Subtarget.isISA3_1()) {
16917 SDValue BVOfZLoad = combineBVZEXTLOAD(N, DAG);
16918 if (BVOfZLoad)
16919 return BVOfZLoad;
16920 }
16921
16922 if (N->getValueType(0) != MVT::v2f64)
16923 return SDValue();
16924
16925 // Looking for:
16926 // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
16927 if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
16928 FirstInput.getOpcode() != ISD::UINT_TO_FP)
16929 return SDValue();
16930 if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
16931 N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
16932 return SDValue();
16933 if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
16934 return SDValue();
16935
16936 SDValue Ext1 = FirstInput.getOperand(0);
16937 SDValue Ext2 = N->getOperand(1).getOperand(0);
16938 if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
16940 return SDValue();
16941
16942 ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
16943 ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
16944 if (!Ext1Op || !Ext2Op)
16945 return SDValue();
16946 if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
16947 Ext1.getOperand(0) != Ext2.getOperand(0))
16948 return SDValue();
16949
16950 int FirstElem = Ext1Op->getZExtValue();
16951 int SecondElem = Ext2Op->getZExtValue();
16952 int SubvecIdx;
16953 if (FirstElem == 0 && SecondElem == 1)
16954 SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
16955 else if (FirstElem == 2 && SecondElem == 3)
16956 SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
16957 else
16958 return SDValue();
16959
16960 SDValue SrcVec = Ext1.getOperand(0);
16961 auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
16962 PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
16963 return DAG.getNode(NodeType, dl, MVT::v2f64,
16964 SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
16965}
16966
16967SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
16968 DAGCombinerInfo &DCI) const {
16969 assert((N->getOpcode() == ISD::SINT_TO_FP ||
16970 N->getOpcode() == ISD::UINT_TO_FP) &&
16971 "Need an int -> FP conversion node here");
16972
16973 if (useSoftFloat() || !Subtarget.has64BitSupport())
16974 return SDValue();
16975
16976 SelectionDAG &DAG = DCI.DAG;
16977 SDLoc dl(N);
16978 SDValue Op(N, 0);
16979
16980 // Don't handle ppc_fp128 here or conversions that are out-of-range capable
16981 // from the hardware.
16982 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
16983 return SDValue();
16984 if (!Op.getOperand(0).getValueType().isSimple())
16985 return SDValue();
16986 if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
16987 Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
16988 return SDValue();
16989
16990 SDValue FirstOperand(Op.getOperand(0));
16991 bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
16992 (FirstOperand.getValueType() == MVT::i8 ||
16993 FirstOperand.getValueType() == MVT::i16);
16994 if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
16995 bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
16996 bool DstDouble = Op.getValueType() == MVT::f64;
16997 unsigned ConvOp = Signed ?
16998 (DstDouble ? PPCISD::FCFID : PPCISD::FCFIDS) :
16999 (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
17000 SDValue WidthConst =
17001 DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
17002 dl, false);
17003 LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
17004 SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
17005 SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
17006 DAG.getVTList(MVT::f64, MVT::Other),
17007 Ops, MVT::i8, LDN->getMemOperand());
17008 DAG.makeEquivalentMemoryOrdering(LDN, Ld);
17009
17010 // For signed conversion, we need to sign-extend the value in the VSR
17011 if (Signed) {
17012 SDValue ExtOps[] = { Ld, WidthConst };
17013 SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
17014 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
17015 } else
17016 return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
17017 }
17018
17019
17020 // For i32 intermediate values, unfortunately, the conversion functions
17021 // leave the upper 32 bits of the value are undefined. Within the set of
17022 // scalar instructions, we have no method for zero- or sign-extending the
17023 // value. Thus, we cannot handle i32 intermediate values here.
17024 if (Op.getOperand(0).getValueType() == MVT::i32)
17025 return SDValue();
17026
17027 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
17028 "UINT_TO_FP is supported only with FPCVT");
17029
17030 // If we have FCFIDS, then use it when converting to single-precision.
17031 // Otherwise, convert to double-precision and then round.
17032 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
17033 ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
17034 : PPCISD::FCFIDS)
17035 : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
17036 : PPCISD::FCFID);
17037 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
17038 ? MVT::f32
17039 : MVT::f64;
17040
17041 // If we're converting from a float, to an int, and back to a float again,
17042 // then we don't need the store/load pair at all.
17043 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
17044 Subtarget.hasFPCVT()) ||
17045 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
17046 SDValue Src = Op.getOperand(0).getOperand(0);
17047 if (Src.getValueType() == MVT::f32) {
17048 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
17049 DCI.AddToWorklist(Src.getNode());
17050 } else if (Src.getValueType() != MVT::f64) {
17051 // Make sure that we don't pick up a ppc_fp128 source value.
17052 return SDValue();
17053 }
17054
17055 unsigned FCTOp =
17056 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
17057 PPCISD::FCTIDUZ;
17058
17059 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
17060 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
17061
17062 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
17063 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
17064 DAG.getIntPtrConstant(0, dl, /*isTarget=*/true));
17065 DCI.AddToWorklist(FP.getNode());
17066 }
17067
17068 return FP;
17069 }
17070
17071 return SDValue();
17072}
17073
17074// expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
17075// builtins) into loads with swaps.
17077 DAGCombinerInfo &DCI) const {
17078 // Delay VSX load for LE combine until after LegalizeOps to prioritize other
17079 // load combines.
17080 if (DCI.isBeforeLegalizeOps())
17081 return SDValue();
17082
17083 SelectionDAG &DAG = DCI.DAG;
17084 SDLoc dl(N);
17085 SDValue Chain;
17086 SDValue Base;
17087 MachineMemOperand *MMO;
17088
17089 switch (N->getOpcode()) {
17090 default:
17091 llvm_unreachable("Unexpected opcode for little endian VSX load");
17092 case ISD::LOAD: {
17094 Chain = LD->getChain();
17095 Base = LD->getBasePtr();
17096 MMO = LD->getMemOperand();
17097 // If the MMO suggests this isn't a load of a full vector, leave
17098 // things alone. For a built-in, we have to make the change for
17099 // correctness, so if there is a size problem that will be a bug.
17100 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
17101 return SDValue();
17102 break;
17103 }
17106 Chain = Intrin->getChain();
17107 // Similarly to the store case below, Intrin->getBasePtr() doesn't get
17108 // us what we want. Get operand 2 instead.
17109 Base = Intrin->getOperand(2);
17110 MMO = Intrin->getMemOperand();
17111 break;
17112 }
17113 }
17114
17115 MVT VecTy = N->getValueType(0).getSimpleVT();
17116
17117 SDValue LoadOps[] = { Chain, Base };
17118 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
17119 DAG.getVTList(MVT::v2f64, MVT::Other),
17120 LoadOps, MVT::v2f64, MMO);
17121
17122 DCI.AddToWorklist(Load.getNode());
17123 Chain = Load.getValue(1);
17124 SDValue Swap = DAG.getNode(
17125 PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
17126 DCI.AddToWorklist(Swap.getNode());
17127
17128 // Add a bitcast if the resulting load type doesn't match v2f64.
17129 if (VecTy != MVT::v2f64) {
17130 SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
17131 DCI.AddToWorklist(N.getNode());
17132 // Package {bitcast value, swap's chain} to match Load's shape.
17133 return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
17134 N, Swap.getValue(1));
17135 }
17136
17137 return Swap;
17138}
17139
17140// expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
17141// builtins) into stores with swaps.
17143 DAGCombinerInfo &DCI) const {
17144 // Delay VSX store for LE combine until after LegalizeOps to prioritize other
17145 // store combines.
17146 if (DCI.isBeforeLegalizeOps())
17147 return SDValue();
17148
17149 SelectionDAG &DAG = DCI.DAG;
17150 SDLoc dl(N);
17151 SDValue Chain;
17152 SDValue Base;
17153 unsigned SrcOpnd;
17154 MachineMemOperand *MMO;
17155
17156 switch (N->getOpcode()) {
17157 default:
17158 llvm_unreachable("Unexpected opcode for little endian VSX store");
17159 case ISD::STORE: {
17161 Chain = ST->getChain();
17162 Base = ST->getBasePtr();
17163 MMO = ST->getMemOperand();
17164 SrcOpnd = 1;
17165 // If the MMO suggests this isn't a store of a full vector, leave
17166 // things alone. For a built-in, we have to make the change for
17167 // correctness, so if there is a size problem that will be a bug.
17168 if (!MMO->getSize().hasValue() || MMO->getSize().getValue() < 16)
17169 return SDValue();
17170 break;
17171 }
17172 case ISD::INTRINSIC_VOID: {
17174 Chain = Intrin->getChain();
17175 // Intrin->getBasePtr() oddly does not get what we want.
17176 Base = Intrin->getOperand(3);
17177 MMO = Intrin->getMemOperand();
17178 SrcOpnd = 2;
17179 break;
17180 }
17181 }
17182
17183 SDValue Src = N->getOperand(SrcOpnd);
17184 MVT VecTy = Src.getValueType().getSimpleVT();
17185
17186 // All stores are done as v2f64 and possible bit cast.
17187 if (VecTy != MVT::v2f64) {
17188 Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
17189 DCI.AddToWorklist(Src.getNode());
17190 }
17191
17192 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
17193 DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
17194 DCI.AddToWorklist(Swap.getNode());
17195 Chain = Swap.getValue(1);
17196 SDValue StoreOps[] = { Chain, Swap, Base };
17197 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
17198 DAG.getVTList(MVT::Other),
17199 StoreOps, VecTy, MMO);
17200 DCI.AddToWorklist(Store.getNode());
17201 return Store;
17202}
17203
17204// Handle DAG combine for STORE (FP_TO_INT F).
17205SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
17206 DAGCombinerInfo &DCI) const {
17207 SelectionDAG &DAG = DCI.DAG;
17208 SDLoc dl(N);
17209 unsigned Opcode = N->getOperand(1).getOpcode();
17210 (void)Opcode;
17211 bool Strict = N->getOperand(1)->isStrictFPOpcode();
17212
17213 assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
17214 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT)
17215 && "Not a FP_TO_INT Instruction!");
17216
17217 SDValue Val = N->getOperand(1).getOperand(Strict ? 1 : 0);
17218 EVT Op1VT = N->getOperand(1).getValueType();
17219 EVT ResVT = Val.getValueType();
17220
17221 if (!Subtarget.hasVSX() || !Subtarget.hasFPCVT() || !isTypeLegal(ResVT))
17222 return SDValue();
17223
17224 // Only perform combine for conversion to i64/i32 or power9 i16/i8.
17225 bool ValidTypeForStoreFltAsInt =
17226 (Op1VT == MVT::i32 || (Op1VT == MVT::i64 && Subtarget.isPPC64()) ||
17227 (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
17228
17229 // TODO: Lower conversion from f128 on all VSX targets
17230 if (ResVT == MVT::ppcf128 || (ResVT == MVT::f128 && !Subtarget.hasP9Vector()))
17231 return SDValue();
17232
17233 if ((Op1VT != MVT::i64 && !Subtarget.hasP8Vector()) ||
17234 cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
17235 return SDValue();
17236
17237 Val = convertFPToInt(N->getOperand(1), DAG, Subtarget);
17238
17239 // Set number of bytes being converted.
17240 unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
17241 SDValue Ops[] = {N->getOperand(0), Val, N->getOperand(2),
17242 DAG.getIntPtrConstant(ByteSize, dl, false),
17243 DAG.getValueType(Op1VT)};
17244
17245 Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
17246 DAG.getVTList(MVT::Other), Ops,
17247 cast<StoreSDNode>(N)->getMemoryVT(),
17248 cast<StoreSDNode>(N)->getMemOperand());
17249
17250 return Val;
17251}
17252
17253static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
17254 // Check that the source of the element keeps flipping
17255 // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
17256 bool PrevElemFromFirstVec = Mask[0] < NumElts;
17257 for (int i = 1, e = Mask.size(); i < e; i++) {
17258 if (PrevElemFromFirstVec && Mask[i] < NumElts)
17259 return false;
17260 if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
17261 return false;
17262 PrevElemFromFirstVec = !PrevElemFromFirstVec;
17263 }
17264 return true;
17265}
17266
17267static bool isSplatBV(SDValue Op) {
17268 if (Op.getOpcode() != ISD::BUILD_VECTOR)
17269 return false;
17270 SDValue FirstOp;
17271
17272 // Find first non-undef input.
17273 for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
17274 FirstOp = Op.getOperand(i);
17275 if (!FirstOp.isUndef())
17276 break;
17277 }
17278
17279 // All inputs are undef or the same as the first non-undef input.
17280 for (int i = 1, e = Op.getNumOperands(); i < e; i++)
17281 if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
17282 return false;
17283 return true;
17284}
17285
17287 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17288 return Op;
17289 if (Op.getOpcode() != ISD::BITCAST)
17290 return SDValue();
17291 Op = Op.getOperand(0);
17292 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
17293 return Op;
17294 return SDValue();
17295}
17296
17297// Fix up the shuffle mask to account for the fact that the result of
17298// scalar_to_vector is not in lane zero. This just takes all values in
17299// the ranges specified by the min/max indices and adds the number of
17300// elements required to ensure each element comes from the respective
17301// position in the valid lane.
17302// On little endian, that's just the corresponding element in the other
17303// half of the vector. On big endian, it is in the same half but right
17304// justified rather than left justified in that half.
17306 SmallVectorImpl<int> &ShuffV, int LHSFirstElt, int LHSLastElt,
17307 int RHSFirstElt, int RHSLastElt, int HalfVec, unsigned LHSNumValidElts,
17308 unsigned RHSNumValidElts, const PPCSubtarget &Subtarget) {
17309 int LHSEltFixup =
17310 Subtarget.isLittleEndian() ? HalfVec : HalfVec - LHSNumValidElts;
17311 int RHSEltFixup =
17312 Subtarget.isLittleEndian() ? HalfVec : HalfVec - RHSNumValidElts;
17313 for (int I = 0, E = ShuffV.size(); I < E; ++I) {
17314 int Idx = ShuffV[I];
17315 if (Idx >= LHSFirstElt && Idx <= LHSLastElt)
17316 ShuffV[I] += LHSEltFixup;
17317 else if (Idx >= RHSFirstElt && Idx <= RHSLastElt)
17318 ShuffV[I] += RHSEltFixup;
17319 }
17320}
17321
17322// Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
17323// the original is:
17324// (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
17325// In such a case, just change the shuffle mask to extract the element
17326// from the permuted index.
17328 const PPCSubtarget &Subtarget) {
17329 SDLoc dl(OrigSToV);
17330 EVT VT = OrigSToV.getValueType();
17331 assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
17332 "Expecting a SCALAR_TO_VECTOR here");
17333 SDValue Input = OrigSToV.getOperand(0);
17334
17335 if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
17336 ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
17337 SDValue OrigVector = Input.getOperand(0);
17338
17339 // Can't handle non-const element indices or different vector types
17340 // for the input to the extract and the output of the scalar_to_vector.
17341 if (Idx && VT == OrigVector.getValueType()) {
17342 unsigned NumElts = VT.getVectorNumElements();
17343 assert(
17344 NumElts > 1 &&
17345 "Cannot produce a permuted scalar_to_vector for one element vector");
17346 SmallVector<int, 16> NewMask(NumElts, -1);
17347 unsigned ResultInElt = NumElts / 2;
17348 ResultInElt -= Subtarget.isLittleEndian() ? 0 : 1;
17349 NewMask[ResultInElt] = Idx->getZExtValue();
17350 return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
17351 }
17352 }
17353 return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
17354 OrigSToV.getOperand(0));
17355}
17356
17358 int HalfVec, int LHSLastElementDefined,
17359 int RHSLastElementDefined) {
17360 for (int Index : ShuffV) {
17361 if (Index < 0) // Skip explicitly undefined mask indices.
17362 continue;
17363 // Handle first input vector of the vector_shuffle.
17364 if ((LHSLastElementDefined >= 0) && (Index < HalfVec) &&
17365 (Index > LHSLastElementDefined))
17366 return false;
17367 // Handle second input vector of the vector_shuffle.
17368 if ((RHSLastElementDefined >= 0) &&
17369 (Index > HalfVec + RHSLastElementDefined))
17370 return false;
17371 }
17372 return true;
17373}
17374
17376 int ScalarSize, uint64_t ShuffleEltWidth, unsigned &NumValidElts,
17377 int FirstElt, int &LastElt, SDValue VecShuffOperand, SDValue SToVNode,
17378 SelectionDAG &DAG, const PPCSubtarget &Subtarget) {
17379 EVT VecShuffOperandType = VecShuffOperand.getValueType();
17380 // Set up the values for the shuffle vector fixup.
17381 NumValidElts = ScalarSize / VecShuffOperandType.getScalarSizeInBits();
17382 // The last element depends on if the input comes from the LHS or RHS.
17383 //
17384 // For example:
17385 // (shuff (s_to_v i32), (bitcast (s_to_v i64), v4i32), ...)
17386 //
17387 // For the LHS: The last element that comes from the LHS is actually 0, not 3
17388 // because elements 1 and higher of a scalar_to_vector are undefined.
17389 // For the RHS: The last element that comes from the RHS is actually 5, not 7
17390 // because elements 1 and higher of a scalar_to_vector are undefined.
17391 // It is also not 4 because the original scalar_to_vector is wider and
17392 // actually contains two i32 elements.
17393 LastElt = (uint64_t)ScalarSize > ShuffleEltWidth
17394 ? ScalarSize / ShuffleEltWidth - 1 + FirstElt
17395 : FirstElt;
17396 SDValue SToVPermuted = getSToVPermuted(SToVNode, DAG, Subtarget);
17397 if (SToVPermuted.getValueType() != VecShuffOperandType)
17398 SToVPermuted = DAG.getBitcast(VecShuffOperandType, SToVPermuted);
17399 return SToVPermuted;
17400}
17401
17402// On little endian subtargets, combine shuffles such as:
17403// vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
17404// into:
17405// vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
17406// because the latter can be matched to a single instruction merge.
17407// Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
17408// to put the value into element zero. Adjust the shuffle mask so that the
17409// vector can remain in permuted form (to prevent a swap prior to a shuffle).
17410// On big endian targets, this is still useful for SCALAR_TO_VECTOR
17411// nodes with elements smaller than doubleword because all the ways
17412// of getting scalar data into a vector register put the value in the
17413// rightmost element of the left half of the vector.
17414SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
17415 SelectionDAG &DAG) const {
17416 SDValue LHS = SVN->getOperand(0);
17417 SDValue RHS = SVN->getOperand(1);
17418 auto Mask = SVN->getMask();
17419 int NumElts = LHS.getValueType().getVectorNumElements();
17420 SDValue Res(SVN, 0);
17421 SDLoc dl(SVN);
17422 bool IsLittleEndian = Subtarget.isLittleEndian();
17423
17424 // On big endian targets this is only useful for subtargets with direct moves.
17425 // On little endian targets it would be useful for all subtargets with VSX.
17426 // However adding special handling for LE subtargets without direct moves
17427 // would be wasted effort since the minimum arch for LE is ISA 2.07 (Power8)
17428 // which includes direct moves.
17429 if (!Subtarget.hasDirectMove())
17430 return Res;
17431
17432 // If this is not a shuffle of a shuffle and the first element comes from
17433 // the second vector, canonicalize to the commuted form. This will make it
17434 // more likely to match one of the single instruction patterns.
17435 if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17436 RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
17437 std::swap(LHS, RHS);
17438 Res = DAG.getCommutedVectorShuffle(*SVN);
17439
17440 if (!isa<ShuffleVectorSDNode>(Res))
17441 return Res;
17442
17443 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17444 }
17445
17446 // Adjust the shuffle mask if either input vector comes from a
17447 // SCALAR_TO_VECTOR and keep the respective input vector in permuted
17448 // form (to prevent the need for a swap).
17449 SmallVector<int, 16> ShuffV(Mask);
17450 SDValue SToVLHS = isScalarToVec(LHS);
17451 SDValue SToVRHS = isScalarToVec(RHS);
17452 if (SToVLHS || SToVRHS) {
17453 EVT VT = SVN->getValueType(0);
17454 uint64_t ShuffleEltWidth = VT.getVectorElementType().getSizeInBits();
17455 int ShuffleNumElts = ShuffV.size();
17456 int HalfVec = ShuffleNumElts / 2;
17457 // The width of the "valid lane" (i.e. the lane that contains the value that
17458 // is vectorized) needs to be expressed in terms of the number of elements
17459 // of the shuffle. It is thereby the ratio of the values before and after
17460 // any bitcast, which will be set later on if the LHS or RHS are
17461 // SCALAR_TO_VECTOR nodes.
17462 unsigned LHSNumValidElts = HalfVec;
17463 unsigned RHSNumValidElts = HalfVec;
17464
17465 // Initially assume that neither input is permuted. These will be adjusted
17466 // accordingly if either input is. Note, that -1 means that all elements
17467 // are undefined.
17468 int LHSFirstElt = 0;
17469 int RHSFirstElt = ShuffleNumElts;
17470 int LHSLastElt = -1;
17471 int RHSLastElt = -1;
17472
17473 // Get the permuted scalar to vector nodes for the source(s) that come from
17474 // ISD::SCALAR_TO_VECTOR.
17475 // On big endian systems, this only makes sense for element sizes smaller
17476 // than 64 bits since for 64-bit elements, all instructions already put
17477 // the value into element zero. Since scalar size of LHS and RHS may differ
17478 // after isScalarToVec, this should be checked using their own sizes.
17479 int LHSScalarSize = 0;
17480 int RHSScalarSize = 0;
17481 if (SToVLHS) {
17482 LHSScalarSize = SToVLHS.getValueType().getScalarSizeInBits();
17483 if (!IsLittleEndian && LHSScalarSize >= 64)
17484 return Res;
17485 }
17486 if (SToVRHS) {
17487 RHSScalarSize = SToVRHS.getValueType().getScalarSizeInBits();
17488 if (!IsLittleEndian && RHSScalarSize >= 64)
17489 return Res;
17490 }
17491 if (LHSScalarSize != 0)
17493 LHSScalarSize, ShuffleEltWidth, LHSNumValidElts, LHSFirstElt,
17494 LHSLastElt, LHS, SToVLHS, DAG, Subtarget);
17495 if (RHSScalarSize != 0)
17497 RHSScalarSize, ShuffleEltWidth, RHSNumValidElts, RHSFirstElt,
17498 RHSLastElt, RHS, SToVRHS, DAG, Subtarget);
17499
17500 if (!isShuffleMaskInRange(ShuffV, HalfVec, LHSLastElt, RHSLastElt))
17501 return Res;
17502
17503 // Fix up the shuffle mask to reflect where the desired element actually is.
17504 // The minimum and maximum indices that correspond to element zero for both
17505 // the LHS and RHS are computed and will control which shuffle mask entries
17506 // are to be changed. For example, if the RHS is permuted, any shuffle mask
17507 // entries in the range [RHSFirstElt,RHSLastElt] will be adjusted.
17509 ShuffV, LHSFirstElt, LHSLastElt, RHSFirstElt, RHSLastElt, HalfVec,
17510 LHSNumValidElts, RHSNumValidElts, Subtarget);
17511 Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17512
17513 // We may have simplified away the shuffle. We won't be able to do anything
17514 // further with it here.
17515 if (!isa<ShuffleVectorSDNode>(Res))
17516 return Res;
17517 Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
17518 }
17519
17520 SDValue TheSplat = IsLittleEndian ? RHS : LHS;
17521 // The common case after we commuted the shuffle is that the RHS is a splat
17522 // and we have elements coming in from the splat at indices that are not
17523 // conducive to using a merge.
17524 // Example:
17525 // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
17526 if (!isSplatBV(TheSplat))
17527 return Res;
17528
17529 // We are looking for a mask such that all even elements are from
17530 // one vector and all odd elements from the other.
17531 if (!isAlternatingShuffMask(Mask, NumElts))
17532 return Res;
17533
17534 // Adjust the mask so we are pulling in the same index from the splat
17535 // as the index from the interesting vector in consecutive elements.
17536 if (IsLittleEndian) {
17537 // Example (even elements from first vector):
17538 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
17539 if (Mask[0] < NumElts)
17540 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17541 if (ShuffV[i] < 0)
17542 continue;
17543 // If element from non-splat is undef, pick first element from splat.
17544 ShuffV[i] = (ShuffV[i - 1] >= 0 ? ShuffV[i - 1] : 0) + NumElts;
17545 }
17546 // Example (odd elements from first vector):
17547 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
17548 else
17549 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17550 if (ShuffV[i] < 0)
17551 continue;
17552 // If element from non-splat is undef, pick first element from splat.
17553 ShuffV[i] = (ShuffV[i + 1] >= 0 ? ShuffV[i + 1] : 0) + NumElts;
17554 }
17555 } else {
17556 // Example (even elements from first vector):
17557 // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> <zero>, t1
17558 if (Mask[0] < NumElts)
17559 for (int i = 0, e = Mask.size(); i < e; i += 2) {
17560 if (ShuffV[i] < 0)
17561 continue;
17562 // If element from non-splat is undef, pick first element from splat.
17563 ShuffV[i] = ShuffV[i + 1] >= 0 ? ShuffV[i + 1] - NumElts : 0;
17564 }
17565 // Example (odd elements from first vector):
17566 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> <zero>, t1
17567 else
17568 for (int i = 1, e = Mask.size(); i < e; i += 2) {
17569 if (ShuffV[i] < 0)
17570 continue;
17571 // If element from non-splat is undef, pick first element from splat.
17572 ShuffV[i] = ShuffV[i - 1] >= 0 ? ShuffV[i - 1] - NumElts : 0;
17573 }
17574 }
17575
17576 // If the RHS has undefs, we need to remove them since we may have created
17577 // a shuffle that adds those instead of the splat value.
17578 SDValue SplatVal =
17579 cast<BuildVectorSDNode>(TheSplat.getNode())->getSplatValue();
17580 TheSplat = DAG.getSplatBuildVector(TheSplat.getValueType(), dl, SplatVal);
17581
17582 if (IsLittleEndian)
17583 RHS = TheSplat;
17584 else
17585 LHS = TheSplat;
17586 return DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
17587}
17588
17589SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
17590 LSBaseSDNode *LSBase,
17591 DAGCombinerInfo &DCI) const {
17592 assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
17593 "Not a reverse memop pattern!");
17594
17595 auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
17596 auto Mask = SVN->getMask();
17597 int i = 0;
17598 auto I = Mask.rbegin();
17599 auto E = Mask.rend();
17600
17601 for (; I != E; ++I) {
17602 if (*I != i)
17603 return false;
17604 i++;
17605 }
17606 return true;
17607 };
17608
17609 SelectionDAG &DAG = DCI.DAG;
17610 EVT VT = SVN->getValueType(0);
17611
17612 if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
17613 return SDValue();
17614
17615 // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
17616 // See comment in PPCVSXSwapRemoval.cpp.
17617 // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
17618 if (!Subtarget.hasP9Vector())
17619 return SDValue();
17620
17621 if(!IsElementReverse(SVN))
17622 return SDValue();
17623
17624 if (LSBase->getOpcode() == ISD::LOAD) {
17625 // If the load return value 0 has more than one user except the
17626 // shufflevector instruction, it is not profitable to replace the
17627 // shufflevector with a reverse load.
17628 for (SDUse &Use : LSBase->uses())
17629 if (Use.getResNo() == 0 &&
17630 Use.getUser()->getOpcode() != ISD::VECTOR_SHUFFLE)
17631 return SDValue();
17632
17633 SDLoc dl(LSBase);
17634 SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
17635 return DAG.getMemIntrinsicNode(
17636 PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
17637 LSBase->getMemoryVT(), LSBase->getMemOperand());
17638 }
17639
17640 if (LSBase->getOpcode() == ISD::STORE) {
17641 // If there are other uses of the shuffle, the swap cannot be avoided.
17642 // Forcing the use of an X-Form (since swapped stores only have
17643 // X-Forms) without removing the swap is unprofitable.
17644 if (!SVN->hasOneUse())
17645 return SDValue();
17646
17647 SDLoc dl(LSBase);
17648 SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
17649 LSBase->getBasePtr()};
17650 return DAG.getMemIntrinsicNode(
17651 PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
17652 LSBase->getMemoryVT(), LSBase->getMemOperand());
17653 }
17654
17655 llvm_unreachable("Expected a load or store node here");
17656}
17657
17658static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth) {
17659 unsigned IntrinsicID = Intrin.getConstantOperandVal(1);
17660 if (IntrinsicID == Intrinsic::ppc_stdcx)
17661 StoreWidth = 8;
17662 else if (IntrinsicID == Intrinsic::ppc_stwcx)
17663 StoreWidth = 4;
17664 else if (IntrinsicID == Intrinsic::ppc_sthcx)
17665 StoreWidth = 2;
17666 else if (IntrinsicID == Intrinsic::ppc_stbcx)
17667 StoreWidth = 1;
17668 else
17669 return false;
17670 return true;
17671}
17672
17675 if (N->getOpcode() == PPCISD::ADDC && N->hasAnyUseOfValue(1)) {
17676 // (ADDC (ADDE 0, 0, C), -1) -> C
17677 SDValue LHS = N->getOperand(0);
17678 SDValue RHS = N->getOperand(1);
17679 if (LHS->getOpcode() == PPCISD::ADDE &&
17680 isNullConstant(LHS->getOperand(0)) &&
17681 isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
17682 return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
17683 }
17684 }
17685 return SDValue();
17686}
17687
17690 if (N->getOpcode() == PPCISD::SUBE) {
17691 SDValue LHS = N->getOperand(0);
17692 SDValue RHS = N->getOperand(1);
17693 SDValue Carry = N->getOperand(2);
17694
17695 // SUBE(ADDC(ADDE(0, 0, C), -1), same, C) -> ADDC(ADDE(0, 0, C), -1)
17696 if (LHS == RHS && LHS.getOpcode() == PPCISD::ADDC) {
17697 SDValue AddcLHS = LHS.getOperand(0);
17698 SDValue AddcRHS = LHS.getOperand(1);
17699 if (AddcLHS.getOpcode() == PPCISD::ADDE &&
17700 isNullConstant(AddcLHS.getOperand(0)) &&
17701 isNullConstant(AddcLHS.getOperand(1)) && isAllOnesConstant(AddcRHS) &&
17702 Carry == AddcLHS.getOperand(2)) {
17703 return LHS;
17704 }
17705 }
17706 }
17707 return SDValue();
17708}
17709
17710/// Optimize the bitfloor(X) pattern for PowerPC.
17711/// Transforms: select_cc X, 0, 0, (srl MinSignedValue, (ctlz X)), seteq
17712/// Into: srl MinSignedValue, (ctlz X)
17713///
17714/// This is safe on PowerPC because the srw instruction returns 0 when the
17715/// shift amount is == bitwidth, which matches the behavior we need for X=0.
17717 if (N->getOpcode() != ISD::SELECT_CC)
17718 return SDValue();
17719
17720 // SELECT_CC operands: LHS, RHS, TrueVal, FalseVal, CC
17721 SDValue CmpLHS = N->getOperand(0);
17722 SDValue CmpRHS = N->getOperand(1);
17723 SDValue TrueVal = N->getOperand(2);
17724 SDValue FalseVal = N->getOperand(3);
17725 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
17726
17727 // Check if condition is (X == 0)
17728 if (CC != ISD::SETEQ || !isNullConstant(CmpRHS))
17729 return SDValue();
17730
17731 // Check if TrueVal is constant 0
17732 if (!isNullConstant(TrueVal))
17733 return SDValue();
17734
17735 // This combine is replacing a select_cc with a PPC srl, not an srl with a
17736 // PPC srl. If the original srl had multiple uses it would just remain in the
17737 // code. This is at most a performance consideration.
17738 if (FalseVal.getOpcode() != ISD::SRL || !FalseVal.hasOneUse())
17739 return SDValue();
17740
17741 SDValue ShiftVal = FalseVal.getOperand(0);
17742 SDValue ShiftAmt = FalseVal.getOperand(1);
17743
17744 // Check if ShiftVal is MinSignedValue
17745 auto *ShiftConst = dyn_cast<ConstantSDNode>(ShiftVal);
17746 if (!ShiftConst || !ShiftConst->getAPIntValue().isMinSignedValue())
17747 return SDValue();
17748
17749 SDValue CtlzArg;
17750 // Check if ShiftAmt is (ctlz CmpLHS) or (truncate (ctlz ...))
17751 if (ShiftAmt.getOpcode() != ISD::CTLZ) {
17752 // Look through truncate if present (for i64 ctlz truncated to i32 shift
17753 // amount)
17754 if (ShiftAmt.getOpcode() != ISD::TRUNCATE)
17755 return SDValue();
17756
17757 // Verify the truncate target type is appropriate for shift amount (i32, not
17758 // i1 or other)
17759 if (ShiftAmt.getValueType() != MVT::i32)
17760 return SDValue();
17761
17762 SDValue CtlzNode = ShiftAmt.getOperand(0);
17763
17764 if (CtlzNode.getOpcode() != ISD::CTLZ)
17765 return SDValue();
17766
17767 CtlzArg = CtlzNode.getOperand(0);
17768 } else {
17769 CtlzArg = ShiftAmt.getOperand(0);
17770 }
17771
17772 // Check if ctlz operates on the same value as the comparison
17773 if (CtlzArg != CmpLHS)
17774 return SDValue();
17775
17776 // Using PPCISD::SRL to ensure well-defined behavior.
17777 // On PowerPC, PPCISD::SRL guarantees that shift by bitwidth returns 0,
17778 // which is exactly what we need for the bitfloor(0) case.
17779 SDLoc DL(N);
17780 SDValue PPCSrl =
17781 DAG.getNode(PPCISD::SRL, DL, FalseVal.getValueType(), ShiftVal, ShiftAmt);
17782 return PPCSrl;
17783}
17784
17785// Optimize zero-extension of setcc when the compared value is known to be 0
17786// or 1.
17787//
17788// Pattern: zext(setcc(Value, 0, seteq/setne)) where Value is 0 or 1
17789// -> zext(xor(Value, 1)) for seteq
17790// -> zext(Value) for setne
17791//
17792// This optimization avoids the i32 -> i1 -> i32/i64 conversion sequence
17793// by keeping the value in its original i32 type throughout.
17794//
17795// Example:
17796// Before: zext(setcc(test_data_class(...), 0, seteq))
17797// // test_data_class returns 0 or 1 in i32
17798// // setcc converts i32 -> i1
17799// // zext converts i1 -> i64
17800// After: zext(xor(test_data_class(...), 1))
17801// // Stays in i32, then extends to i64
17802//
17803// This is beneficial because:
17804// 1. Eliminates the setcc instruction
17805// 2. Avoids i32 -> i1 truncation
17806// 3. Keeps computation in native integer width
17807
17809 // Check if this is a zero_extend
17810 if (N->getOpcode() != ISD::ZERO_EXTEND)
17811 return SDValue();
17812
17813 SDValue Src = N->getOperand(0);
17814
17815 // Check if the source is a setcc
17816 if (Src.getOpcode() != ISD::SETCC)
17817 return SDValue();
17818
17819 SDValue LHS = Src.getOperand(0);
17820 SDValue RHS = Src.getOperand(1);
17821 ISD::CondCode CC = cast<CondCodeSDNode>(Src.getOperand(2))->get();
17822
17824 return SDValue();
17825
17826 SDValue NonNullConstant = isNullConstant(RHS) ? LHS : RHS;
17827
17828 auto isZeroOrOne = [=](SDValue &V) {
17829 if (V.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
17830 V.getConstantOperandVal(0) == Intrinsic::ppc_test_data_class)
17831 return true;
17832 return false;
17833 };
17834
17835 if (!isZeroOrOne(NonNullConstant))
17836 return SDValue();
17837
17838 // Check for pattern: zext(setcc (Value), 0, seteq)) or
17839 // zext(setcc (Value), 0, setne))
17840 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
17841 // Replace with: zext(xor(Value, 1)) for seteq
17842 // or: zext(Value) for setne
17843 // This keeps the value in i32 instead of converting to i1
17844 SDLoc DL(N);
17845 EVT VType = N->getValueType(0);
17846 SDValue NewNonNullConstant = DAG.getZExtOrTrunc(NonNullConstant, DL, VType);
17847
17848 if (CC == ISD::SETNE)
17849 return NewNonNullConstant;
17850
17851 SDValue One = DAG.getConstant(1, DL, VType);
17852 return DAG.getNode(ISD::XOR, DL, VType, NewNonNullConstant, One);
17853 }
17854
17855 return SDValue();
17856}
17857
17858// Combine XOR patterns with SELECT_CC_I4/I8, for Example:
17859// 1. XOR(SELECT_CC_I4(cond, 1, 0, cc), 1) -> SELECT_CC_I4(cond, 0, 1, cc)
17860// 2. XOR(ZEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond, 0,
17861// 1, cc))
17862// 3. XOR(ANYEXT(SELECT_CC_I4(cond, 1, 0, cc)), 1) -> SELECT_CC_I4/I8(cond,
17863// 0, 1, cc))
17864// 4. etc
17866 assert(N->getOpcode() == ISD::XOR && "Expected XOR node");
17867
17868 EVT XorVT = N->getValueType(0);
17869 if ((XorVT != MVT::i32 && XorVT != MVT::i64))
17870 return SDValue();
17871
17872 SDValue LHS = N->getOperand(0);
17873 SDValue RHS = N->getOperand(1);
17874
17875 // Check for XOR with constant 1
17877 if (!XorConst || !XorConst->isOne()) {
17878 XorConst = dyn_cast<ConstantSDNode>(LHS);
17879 if (!XorConst || !XorConst->isOne())
17880 return SDValue();
17881 // Swap so LHS is the SELECT_CC_I4 (or extension) and RHS is the constant
17882 std::swap(LHS, RHS);
17883 }
17884
17885 // Check if LHS has only one use
17886 if (!LHS.hasOneUse())
17887 return SDValue();
17888
17889 // Handle extensions: ZEXT, ANYEXT
17890 SDValue SelectNode = LHS;
17891
17892 if (LHS.getOpcode() == ISD::ZERO_EXTEND ||
17893 LHS.getOpcode() == ISD::ANY_EXTEND) {
17894 SelectNode = LHS.getOperand(0);
17895
17896 // Check if the extension input has only one use
17897 if (!SelectNode.hasOneUse())
17898 return SDValue();
17899 }
17900
17901 // Check if SelectNode is a MachineSDNode with SELECT_CC_I4/I8 opcode
17902 if (!SelectNode.isMachineOpcode())
17903 return SDValue();
17904
17905 unsigned MachineOpc = SelectNode.getMachineOpcode();
17906
17907 // Handle both SELECT_CC_I4 and SELECT_CC_I8
17908 if (MachineOpc != PPC::SELECT_CC_I4 && MachineOpc != PPC::SELECT_CC_I8)
17909 return SDValue();
17910
17911 // SELECT_CC_I4 operands: (cond, true_val, false_val, bropc)
17912 if (SelectNode.getNumOperands() != 4)
17913 return SDValue();
17914
17915 ConstantSDNode *ConstOp1 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(1));
17916 ConstantSDNode *ConstOp2 = dyn_cast<ConstantSDNode>(SelectNode.getOperand(2));
17917
17918 if (!ConstOp1 || !ConstOp2)
17919 return SDValue();
17920
17921 // Only optimize if operands are {0, 1} or {1, 0}
17922 if (!((ConstOp1->isOne() && ConstOp2->isZero()) ||
17923 (ConstOp1->isZero() && ConstOp2->isOne())))
17924 return SDValue();
17925
17926 // Pattern matched! Create new SELECT_CC with swapped 0/1 operands to
17927 // eliminate XOR. If original was SELECT_CC(cond, 1, 0, pred), create
17928 // SELECT_CC(cond, 0, 1, pred). If original was SELECT_CC(cond, 0, 1, pred),
17929 // create SELECT_CC(cond, 1, 0, pred).
17930 SDLoc DL(N);
17931 MachineOpc = (XorVT == MVT::i32) ? PPC::SELECT_CC_I4 : PPC::SELECT_CC_I8;
17932
17933 bool ConstOp1IsOne = ConstOp1->isOne();
17934 return SDValue(
17935 DAG.getMachineNode(MachineOpc, DL, XorVT,
17936 {SelectNode.getOperand(0),
17937 DAG.getConstant(ConstOp1IsOne ? 0 : 1, DL, XorVT),
17938 DAG.getConstant(ConstOp1IsOne ? 1 : 0, DL, XorVT),
17939 SelectNode.getOperand(3)}),
17940 0);
17941}
17942
17944 DAGCombinerInfo &DCI) const {
17945 SelectionDAG &DAG = DCI.DAG;
17946 SDLoc dl(N);
17947 switch (N->getOpcode()) {
17948 default: break;
17949 case ISD::ADD:
17950 return combineADD(N, DCI);
17951 case ISD::AND: {
17952 // We don't want (and (zext (shift...)), C) if C fits in the width of the
17953 // original input as that will prevent us from selecting optimal rotates.
17954 // This only matters if the input to the extend is i32 widened to i64.
17955 SDValue Op1 = N->getOperand(0);
17956 SDValue Op2 = N->getOperand(1);
17957 if ((Op1.getOpcode() != ISD::ZERO_EXTEND &&
17958 Op1.getOpcode() != ISD::ANY_EXTEND) ||
17959 !isa<ConstantSDNode>(Op2) || N->getValueType(0) != MVT::i64 ||
17960 Op1.getOperand(0).getValueType() != MVT::i32)
17961 break;
17962 SDValue NarrowOp = Op1.getOperand(0);
17963 if (NarrowOp.getOpcode() != ISD::SHL && NarrowOp.getOpcode() != ISD::SRL &&
17964 NarrowOp.getOpcode() != ISD::ROTL && NarrowOp.getOpcode() != ISD::ROTR)
17965 break;
17966
17967 uint64_t Imm = Op2->getAsZExtVal();
17968 // Make sure that the constant is narrow enough to fit in the narrow type.
17969 if (!isUInt<32>(Imm))
17970 break;
17971 SDValue ConstOp = DAG.getConstant(Imm, dl, MVT::i32);
17972 SDValue NarrowAnd = DAG.getNode(ISD::AND, dl, MVT::i32, NarrowOp, ConstOp);
17973 return DAG.getZExtOrTrunc(NarrowAnd, dl, N->getValueType(0));
17974 }
17975 case ISD::XOR: {
17976 // Optimize XOR(ISEL(1,0,CR), 1) -> ISEL(0,1,CR)
17977 if (SDValue V = combineXorSelectCC(N, DAG))
17978 return V;
17979 break;
17980 }
17981 case ISD::SHL:
17982 return combineSHL(N, DCI);
17983 case ISD::SRA:
17984 return combineSRA(N, DCI);
17985 case ISD::SRL:
17986 return combineSRL(N, DCI);
17987 case ISD::MUL:
17988 return combineMUL(N, DCI);
17989 case ISD::FMA:
17990 case PPCISD::FNMSUB:
17991 return combineFMALike(N, DCI);
17992 case PPCISD::SHL:
17993 if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
17994 return N->getOperand(0);
17995 break;
17996 case PPCISD::SRL:
17997 if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
17998 return N->getOperand(0);
17999 break;
18000 case PPCISD::SRA:
18001 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
18002 if (C->isZero() || // 0 >>s V -> 0.
18003 C->isAllOnes()) // -1 >>s V -> -1.
18004 return N->getOperand(0);
18005 }
18006 break;
18007 case ISD::SIGN_EXTEND: {
18008 // Optimize: sign_extend(scmp) -> scmp with i64 result (on PPC64)
18009 // This eliminates the sign_extend when scmp result is being extended to i64
18010 // Pattern: t6: i64 = sign_extend t5:i32
18011 // t5: i32 = scmp t2, t4
18012 // Result: t5: i64 = scmp t2, t4
18013 SDValue N0 = N->getOperand(0);
18014 if (Subtarget.isPPC64() && N0.getOpcode() == ISD::SCMP &&
18015 N->getValueType(0) == MVT::i64 && N0.getValueType() == MVT::i32 &&
18016 N0.hasOneUse()) {
18017 // Recreate the SCMP with i64 result type directly
18018 SDValue LHS = N0.getOperand(0);
18019 SDValue RHS = N0.getOperand(1);
18020 return DAG.getNode(ISD::SCMP, dl, MVT::i64, LHS, RHS);
18021 }
18022
18023 if (SDValue SECC = combineSignExtendSetCC(N, DCI))
18024 return SECC;
18025 [[fallthrough]];
18026 }
18027 case ISD::ZERO_EXTEND:
18028 if (SDValue RetV = combineZextSetccWithZero(N, DCI.DAG))
18029 return RetV;
18030 [[fallthrough]];
18031 case ISD::ANY_EXTEND:
18032 return DAGCombineExtBoolTrunc(N, DCI);
18033 case ISD::TRUNCATE:
18034 return combineTRUNCATE(N, DCI);
18035 case ISD::SETCC:
18036 if (SDValue CSCC = combineSetCC(N, DCI))
18037 return CSCC;
18038 [[fallthrough]];
18039 case ISD::SELECT_CC:
18040 if (SDValue V = combineSELECT_CCBitFloor(N, DAG))
18041 return V;
18042 return DAGCombineTruncBoolExt(N, DCI);
18043 case ISD::SINT_TO_FP:
18044 case ISD::UINT_TO_FP:
18045 return combineFPToIntToFP(N, DCI);
18047 if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
18048 LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
18049 return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
18050 }
18051 return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
18052 case ISD::STORE: {
18053
18054 EVT Op1VT = N->getOperand(1).getValueType();
18055 unsigned Opcode = N->getOperand(1).getOpcode();
18056
18057 if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT ||
18058 Opcode == ISD::STRICT_FP_TO_SINT || Opcode == ISD::STRICT_FP_TO_UINT) {
18059 SDValue Val = combineStoreFPToInt(N, DCI);
18060 if (Val)
18061 return Val;
18062 }
18063
18064 if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
18065 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
18066 SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
18067 if (Val)
18068 return Val;
18069 }
18070
18071 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
18072 if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
18073 N->getOperand(1).getNode()->hasOneUse() &&
18074 (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
18075 (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
18076
18077 // STBRX can only handle simple types and it makes no sense to store less
18078 // two bytes in byte-reversed order.
18079 EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
18080 if (mVT.isExtended() || mVT.getSizeInBits() < 16)
18081 break;
18082
18083 SDValue BSwapOp = N->getOperand(1).getOperand(0);
18084 // Do an any-extend to 32-bits if this is a half-word input.
18085 if (BSwapOp.getValueType() == MVT::i16)
18086 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
18087
18088 // If the type of BSWAP operand is wider than stored memory width
18089 // it need to be shifted to the right side before STBRX.
18090 if (Op1VT.bitsGT(mVT)) {
18091 int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
18092 BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
18093 DAG.getConstant(Shift, dl, MVT::i32));
18094 // Need to truncate if this is a bswap of i64 stored as i32/i16.
18095 if (Op1VT == MVT::i64)
18096 BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
18097 }
18098
18099 SDValue Ops[] = {
18100 N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
18101 };
18102 return
18103 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
18104 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
18105 cast<StoreSDNode>(N)->getMemOperand());
18106 }
18107
18108 // STORE Constant:i32<0> -> STORE<trunc to i32> Constant:i64<0>
18109 // So it can increase the chance of CSE constant construction.
18110 if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
18111 isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
18112 // Need to sign-extended to 64-bits to handle negative values.
18113 EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
18114 uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
18115 MemVT.getSizeInBits());
18116 SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
18117
18118 auto *ST = cast<StoreSDNode>(N);
18119 SDValue NewST = DAG.getStore(ST->getChain(), dl, Const64,
18120 ST->getBasePtr(), ST->getOffset(), MemVT,
18121 ST->getMemOperand(), ST->getAddressingMode(),
18122 /*IsTruncating=*/true);
18123 // Note we use CombineTo here to prevent DAGCombiner from visiting the
18124 // new store which will change the constant by removing non-demanded bits.
18125 return ST->isUnindexed()
18126 ? DCI.CombineTo(N, NewST, /*AddTo=*/false)
18127 : DCI.CombineTo(N, NewST, NewST.getValue(1), /*AddTo=*/false);
18128 }
18129
18130 // For little endian, VSX stores require generating xxswapd/lxvd2x.
18131 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18132 if (Op1VT.isSimple()) {
18133 MVT StoreVT = Op1VT.getSimpleVT();
18134 if (Subtarget.needsSwapsForVSXMemOps() &&
18135 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
18136 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
18137 return expandVSXStoreForLE(N, DCI);
18138 }
18139 break;
18140 }
18141 case ISD::LOAD: {
18143 EVT VT = LD->getValueType(0);
18144
18145 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18146 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18147 if (VT.isSimple()) {
18148 MVT LoadVT = VT.getSimpleVT();
18149 if (Subtarget.needsSwapsForVSXMemOps() &&
18150 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
18151 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
18152 return expandVSXLoadForLE(N, DCI);
18153 }
18154
18155 // We sometimes end up with a 64-bit integer load, from which we extract
18156 // two single-precision floating-point numbers. This happens with
18157 // std::complex<float>, and other similar structures, because of the way we
18158 // canonicalize structure copies. However, if we lack direct moves,
18159 // then the final bitcasts from the extracted integer values to the
18160 // floating-point numbers turn into store/load pairs. Even with direct moves,
18161 // just loading the two floating-point numbers is likely better.
18162 auto ReplaceTwoFloatLoad = [&]() {
18163 if (VT != MVT::i64)
18164 return false;
18165
18166 if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
18167 LD->isVolatile())
18168 return false;
18169
18170 // We're looking for a sequence like this:
18171 // t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
18172 // t16: i64 = srl t13, Constant:i32<32>
18173 // t17: i32 = truncate t16
18174 // t18: f32 = bitcast t17
18175 // t19: i32 = truncate t13
18176 // t20: f32 = bitcast t19
18177
18178 if (!LD->hasNUsesOfValue(2, 0))
18179 return false;
18180
18181 auto UI = LD->user_begin();
18182 while (UI.getUse().getResNo() != 0) ++UI;
18183 SDNode *Trunc = *UI++;
18184 while (UI.getUse().getResNo() != 0) ++UI;
18185 SDNode *RightShift = *UI;
18186 if (Trunc->getOpcode() != ISD::TRUNCATE)
18187 std::swap(Trunc, RightShift);
18188
18189 if (Trunc->getOpcode() != ISD::TRUNCATE ||
18190 Trunc->getValueType(0) != MVT::i32 ||
18191 !Trunc->hasOneUse())
18192 return false;
18193 if (RightShift->getOpcode() != ISD::SRL ||
18194 !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
18195 RightShift->getConstantOperandVal(1) != 32 ||
18196 !RightShift->hasOneUse())
18197 return false;
18198
18199 SDNode *Trunc2 = *RightShift->user_begin();
18200 if (Trunc2->getOpcode() != ISD::TRUNCATE ||
18201 Trunc2->getValueType(0) != MVT::i32 ||
18202 !Trunc2->hasOneUse())
18203 return false;
18204
18205 SDNode *Bitcast = *Trunc->user_begin();
18206 SDNode *Bitcast2 = *Trunc2->user_begin();
18207
18208 if (Bitcast->getOpcode() != ISD::BITCAST ||
18209 Bitcast->getValueType(0) != MVT::f32)
18210 return false;
18211 if (Bitcast2->getOpcode() != ISD::BITCAST ||
18212 Bitcast2->getValueType(0) != MVT::f32)
18213 return false;
18214
18215 if (Subtarget.isLittleEndian())
18216 std::swap(Bitcast, Bitcast2);
18217
18218 // Bitcast has the second float (in memory-layout order) and Bitcast2
18219 // has the first one.
18220
18221 SDValue BasePtr = LD->getBasePtr();
18222 if (LD->isIndexed()) {
18223 assert(LD->getAddressingMode() == ISD::PRE_INC &&
18224 "Non-pre-inc AM on PPC?");
18225 BasePtr =
18226 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18227 LD->getOffset());
18228 }
18229
18230 auto MMOFlags =
18231 LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
18232 SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
18233 LD->getPointerInfo(), LD->getAlign(),
18234 MMOFlags, LD->getAAInfo());
18235 SDValue AddPtr =
18236 DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
18237 BasePtr, DAG.getIntPtrConstant(4, dl));
18238 SDValue FloatLoad2 = DAG.getLoad(
18239 MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
18240 LD->getPointerInfo().getWithOffset(4),
18241 commonAlignment(LD->getAlign(), 4), MMOFlags, LD->getAAInfo());
18242
18243 if (LD->isIndexed()) {
18244 // Note that DAGCombine should re-form any pre-increment load(s) from
18245 // what is produced here if that makes sense.
18246 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
18247 }
18248
18249 DCI.CombineTo(Bitcast2, FloatLoad);
18250 DCI.CombineTo(Bitcast, FloatLoad2);
18251
18252 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
18253 SDValue(FloatLoad2.getNode(), 1));
18254 return true;
18255 };
18256
18257 if (ReplaceTwoFloatLoad())
18258 return SDValue(N, 0);
18259
18260 EVT MemVT = LD->getMemoryVT();
18261 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
18262 Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
18263 if (LD->isUnindexed() && VT.isVector() &&
18264 ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
18265 // P8 and later hardware should just use LOAD.
18266 !Subtarget.hasP8Vector() &&
18267 (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
18268 VT == MVT::v4f32))) &&
18269 LD->getAlign() < ABIAlignment) {
18270 // This is a type-legal unaligned Altivec load.
18271 SDValue Chain = LD->getChain();
18272 SDValue Ptr = LD->getBasePtr();
18273 bool isLittleEndian = Subtarget.isLittleEndian();
18274
18275 // This implements the loading of unaligned vectors as described in
18276 // the venerable Apple Velocity Engine overview. Specifically:
18277 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
18278 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
18279 //
18280 // The general idea is to expand a sequence of one or more unaligned
18281 // loads into an alignment-based permutation-control instruction (lvsl
18282 // or lvsr), a series of regular vector loads (which always truncate
18283 // their input address to an aligned address), and a series of
18284 // permutations. The results of these permutations are the requested
18285 // loaded values. The trick is that the last "extra" load is not taken
18286 // from the address you might suspect (sizeof(vector) bytes after the
18287 // last requested load), but rather sizeof(vector) - 1 bytes after the
18288 // last requested vector. The point of this is to avoid a page fault if
18289 // the base address happened to be aligned. This works because if the
18290 // base address is aligned, then adding less than a full vector length
18291 // will cause the last vector in the sequence to be (re)loaded.
18292 // Otherwise, the next vector will be fetched as you might suspect was
18293 // necessary.
18294
18295 // We might be able to reuse the permutation generation from
18296 // a different base address offset from this one by an aligned amount.
18297 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
18298 // optimization later.
18299 Intrinsic::ID Intr, IntrLD, IntrPerm;
18300 MVT PermCntlTy, PermTy, LDTy;
18301 Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18302 : Intrinsic::ppc_altivec_lvsl;
18303 IntrLD = Intrinsic::ppc_altivec_lvx;
18304 IntrPerm = Intrinsic::ppc_altivec_vperm;
18305 PermCntlTy = MVT::v16i8;
18306 PermTy = MVT::v4i32;
18307 LDTy = MVT::v4i32;
18308
18309 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
18310
18311 // Create the new MMO for the new base load. It is like the original MMO,
18312 // but represents an area in memory almost twice the vector size centered
18313 // on the original address. If the address is unaligned, we might start
18314 // reading up to (sizeof(vector)-1) bytes below the address of the
18315 // original unaligned load.
18317 MachineMemOperand *BaseMMO =
18318 MF.getMachineMemOperand(LD->getMemOperand(),
18319 -(int64_t)MemVT.getStoreSize()+1,
18320 2*MemVT.getStoreSize()-1);
18321
18322 // Create the new base load.
18323 SDValue LDXIntID =
18324 DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
18325 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
18326 SDValue BaseLoad =
18328 DAG.getVTList(PermTy, MVT::Other),
18329 BaseLoadOps, LDTy, BaseMMO);
18330
18331 // Note that the value of IncOffset (which is provided to the next
18332 // load's pointer info offset value, and thus used to calculate the
18333 // alignment), and the value of IncValue (which is actually used to
18334 // increment the pointer value) are different! This is because we
18335 // require the next load to appear to be aligned, even though it
18336 // is actually offset from the base pointer by a lesser amount.
18337 int IncOffset = VT.getSizeInBits() / 8;
18338 int IncValue = IncOffset;
18339
18340 // Walk (both up and down) the chain looking for another load at the real
18341 // (aligned) offset (the alignment of the other load does not matter in
18342 // this case). If found, then do not use the offset reduction trick, as
18343 // that will prevent the loads from being later combined (as they would
18344 // otherwise be duplicates).
18345 if (!findConsecutiveLoad(LD, DAG))
18346 --IncValue;
18347
18349 DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
18350 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
18351
18352 MachineMemOperand *ExtraMMO =
18353 MF.getMachineMemOperand(LD->getMemOperand(),
18354 1, 2*MemVT.getStoreSize()-1);
18355 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
18356 SDValue ExtraLoad =
18358 DAG.getVTList(PermTy, MVT::Other),
18359 ExtraLoadOps, LDTy, ExtraMMO);
18360
18361 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18362 BaseLoad.getValue(1), ExtraLoad.getValue(1));
18363
18364 // Because vperm has a big-endian bias, we must reverse the order
18365 // of the input vectors and complement the permute control vector
18366 // when generating little endian code. We have already handled the
18367 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
18368 // and ExtraLoad here.
18369 SDValue Perm;
18370 if (isLittleEndian)
18371 Perm = BuildIntrinsicOp(IntrPerm,
18372 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
18373 else
18374 Perm = BuildIntrinsicOp(IntrPerm,
18375 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
18376
18377 if (VT != PermTy)
18378 Perm = Subtarget.hasAltivec()
18379 ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
18380 : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
18381 DAG.getTargetConstant(1, dl, MVT::i64));
18382 // second argument is 1 because this rounding
18383 // is always exact.
18384
18385 // The output of the permutation is our loaded result, the TokenFactor is
18386 // our new chain.
18387 DCI.CombineTo(N, Perm, TF);
18388 return SDValue(N, 0);
18389 }
18390 }
18391 break;
18393 bool isLittleEndian = Subtarget.isLittleEndian();
18394 unsigned IID = N->getConstantOperandVal(0);
18395 Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
18396 : Intrinsic::ppc_altivec_lvsl);
18397 if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
18398 SDValue Add = N->getOperand(1);
18399
18400 int Bits = 4 /* 16 byte alignment */;
18401
18402 if (DAG.MaskedValueIsZero(Add->getOperand(1),
18403 APInt::getAllOnes(Bits /* alignment */)
18404 .zext(Add.getScalarValueSizeInBits()))) {
18405 SDNode *BasePtr = Add->getOperand(0).getNode();
18406 for (SDNode *U : BasePtr->users()) {
18407 if (U->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18408 U->getConstantOperandVal(0) == IID) {
18409 // We've found another LVSL/LVSR, and this address is an aligned
18410 // multiple of that one. The results will be the same, so use the
18411 // one we've just found instead.
18412
18413 return SDValue(U, 0);
18414 }
18415 }
18416 }
18417
18418 if (isa<ConstantSDNode>(Add->getOperand(1))) {
18419 SDNode *BasePtr = Add->getOperand(0).getNode();
18420 for (SDNode *U : BasePtr->users()) {
18421 if (U->getOpcode() == ISD::ADD &&
18422 isa<ConstantSDNode>(U->getOperand(1)) &&
18423 (Add->getConstantOperandVal(1) - U->getConstantOperandVal(1)) %
18424 (1ULL << Bits) ==
18425 0) {
18426 SDNode *OtherAdd = U;
18427 for (SDNode *V : OtherAdd->users()) {
18428 if (V->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18429 V->getConstantOperandVal(0) == IID) {
18430 return SDValue(V, 0);
18431 }
18432 }
18433 }
18434 }
18435 }
18436 }
18437
18438 // Combine vmaxsw/h/b(a, a's negation) to abs(a)
18439 // Expose the vabsduw/h/b opportunity for down stream
18440 if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
18441 (IID == Intrinsic::ppc_altivec_vmaxsw ||
18442 IID == Intrinsic::ppc_altivec_vmaxsh ||
18443 IID == Intrinsic::ppc_altivec_vmaxsb)) {
18444 SDValue V1 = N->getOperand(1);
18445 SDValue V2 = N->getOperand(2);
18446 if ((V1.getSimpleValueType() == MVT::v4i32 ||
18447 V1.getSimpleValueType() == MVT::v8i16 ||
18448 V1.getSimpleValueType() == MVT::v16i8) &&
18449 V1.getSimpleValueType() == V2.getSimpleValueType()) {
18450 // (0-a, a)
18451 if (V1.getOpcode() == ISD::SUB &&
18452 ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
18453 V1.getOperand(1) == V2) {
18454 return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
18455 }
18456 // (a, 0-a)
18457 if (V2.getOpcode() == ISD::SUB &&
18459 V2.getOperand(1) == V1) {
18460 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18461 }
18462 // (x-y, y-x)
18463 if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
18464 V1.getOperand(0) == V2.getOperand(1) &&
18465 V1.getOperand(1) == V2.getOperand(0)) {
18466 return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
18467 }
18468 }
18469 }
18470 }
18471
18472 break;
18474 switch (N->getConstantOperandVal(1)) {
18475 default:
18476 break;
18477 case Intrinsic::ppc_altivec_vsum4sbs:
18478 case Intrinsic::ppc_altivec_vsum4shs:
18479 case Intrinsic::ppc_altivec_vsum4ubs: {
18480 // These sum-across intrinsics only have a chain due to the side effect
18481 // that they may set the SAT bit. If we know the SAT bit will not be set
18482 // for some inputs, we can replace any uses of their chain with the
18483 // input chain.
18484 if (BuildVectorSDNode *BVN =
18485 dyn_cast<BuildVectorSDNode>(N->getOperand(3))) {
18486 APInt APSplatBits, APSplatUndef;
18487 unsigned SplatBitSize;
18488 bool HasAnyUndefs;
18489 bool BVNIsConstantSplat = BVN->isConstantSplat(
18490 APSplatBits, APSplatUndef, SplatBitSize, HasAnyUndefs, 0,
18491 !Subtarget.isLittleEndian());
18492 // If the constant splat vector is 0, the SAT bit will not be set.
18493 if (BVNIsConstantSplat && APSplatBits == 0)
18494 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), N->getOperand(0));
18495 }
18496 return SDValue();
18497 }
18498 case Intrinsic::ppc_vsx_lxvw4x:
18499 case Intrinsic::ppc_vsx_lxvd2x:
18500 // For little endian, VSX loads require generating lxvd2x/xxswapd.
18501 // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
18502 if (Subtarget.needsSwapsForVSXMemOps())
18503 return expandVSXLoadForLE(N, DCI);
18504 break;
18505 }
18506 break;
18508 // For little endian, VSX stores require generating xxswapd/stxvd2x.
18509 // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
18510 if (Subtarget.needsSwapsForVSXMemOps()) {
18511 switch (N->getConstantOperandVal(1)) {
18512 default:
18513 break;
18514 case Intrinsic::ppc_vsx_stxvw4x:
18515 case Intrinsic::ppc_vsx_stxvd2x:
18516 return expandVSXStoreForLE(N, DCI);
18517 }
18518 }
18519 break;
18520 case ISD::BSWAP: {
18521 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
18522 // For subtargets without LDBRX, we can still do better than the default
18523 // expansion even for 64-bit BSWAP (LOAD).
18524 bool Is64BitBswapOn64BitTgt =
18525 Subtarget.isPPC64() && N->getValueType(0) == MVT::i64;
18526 bool IsSingleUseNormalLd = ISD::isNormalLoad(N->getOperand(0).getNode()) &&
18527 N->getOperand(0).hasOneUse();
18528 if (IsSingleUseNormalLd &&
18529 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
18530 (Subtarget.hasLDBRX() && Is64BitBswapOn64BitTgt))) {
18531 SDValue Load = N->getOperand(0);
18533 // Create the byte-swapping load.
18534 SDValue Ops[] = {
18535 LD->getChain(), // Chain
18536 LD->getBasePtr(), // Ptr
18537 DAG.getValueType(N->getValueType(0)) // VT
18538 };
18539 SDValue BSLoad =
18540 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
18541 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
18542 MVT::i64 : MVT::i32, MVT::Other),
18543 Ops, LD->getMemoryVT(), LD->getMemOperand());
18544
18545 // If this is an i16 load, insert the truncate.
18546 SDValue ResVal = BSLoad;
18547 if (N->getValueType(0) == MVT::i16)
18548 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
18549
18550 // First, combine the bswap away. This makes the value produced by the
18551 // load dead.
18552 DCI.CombineTo(N, ResVal);
18553
18554 // Next, combine the load away, we give it a bogus result value but a real
18555 // chain result. The result value is dead because the bswap is dead.
18556 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
18557
18558 // Return N so it doesn't get rechecked!
18559 return SDValue(N, 0);
18560 }
18561 // Convert this to two 32-bit bswap loads and a BUILD_PAIR. Do this only
18562 // before legalization so that the BUILD_PAIR is handled correctly.
18563 if (!DCI.isBeforeLegalize() || !Is64BitBswapOn64BitTgt ||
18564 !IsSingleUseNormalLd)
18565 return SDValue();
18566 LoadSDNode *LD = cast<LoadSDNode>(N->getOperand(0));
18567
18568 // Can't split volatile or atomic loads.
18569 if (!LD->isSimple())
18570 return SDValue();
18571 SDValue BasePtr = LD->getBasePtr();
18572 SDValue Lo = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr,
18573 LD->getPointerInfo(), LD->getAlign());
18574 Lo = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Lo);
18575 BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
18576 DAG.getIntPtrConstant(4, dl));
18578 LD->getMemOperand(), 4, 4);
18579 SDValue Hi = DAG.getLoad(MVT::i32, dl, LD->getChain(), BasePtr, NewMMO);
18580 Hi = DAG.getNode(ISD::BSWAP, dl, MVT::i32, Hi);
18581 SDValue Res;
18582 if (Subtarget.isLittleEndian())
18583 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Hi, Lo);
18584 else
18585 Res = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
18586 SDValue TF =
18587 DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18588 Hi.getOperand(0).getValue(1), Lo.getOperand(0).getValue(1));
18589 DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), TF);
18590 return Res;
18591 }
18592 case PPCISD::VCMP:
18593 // If a VCMP_rec node already exists with exactly the same operands as this
18594 // node, use its result instead of this node (VCMP_rec computes both a CR6
18595 // and a normal output).
18596 //
18597 if (!N->getOperand(0).hasOneUse() &&
18598 !N->getOperand(1).hasOneUse() &&
18599 !N->getOperand(2).hasOneUse()) {
18600
18601 // Scan all of the users of the LHS, looking for VCMP_rec's that match.
18602 SDNode *VCMPrecNode = nullptr;
18603
18604 SDNode *LHSN = N->getOperand(0).getNode();
18605 for (SDNode *User : LHSN->users())
18606 if (User->getOpcode() == PPCISD::VCMP_rec &&
18607 User->getOperand(1) == N->getOperand(1) &&
18608 User->getOperand(2) == N->getOperand(2) &&
18609 User->getOperand(0) == N->getOperand(0)) {
18610 VCMPrecNode = User;
18611 break;
18612 }
18613
18614 // If there is no VCMP_rec node, or if the flag value has a single use,
18615 // don't transform this.
18616 if (!VCMPrecNode || VCMPrecNode->hasNUsesOfValue(0, 1))
18617 break;
18618
18619 // Look at the (necessarily single) use of the flag value. If it has a
18620 // chain, this transformation is more complex. Note that multiple things
18621 // could use the value result, which we should ignore.
18622 SDNode *FlagUser = nullptr;
18623 for (SDNode::use_iterator UI = VCMPrecNode->use_begin();
18624 FlagUser == nullptr; ++UI) {
18625 assert(UI != VCMPrecNode->use_end() && "Didn't find user!");
18626 SDNode *User = UI->getUser();
18627 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
18628 if (User->getOperand(i) == SDValue(VCMPrecNode, 1)) {
18629 FlagUser = User;
18630 break;
18631 }
18632 }
18633 }
18634
18635 // If the user is a MFOCRF instruction, we know this is safe.
18636 // Otherwise we give up for right now.
18637 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
18638 return SDValue(VCMPrecNode, 0);
18639 }
18640 break;
18641 case ISD::BR_CC: {
18642 // If this is a branch on an altivec predicate comparison, lower this so
18643 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
18644 // lowering is done pre-legalize, because the legalizer lowers the predicate
18645 // compare down to code that is difficult to reassemble.
18646 // This code also handles branches that depend on the result of a store
18647 // conditional.
18648 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
18649 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
18650
18651 int CompareOpc;
18652 bool isDot;
18653
18654 if (!isa<ConstantSDNode>(RHS) || (CC != ISD::SETEQ && CC != ISD::SETNE))
18655 break;
18656
18657 // Since we are doing this pre-legalize, the RHS can be a constant of
18658 // arbitrary bitwidth which may cause issues when trying to get the value
18659 // from the underlying APInt.
18660 auto RHSAPInt = RHS->getAsAPIntVal();
18661 if (!RHSAPInt.isIntN(64))
18662 break;
18663
18664 unsigned Val = RHSAPInt.getZExtValue();
18665 auto isImpossibleCompare = [&]() {
18666 // If this is a comparison against something other than 0/1, then we know
18667 // that the condition is never/always true.
18668 if (Val != 0 && Val != 1) {
18669 if (CC == ISD::SETEQ) // Cond never true, remove branch.
18670 return N->getOperand(0);
18671 // Always !=, turn it into an unconditional branch.
18672 return DAG.getNode(ISD::BR, dl, MVT::Other,
18673 N->getOperand(0), N->getOperand(4));
18674 }
18675 return SDValue();
18676 };
18677 // Combine branches fed by store conditional instructions (st[bhwd]cx).
18678 unsigned StoreWidth = 0;
18679 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
18680 isStoreConditional(LHS, StoreWidth)) {
18681 if (SDValue Impossible = isImpossibleCompare())
18682 return Impossible;
18683 PPC::Predicate CompOpc;
18684 // eq 0 => ne
18685 // ne 0 => eq
18686 // eq 1 => eq
18687 // ne 1 => ne
18688 if (Val == 0)
18689 CompOpc = CC == ISD::SETEQ ? PPC::PRED_NE : PPC::PRED_EQ;
18690 else
18691 CompOpc = CC == ISD::SETEQ ? PPC::PRED_EQ : PPC::PRED_NE;
18692
18693 SDValue Ops[] = {LHS.getOperand(0), LHS.getOperand(2), LHS.getOperand(3),
18694 DAG.getConstant(StoreWidth, dl, MVT::i32)};
18695 auto *MemNode = cast<MemSDNode>(LHS);
18696 SDValue ConstSt = DAG.getMemIntrinsicNode(
18697 PPCISD::STORE_COND, dl,
18698 DAG.getVTList(MVT::i32, MVT::Other, MVT::Glue), Ops,
18699 MemNode->getMemoryVT(), MemNode->getMemOperand());
18700
18701 SDValue InChain;
18702 // Unchain the branch from the original store conditional.
18703 if (N->getOperand(0) == LHS.getValue(1))
18704 InChain = LHS.getOperand(0);
18705 else if (N->getOperand(0).getOpcode() == ISD::TokenFactor) {
18706 SmallVector<SDValue, 4> InChains;
18707 SDValue InTF = N->getOperand(0);
18708 for (int i = 0, e = InTF.getNumOperands(); i < e; i++)
18709 if (InTF.getOperand(i) != LHS.getValue(1))
18710 InChains.push_back(InTF.getOperand(i));
18711 InChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, InChains);
18712 }
18713
18714 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, InChain,
18715 DAG.getConstant(CompOpc, dl, MVT::i32),
18716 DAG.getRegister(PPC::CR0, MVT::i32), N->getOperand(4),
18717 ConstSt.getValue(2));
18718 }
18719
18720 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
18721 getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
18722 assert(isDot && "Can't compare against a vector result!");
18723
18724 if (SDValue Impossible = isImpossibleCompare())
18725 return Impossible;
18726
18727 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
18728 // Create the PPCISD altivec 'dot' comparison node.
18729 SDValue Ops[] = {
18730 LHS.getOperand(2), // LHS of compare
18731 LHS.getOperand(3), // RHS of compare
18732 DAG.getConstant(CompareOpc, dl, MVT::i32)
18733 };
18734 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
18735 SDValue CompNode = DAG.getNode(PPCISD::VCMP_rec, dl, VTs, Ops);
18736
18737 // Unpack the result based on how the target uses it.
18738 PPC::Predicate CompOpc;
18739 switch (LHS.getConstantOperandVal(1)) {
18740 default: // Can't happen, don't crash on invalid number though.
18741 case 0: // Branch on the value of the EQ bit of CR6.
18742 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
18743 break;
18744 case 1: // Branch on the inverted value of the EQ bit of CR6.
18745 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
18746 break;
18747 case 2: // Branch on the value of the LT bit of CR6.
18748 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
18749 break;
18750 case 3: // Branch on the inverted value of the LT bit of CR6.
18751 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
18752 break;
18753 }
18754
18755 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
18756 DAG.getConstant(CompOpc, dl, MVT::i32),
18757 DAG.getRegister(PPC::CR6, MVT::i32),
18758 N->getOperand(4), CompNode.getValue(1));
18759 }
18760 break;
18761 }
18762 case ISD::BUILD_VECTOR:
18763 return DAGCombineBuildVector(N, DCI);
18764 case PPCISD::ADDC:
18765 return DAGCombineAddc(N, DCI);
18766 case PPCISD::SUBE:
18767 return DAGCombineSube(N, DCI);
18768
18769 case ISD::BITCAST:
18770 return DAGCombineBitcast(N, DCI);
18771 }
18772
18773 return SDValue();
18774}
18775
18776SDValue
18778 SelectionDAG &DAG,
18779 SmallVectorImpl<SDNode *> &Created) const {
18780 // fold (sdiv X, pow2)
18781 EVT VT = N->getValueType(0);
18782 if (VT == MVT::i64 && !Subtarget.isPPC64())
18783 return SDValue();
18784 if ((VT != MVT::i32 && VT != MVT::i64) ||
18785 !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
18786 return SDValue();
18787
18788 SDLoc DL(N);
18789 SDValue N0 = N->getOperand(0);
18790
18791 bool IsNegPow2 = Divisor.isNegatedPowerOf2();
18792 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countr_zero();
18793 SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
18794
18795 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
18796 Created.push_back(Op.getNode());
18797
18798 if (IsNegPow2) {
18799 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
18800 Created.push_back(Op.getNode());
18801 }
18802
18803 return Op;
18804}
18805
18806//===----------------------------------------------------------------------===//
18807// Inline Assembly Support
18808//===----------------------------------------------------------------------===//
18809
18812 const APInt &DemandedElts,
18813 const SelectionDAG &DAG,
18814 unsigned Depth) const {
18815 Known.resetAll();
18816 switch (Op.getOpcode()) {
18817 default: break;
18818 case PPCISD::LBRX: {
18819 // lhbrx is known to have the top bits cleared out.
18820 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
18821 Known.Zero = 0xFFFF0000;
18822 break;
18823 }
18824 case PPCISD::ADDE: {
18825 if (Op.getResNo() == 0) {
18826 // (0|1), _ = ADDE 0, 0, CARRY
18827 SDValue LHS = Op.getOperand(0);
18828 SDValue RHS = Op.getOperand(1);
18829 if (isNullConstant(LHS) && isNullConstant(RHS))
18830 Known.Zero = ~1ULL;
18831 }
18832 break;
18833 }
18835 switch (Op.getConstantOperandVal(0)) {
18836 default: break;
18837 case Intrinsic::ppc_altivec_vcmpbfp_p:
18838 case Intrinsic::ppc_altivec_vcmpeqfp_p:
18839 case Intrinsic::ppc_altivec_vcmpequb_p:
18840 case Intrinsic::ppc_altivec_vcmpequh_p:
18841 case Intrinsic::ppc_altivec_vcmpequw_p:
18842 case Intrinsic::ppc_altivec_vcmpequd_p:
18843 case Intrinsic::ppc_altivec_vcmpequq_p:
18844 case Intrinsic::ppc_altivec_vcmpgefp_p:
18845 case Intrinsic::ppc_altivec_vcmpgtfp_p:
18846 case Intrinsic::ppc_altivec_vcmpgtsb_p:
18847 case Intrinsic::ppc_altivec_vcmpgtsh_p:
18848 case Intrinsic::ppc_altivec_vcmpgtsw_p:
18849 case Intrinsic::ppc_altivec_vcmpgtsd_p:
18850 case Intrinsic::ppc_altivec_vcmpgtsq_p:
18851 case Intrinsic::ppc_altivec_vcmpgtub_p:
18852 case Intrinsic::ppc_altivec_vcmpgtuh_p:
18853 case Intrinsic::ppc_altivec_vcmpgtuw_p:
18854 case Intrinsic::ppc_altivec_vcmpgtud_p:
18855 case Intrinsic::ppc_altivec_vcmpgtuq_p:
18856 Known.Zero = ~1U; // All bits but the low one are known to be zero.
18857 break;
18858 }
18859 break;
18860 }
18862 switch (Op.getConstantOperandVal(1)) {
18863 default:
18864 break;
18865 case Intrinsic::ppc_load2r:
18866 // Top bits are cleared for load2r (which is the same as lhbrx).
18867 Known.Zero = 0xFFFF0000;
18868 break;
18869 }
18870 break;
18871 }
18872 }
18873}
18874
18876 MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const {
18877 switch (Subtarget.getCPUDirective()) {
18878 default: break;
18879 case PPC::DIR_970:
18880 case PPC::DIR_PWR4:
18881 case PPC::DIR_PWR5:
18882 case PPC::DIR_PWR5X:
18883 case PPC::DIR_PWR6:
18884 case PPC::DIR_PWR6X:
18885 case PPC::DIR_PWR7:
18886 case PPC::DIR_PWR8:
18887 case PPC::DIR_PWR9:
18888 case PPC::DIR_PWR10:
18889 case PPC::DIR_PWR11:
18890 case PPC::DIR_PWR_FUTURE: {
18891 if (!ML)
18892 break;
18893
18895 // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
18896 // so that we can decrease cache misses and branch-prediction misses.
18897 // Actual alignment of the loop will depend on the hotness check and other
18898 // logic in alignBlocks.
18899 if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
18900 return Align(32);
18901 }
18902
18903 const PPCInstrInfo *TII = Subtarget.getInstrInfo();
18904
18905 // For small loops (between 5 and 8 instructions), align to a 32-byte
18906 // boundary so that the entire loop fits in one instruction-cache line.
18907 uint64_t LoopSize = 0;
18908 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
18909 for (const MachineInstr &J : **I) {
18910 LoopSize += TII->getInstSizeInBytes(J);
18911 if (LoopSize > 32)
18912 break;
18913 }
18914
18915 if (LoopSize > 16 && LoopSize <= 32)
18916 return Align(32);
18917
18918 break;
18919 }
18920 }
18921
18923}
18924
18925/// getConstraintType - Given a constraint, return the type of
18926/// constraint it is for this target.
18929 if (Constraint.size() == 1) {
18930 switch (Constraint[0]) {
18931 default: break;
18932 case 'b':
18933 case 'r':
18934 case 'f':
18935 case 'd':
18936 case 'v':
18937 case 'y':
18938 return C_RegisterClass;
18939 case 'Z':
18940 // FIXME: While Z does indicate a memory constraint, it specifically
18941 // indicates an r+r address (used in conjunction with the 'y' modifier
18942 // in the replacement string). Currently, we're forcing the base
18943 // register to be r0 in the asm printer (which is interpreted as zero)
18944 // and forming the complete address in the second register. This is
18945 // suboptimal.
18946 return C_Memory;
18947 }
18948 } else if (Constraint == "wc") { // individual CR bits.
18949 return C_RegisterClass;
18950 } else if (Constraint == "wa" || Constraint == "wd" ||
18951 Constraint == "wf" || Constraint == "ws" ||
18952 Constraint == "wi" || Constraint == "ww") {
18953 return C_RegisterClass; // VSX registers.
18954 }
18955 return TargetLowering::getConstraintType(Constraint);
18956}
18957
18958/// Examine constraint type and operand type and determine a weight value.
18959/// This object must already have been set up with the operand type
18960/// and the current alternative constraint selected.
18963 AsmOperandInfo &info, const char *constraint) const {
18965 Value *CallOperandVal = info.CallOperandVal;
18966 // If we don't have a value, we can't do a match,
18967 // but allow it at the lowest weight.
18968 if (!CallOperandVal)
18969 return CW_Default;
18970 Type *type = CallOperandVal->getType();
18971
18972 // Look at the constraint type.
18973 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
18974 return CW_Register; // an individual CR bit.
18975 else if ((StringRef(constraint) == "wa" ||
18976 StringRef(constraint) == "wd" ||
18977 StringRef(constraint) == "wf") &&
18978 type->isVectorTy())
18979 return CW_Register;
18980 else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
18981 return CW_Register; // just hold 64-bit integers data.
18982 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
18983 return CW_Register;
18984 else if (StringRef(constraint) == "ww" && type->isFloatTy())
18985 return CW_Register;
18986
18987 switch (*constraint) {
18988 default:
18990 break;
18991 case 'b':
18992 if (type->isIntegerTy())
18993 weight = CW_Register;
18994 break;
18995 case 'f':
18996 if (type->isFloatTy())
18997 weight = CW_Register;
18998 break;
18999 case 'd':
19000 if (type->isDoubleTy())
19001 weight = CW_Register;
19002 break;
19003 case 'v':
19004 if (type->isVectorTy())
19005 weight = CW_Register;
19006 break;
19007 case 'y':
19008 weight = CW_Register;
19009 break;
19010 case 'Z':
19011 weight = CW_Memory;
19012 break;
19013 }
19014 return weight;
19015}
19016
19017std::pair<unsigned, const TargetRegisterClass *>
19019 StringRef Constraint,
19020 MVT VT) const {
19021 if (Constraint.size() == 1) {
19022 // GCC RS6000 Constraint Letters
19023 switch (Constraint[0]) {
19024 case 'b': // R1-R31
19025 if (VT == MVT::i64 && Subtarget.isPPC64())
19026 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
19027 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
19028 case 'r': // R0-R31
19029 if (VT == MVT::i64 && Subtarget.isPPC64())
19030 return std::make_pair(0U, &PPC::G8RCRegClass);
19031 return std::make_pair(0U, &PPC::GPRCRegClass);
19032 // 'd' and 'f' constraints are both defined to be "the floating point
19033 // registers", where one is for 32-bit and the other for 64-bit. We don't
19034 // really care overly much here so just give them all the same reg classes.
19035 case 'd':
19036 case 'f':
19037 if (Subtarget.hasSPE()) {
19038 if (VT == MVT::f32 || VT == MVT::i32)
19039 return std::make_pair(0U, &PPC::GPRCRegClass);
19040 if (VT == MVT::f64 || VT == MVT::i64)
19041 return std::make_pair(0U, &PPC::SPERCRegClass);
19042 } else {
19043 if (VT == MVT::f32 || VT == MVT::i32)
19044 return std::make_pair(0U, &PPC::F4RCRegClass);
19045 if (VT == MVT::f64 || VT == MVT::i64)
19046 return std::make_pair(0U, &PPC::F8RCRegClass);
19047 }
19048 break;
19049 case 'v':
19050 if (Subtarget.hasAltivec() && VT.isVector())
19051 return std::make_pair(0U, &PPC::VRRCRegClass);
19052 else if (Subtarget.hasVSX())
19053 // Scalars in Altivec registers only make sense with VSX.
19054 return std::make_pair(0U, &PPC::VFRCRegClass);
19055 break;
19056 case 'y': // crrc
19057 return std::make_pair(0U, &PPC::CRRCRegClass);
19058 }
19059 } else if (Constraint == "wc" && Subtarget.useCRBits()) {
19060 // An individual CR bit.
19061 return std::make_pair(0U, &PPC::CRBITRCRegClass);
19062 } else if ((Constraint == "wa" || Constraint == "wd" ||
19063 Constraint == "wf" || Constraint == "wi") &&
19064 Subtarget.hasVSX()) {
19065 // A VSX register for either a scalar (FP) or vector. There is no
19066 // support for single precision scalars on subtargets prior to Power8.
19067 if (VT.isVector())
19068 return std::make_pair(0U, &PPC::VSRCRegClass);
19069 if (VT == MVT::f32 && Subtarget.hasP8Vector())
19070 return std::make_pair(0U, &PPC::VSSRCRegClass);
19071 return std::make_pair(0U, &PPC::VSFRCRegClass);
19072 } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
19073 if (VT == MVT::f32 && Subtarget.hasP8Vector())
19074 return std::make_pair(0U, &PPC::VSSRCRegClass);
19075 else
19076 return std::make_pair(0U, &PPC::VSFRCRegClass);
19077 } else if (Constraint == "lr") {
19078 if (VT == MVT::i64)
19079 return std::make_pair(0U, &PPC::LR8RCRegClass);
19080 else
19081 return std::make_pair(0U, &PPC::LRRCRegClass);
19082 }
19083
19084 // Handle special cases of physical registers that are not properly handled
19085 // by the base class.
19086 if (Constraint[0] == '{' && Constraint[Constraint.size() - 1] == '}') {
19087 // If we name a VSX register, we can't defer to the base class because it
19088 // will not recognize the correct register (their names will be VSL{0-31}
19089 // and V{0-31} so they won't match). So we match them here.
19090 if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
19091 int VSNum = atoi(Constraint.data() + 3);
19092 assert(VSNum >= 0 && VSNum <= 63 &&
19093 "Attempted to access a vsr out of range");
19094 if (VSNum < 32)
19095 return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
19096 return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
19097 }
19098
19099 // For float registers, we can't defer to the base class as it will match
19100 // the SPILLTOVSRRC class.
19101 if (Constraint.size() > 3 && Constraint[1] == 'f') {
19102 int RegNum = atoi(Constraint.data() + 2);
19103 if (RegNum > 31 || RegNum < 0)
19104 report_fatal_error("Invalid floating point register number");
19105 if (VT == MVT::f32 || VT == MVT::i32)
19106 return Subtarget.hasSPE()
19107 ? std::make_pair(PPC::R0 + RegNum, &PPC::GPRCRegClass)
19108 : std::make_pair(PPC::F0 + RegNum, &PPC::F4RCRegClass);
19109 if (VT == MVT::f64 || VT == MVT::i64)
19110 return Subtarget.hasSPE()
19111 ? std::make_pair(PPC::S0 + RegNum, &PPC::SPERCRegClass)
19112 : std::make_pair(PPC::F0 + RegNum, &PPC::F8RCRegClass);
19113 }
19114 }
19115
19116 std::pair<unsigned, const TargetRegisterClass *> R =
19118
19119 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
19120 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
19121 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
19122 // register.
19123 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
19124 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
19125 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
19126 PPC::GPRCRegClass.contains(R.first))
19127 return std::make_pair(TRI->getMatchingSuperReg(R.first,
19128 PPC::sub_32, &PPC::G8RCRegClass),
19129 &PPC::G8RCRegClass);
19130
19131 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
19132 if (!R.second && StringRef("{cc}").equals_insensitive(Constraint)) {
19133 R.first = PPC::CR0;
19134 R.second = &PPC::CRRCRegClass;
19135 }
19136 // FIXME: This warning should ideally be emitted in the front end.
19137 if (Subtarget.isAIXABI() && !Subtarget.isAIXExtendedAltivecABI()) {
19138 if (((R.first >= PPC::V20 && R.first <= PPC::V31) ||
19139 (R.first >= PPC::VF20 && R.first <= PPC::VF31)) &&
19140 (R.second == &PPC::VSRCRegClass || R.second == &PPC::VSFRCRegClass))
19141 errs() << "warning: vector registers 20 to 32 are reserved in the "
19142 "default AIX AltiVec ABI and cannot be used\n";
19143 }
19144
19145 return R;
19146}
19147
19148/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
19149/// vector. If it is invalid, don't add anything to Ops.
19151 StringRef Constraint,
19152 std::vector<SDValue> &Ops,
19153 SelectionDAG &DAG) const {
19154 SDValue Result;
19155
19156 // Only support length 1 constraints.
19157 if (Constraint.size() > 1)
19158 return;
19159
19160 char Letter = Constraint[0];
19161 switch (Letter) {
19162 default: break;
19163 case 'I':
19164 case 'J':
19165 case 'K':
19166 case 'L':
19167 case 'M':
19168 case 'N':
19169 case 'O':
19170 case 'P': {
19172 if (!CST) return; // Must be an immediate to match.
19173 SDLoc dl(Op);
19174 int64_t Value = CST->getSExtValue();
19175 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
19176 // numbers are printed as such.
19177 switch (Letter) {
19178 default: llvm_unreachable("Unknown constraint letter!");
19179 case 'I': // "I" is a signed 16-bit constant.
19180 if (isInt<16>(Value))
19181 Result = DAG.getTargetConstant(Value, dl, TCVT);
19182 break;
19183 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
19185 Result = DAG.getTargetConstant(Value, dl, TCVT);
19186 break;
19187 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
19189 Result = DAG.getTargetConstant(Value, dl, TCVT);
19190 break;
19191 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
19192 if (isUInt<16>(Value))
19193 Result = DAG.getTargetConstant(Value, dl, TCVT);
19194 break;
19195 case 'M': // "M" is a constant that is greater than 31.
19196 if (Value > 31)
19197 Result = DAG.getTargetConstant(Value, dl, TCVT);
19198 break;
19199 case 'N': // "N" is a positive constant that is an exact power of two.
19200 if (Value > 0 && isPowerOf2_64(Value))
19201 Result = DAG.getTargetConstant(Value, dl, TCVT);
19202 break;
19203 case 'O': // "O" is the constant zero.
19204 if (Value == 0)
19205 Result = DAG.getTargetConstant(Value, dl, TCVT);
19206 break;
19207 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
19208 if (isInt<16>(-Value))
19209 Result = DAG.getTargetConstant(Value, dl, TCVT);
19210 break;
19211 }
19212 break;
19213 }
19214 }
19215
19216 if (Result.getNode()) {
19217 Ops.push_back(Result);
19218 return;
19219 }
19220
19221 // Handle standard constraint letters.
19223}
19224
19227 SelectionDAG &DAG) const {
19228 if (I.getNumOperands() <= 1)
19229 return;
19230 if (!isa<ConstantSDNode>(Ops[1].getNode()))
19231 return;
19232 auto IntrinsicID = Ops[1].getNode()->getAsZExtVal();
19233 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
19234 IntrinsicID != Intrinsic::ppc_trapd && IntrinsicID != Intrinsic::ppc_trap)
19235 return;
19236
19237 if (MDNode *MDN = I.getMetadata(LLVMContext::MD_annotation))
19238 Ops.push_back(DAG.getMDNode(MDN));
19239}
19240
19241// isLegalAddressingMode - Return true if the addressing mode represented
19242// by AM is legal for this target, for a load/store of the specified type.
19244 const AddrMode &AM, Type *Ty,
19245 unsigned AS,
19246 Instruction *I) const {
19247 // Vector type r+i form is supported since power9 as DQ form. We don't check
19248 // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
19249 // imm form is preferred and the offset can be adjusted to use imm form later
19250 // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
19251 // max offset to check legal addressing mode, we should be a little aggressive
19252 // to contain other offsets for that LSRUse.
19253 if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
19254 return false;
19255
19256 // PPC allows a sign-extended 16-bit immediate field.
19257 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
19258 return false;
19259
19260 // No global is ever allowed as a base.
19261 if (AM.BaseGV)
19262 return false;
19263
19264 // PPC only support r+r,
19265 switch (AM.Scale) {
19266 case 0: // "r+i" or just "i", depending on HasBaseReg.
19267 break;
19268 case 1:
19269 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
19270 return false;
19271 // Otherwise we have r+r or r+i.
19272 break;
19273 case 2:
19274 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
19275 return false;
19276 // Allow 2*r as r+r.
19277 break;
19278 default:
19279 // No other scales are supported.
19280 return false;
19281 }
19282
19283 return true;
19284}
19285
19286SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
19287 SelectionDAG &DAG) const {
19289 MachineFrameInfo &MFI = MF.getFrameInfo();
19290 MFI.setReturnAddressIsTaken(true);
19291
19292 SDLoc dl(Op);
19293 unsigned Depth = Op.getConstantOperandVal(0);
19294
19295 // Make sure the function does not optimize away the store of the RA to
19296 // the stack.
19297 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
19298 FuncInfo->setLRStoreRequired();
19299 auto PtrVT = getPointerTy(MF.getDataLayout());
19300
19301 if (Depth > 0) {
19302 // The link register (return address) is saved in the caller's frame
19303 // not the callee's stack frame. So we must get the caller's frame
19304 // address and load the return address at the LR offset from there.
19305 SDValue FrameAddr =
19306 DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19308 SDValue Offset =
19309 DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
19310 Subtarget.getScalarIntVT());
19311 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
19312 DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
19314 }
19315
19316 // Just load the return address off the stack.
19317 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
19318 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
19320}
19321
19322SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
19323 SelectionDAG &DAG) const {
19324 SDLoc dl(Op);
19325 unsigned Depth = Op.getConstantOperandVal(0);
19326
19328 MachineFrameInfo &MFI = MF.getFrameInfo();
19329 MFI.setFrameAddressIsTaken(true);
19330
19331 EVT PtrVT = getPointerTy(MF.getDataLayout());
19332 bool isPPC64 = PtrVT == MVT::i64;
19333
19334 // Naked functions never have a frame pointer, and so we use r1. For all
19335 // other functions, this decision must be delayed until during PEI.
19336 unsigned FrameReg;
19337 if (MF.getFunction().hasFnAttribute(Attribute::Naked))
19338 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
19339 else
19340 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
19341
19342 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
19343 PtrVT);
19344 while (Depth--)
19345 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
19346 FrameAddr, MachinePointerInfo());
19347 return FrameAddr;
19348}
19349
19350#define GET_REGISTER_MATCHER
19351#include "PPCGenAsmMatcher.inc"
19352
19354 const MachineFunction &MF) const {
19355 bool IsPPC64 = Subtarget.isPPC64();
19356
19357 bool Is64Bit = IsPPC64 && VT == LLT::scalar(64);
19358 if (!Is64Bit && VT != LLT::scalar(32))
19359 report_fatal_error("Invalid register global variable type");
19360
19362 if (!Reg)
19363 return Reg;
19364
19365 // FIXME: Unable to generate code for `-O2` but okay for `-O0`.
19366 // Need followup investigation as to why.
19367 if ((IsPPC64 && Reg == PPC::R2) || Reg == PPC::R0)
19368 report_fatal_error(Twine("Trying to reserve an invalid register \"" +
19369 StringRef(RegName) + "\"."));
19370
19371 // Convert GPR to GP8R register for 64bit.
19372 if (Is64Bit && StringRef(RegName).starts_with_insensitive("r"))
19373 Reg = Reg.id() - PPC::R0 + PPC::X0;
19374
19375 return Reg;
19376}
19377
19379 // 32-bit SVR4 ABI access everything as got-indirect.
19380 if (Subtarget.is32BitELFABI())
19381 return true;
19382
19383 // AIX accesses everything indirectly through the TOC, which is similar to
19384 // the GOT.
19385 if (Subtarget.isAIXABI())
19386 return true;
19387
19389 // If it is small or large code model, module locals are accessed
19390 // indirectly by loading their address from .toc/.got.
19391 if (CModel == CodeModel::Small || CModel == CodeModel::Large)
19392 return true;
19393
19394 // JumpTable and BlockAddress are accessed as got-indirect.
19396 return true;
19397
19399 return Subtarget.isGVIndirectSymbol(G->getGlobal());
19400
19401 return false;
19402}
19403
19404bool
19406 // The PowerPC target isn't yet aware of offsets.
19407 return false;
19408}
19409
19412 MachineFunction &MF, unsigned Intrinsic) const {
19413 IntrinsicInfo Info;
19414 switch (Intrinsic) {
19415 case Intrinsic::ppc_atomicrmw_xchg_i128:
19416 case Intrinsic::ppc_atomicrmw_add_i128:
19417 case Intrinsic::ppc_atomicrmw_sub_i128:
19418 case Intrinsic::ppc_atomicrmw_nand_i128:
19419 case Intrinsic::ppc_atomicrmw_and_i128:
19420 case Intrinsic::ppc_atomicrmw_or_i128:
19421 case Intrinsic::ppc_atomicrmw_xor_i128:
19422 case Intrinsic::ppc_cmpxchg_i128:
19423 Info.opc = ISD::INTRINSIC_W_CHAIN;
19424 Info.memVT = MVT::i128;
19425 Info.ptrVal = I.getArgOperand(0);
19426 Info.offset = 0;
19427 Info.align = Align(16);
19430 Infos.push_back(Info);
19431 return;
19432 case Intrinsic::ppc_atomic_load_i128:
19433 Info.opc = ISD::INTRINSIC_W_CHAIN;
19434 Info.memVT = MVT::i128;
19435 Info.ptrVal = I.getArgOperand(0);
19436 Info.offset = 0;
19437 Info.align = Align(16);
19439 Infos.push_back(Info);
19440 return;
19441 case Intrinsic::ppc_atomic_store_i128:
19442 Info.opc = ISD::INTRINSIC_VOID;
19443 Info.memVT = MVT::i128;
19444 Info.ptrVal = I.getArgOperand(2);
19445 Info.offset = 0;
19446 Info.align = Align(16);
19448 Infos.push_back(Info);
19449 return;
19450 case Intrinsic::ppc_altivec_lvx:
19451 case Intrinsic::ppc_altivec_lvxl:
19452 case Intrinsic::ppc_altivec_lvebx:
19453 case Intrinsic::ppc_altivec_lvehx:
19454 case Intrinsic::ppc_altivec_lvewx:
19455 case Intrinsic::ppc_vsx_lxvd2x:
19456 case Intrinsic::ppc_vsx_lxvw4x:
19457 case Intrinsic::ppc_vsx_lxvd2x_be:
19458 case Intrinsic::ppc_vsx_lxvw4x_be:
19459 case Intrinsic::ppc_vsx_lxvl:
19460 case Intrinsic::ppc_vsx_lxvll: {
19461 EVT VT;
19462 switch (Intrinsic) {
19463 case Intrinsic::ppc_altivec_lvebx:
19464 VT = MVT::i8;
19465 break;
19466 case Intrinsic::ppc_altivec_lvehx:
19467 VT = MVT::i16;
19468 break;
19469 case Intrinsic::ppc_altivec_lvewx:
19470 VT = MVT::i32;
19471 break;
19472 case Intrinsic::ppc_vsx_lxvd2x:
19473 case Intrinsic::ppc_vsx_lxvd2x_be:
19474 VT = MVT::v2f64;
19475 break;
19476 default:
19477 VT = MVT::v4i32;
19478 break;
19479 }
19480
19481 Info.opc = ISD::INTRINSIC_W_CHAIN;
19482 Info.memVT = VT;
19483 Info.ptrVal = I.getArgOperand(0);
19484 Info.offset = -VT.getStoreSize()+1;
19485 Info.size = 2*VT.getStoreSize()-1;
19486 Info.align = Align(1);
19487 Info.flags = MachineMemOperand::MOLoad;
19488 Infos.push_back(Info);
19489 return;
19490 }
19491 case Intrinsic::ppc_altivec_stvx:
19492 case Intrinsic::ppc_altivec_stvxl:
19493 case Intrinsic::ppc_altivec_stvebx:
19494 case Intrinsic::ppc_altivec_stvehx:
19495 case Intrinsic::ppc_altivec_stvewx:
19496 case Intrinsic::ppc_vsx_stxvd2x:
19497 case Intrinsic::ppc_vsx_stxvw4x:
19498 case Intrinsic::ppc_vsx_stxvd2x_be:
19499 case Intrinsic::ppc_vsx_stxvw4x_be:
19500 case Intrinsic::ppc_vsx_stxvl:
19501 case Intrinsic::ppc_vsx_stxvll: {
19502 EVT VT;
19503 switch (Intrinsic) {
19504 case Intrinsic::ppc_altivec_stvebx:
19505 VT = MVT::i8;
19506 break;
19507 case Intrinsic::ppc_altivec_stvehx:
19508 VT = MVT::i16;
19509 break;
19510 case Intrinsic::ppc_altivec_stvewx:
19511 VT = MVT::i32;
19512 break;
19513 case Intrinsic::ppc_vsx_stxvd2x:
19514 case Intrinsic::ppc_vsx_stxvd2x_be:
19515 VT = MVT::v2f64;
19516 break;
19517 default:
19518 VT = MVT::v4i32;
19519 break;
19520 }
19521
19522 Info.opc = ISD::INTRINSIC_VOID;
19523 Info.memVT = VT;
19524 Info.ptrVal = I.getArgOperand(1);
19525 Info.offset = -VT.getStoreSize()+1;
19526 Info.size = 2*VT.getStoreSize()-1;
19527 Info.align = Align(1);
19528 Info.flags = MachineMemOperand::MOStore;
19529 Infos.push_back(Info);
19530 return;
19531 }
19532 case Intrinsic::ppc_stdcx:
19533 case Intrinsic::ppc_stwcx:
19534 case Intrinsic::ppc_sthcx:
19535 case Intrinsic::ppc_stbcx: {
19536 EVT VT;
19537 auto Alignment = Align(8);
19538 switch (Intrinsic) {
19539 case Intrinsic::ppc_stdcx:
19540 VT = MVT::i64;
19541 break;
19542 case Intrinsic::ppc_stwcx:
19543 VT = MVT::i32;
19544 Alignment = Align(4);
19545 break;
19546 case Intrinsic::ppc_sthcx:
19547 VT = MVT::i16;
19548 Alignment = Align(2);
19549 break;
19550 case Intrinsic::ppc_stbcx:
19551 VT = MVT::i8;
19552 Alignment = Align(1);
19553 break;
19554 }
19555 Info.opc = ISD::INTRINSIC_W_CHAIN;
19556 Info.memVT = VT;
19557 Info.ptrVal = I.getArgOperand(0);
19558 Info.offset = 0;
19559 Info.align = Alignment;
19561 Infos.push_back(Info);
19562 return;
19563 }
19564 default:
19565 break;
19566 }
19567}
19568
19569/// It returns EVT::Other if the type should be determined using generic
19570/// target-independent logic.
19572 LLVMContext &Context, const MemOp &Op,
19573 const AttributeList &FuncAttributes) const {
19574 if (getTargetMachine().getOptLevel() != CodeGenOptLevel::None) {
19575 // We should use Altivec/VSX loads and stores when available. For unaligned
19576 // addresses, unaligned VSX loads are only fast starting with the P8.
19577 if (Subtarget.hasAltivec() && Op.size() >= 16) {
19578 if (Op.isMemset() && Subtarget.hasVSX()) {
19579 uint64_t TailSize = Op.size() % 16;
19580 // For memset lowering, EXTRACT_VECTOR_ELT tries to return constant
19581 // element if vector element type matches tail store. For tail size
19582 // 3/4, the tail store is i32, v4i32 cannot be used, need a legal one.
19583 if (TailSize > 2 && TailSize <= 4) {
19584 return MVT::v8i16;
19585 }
19586 return MVT::v4i32;
19587 }
19588 if (Op.isAligned(Align(16)) || Subtarget.hasP8Vector())
19589 return MVT::v4i32;
19590 }
19591 }
19592
19593 if (Subtarget.isPPC64()) {
19594 return MVT::i64;
19595 }
19596
19597 return MVT::i32;
19598}
19599
19600/// Returns true if it is beneficial to convert a load of a constant
19601/// to just the constant itself.
19603 Type *Ty) const {
19604 assert(Ty->isIntegerTy());
19605
19606 unsigned BitSize = Ty->getPrimitiveSizeInBits();
19607 return !(BitSize == 0 || BitSize > 64);
19608}
19609
19611 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19612 return false;
19613 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19614 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19615 return NumBits1 == 64 && NumBits2 == 32;
19616}
19617
19619 if (!VT1.isInteger() || !VT2.isInteger())
19620 return false;
19621 unsigned NumBits1 = VT1.getSizeInBits();
19622 unsigned NumBits2 = VT2.getSizeInBits();
19623 return NumBits1 == 64 && NumBits2 == 32;
19624}
19625
19627 // Generally speaking, zexts are not free, but they are free when they can be
19628 // folded with other operations.
19629 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
19630 EVT MemVT = LD->getMemoryVT();
19631 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
19632 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
19633 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
19634 LD->getExtensionType() == ISD::ZEXTLOAD))
19635 return true;
19636 }
19637
19638 // FIXME: Add other cases...
19639 // - 32-bit shifts with a zext to i64
19640 // - zext after ctlz, bswap, etc.
19641 // - zext after and by a constant mask
19642
19643 return TargetLowering::isZExtFree(Val, VT2);
19644}
19645
19646bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
19647 assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
19648 "invalid fpext types");
19649 // Extending to float128 is not free.
19650 if (DestVT == MVT::f128)
19651 return false;
19652 return true;
19653}
19654
19656 return isInt<16>(Imm) || isUInt<16>(Imm);
19657}
19658
19660 return isInt<16>(Imm) || isUInt<16>(Imm);
19661}
19662
19665 unsigned *Fast) const {
19666 if (!EnablePPCUnaligned)
19667 return false;
19668
19669 // PowerPC supports unaligned memory access for simple non-vector types.
19670 // Although accessing unaligned addresses is not as efficient as accessing
19671 // aligned addresses, it is generally more efficient than manual expansion,
19672 // and generally only traps for software emulation when crossing page
19673 // boundaries.
19674
19675 if (!VT.isSimple())
19676 return false;
19677
19678 if (VT.isFloatingPoint() && !VT.isVector() &&
19679 !Subtarget.allowsUnalignedFPAccess())
19680 return false;
19681
19682 if (VT.getSimpleVT().isVector()) {
19683 if (Subtarget.hasVSX()) {
19684 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
19685 VT != MVT::v4f32 && VT != MVT::v4i32)
19686 return false;
19687 } else {
19688 return false;
19689 }
19690 }
19691
19692 if (VT == MVT::ppcf128)
19693 return false;
19694
19695 if (Fast)
19696 *Fast = 1;
19697
19698 return true;
19699}
19700
19702 SDValue C) const {
19703 // Check integral scalar types.
19704 if (!VT.isScalarInteger())
19705 return false;
19706 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
19707 if (!ConstNode->getAPIntValue().isSignedIntN(64))
19708 return false;
19709 // This transformation will generate >= 2 operations. But the following
19710 // cases will generate <= 2 instructions during ISEL. So exclude them.
19711 // 1. If the constant multiplier fits 16 bits, it can be handled by one
19712 // HW instruction, ie. MULLI
19713 // 2. If the multiplier after shifted fits 16 bits, an extra shift
19714 // instruction is needed than case 1, ie. MULLI and RLDICR
19715 int64_t Imm = ConstNode->getSExtValue();
19716 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
19717 Imm >>= Shift;
19718 if (isInt<16>(Imm))
19719 return false;
19720 uint64_t UImm = static_cast<uint64_t>(Imm);
19721 if (isPowerOf2_64(UImm + 1) || isPowerOf2_64(UImm - 1) ||
19722 isPowerOf2_64(1 - UImm) || isPowerOf2_64(-1 - UImm))
19723 return true;
19724 }
19725 return false;
19726}
19727
19733
19735 Type *Ty) const {
19736 if (Subtarget.hasSPE() || Subtarget.useSoftFloat())
19737 return false;
19738 switch (Ty->getScalarType()->getTypeID()) {
19739 case Type::FloatTyID:
19740 case Type::DoubleTyID:
19741 return true;
19742 case Type::FP128TyID:
19743 return Subtarget.hasP9Vector();
19744 default:
19745 return false;
19746 }
19747}
19748
19749// FIXME: add more patterns which are not profitable to hoist.
19751 if (!I->hasOneUse())
19752 return true;
19753
19754 Instruction *User = I->user_back();
19755 assert(User && "A single use instruction with no uses.");
19756
19757 switch (I->getOpcode()) {
19758 case Instruction::FMul: {
19759 // Don't break FMA, PowerPC prefers FMA.
19760 if (User->getOpcode() != Instruction::FSub &&
19761 User->getOpcode() != Instruction::FAdd)
19762 return true;
19763
19764 const Function *F = I->getFunction();
19765 const DataLayout &DL = F->getDataLayout();
19766 Type *Ty = User->getOperand(0)->getType();
19767 bool AllowContract = I->getFastMathFlags().allowContract() &&
19768 User->getFastMathFlags().allowContract();
19769
19770 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
19772 AllowContract);
19773 }
19774 case Instruction::Load: {
19775 // Don't break "store (load float*)" pattern, this pattern will be combined
19776 // to "store (load int32)" in later InstCombine pass. See function
19777 // combineLoadToOperationType. On PowerPC, loading a float point takes more
19778 // cycles than loading a 32 bit integer.
19779 LoadInst *LI = cast<LoadInst>(I);
19780 // For the loads that combineLoadToOperationType does nothing, like
19781 // ordered load, it should be profitable to hoist them.
19782 // For swifterror load, it can only be used for pointer to pointer type, so
19783 // later type check should get rid of this case.
19784 if (!LI->isUnordered())
19785 return true;
19786
19787 if (User->getOpcode() != Instruction::Store)
19788 return true;
19789
19790 if (I->getType()->getTypeID() != Type::FloatTyID)
19791 return true;
19792
19793 return false;
19794 }
19795 default:
19796 return true;
19797 }
19798 return true;
19799}
19800
19801const MCPhysReg *
19803 // LR is a callee-save register, but we must treat it as clobbered by any call
19804 // site. Hence we include LR in the scratch registers, which are in turn added
19805 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
19806 // to CTR, which is used by any indirect call.
19807 static const MCPhysReg ScratchRegs[] = {
19808 PPC::X12, PPC::LR8, PPC::CTR8, 0
19809 };
19810
19811 return ScratchRegs;
19812}
19813
19815 ExceptionHandling EH, const Constant *PersonalityFn) const {
19816 return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
19817}
19818
19820 ExceptionHandling EH, const Constant *PersonalityFn) const {
19821 return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
19822}
19823
19824bool
19826 EVT VT , unsigned DefinedValues) const {
19827 if (VT == MVT::v2i64)
19828 return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
19829
19830 if (Subtarget.hasVSX())
19831 return true;
19832
19834}
19835
19837 if (!EnableILPPref || Subtarget.enableMachineScheduler())
19839
19840 return Sched::ILP;
19841}
19842
19843// Create a fast isel object.
19845 FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo,
19846 const LibcallLoweringInfo *LibcallLowering) const {
19847 return PPC::createFastISel(FuncInfo, LibInfo, LibcallLowering);
19848}
19849
19850// 'Inverted' means the FMA opcode after negating one multiplicand.
19851// For example, (fma -a b c) = (fnmsub a b c)
19852static unsigned invertFMAOpcode(unsigned Opc) {
19853 switch (Opc) {
19854 default:
19855 llvm_unreachable("Invalid FMA opcode for PowerPC!");
19856 case ISD::FMA:
19857 return PPCISD::FNMSUB;
19858 case PPCISD::FNMSUB:
19859 return ISD::FMA;
19860 }
19861}
19862
19864 bool LegalOps, bool OptForSize,
19866 unsigned Depth) const {
19868 return SDValue();
19869
19870 unsigned Opc = Op.getOpcode();
19871 EVT VT = Op.getValueType();
19872 SDNodeFlags Flags = Op.getNode()->getFlags();
19873
19874 switch (Opc) {
19875 case PPCISD::FNMSUB:
19876 if (!Op.hasOneUse() || !isTypeLegal(VT))
19877 break;
19878
19879 SDValue N0 = Op.getOperand(0);
19880 SDValue N1 = Op.getOperand(1);
19881 SDValue N2 = Op.getOperand(2);
19882 SDLoc Loc(Op);
19883
19885 SDValue NegN2 =
19886 getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
19887
19888 if (!NegN2)
19889 return SDValue();
19890
19891 // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
19892 // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
19893 // These transformations may change sign of zeroes. For example,
19894 // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
19895 if (Flags.hasNoSignedZeros()) {
19896 // Try and choose the cheaper one to negate.
19898 SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
19899 N0Cost, Depth + 1);
19900
19902 SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
19903 N1Cost, Depth + 1);
19904
19905 if (NegN0 && N0Cost <= N1Cost) {
19906 Cost = std::min(N0Cost, N2Cost);
19907 return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
19908 } else if (NegN1) {
19909 Cost = std::min(N1Cost, N2Cost);
19910 return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
19911 }
19912 }
19913
19914 // (fneg (fnmsub a b c)) => (fma a b (fneg c))
19915 if (isOperationLegal(ISD::FMA, VT)) {
19916 Cost = N2Cost;
19917 return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
19918 }
19919
19920 break;
19921 }
19922
19923 return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
19924 Cost, Depth);
19925}
19926
19927// Override to enable LOAD_STACK_GUARD lowering on Linux.
19929 if (M.getStackProtectorGuard() == "tls" || Subtarget.isTargetLinux())
19930 return true;
19932}
19933
19936 bool ForCodeSize) const {
19937 if (!VT.isSimple() || !Subtarget.hasVSX())
19939
19940 switch(VT.getSimpleVT().SimpleTy) {
19941 default:
19942 // For FP types that are currently not supported by PPC backend, return
19943 // false. Examples: f16, f80.
19945 case MVT::f32:
19946 case MVT::f64: {
19947 if (Subtarget.hasPrefixInstrs() && Subtarget.hasP10Vector()) {
19948 // we can materialize all immediatess via XXSPLTI32DX and XXSPLTIDP.
19949 return FPImmAction::Legal;
19950 }
19951 bool IsExact;
19952 APSInt IntResult(16, false);
19953 // The rounding mode doesn't really matter because we only care about floats
19954 // that can be converted to integers exactly.
19955 Imm.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
19956 // For exact values in the range [-16, 15] we can materialize the float.
19957 if (IsExact && IntResult <= 15 && IntResult >= -16)
19958 return FPImmAction::Legal;
19960 }
19961 case MVT::ppcf128:
19962 return Imm.isPosZero() ? FPImmAction::Legal : FPImmAction::ConstantPool;
19963 }
19964}
19965
19966// For vector shift operation op, fold
19967// (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
19969 SelectionDAG &DAG) {
19970 SDValue N0 = N->getOperand(0);
19971 SDValue N1 = N->getOperand(1);
19972 EVT VT = N0.getValueType();
19973 unsigned OpSizeInBits = VT.getScalarSizeInBits();
19974 unsigned Opcode = N->getOpcode();
19975 unsigned TargetOpcode;
19976
19977 switch (Opcode) {
19978 default:
19979 llvm_unreachable("Unexpected shift operation");
19980 case ISD::SHL:
19981 TargetOpcode = PPCISD::SHL;
19982 break;
19983 case ISD::SRL:
19984 TargetOpcode = PPCISD::SRL;
19985 break;
19986 case ISD::SRA:
19987 TargetOpcode = PPCISD::SRA;
19988 break;
19989 }
19990
19991 if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
19992 N1->getOpcode() == ISD::AND)
19993 if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
19994 if (Mask->getZExtValue() == OpSizeInBits - 1)
19995 return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
19996
19997 return SDValue();
19998}
19999
20000SDValue PPCTargetLowering::combineVectorShift(SDNode *N,
20001 DAGCombinerInfo &DCI) const {
20002 EVT VT = N->getValueType(0);
20003 assert(VT.isVector() && "Vector type expected.");
20004
20005 unsigned Opc = N->getOpcode();
20006 assert((Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
20007 "Unexpected opcode.");
20008
20009 if (!isOperationLegal(Opc, VT))
20010 return SDValue();
20011
20012 EVT EltTy = VT.getScalarType();
20013 unsigned EltBits = EltTy.getSizeInBits();
20014 if (EltTy != MVT::i64 && EltTy != MVT::i32)
20015 return SDValue();
20016
20017 SDValue N1 = N->getOperand(1);
20018 uint64_t SplatBits = 0;
20019 bool AddSplatCase = false;
20020 unsigned OpcN1 = N1.getOpcode();
20021 if (OpcN1 == PPCISD::VADD_SPLAT &&
20023 AddSplatCase = true;
20024 SplatBits = N1.getConstantOperandVal(0);
20025 }
20026
20027 if (!AddSplatCase) {
20028 if (OpcN1 != ISD::BUILD_VECTOR)
20029 return SDValue();
20030
20031 unsigned SplatBitSize;
20032 bool HasAnyUndefs;
20033 APInt APSplatBits, APSplatUndef;
20034 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(N1);
20035 bool BVNIsConstantSplat =
20036 BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
20037 HasAnyUndefs, 0, !Subtarget.isLittleEndian());
20038 if (!BVNIsConstantSplat || SplatBitSize != EltBits)
20039 return SDValue();
20040 SplatBits = APSplatBits.getZExtValue();
20041 }
20042
20043 SDLoc DL(N);
20044 SDValue N0 = N->getOperand(0);
20045 // PPC vector shifts by word/double look at only the low 5/6 bits of the
20046 // shift vector, which means the max value is 31/63. A shift vector of all
20047 // 1s will be truncated to 31/63, which is useful as vspltiw is limited to
20048 // -16 to 15 range.
20049 if (SplatBits == (EltBits - 1)) {
20050 unsigned NewOpc;
20051 switch (Opc) {
20052 case ISD::SHL:
20053 NewOpc = PPCISD::SHL;
20054 break;
20055 case ISD::SRL:
20056 NewOpc = PPCISD::SRL;
20057 break;
20058 case ISD::SRA:
20059 NewOpc = PPCISD::SRA;
20060 break;
20061 }
20062 SDValue SplatOnes = getCanonicalConstSplat(255, 1, VT, DCI.DAG, DL);
20063 return DCI.DAG.getNode(NewOpc, DL, VT, N0, SplatOnes);
20064 }
20065
20066 if (Opc != ISD::SHL || !isOperationLegal(ISD::ADD, VT))
20067 return SDValue();
20068
20069 // For 64-bit there is no splat immediate so we want to catch shift by 1 here
20070 // before the BUILD_VECTOR is replaced by a load.
20071 if (EltTy != MVT::i64 || SplatBits != 1)
20072 return SDValue();
20073
20074 return DCI.DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20075}
20076
20077SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
20078 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
20079 return Value;
20080
20081 if (N->getValueType(0).isVector())
20082 return combineVectorShift(N, DCI);
20083
20084 SDValue N0 = N->getOperand(0);
20085 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
20086 if (!Subtarget.isISA3_0() || !Subtarget.isPPC64() ||
20087 N0.getOpcode() != ISD::SIGN_EXTEND ||
20088 N0.getOperand(0).getValueType() != MVT::i32 || CN1 == nullptr ||
20089 N->getValueType(0) != MVT::i64)
20090 return SDValue();
20091
20092 // We can't save an operation here if the value is already extended, and
20093 // the existing shift is easier to combine.
20094 SDValue ExtsSrc = N0.getOperand(0);
20095 if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
20096 ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
20097 return SDValue();
20098
20099 SDLoc DL(N0);
20100 SDValue ShiftBy = SDValue(CN1, 0);
20101 // We want the shift amount to be i32 on the extswli, but the shift could
20102 // have an i64.
20103 if (ShiftBy.getValueType() == MVT::i64)
20104 ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
20105
20106 return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
20107 ShiftBy);
20108}
20109
20110SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
20111 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
20112 return Value;
20113
20114 if (N->getValueType(0).isVector())
20115 return combineVectorShift(N, DCI);
20116
20117 return SDValue();
20118}
20119
20120SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
20121 if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
20122 return Value;
20123
20124 if (N->getValueType(0).isVector())
20125 return combineVectorShift(N, DCI);
20126
20127 return SDValue();
20128}
20129
20130// Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
20131// Transform (add X, (zext(sete Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
20132// When C is zero, the equation (addi Z, -C) can be simplified to Z
20133// Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
20135 const PPCSubtarget &Subtarget) {
20136 if (!Subtarget.isPPC64())
20137 return SDValue();
20138
20139 SDValue LHS = N->getOperand(0);
20140 SDValue RHS = N->getOperand(1);
20141
20142 auto isZextOfCompareWithConstant = [](SDValue Op) {
20143 if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
20144 Op.getValueType() != MVT::i64)
20145 return false;
20146
20147 SDValue Cmp = Op.getOperand(0);
20148 if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
20149 Cmp.getOperand(0).getValueType() != MVT::i64)
20150 return false;
20151
20152 if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
20153 int64_t NegConstant = 0 - Constant->getSExtValue();
20154 // Due to the limitations of the addi instruction,
20155 // -C is required to be [-32768, 32767].
20156 return isInt<16>(NegConstant);
20157 }
20158
20159 return false;
20160 };
20161
20162 bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
20163 bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
20164
20165 // If there is a pattern, canonicalize a zext operand to the RHS.
20166 if (LHSHasPattern && !RHSHasPattern)
20167 std::swap(LHS, RHS);
20168 else if (!LHSHasPattern && !RHSHasPattern)
20169 return SDValue();
20170
20171 SDLoc DL(N);
20172 EVT CarryType = Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
20173 SDVTList VTs = DAG.getVTList(MVT::i64, CarryType);
20174 SDValue Cmp = RHS.getOperand(0);
20175 SDValue Z = Cmp.getOperand(0);
20176 auto *Constant = cast<ConstantSDNode>(Cmp.getOperand(1));
20177 int64_t NegConstant = 0 - Constant->getSExtValue();
20178
20179 switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
20180 default: break;
20181 case ISD::SETNE: {
20182 // when C == 0
20183 // --> addze X, (addic Z, -1).carry
20184 // /
20185 // add X, (zext(setne Z, C))--
20186 // \ when -32768 <= -C <= 32767 && C != 0
20187 // --> addze X, (addic (addi Z, -C), -1).carry
20188 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20189 DAG.getConstant(NegConstant, DL, MVT::i64));
20190 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20191 SDValue Addc =
20192 DAG.getNode(ISD::UADDO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20193 AddOrZ, DAG.getAllOnesConstant(DL, MVT::i64),
20194 DAG.getConstant(0, DL, CarryType));
20195 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20196 DAG.getConstant(0, DL, MVT::i64),
20197 SDValue(Addc.getNode(), 1));
20198 }
20199 case ISD::SETEQ: {
20200 // when C == 0
20201 // --> addze X, (subfic Z, 0).carry
20202 // /
20203 // add X, (zext(sete Z, C))--
20204 // \ when -32768 <= -C <= 32767 && C != 0
20205 // --> addze X, (subfic (addi Z, -C), 0).carry
20206 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
20207 DAG.getConstant(NegConstant, DL, MVT::i64));
20208 SDValue AddOrZ = NegConstant != 0 ? Add : Z;
20209 SDValue Subc =
20210 DAG.getNode(ISD::USUBO_CARRY, DL, DAG.getVTList(MVT::i64, CarryType),
20211 DAG.getConstant(0, DL, MVT::i64), AddOrZ,
20212 DAG.getConstant(0, DL, CarryType));
20213 SDValue Invert = DAG.getNode(ISD::XOR, DL, CarryType, Subc.getValue(1),
20214 DAG.getConstant(1UL, DL, CarryType));
20215 return DAG.getNode(ISD::UADDO_CARRY, DL, VTs, LHS,
20216 DAG.getConstant(0, DL, MVT::i64), Invert);
20217 }
20218 }
20219
20220 return SDValue();
20221}
20222
20223// Transform
20224// (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
20225// (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
20226// In this case both C1 and C2 must be known constants.
20227// C1+C2 must fit into a 34 bit signed integer.
20229 const PPCSubtarget &Subtarget) {
20230 if (!Subtarget.isUsingPCRelativeCalls())
20231 return SDValue();
20232
20233 // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
20234 // If we find that node try to cast the Global Address and the Constant.
20235 SDValue LHS = N->getOperand(0);
20236 SDValue RHS = N->getOperand(1);
20237
20238 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20239 std::swap(LHS, RHS);
20240
20241 if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
20242 return SDValue();
20243
20244 // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
20247
20248 // Check that both casts succeeded.
20249 if (!GSDN || !ConstNode)
20250 return SDValue();
20251
20252 int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
20253 SDLoc DL(GSDN);
20254
20255 // The signed int offset needs to fit in 34 bits.
20256 if (!isInt<34>(NewOffset))
20257 return SDValue();
20258
20259 // The new global address is a copy of the old global address except
20260 // that it has the updated Offset.
20261 SDValue GA =
20262 DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
20263 NewOffset, GSDN->getTargetFlags());
20264 SDValue MatPCRel =
20265 DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
20266 return MatPCRel;
20267}
20268
20269// Transform (add X, (build_vector (T 1), (T 1), ...)) -> (sub X, (XXLEQVOnes))
20270// XXLEQVOnes creates an all-1s vector (0xFFFFFFFF...) efficiently via xxleqv
20271// Mathematical identity: X + 1 = X - (-1)
20272// Applies to v4i32, v2i64, v8i16, v16i8 where all elements are constant 1
20273// Requirement: VSX feature for efficient xxleqv generation
20275 const PPCSubtarget &Subtarget) {
20276
20277 EVT VT = N->getValueType(0);
20278 if (!Subtarget.hasVSX())
20279 return SDValue();
20280
20281 // Handle v2i64, v4i32, v8i16 and v16i8 types
20282 if (!(VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v4i32 ||
20283 VT == MVT::v2i64))
20284 return SDValue();
20285
20286 SDValue LHS = N->getOperand(0);
20287 SDValue RHS = N->getOperand(1);
20288
20289 // Check if RHS is BUILD_VECTOR
20290 if (RHS.getOpcode() != ISD::BUILD_VECTOR)
20291 return SDValue();
20292
20293 // Check if all the elements are 1
20294 unsigned NumOfEles = RHS.getNumOperands();
20295 for (unsigned i = 0; i < NumOfEles; ++i) {
20296 auto *CN = dyn_cast<ConstantSDNode>(RHS.getOperand(i));
20297 if (!CN || CN->getSExtValue() != 1)
20298 return SDValue();
20299 }
20300 SDLoc DL(N);
20301
20302 SDValue MinusOne = DAG.getConstant(APInt::getAllOnes(32), DL, MVT::i32);
20303 SmallVector<SDValue, 4> Ops(4, MinusOne);
20304 SDValue AllOnesVec = DAG.getBuildVector(MVT::v4i32, DL, Ops);
20305
20306 // Bitcast to the target vector type
20307 SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT, AllOnesVec);
20308
20309 return DAG.getNode(ISD::SUB, DL, VT, LHS, Bitcast);
20310}
20311
20312SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
20313 if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
20314 return Value;
20315
20316 if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
20317 return Value;
20318
20319 if (auto Value = combineADDToSUB(N, DCI.DAG, Subtarget))
20320 return Value;
20321 return SDValue();
20322}
20323
20324// Detect TRUNCATE operations on bitcasts of float128 values.
20325// What we are looking for here is the situtation where we extract a subset
20326// of bits from a 128 bit float.
20327// This can be of two forms:
20328// 1) BITCAST of f128 feeding TRUNCATE
20329// 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
20330// The reason this is required is because we do not have a legal i128 type
20331// and so we want to prevent having to store the f128 and then reload part
20332// of it.
20333SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
20334 DAGCombinerInfo &DCI) const {
20335 // If we are using CRBits then try that first.
20336 if (Subtarget.useCRBits()) {
20337 // Check if CRBits did anything and return that if it did.
20338 if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
20339 return CRTruncValue;
20340 }
20341
20342 SDLoc dl(N);
20343 SDValue Op0 = N->getOperand(0);
20344
20345 // Looking for a truncate of i128 to i64.
20346 if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
20347 return SDValue();
20348
20349 int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
20350
20351 // SRL feeding TRUNCATE.
20352 if (Op0.getOpcode() == ISD::SRL) {
20353 ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
20354 // The right shift has to be by 64 bits.
20355 if (!ConstNode || ConstNode->getZExtValue() != 64)
20356 return SDValue();
20357
20358 // Switch the element number to extract.
20359 EltToExtract = EltToExtract ? 0 : 1;
20360 // Update Op0 past the SRL.
20361 Op0 = Op0.getOperand(0);
20362 }
20363
20364 // BITCAST feeding a TRUNCATE possibly via SRL.
20365 if (Op0.getOpcode() == ISD::BITCAST &&
20366 Op0.getValueType() == MVT::i128 &&
20367 Op0.getOperand(0).getValueType() == MVT::f128) {
20368 SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
20369 return DCI.DAG.getNode(
20370 ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
20371 DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
20372 }
20373 return SDValue();
20374}
20375
20376SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
20377 SelectionDAG &DAG = DCI.DAG;
20378
20379 ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
20380 if (!ConstOpOrElement)
20381 return SDValue();
20382
20383 // An imul is usually smaller than the alternative sequence for legal type.
20385 isOperationLegal(ISD::MUL, N->getValueType(0)))
20386 return SDValue();
20387
20388 auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
20389 switch (this->Subtarget.getCPUDirective()) {
20390 default:
20391 // TODO: enhance the condition for subtarget before pwr8
20392 return false;
20393 case PPC::DIR_PWR8:
20394 // type mul add shl
20395 // scalar 4 1 1
20396 // vector 7 2 2
20397 return true;
20398 case PPC::DIR_PWR9:
20399 case PPC::DIR_PWR10:
20400 case PPC::DIR_PWR11:
20402 // type mul add shl
20403 // scalar 5 2 2
20404 // vector 7 2 2
20405
20406 // The cycle RATIO of related operations are showed as a table above.
20407 // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
20408 // scalar and vector type. For 2 instrs patterns, add/sub + shl
20409 // are 4, it is always profitable; but for 3 instrs patterns
20410 // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
20411 // So we should only do it for vector type.
20412 return IsAddOne && IsNeg ? VT.isVector() : true;
20413 }
20414 };
20415
20416 EVT VT = N->getValueType(0);
20417 SDLoc DL(N);
20418
20419 const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
20420 bool IsNeg = MulAmt.isNegative();
20421 APInt MulAmtAbs = MulAmt.abs();
20422
20423 if ((MulAmtAbs - 1).isPowerOf2()) {
20424 // (mul x, 2^N + 1) => (add (shl x, N), x)
20425 // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
20426
20427 if (!IsProfitable(IsNeg, true, VT))
20428 return SDValue();
20429
20430 SDValue Op0 = N->getOperand(0);
20431 SDValue Op1 =
20432 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20433 DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
20434 SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
20435
20436 if (!IsNeg)
20437 return Res;
20438
20439 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
20440 } else if ((MulAmtAbs + 1).isPowerOf2()) {
20441 // (mul x, 2^N - 1) => (sub (shl x, N), x)
20442 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
20443
20444 if (!IsProfitable(IsNeg, false, VT))
20445 return SDValue();
20446
20447 SDValue Op0 = N->getOperand(0);
20448 SDValue Op1 =
20449 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20450 DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
20451
20452 if (!IsNeg)
20453 return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
20454 else
20455 return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
20456
20457 } else {
20458 return SDValue();
20459 }
20460}
20461
20462// Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
20463// in combiner since we need to check SD flags and other subtarget features.
20464SDValue PPCTargetLowering::combineFMALike(SDNode *N,
20465 DAGCombinerInfo &DCI) const {
20466 SDValue N0 = N->getOperand(0);
20467 SDValue N1 = N->getOperand(1);
20468 SDValue N2 = N->getOperand(2);
20469 SDNodeFlags Flags = N->getFlags();
20470 EVT VT = N->getValueType(0);
20471 SelectionDAG &DAG = DCI.DAG;
20472 unsigned Opc = N->getOpcode();
20474 bool LegalOps = !DCI.isBeforeLegalizeOps();
20475 SDLoc Loc(N);
20476
20477 if (!isOperationLegal(ISD::FMA, VT))
20478 return SDValue();
20479
20480 // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
20481 // since (fnmsub a b c)=-0 while c-ab=+0.
20482 if (!Flags.hasNoSignedZeros())
20483 return SDValue();
20484
20485 // (fma (fneg a) b c) => (fnmsub a b c)
20486 // (fnmsub (fneg a) b c) => (fma a b c)
20487 if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
20488 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
20489
20490 // (fma a (fneg b) c) => (fnmsub a b c)
20491 // (fnmsub a (fneg b) c) => (fma a b c)
20492 if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
20493 return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
20494
20495 return SDValue();
20496}
20497
20498bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
20499 // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
20500 if (!Subtarget.is64BitELFABI())
20501 return false;
20502
20503 // If not a tail call then no need to proceed.
20504 if (!CI->isTailCall())
20505 return false;
20506
20507 // If sibling calls have been disabled and tail-calls aren't guaranteed
20508 // there is no reason to duplicate.
20509 auto &TM = getTargetMachine();
20510 if (!TM.Options.GuaranteedTailCallOpt && !EnableSCO)
20511 return false;
20512
20513 // Can't tail call a function called indirectly, or if it has variadic args.
20514 const Function *Callee = CI->getCalledFunction();
20515 if (!Callee || Callee->isVarArg())
20516 return false;
20517
20518 // Make sure the callee and caller calling conventions are eligible for tco.
20519 const Function *Caller = CI->getParent()->getParent();
20520 if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
20521 CI->getCallingConv()))
20522 return false;
20523
20524 // If the function is local then we have a good chance at tail-calling it
20525 return getTargetMachine().shouldAssumeDSOLocal(Callee);
20526}
20527
20528bool PPCTargetLowering::
20529isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
20530 const Value *Mask = AndI.getOperand(1);
20531 // If the mask is suitable for andi. or andis. we should sink the and.
20532 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
20533 // Can't handle constants wider than 64-bits.
20534 if (CI->getBitWidth() > 64)
20535 return false;
20536 int64_t ConstVal = CI->getZExtValue();
20537 return isUInt<16>(ConstVal) ||
20538 (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
20539 }
20540
20541 // For non-constant masks, we can always use the record-form and.
20542 return true;
20543}
20544
20545/// getAddrModeForFlags - Based on the set of address flags, select the most
20546/// optimal instruction format to match by.
20547PPC::AddrMode PPCTargetLowering::getAddrModeForFlags(unsigned Flags) const {
20548 // This is not a node we should be handling here.
20549 if (Flags == PPC::MOF_None)
20550 return PPC::AM_None;
20551 // Unaligned D-Forms are tried first, followed by the aligned D-Forms.
20552 for (auto FlagSet : AddrModesMap.at(PPC::AM_DForm))
20553 if ((Flags & FlagSet) == FlagSet)
20554 return PPC::AM_DForm;
20555 for (auto FlagSet : AddrModesMap.at(PPC::AM_DSForm))
20556 if ((Flags & FlagSet) == FlagSet)
20557 return PPC::AM_DSForm;
20558 for (auto FlagSet : AddrModesMap.at(PPC::AM_DQForm))
20559 if ((Flags & FlagSet) == FlagSet)
20560 return PPC::AM_DQForm;
20561 for (auto FlagSet : AddrModesMap.at(PPC::AM_PrefixDForm))
20562 if ((Flags & FlagSet) == FlagSet)
20563 return PPC::AM_PrefixDForm;
20564 // If no other forms are selected, return an X-Form as it is the most
20565 // general addressing mode.
20566 return PPC::AM_XForm;
20567}
20568
20569/// Set alignment flags based on whether or not the Frame Index is aligned.
20570/// Utilized when computing flags for address computation when selecting
20571/// load and store instructions.
20572static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet,
20573 SelectionDAG &DAG) {
20574 bool IsAdd = ((N.getOpcode() == ISD::ADD) || (N.getOpcode() == ISD::OR));
20575 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(IsAdd ? N.getOperand(0) : N);
20576 if (!FI)
20577 return;
20579 unsigned FrameIndexAlign = MFI.getObjectAlign(FI->getIndex()).value();
20580 // If this is (add $FI, $S16Imm), the alignment flags are already set
20581 // based on the immediate. We just need to clear the alignment flags
20582 // if the FI alignment is weaker.
20583 if ((FrameIndexAlign % 4) != 0)
20584 FlagSet &= ~PPC::MOF_RPlusSImm16Mult4;
20585 if ((FrameIndexAlign % 16) != 0)
20586 FlagSet &= ~PPC::MOF_RPlusSImm16Mult16;
20587 // If the address is a plain FrameIndex, set alignment flags based on
20588 // FI alignment.
20589 if (!IsAdd) {
20590 if ((FrameIndexAlign % 4) == 0)
20591 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20592 if ((FrameIndexAlign % 16) == 0)
20593 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20594 }
20595}
20596
20597/// Given a node, compute flags that are used for address computation when
20598/// selecting load and store instructions. The flags computed are stored in
20599/// FlagSet. This function takes into account whether the node is a constant,
20600/// an ADD, OR, or a constant, and computes the address flags accordingly.
20601static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet,
20602 SelectionDAG &DAG) {
20603 // Set the alignment flags for the node depending on if the node is
20604 // 4-byte or 16-byte aligned.
20605 auto SetAlignFlagsForImm = [&](uint64_t Imm) {
20606 if ((Imm & 0x3) == 0)
20607 FlagSet |= PPC::MOF_RPlusSImm16Mult4;
20608 if ((Imm & 0xf) == 0)
20609 FlagSet |= PPC::MOF_RPlusSImm16Mult16;
20610 };
20611
20613 // All 32-bit constants can be computed as LIS + Disp.
20614 const APInt &ConstImm = CN->getAPIntValue();
20615 if (ConstImm.isSignedIntN(32)) { // Flag to handle 32-bit constants.
20616 FlagSet |= PPC::MOF_AddrIsSImm32;
20617 SetAlignFlagsForImm(ConstImm.getZExtValue());
20618 setAlignFlagsForFI(N, FlagSet, DAG);
20619 }
20620 if (ConstImm.isSignedIntN(34)) // Flag to handle 34-bit constants.
20621 FlagSet |= PPC::MOF_RPlusSImm34;
20622 else // Let constant materialization handle large constants.
20623 FlagSet |= PPC::MOF_NotAddNorCst;
20624 } else if (N.getOpcode() == ISD::ADD || provablyDisjointOr(DAG, N)) {
20625 // This address can be represented as an addition of:
20626 // - Register + Imm16 (possibly a multiple of 4/16)
20627 // - Register + Imm34
20628 // - Register + PPCISD::Lo
20629 // - Register + Register
20630 // In any case, we won't have to match this as Base + Zero.
20631 SDValue RHS = N.getOperand(1);
20633 const APInt &ConstImm = CN->getAPIntValue();
20634 if (ConstImm.isSignedIntN(16)) {
20635 FlagSet |= PPC::MOF_RPlusSImm16; // Signed 16-bit immediates.
20636 SetAlignFlagsForImm(ConstImm.getZExtValue());
20637 setAlignFlagsForFI(N, FlagSet, DAG);
20638 }
20639 if (ConstImm.isSignedIntN(34))
20640 FlagSet |= PPC::MOF_RPlusSImm34; // Signed 34-bit immediates.
20641 else
20642 FlagSet |= PPC::MOF_RPlusR; // Register.
20643 } else if (RHS.getOpcode() == PPCISD::Lo && !RHS.getConstantOperandVal(1))
20644 FlagSet |= PPC::MOF_RPlusLo; // PPCISD::Lo.
20645 else
20646 FlagSet |= PPC::MOF_RPlusR;
20647 } else { // The address computation is not a constant or an addition.
20648 setAlignFlagsForFI(N, FlagSet, DAG);
20649 FlagSet |= PPC::MOF_NotAddNorCst;
20650 }
20651}
20652
20653static bool isPCRelNode(SDValue N) {
20654 return (N.getOpcode() == PPCISD::MAT_PCREL_ADDR ||
20659}
20660
20661/// computeMOFlags - Given a node N and it's Parent (a MemSDNode), compute
20662/// the address flags of the load/store instruction that is to be matched.
20663unsigned PPCTargetLowering::computeMOFlags(const SDNode *Parent, SDValue N,
20664 SelectionDAG &DAG) const {
20665 unsigned FlagSet = PPC::MOF_None;
20666
20667 // Compute subtarget flags.
20668 if (!Subtarget.hasP9Vector())
20669 FlagSet |= PPC::MOF_SubtargetBeforeP9;
20670 else
20671 FlagSet |= PPC::MOF_SubtargetP9;
20672
20673 if (Subtarget.hasPrefixInstrs())
20674 FlagSet |= PPC::MOF_SubtargetP10;
20675
20676 if (Subtarget.hasSPE())
20677 FlagSet |= PPC::MOF_SubtargetSPE;
20678
20679 // Check if we have a PCRel node and return early.
20680 if ((FlagSet & PPC::MOF_SubtargetP10) && isPCRelNode(N))
20681 return FlagSet;
20682
20683 // If the node is the paired load/store intrinsics, compute flags for
20684 // address computation and return early.
20685 unsigned ParentOp = Parent->getOpcode();
20686 if (Subtarget.isISA3_1() && ((ParentOp == ISD::INTRINSIC_W_CHAIN) ||
20687 (ParentOp == ISD::INTRINSIC_VOID))) {
20688 unsigned ID = Parent->getConstantOperandVal(1);
20689 if ((ID == Intrinsic::ppc_vsx_lxvp) || (ID == Intrinsic::ppc_vsx_stxvp)) {
20690 SDValue IntrinOp = (ID == Intrinsic::ppc_vsx_lxvp)
20691 ? Parent->getOperand(2)
20692 : Parent->getOperand(3);
20693 computeFlagsForAddressComputation(IntrinOp, FlagSet, DAG);
20694 FlagSet |= PPC::MOF_Vector;
20695 return FlagSet;
20696 }
20697 }
20698
20699 // Mark this as something we don't want to handle here if it is atomic
20700 // or pre-increment instruction.
20701 if (const LSBaseSDNode *LSB = dyn_cast<LSBaseSDNode>(Parent))
20702 if (LSB->isIndexed())
20703 return PPC::MOF_None;
20704
20705 // Compute in-memory type flags. This is based on if there are scalars,
20706 // floats or vectors.
20707 const MemSDNode *MN = dyn_cast<MemSDNode>(Parent);
20708 assert(MN && "Parent should be a MemSDNode!");
20709 EVT MemVT = MN->getMemoryVT();
20710 unsigned Size = MemVT.getSizeInBits();
20711 if (MemVT.isScalarInteger()) {
20712 assert(Size <= 128 &&
20713 "Not expecting scalar integers larger than 16 bytes!");
20714 if (Size < 32)
20715 FlagSet |= PPC::MOF_SubWordInt;
20716 else if (Size == 32)
20717 FlagSet |= PPC::MOF_WordInt;
20718 else
20719 FlagSet |= PPC::MOF_DoubleWordInt;
20720 } else if (MemVT.isVector() && !MemVT.isFloatingPoint()) { // Integer vectors.
20721 if (Size == 128)
20722 FlagSet |= PPC::MOF_Vector;
20723 else if (Size == 256) {
20724 assert(Subtarget.pairedVectorMemops() &&
20725 "256-bit vectors are only available when paired vector memops is "
20726 "enabled!");
20727 FlagSet |= PPC::MOF_Vector;
20728 } else
20729 llvm_unreachable("Not expecting illegal vectors!");
20730 } else { // Floating point type: can be scalar, f128 or vector types.
20731 if (Size == 32 || Size == 64)
20732 FlagSet |= PPC::MOF_ScalarFloat;
20733 else if (MemVT == MVT::f128 || MemVT.isVector())
20734 FlagSet |= PPC::MOF_Vector;
20735 else
20736 llvm_unreachable("Not expecting illegal scalar floats!");
20737 }
20738
20739 // Compute flags for address computation.
20740 computeFlagsForAddressComputation(N, FlagSet, DAG);
20741
20742 // Compute type extension flags.
20743 if (const LoadSDNode *LN = dyn_cast<LoadSDNode>(Parent)) {
20744 switch (LN->getExtensionType()) {
20745 case ISD::SEXTLOAD:
20746 FlagSet |= PPC::MOF_SExt;
20747 break;
20748 case ISD::EXTLOAD:
20749 case ISD::ZEXTLOAD:
20750 FlagSet |= PPC::MOF_ZExt;
20751 break;
20752 case ISD::NON_EXTLOAD:
20753 FlagSet |= PPC::MOF_NoExt;
20754 break;
20755 }
20756 } else
20757 FlagSet |= PPC::MOF_NoExt;
20758
20759 // For integers, no extension is the same as zero extension.
20760 // We set the extension mode to zero extension so we don't have
20761 // to add separate entries in AddrModesMap for loads and stores.
20762 if (MemVT.isScalarInteger() && (FlagSet & PPC::MOF_NoExt)) {
20763 FlagSet |= PPC::MOF_ZExt;
20764 FlagSet &= ~PPC::MOF_NoExt;
20765 }
20766
20767 // If we don't have prefixed instructions, 34-bit constants should be
20768 // treated as PPC::MOF_NotAddNorCst so they can match D-Forms.
20769 bool IsNonP1034BitConst =
20771 FlagSet) == PPC::MOF_RPlusSImm34;
20772 if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::OR &&
20773 IsNonP1034BitConst)
20774 FlagSet |= PPC::MOF_NotAddNorCst;
20775
20776 return FlagSet;
20777}
20778
20779/// SelectForceXFormMode - Given the specified address, force it to be
20780/// represented as an indexed [r+r] operation (an XForm instruction).
20782 SDValue &Base,
20783 SelectionDAG &DAG) const {
20784
20786 int16_t ForceXFormImm = 0;
20787 if (provablyDisjointOr(DAG, N) &&
20788 !isIntS16Immediate(N.getOperand(1), ForceXFormImm)) {
20789 Disp = N.getOperand(0);
20790 Base = N.getOperand(1);
20791 return Mode;
20792 }
20793
20794 // If the address is the result of an add, we will utilize the fact that the
20795 // address calculation includes an implicit add. However, we can reduce
20796 // register pressure if we do not materialize a constant just for use as the
20797 // index register. We only get rid of the add if it is not an add of a
20798 // value and a 16-bit signed constant and both have a single use.
20799 if (N.getOpcode() == ISD::ADD &&
20800 (!isIntS16Immediate(N.getOperand(1), ForceXFormImm) ||
20801 !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
20802 Disp = N.getOperand(0);
20803 Base = N.getOperand(1);
20804 return Mode;
20805 }
20806
20807 // Otherwise, use R0 as the base register.
20808 Disp = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
20809 N.getValueType());
20810 Base = N;
20811
20812 return Mode;
20813}
20814
20816 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
20817 unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
20818 EVT ValVT = Val.getValueType();
20819 // If we are splitting a scalar integer into f64 parts (i.e. so they
20820 // can be placed into VFRC registers), we need to zero extend and
20821 // bitcast the values. This will ensure the value is placed into a
20822 // VSR using direct moves or stack operations as needed.
20823 if (PartVT == MVT::f64 &&
20824 (ValVT == MVT::i32 || ValVT == MVT::i16 || ValVT == MVT::i8)) {
20825 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
20826 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f64, Val);
20827 Parts[0] = Val;
20828 return true;
20829 }
20830 return false;
20831}
20832
20833SDValue PPCTargetLowering::lowerToLibCall(const char *LibCallName, SDValue Op,
20834 SelectionDAG &DAG) const {
20835 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20837 EVT RetVT = Op.getValueType();
20838 Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
20839 SDValue Callee =
20840 DAG.getExternalSymbol(LibCallName, TLI.getPointerTy(DAG.getDataLayout()));
20841 bool SignExtend = TLI.shouldSignExtendTypeInLibCall(RetTy, false);
20843 for (const SDValue &N : Op->op_values()) {
20844 EVT ArgVT = N.getValueType();
20845 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
20846 TargetLowering::ArgListEntry Entry(N, ArgTy);
20847 Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgTy, SignExtend);
20848 Entry.IsZExt = !Entry.IsSExt;
20849 Args.push_back(Entry);
20850 }
20851
20852 SDValue InChain = DAG.getEntryNode();
20853 SDValue TCChain = InChain;
20854 const Function &F = DAG.getMachineFunction().getFunction();
20855 bool isTailCall =
20856 TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
20857 (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
20858 if (isTailCall)
20859 InChain = TCChain;
20860 CLI.setDebugLoc(SDLoc(Op))
20861 .setChain(InChain)
20862 .setLibCallee(CallingConv::C, RetTy, Callee, std::move(Args))
20863 .setTailCall(isTailCall)
20864 .setSExtResult(SignExtend)
20865 .setZExtResult(!SignExtend)
20867 return TLI.LowerCallTo(CLI).first;
20868}
20869
20870SDValue PPCTargetLowering::lowerLibCallBasedOnType(
20871 const char *LibCallFloatName, const char *LibCallDoubleName, SDValue Op,
20872 SelectionDAG &DAG) const {
20873 if (Op.getValueType() == MVT::f32)
20874 return lowerToLibCall(LibCallFloatName, Op, DAG);
20875
20876 if (Op.getValueType() == MVT::f64)
20877 return lowerToLibCall(LibCallDoubleName, Op, DAG);
20878
20879 return SDValue();
20880}
20881
20882bool PPCTargetLowering::isLowringToMASSFiniteSafe(SDValue Op) const {
20883 SDNodeFlags Flags = Op.getNode()->getFlags();
20884 return isLowringToMASSSafe(Op) && Flags.hasNoSignedZeros() &&
20885 Flags.hasNoNaNs() && Flags.hasNoInfs();
20886}
20887
20888bool PPCTargetLowering::isLowringToMASSSafe(SDValue Op) const {
20889 return Op.getNode()->getFlags().hasApproximateFuncs();
20890}
20891
20892bool PPCTargetLowering::isScalarMASSConversionEnabled() const {
20895}
20896
20897SDValue PPCTargetLowering::lowerLibCallBase(const char *LibCallDoubleName,
20898 const char *LibCallFloatName,
20899 const char *LibCallDoubleNameFinite,
20900 const char *LibCallFloatNameFinite,
20901 SDValue Op,
20902 SelectionDAG &DAG) const {
20903 if (!isScalarMASSConversionEnabled() || !isLowringToMASSSafe(Op))
20904 return SDValue();
20905
20906 if (!isLowringToMASSFiniteSafe(Op))
20907 return lowerLibCallBasedOnType(LibCallFloatName, LibCallDoubleName, Op,
20908 DAG);
20909
20910 return lowerLibCallBasedOnType(LibCallFloatNameFinite,
20911 LibCallDoubleNameFinite, Op, DAG);
20912}
20913
20914SDValue PPCTargetLowering::lowerPow(SDValue Op, SelectionDAG &DAG) const {
20915 return lowerLibCallBase("__xl_pow", "__xl_powf", "__xl_pow_finite",
20916 "__xl_powf_finite", Op, DAG);
20917}
20918
20919SDValue PPCTargetLowering::lowerSin(SDValue Op, SelectionDAG &DAG) const {
20920 return lowerLibCallBase("__xl_sin", "__xl_sinf", "__xl_sin_finite",
20921 "__xl_sinf_finite", Op, DAG);
20922}
20923
20924SDValue PPCTargetLowering::lowerCos(SDValue Op, SelectionDAG &DAG) const {
20925 return lowerLibCallBase("__xl_cos", "__xl_cosf", "__xl_cos_finite",
20926 "__xl_cosf_finite", Op, DAG);
20927}
20928
20929SDValue PPCTargetLowering::lowerLog(SDValue Op, SelectionDAG &DAG) const {
20930 return lowerLibCallBase("__xl_log", "__xl_logf", "__xl_log_finite",
20931 "__xl_logf_finite", Op, DAG);
20932}
20933
20934SDValue PPCTargetLowering::lowerLog10(SDValue Op, SelectionDAG &DAG) const {
20935 return lowerLibCallBase("__xl_log10", "__xl_log10f", "__xl_log10_finite",
20936 "__xl_log10f_finite", Op, DAG);
20937}
20938
20939SDValue PPCTargetLowering::lowerExp(SDValue Op, SelectionDAG &DAG) const {
20940 return lowerLibCallBase("__xl_exp", "__xl_expf", "__xl_exp_finite",
20941 "__xl_expf_finite", Op, DAG);
20942}
20943
20944// If we happen to match to an aligned D-Form, check if the Frame Index is
20945// adequately aligned. If it is not, reset the mode to match to X-Form.
20946static void setXFormForUnalignedFI(SDValue N, unsigned Flags,
20949 return;
20950 if ((Mode == PPC::AM_DSForm && !(Flags & PPC::MOF_RPlusSImm16Mult4)) ||
20953}
20954
20955/// SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode),
20956/// compute the address flags of the node, get the optimal address mode based
20957/// on the flags, and set the Base and Disp based on the address mode.
20959 SDValue N, SDValue &Disp,
20960 SDValue &Base,
20961 SelectionDAG &DAG,
20962 MaybeAlign Align) const {
20963 SDLoc DL(Parent);
20964
20965 // Compute the address flags.
20966 unsigned Flags = computeMOFlags(Parent, N, DAG);
20967
20968 // Get the optimal address mode based on the Flags.
20969 PPC::AddrMode Mode = getAddrModeForFlags(Flags);
20970
20971 // If the address mode is DS-Form or DQ-Form, check if the FI is aligned.
20972 // Select an X-Form load if it is not.
20973 setXFormForUnalignedFI(N, Flags, Mode);
20974
20975 // Set the mode to PC-Relative addressing mode if we have a valid PC-Rel node.
20976 if ((Mode == PPC::AM_XForm) && isPCRelNode(N)) {
20977 assert(Subtarget.isUsingPCRelativeCalls() &&
20978 "Must be using PC-Relative calls when a valid PC-Relative node is "
20979 "present!");
20980 Mode = PPC::AM_PCRel;
20981 }
20982
20983 // Set Base and Disp accordingly depending on the address mode.
20984 switch (Mode) {
20985 case PPC::AM_DForm:
20986 case PPC::AM_DSForm:
20987 case PPC::AM_DQForm: {
20988 // This is a register plus a 16-bit immediate. The base will be the
20989 // register and the displacement will be the immediate unless it
20990 // isn't sufficiently aligned.
20991 if (Flags & PPC::MOF_RPlusSImm16) {
20992 SDValue Op0 = N.getOperand(0);
20993 SDValue Op1 = N.getOperand(1);
20994 int16_t Imm = Op1->getAsZExtVal();
20995 if (!Align || isAligned(*Align, Imm)) {
20996 Disp = DAG.getSignedTargetConstant(Imm, DL, N.getValueType());
20997 Base = Op0;
20999 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
21000 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
21001 }
21002 break;
21003 }
21004 }
21005 // This is a register plus the @lo relocation. The base is the register
21006 // and the displacement is the global address.
21007 else if (Flags & PPC::MOF_RPlusLo) {
21008 Disp = N.getOperand(1).getOperand(0); // The global address.
21013 Base = N.getOperand(0);
21014 break;
21015 }
21016 // This is a constant address at most 32 bits. The base will be
21017 // zero or load-immediate-shifted and the displacement will be
21018 // the low 16 bits of the address.
21019 else if (Flags & PPC::MOF_AddrIsSImm32) {
21020 auto *CN = cast<ConstantSDNode>(N);
21021 EVT CNType = CN->getValueType(0);
21022 uint64_t CNImm = CN->getZExtValue();
21023 // If this address fits entirely in a 16-bit sext immediate field, codegen
21024 // this as "d, 0".
21025 int16_t Imm;
21026 if (isIntS16Immediate(CN, Imm) && (!Align || isAligned(*Align, Imm))) {
21027 Disp = DAG.getSignedTargetConstant(Imm, DL, CNType);
21028 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
21029 CNType);
21030 break;
21031 }
21032 // Handle 32-bit sext immediate with LIS + Addr mode.
21033 if ((CNType == MVT::i32 || isInt<32>(CNImm)) &&
21034 (!Align || isAligned(*Align, CNImm))) {
21035 int32_t Addr = (int32_t)CNImm;
21036 // Otherwise, break this down into LIS + Disp.
21037 Disp = DAG.getSignedTargetConstant((int16_t)Addr, DL, MVT::i32);
21038 Base = DAG.getSignedTargetConstant((Addr - (int16_t)Addr) >> 16, DL,
21039 MVT::i32);
21040 uint32_t LIS = CNType == MVT::i32 ? PPC::LIS : PPC::LIS8;
21041 Base = SDValue(DAG.getMachineNode(LIS, DL, CNType, Base), 0);
21042 break;
21043 }
21044 }
21045 // Otherwise, the PPC:MOF_NotAdd flag is set. Load/Store is Non-foldable.
21046 Disp = DAG.getTargetConstant(0, DL, getPointerTy(DAG.getDataLayout()));
21048 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
21049 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
21050 } else
21051 Base = N;
21052 break;
21053 }
21054 case PPC::AM_PrefixDForm: {
21055 int64_t Imm34 = 0;
21056 unsigned Opcode = N.getOpcode();
21057 if (((Opcode == ISD::ADD) || (Opcode == ISD::OR)) &&
21058 (isIntS34Immediate(N.getOperand(1), Imm34))) {
21059 // N is an Add/OR Node, and it's operand is a 34-bit signed immediate.
21060 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
21061 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0)))
21062 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
21063 else
21064 Base = N.getOperand(0);
21065 } else if (isIntS34Immediate(N, Imm34)) {
21066 // The address is a 34-bit signed immediate.
21067 Disp = DAG.getSignedTargetConstant(Imm34, DL, N.getValueType());
21068 Base = DAG.getRegister(PPC::ZERO8, N.getValueType());
21069 }
21070 break;
21071 }
21072 case PPC::AM_PCRel: {
21073 // When selecting PC-Relative instructions, "Base" is not utilized as
21074 // we select the address as [PC+imm].
21075 Disp = N;
21076 break;
21077 }
21078 case PPC::AM_None:
21079 break;
21080 default: { // By default, X-Form is always available to be selected.
21081 // When a frame index is not aligned, we also match by XForm.
21083 Base = FI ? N : N.getOperand(1);
21084 Disp = FI ? DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
21085 N.getValueType())
21086 : N.getOperand(0);
21087 break;
21088 }
21089 }
21090 return Mode;
21091}
21092
21094 bool Return,
21095 bool IsVarArg) const {
21096 switch (CC) {
21097 case CallingConv::Cold:
21098 return (Return ? RetCC_PPC_Cold : CC_PPC64_ELF);
21099 default:
21100 return CC_PPC64_ELF;
21101 }
21102}
21103
21105 return Subtarget.isPPC64() && Subtarget.hasQuadwordAtomics();
21106}
21107
21110 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
21111 if (shouldInlineQuadwordAtomics() && Size == 128)
21113
21114 switch (AI->getOperation()) {
21120 default:
21122 }
21123
21124 llvm_unreachable("unreachable atomicrmw operation");
21125}
21126
21135
21136static Intrinsic::ID
21138 switch (BinOp) {
21139 default:
21140 llvm_unreachable("Unexpected AtomicRMW BinOp");
21142 return Intrinsic::ppc_atomicrmw_xchg_i128;
21143 case AtomicRMWInst::Add:
21144 return Intrinsic::ppc_atomicrmw_add_i128;
21145 case AtomicRMWInst::Sub:
21146 return Intrinsic::ppc_atomicrmw_sub_i128;
21147 case AtomicRMWInst::And:
21148 return Intrinsic::ppc_atomicrmw_and_i128;
21149 case AtomicRMWInst::Or:
21150 return Intrinsic::ppc_atomicrmw_or_i128;
21151 case AtomicRMWInst::Xor:
21152 return Intrinsic::ppc_atomicrmw_xor_i128;
21154 return Intrinsic::ppc_atomicrmw_nand_i128;
21155 }
21156}
21157
21159 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
21160 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
21161 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21162 Module *M = Builder.getModule();
21163 Type *ValTy = Incr->getType();
21164 assert(ValTy->getPrimitiveSizeInBits() == 128);
21165 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21166 Value *IncrLo = Builder.CreateTrunc(Incr, Int64Ty, "incr_lo");
21167 Value *IncrHi =
21168 Builder.CreateTrunc(Builder.CreateLShr(Incr, 64), Int64Ty, "incr_hi");
21169 Value *LoHi = Builder.CreateIntrinsic(
21171 {AlignedAddr, IncrLo, IncrHi});
21172 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21173 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21174 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21175 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21176 return Builder.CreateOr(
21177 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21178}
21179
21181 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
21182 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
21183 assert(shouldInlineQuadwordAtomics() && "Only support quadword now");
21184 Module *M = Builder.getModule();
21185 Type *ValTy = CmpVal->getType();
21186 assert(ValTy->getPrimitiveSizeInBits() == 128);
21187 Function *IntCmpXchg =
21188 Intrinsic::getOrInsertDeclaration(M, Intrinsic::ppc_cmpxchg_i128);
21189 Type *Int64Ty = Type::getInt64Ty(M->getContext());
21190 Value *CmpLo = Builder.CreateTrunc(CmpVal, Int64Ty, "cmp_lo");
21191 Value *CmpHi =
21192 Builder.CreateTrunc(Builder.CreateLShr(CmpVal, 64), Int64Ty, "cmp_hi");
21193 Value *NewLo = Builder.CreateTrunc(NewVal, Int64Ty, "new_lo");
21194 Value *NewHi =
21195 Builder.CreateTrunc(Builder.CreateLShr(NewVal, 64), Int64Ty, "new_hi");
21196 emitLeadingFence(Builder, CI, Ord);
21197 Value *LoHi =
21198 Builder.CreateCall(IntCmpXchg, {AlignedAddr, CmpLo, CmpHi, NewLo, NewHi});
21199 emitTrailingFence(Builder, CI, Ord);
21200 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
21201 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
21202 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
21203 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
21204 return Builder.CreateOr(
21205 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
21206}
21207
21209 return Subtarget.useCRBits();
21210}
21211
21212/// Shuffle masks for vectors of bits are not legal as such vectors are
21213/// reserved for MMA/DM.
21214bool PPCTargetLowering::isShuffleMaskLegal(ArrayRef<int> Mask, EVT VT) const {
21215 if (VT.getScalarType() == MVT::i1)
21216 return false;
21217 return TargetLowering::isShuffleMaskLegal(Mask, VT);
21218}
21219
21220// Optimize the following patterns using vbpermq/vbpermd:
21221// i16 = bitcast(v16i1 truncate(v16i8))
21222// i8 = bitcast(v8i1 truncate(v8i16))
21223// i8 = bitcast(v8i1 truncate(v8i8))
21224SDValue PPCTargetLowering::DAGCombineBitcast(SDNode *N,
21225 DAGCombinerInfo &DCI) const {
21226 SDValue Op0 = N->getOperand(0);
21227 if (Op0.getOpcode() != ISD::TRUNCATE)
21228 return SDValue();
21229 SDValue Src = Op0.getOperand(0);
21230 EVT ResVT = N->getValueType(0);
21231 EVT TruncResVT = Op0.getValueType();
21232 EVT SrcVT = Src.getValueType();
21233 SDLoc dl(N);
21234 SelectionDAG &DAG = DCI.DAG;
21235 bool IsLittleEndian = Subtarget.isLittleEndian();
21236
21237 if (ResVT != MVT::i16 && ResVT != MVT::i8)
21238 return SDValue();
21239 SDValue VBPerm =
21240 GenerateVBPERM(DAG, dl, Src, SrcVT, TruncResVT, IsLittleEndian);
21241 if (!VBPerm)
21242 return SDValue();
21243 SDValue ForExtract = DAG.getBitcast(MVT::v4i32, VBPerm);
21244 SDValue Extracted =
21245 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, ForExtract,
21246 DAG.getIntPtrConstant(IsLittleEndian ? 2 : 1, dl));
21247 return DAG.getNode(ISD::TRUNCATE, dl, ResVT, Extracted);
21248}
21249
21250SDValue PPCTargetLowering::GenerateVBPERM(SelectionDAG &DAG, SDLoc dl,
21251 SDValue Src, EVT SrcVT, EVT ResVT,
21252 bool IsLE) const {
21253 bool IsV16i8 = (ResVT == MVT::v16i1 && SrcVT == MVT::v16i8);
21254 bool IsV8i16 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i16);
21255 bool IsV8i8 = (ResVT == MVT::v8i1 && SrcVT == MVT::v8i8);
21256
21257 if (!IsV16i8 && !IsV8i16 && !IsV8i8)
21258 return SDValue();
21259
21260 if (IsV8i8) {
21261 Src = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, MVT::v16i8,
21262 DAG.getUNDEF(MVT::v16i8), Src,
21263 DAG.getIntPtrConstant(0, dl));
21264 }
21265 SmallVector<int, 16> BitIndices(16, 128);
21266 unsigned NumElts = SrcVT.getVectorNumElements();
21267 unsigned EltSize = SrcVT.getScalarType().getSizeInBits();
21268 for (int Idx = 0, End = SrcVT.getVectorNumElements(); Idx < End; Idx++) {
21269 BitIndices[Idx] = EltSize * (NumElts - Idx) - 1;
21270 if (IsV8i8 && IsLE)
21271 BitIndices[Idx] += 64;
21272 }
21273 if (!IsLE)
21274 std::reverse(BitIndices.begin(), BitIndices.end());
21276 for (auto Idx : BitIndices)
21277 BVOps.push_back(DAG.getConstant(Idx, dl, MVT::i8));
21278 SDValue VRB = DAG.getBuildVector(MVT::v16i8, dl, BVOps);
21279 return DAG.getNode(
21280 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v16i8,
21281 DAG.getConstant(Intrinsic::ppc_altivec_vbpermq, dl, MVT::i32),
21282 DAG.getBitcast(MVT::v16i8, Src), VRB);
21283}
21284
21285// For Power8/9, optimize vec splats of small FP values that can be
21286// represented as integers. Use vspltisw + xvcvsxwdp/xvcvsxwsp instead of
21287// loading from constant pool.
21288SDValue PPCTargetLowering::LowerVecSplatSmallFP(SDValue Op, SelectionDAG &DAG,
21289 bool BVNIsConstantSplat,
21290 unsigned SplatBitSize) const {
21291
21292 if (!BVNIsConstantSplat || !Subtarget.hasVSX() || !Subtarget.hasP8Vector() ||
21293 Subtarget.hasP10Vector())
21294 return SDValue();
21295
21296 EVT VT = Op->getValueType(0);
21297 if (!((SplatBitSize == 64 && VT == MVT::v2f64) ||
21298 (SplatBitSize == 32 && VT == MVT::v4f32)))
21299 return SDValue();
21300
21301 auto *CN = dyn_cast<ConstantFPSDNode>(Op.getOperand(0));
21302 if (!CN)
21303 return SDValue();
21304
21305 APFloat APFloatVal = CN->getValueAPF();
21306 bool IsExact;
21307 APSInt IntResult(16, false);
21308 APFloatVal.convertToInteger(IntResult, APFloat::rmTowardZero, &IsExact);
21309
21310 if (!(IsExact && IntResult <= 15 && IntResult >= -16 && !APFloatVal.isZero()))
21311 return SDValue();
21312
21313 int64_t IntVal = IntResult.getSExtValue();
21314
21315 SDLoc dl(Op);
21316 SDValue IntSplat = getCanonicalConstSplat(IntVal, 4, MVT::v4i32, DAG, dl);
21317
21318 if (SplatBitSize == 64)
21319 return DAG.getNode(
21320 ISD::INTRINSIC_WO_CHAIN, dl, MVT::v2f64,
21321 DAG.getConstant(Intrinsic::ppc_vsx_xvcvsxwdp, dl, MVT::i32), IntSplat);
21322
21323 return DAG.getNode(PPCISD::XVCVSXWSP, dl, MVT::v4f32, IntSplat);
21324}
static MCRegister MatchRegisterName(StringRef Name)
static unsigned getCallOpcode(const MachineFunction &CallerF, bool IsIndirect, bool IsTailCall, std::optional< CallLowering::PtrAuthInfo > &PAI, MachineRegisterInfo &MRI)
static bool isSignExtended(SDValue N, SelectionDAG &DAG)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
uint64_t Imm
static std::pair< Register, unsigned > getBaseWithConstantOffset(MachineRegisterInfo &MRI, Register Reg)
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
This file implements the APSInt class, which is a simple class that represents an arbitrary sized int...
static bool isLoad(int Opcode)
static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, SDValue RHS, SelectionDAG &DAG, const SDLoc &dl)
GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit the specified operations t...
static bool isFloatingPointZero(SDValue Op)
isFloatingPointZero - Return true if this is +0.0.
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
Atomic ordering constants.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static RegisterPass< DebugifyModulePass > DM("debugify", "Attach debug info to everything")
This file defines the DenseMap class.
const HexagonInstrInfo * TII
static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, const SDLoc &dl)
CreateCopyOfByValArgument - Make a copy of an aggregate at address specified by "Src" to address "Dst...
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
This defines the Use class.
iv users
Definition IVUsers.cpp:48
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define RegName(no)
static LVOptions Options
Definition LVOptions.cpp:25
lazy value info
This file implements the LivePhysRegs utility for tracking liveness of physical registers.
static int getEstimateRefinementSteps(EVT VT, const LoongArchSubtarget &Subtarget)
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define T
static bool isConstantOrUndef(const SDValue Op)
#define P(N)
static CodeModel::Model getCodeModel(const PPCSubtarget &S, const TargetMachine &TM, const MachineOperand &MO)
cl::opt< bool > ANDIGlueBug("ppc-expose-andi-glue-bug", cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden)
static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT, SelectionDAG &DAG, const SDLoc &dl)
getCanonicalConstSplat - Build a canonical splat immediate of Val with an element size of SplatSize.
static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
static const TargetRegisterClass * getRegClassForSVT(MVT::SimpleValueType SVT, bool IsPPC64, bool HasP8Vector, bool HasVSX)
static bool isGPRShadowAligned(MCPhysReg Reg, Align RequiredAlign)
static SDValue DAGCombineAddc(SDNode *N, llvm::PPCTargetLowering::DAGCombinerInfo &DCI)
static bool needStackSlotPassParameters(const PPCSubtarget &Subtarget, const SmallVectorImpl< ISD::OutputArg > &Outs)
std::tuple< uint32_t, uint8_t > LXVKQPattern
static bool isAlternatingShuffMask(const ArrayRef< int > &Mask, int NumElts)
static bool isShuffleMaskInRange(const SmallVectorImpl< int > &ShuffV, int HalfVec, int LHSLastElementDefined, int RHSLastElementDefined)
static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG, SDValue Input, uint64_t Elems, uint64_t CorrectElems)
static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG)
static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement, bool Swap, SDLoc &DL, SelectionDAG &DAG)
This function is called when we have proved that a SETCC node can be replaced by subtraction (and oth...
static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL)
static void CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool IsPPC64, SDValue Arg, int SPDiff, unsigned ArgOffset, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments)
CalculateTailCallArgDest - Remember Argument for later processing.
static MachineBasicBlock * emitAtomicCmpSwapSoftware(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit software-emulated atomic compare-and-swap for I8/I16 without hardware partword atomic support.
static SDValue DAGCombineSube(SDNode *N, llvm::PPCTargetLowering::DAGCombinerInfo &DCI)
static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void setAlignFlagsForFI(SDValue N, unsigned &FlagSet, SelectionDAG &DAG)
Set alignment flags based on whether or not the Frame Index is aligned.
static bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget)
static cl::opt< bool > EnableILPPref("ppc-ilp-pref", cl::desc("Set the node scheduling preference to ILP on PPC"), cl::init(true), cl::Hidden)
static void updateForAIXShLibTLSModelOpt(TLSModel::Model &Model, SelectionDAG &DAG, const TargetMachine &TM)
updateForAIXShLibTLSModelOpt - Helper to initialize TLS model opt settings, and then apply the update...
static cl::opt< bool > EnableInnermostLoopAlign32("ppc-innermost-loop-align32", cl::desc("Align innermost loops to 32 bytes on ppc"), cl::init(true), cl::Hidden)
static bool IsSelect(unsigned Opcode, bool CheckOnlyCC=false)
Check if the opcode is a SELECT or SELECT_CC variant.
static bool provablyDisjointOr(SelectionDAG &DAG, const SDValue &N)
Used when computing address flags for selecting loads and stores.
static bool callsShareTOCBase(const Function *Caller, const GlobalValue *CalleeGV, const TargetMachine &TM)
static void prepareOutOfLineGlueCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, SDValue CallSeqStart, const CallBase *CB, const SDLoc &dl, bool hasNest, const PPCSubtarget &Subtarget)
static SDValue generateSToVPermutedForVecShuffle(int ScalarSize, uint64_t ShuffleEltWidth, unsigned &NumValidElts, int FirstElt, int &LastElt, SDValue VecShuffOperand, SDValue SToVNode, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
constexpr uint64_t AIXSmallTlsPolicySizeLimit
static bool isPCRelNode(SDValue N)
static void LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, bool isTailCall, bool isVector, SmallVectorImpl< SDValue > &MemOpChains, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments, const SDLoc &dl)
LowerMemOpCallTo - Store the argument to the stack or remember it in case of tail calls.
static cl::opt< unsigned > PPCGatherAllAliasesMaxDepth("ppc-gather-alias-max-depth", cl::init(18), cl::Hidden, cl::desc("max depth when checking alias info in GatherAllAliases()"))
static bool IsSelectCC(unsigned Opcode)
static bool areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC, CallingConv::ID CalleeCC)
static const MCPhysReg FPR[]
FPR - The set of FP registers that should be allocated for arguments on Darwin and AIX.
static SDNode * isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG)
isCallCompatibleAddress - Return the immediate to use if the specified 32-bit value is representable ...
static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize)
CalculateStackSlotAlignment - Calculates the alignment of this argument on the stack.
static SDValue ConvertCarryFlagToCarryValue(EVT SumType, SDValue Flag, EVT CarryType, SelectionDAG &DAG, const PPCSubtarget &STI)
static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V, bool HasDirectMove, bool HasP8Vector)
Do we have an efficient pattern in a .td file for this node?
static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void setUsesTOCBasePtr(MachineFunction &MF)
static SDValue combineXorSelectCC(SDNode *N, SelectionDAG &DAG)
static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG, const SDLoc &dl, const PPCSubtarget &Subtarget)
static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, unsigned NumBytes)
EnsureStackAlignment - Round stack frame size up from NumBytes to ensure minimum alignment required f...
static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N, SelectionDAG &DAG)
static bool isStoreConditional(SDValue Intrin, unsigned &StoreWidth)
static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB)
static cl::opt< bool > EnablePerfectShuffle("ppc-perfect-shuffle", cl::desc("enable vector permute decomposition"), cl::init(false), cl::Hidden)
static bool isFPExtLoad(SDValue Op)
static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, const SDLoc &dl, EVT DestVT=MVT::Other)
BuildIntrinsicOp - Return a unary operator intrinsic node with the specified intrinsic ID.
static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG)
static bool canConvertToVcmpequb(SDValue &LHS, SDValue &RHS, bool IsPPC64)
static void StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, SDValue Chain, const SmallVectorImpl< TailCallArgumentInfo > &TailCallArgs, SmallVectorImpl< SDValue > &MemOpChains, const SDLoc &dl)
StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
static cl::opt< bool > UseAbsoluteJumpTables("ppc-use-absolute-jumptables", cl::desc("use absolute jump tables on ppc"), cl::Hidden)
static void setXFormForUnalignedFI(SDValue N, unsigned Flags, PPC::AddrMode &Mode)
static cl::opt< unsigned > PPCMinimumBitTestCmps("ppc-min-bit-test-cmps", cl::init(3), cl::Hidden, cl::desc("Set minimum of largest number of comparisons to use bit test for " "switch on PPC."))
static CallInst * callIntrinsic(IRBuilderBase &Builder, Intrinsic::ID Id)
static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign)
getMaxByValAlign - Helper for getByValTypeAlignment to determine the desired ByVal argument alignment...
static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG)
static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned LHSStart, unsigned RHSStart)
isVMerge - Common function, used to match vmrg* shuffles.
static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget, unsigned &HiOpFlags, unsigned &LoOpFlags, const GlobalValue *GV=nullptr)
Return true if we should reference labels using a PICBase, set the HiOpFlags and LoOpFlags to the tar...
static void buildCallOperands(SmallVectorImpl< SDValue > &Ops, PPCTargetLowering::CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG, SmallVector< std::pair< unsigned, SDValue >, 8 > &RegsToPass, SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff, const PPCSubtarget &Subtarget)
static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget &ST)
Returns true if we should use a direct load into vector instruction (such as lxsd or lfd),...
static SDValue getDataClassTest(SDValue Op, FPClassTest Mask, const SDLoc &Dl, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl< int > &ShuffV, int LHSFirstElt, int LHSLastElt, int RHSFirstElt, int RHSLastElt, int HalfVec, unsigned LHSNumValidElts, unsigned RHSNumValidElts, const PPCSubtarget &Subtarget)
static SDValue AdjustLength(SDValue Val, unsigned Bits, bool Left, SelectionDAG &DAG)
static std::optional< LXVKQPattern > getPatternInfo(const APInt &FullVal)
static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT)
static SDValue ConvertSETCCToXori(SDNode *N, SelectionDAG &DAG)
static Intrinsic::ID getIntrinsicForAtomicRMWBinOp128(AtomicRMWInst::BinOp BinOp)
static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize)
CalculateStackSlotSize - Calculates the size reserved for this argument on the stack.
static int CalculateTailCallSPDiff(SelectionDAG &DAG, bool isTailCall, unsigned ParamSize)
CalculateTailCallSPDiff - Get the amount the stack pointer has to be adjusted to accommodate the argu...
static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, const SDLoc &dl)
static cl::opt< bool > EnableP10StoreForward("ppc-p10-store-forward", cl::desc("enable P10 store forward-friendly conversion"), cl::init(true), cl::Hidden)
static SDValue combineSELECT_CCBitFloor(SDNode *N, SelectionDAG &DAG)
Optimize the bitfloor(X) pattern for PowerPC.
static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, SelectionDAG &DAG)
static SDValue isScalarToVec(SDValue Op)
static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl)
bool isValidMtVsrBmi(APInt &BitMask, BuildVectorSDNode &BVN, bool IsLittleEndian)
static MachineBasicBlock * emitSelect(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit SELECT instruction, using ISEL if available, otherwise use branch-based control flow.
static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, bool &isDot, const PPCSubtarget &Subtarget)
getVectorCompareInfo - Given an intrinsic, return false if it is not a vector comparison.
static unsigned invertFMAOpcode(unsigned Opc)
static SDValue combineADDToSUB(SDNode *N, SelectionDAG &DAG, const PPCSubtarget &Subtarget)
static const SDValue * getNormalLoadInput(const SDValue &Op, bool &IsPermuted)
static bool canConvertSETCCToXori(SDNode *N)
static cl::opt< unsigned > PPCMinimumJumpTableEntries("ppc-min-jump-table-entries", cl::init(64), cl::Hidden, cl::desc("Set minimum number of entries to use a jump table on PPC"))
static bool isValidSplatLoad(const PPCSubtarget &Subtarget, const SDValue &Op, unsigned &Opcode)
static SDValue ConvertCarryValueToCarryFlag(EVT SumType, SDValue Value, SelectionDAG &DAG, const PPCSubtarget &STI)
static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG, const PPCSubtarget &Subtarget, SDValue Chain=SDValue())
cl::opt< bool > EnableAutoPairedVecSt("ppc-auto-paired-vec-st", cl::desc("enable automatically generated 32byte paired vector stores"), cl::init(false), cl::Hidden)
static cl::opt< bool > EnableSCO("ppc-sco", cl::desc("enable sibling call optimization on ppc"), cl::init(true), cl::Hidden)
static void PrepareTailCall(SelectionDAG &DAG, SDValue &InGlue, SDValue &Chain, const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp, SDValue FPOp, SmallVectorImpl< TailCallArgumentInfo > &TailCallArguments)
static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain, SDValue OldRetAddr, SDValue OldFP, int SPDiff, const SDLoc &dl)
EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to the appropriate stack sl...
static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, SelectionDAG &DAG, const SDLoc &dl)
BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified amount.
static void createAtomicLoopBlocks(MachineFunction *F, MachineBasicBlock *BB, MachineBasicBlock *&loop1MBB, MachineBasicBlock *&loop2MBB, MachineBasicBlock *&exitMBB, MachineInstr &MI, MachineFunction::iterator It)
Helper function to create basic blocks for atomic compare-and-swap.
cl::opt< bool > EnablePPCGenScalarMASSEntries
static SDValue combineBVZEXTLOAD(SDNode *N, SelectionDAG &DAG)
static SDValue combineZextSetccWithZero(SDNode *N, SelectionDAG &DAG)
static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT, SelectionDAG &DAG, SDValue ArgValue, MVT LocVT, const SDLoc &dl)
static void computeFlagsForAddressComputation(SDValue N, unsigned &FlagSet, SelectionDAG &DAG)
Given a node, compute flags that are used for address computation when selecting load and store instr...
static MachineBasicBlock * emitAtomicCmpSwapHardware(MachineInstr &MI, MachineBasicBlock *BB, const TargetInstrInfo *TII, const PPCSubtarget &Subtarget)
Emit hardware-supported atomic compare-and-swap for I32/I64 and I8/I16 with partword atomic support.
SDValue convertTwoLoadsAndCmpToVCMPEQUB(SelectionDAG &DAG, SDNode *N, const SDLoc &DL)
static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart)
static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize, unsigned LinkageSize, unsigned ParamAreaSize, unsigned &ArgOffset, unsigned &AvailableFPRs, unsigned &AvailableVRs)
CalculateStackSlotUsed - Return whether this argument will use its stack slot (instead of being passe...
static void signExtendOperandIfUnknown(MachineInstr &MI, MachineBasicBlock *BB, unsigned OpIdx, bool IsByte, const PPCInstrInfo *TII)
static cl::opt< unsigned > PPCAIXTLSModelOptUseIEForLDLimit("ppc-aix-shared-lib-tls-model-opt-limit", cl::init(1), cl::Hidden, cl::desc("Set inclusive limit count of TLS local-dynamic access(es) in a " "function to use initial-exec"))
static unsigned getPPCStrictOpcode(unsigned Opc)
static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee, SDValue &Glue, SDValue &Chain, SDValue CallSeqStart, const CallBase *CB, const SDLoc &dl, bool hasNest, const PPCSubtarget &Subtarget)
static bool isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width)
static bool isFunctionGlobalAddress(const GlobalValue *CalleeGV)
static cl::opt< bool > EnablePPCPreinc("ppc-preinc", cl::desc("enable preincrement load/store generation on PPC"), cl::init(true), cl::Hidden)
static bool isSplatBV(SDValue Op)
static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG)
static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int)
Check that the mask is shuffling N byte elements.
static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG)
Reduce the number of loads when building a vector.
static cl::opt< bool > EnablePPCUnaligned("ppc-unaligned", cl::desc("enable unaligned load/store generation on PPC"), cl::init(true), cl::Hidden)
static bool isValidPCRelNode(SDValue N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
if(PassOpts->AAPipeline)
pre isel intrinsic Pre ISel Intrinsic Lowering
static constexpr MCPhysReg SPReg
SmallVector< MachineOperand, 4 > Cond
RISCVCC::CondCode CC
MachineRegisterInfo & MRI
MachineInstr *& Lo
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
SI optimize exec mask operations pre RA
static const MCExpr * MaskShift(const MCExpr *Val, uint32_t Mask, uint32_t Shift, MCContext &Ctx)
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition Value.cpp:480
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG, const SparcSubtarget *Subtarget)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file describes how to lower LLVM code to machine code.
static constexpr int TPOffset
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
static const fltSemantics & IEEEsingle()
Definition APFloat.h:304
static constexpr roundingMode rmTowardZero
Definition APFloat.h:365
static constexpr roundingMode rmNearestTiesToEven
Definition APFloat.h:361
static const fltSemantics & PPCDoubleDouble()
Definition APFloat.h:310
LLVM_ABI opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo)
Definition APFloat.cpp:6044
bool isDenormal() const
Definition APFloat.h:1584
bool isZero() const
Definition APFloat.h:1579
APInt bitcastToAPInt() const
Definition APFloat.h:1475
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
Definition APFloat.h:1436
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isNegatedPowerOf2() const
Check if this APInt's negated value is a power of two greater than zero.
Definition APInt.h:445
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
APInt abs() const
Get the absolute value.
Definition APInt.h:1815
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
void clearAllBits()
Set every bit to 0.
Definition APInt.h:1416
bool isSignedIntN(unsigned N) const
Check if this APInt has an N-bits signed integer value.
Definition APInt.h:431
LLVM_ABI void insertBits(const APInt &SubBits, unsigned bitPosition)
Insert the bits from a smaller APInt starting at bitPosition.
Definition APInt.cpp:393
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
double bitsToDouble() const
Converts APInt bits to a double.
Definition APInt.h:1742
bool isPowerOf2() const
Check if this APInt's value is a power of two greater than zero.
Definition APInt.h:436
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
LLVM_ABI APInt extractBits(unsigned numBits, unsigned bitPosition) const
Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
Definition APInt.cpp:478
An arbitrary precision integer that knows its signedness.
Definition APSInt.h:24
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
An instruction that atomically checks whether a specified value is in a memory location,...
an instruction that atomically reads a memory location, combines it with another value,...
BinOp
This enumeration lists the possible modifications atomicrmw can make.
@ Add
*p = old + v
@ USubCond
Subtract only if no unsigned overflow.
@ Sub
*p = old - v
@ And
*p = old & v
@ Xor
*p = old ^ v
@ USubSat
*p = usub.sat(old, v) usub.sat matches the behavior of llvm.usub.sat.
@ UIncWrap
Increment one up to a maximum value.
@ UDecWrap
Decrement one until a minimum value or zero.
@ Nand
*p = ~(old & v)
BinOp getOperation() const
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
const BlockAddress * getBlockAddress() const
static constexpr BranchProbability getOne()
static constexpr BranchProbability getZero()
A "pseudo-class" with methods for operating on BUILD_VECTORs.
LLVM_ABI bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef, unsigned &SplatBitSize, bool &HasAnyUndefs, unsigned MinSplatBits=0, bool isBigEndian=false) const
Check if this is a constant splat, and if so, find the smallest element size that splats the vector.
CCState - This class holds information needed while lowering arguments and return values.
Register getLocReg() const
LocInfo getLocInfo() const
static CCValAssign getReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP, bool IsCustom=false)
static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT, MCRegister Reg, MVT LocVT, LocInfo HTP)
static CCValAssign getMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP, bool IsCustom=false)
bool needsCustom() const
int64_t getLocMemOffset() const
unsigned getValNo() const
static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT, int64_t Offset, MVT LocVT, LocInfo HTP)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
bool isStrictFP() const
Determine if the call requires strict floating point semantics.
CallingConv::ID getCallingConv() const
User::op_iterator arg_begin()
Return the iterator pointing to the beginning of the argument list.
LLVM_ABI bool isMustTailCall() const
Tests if this call site must be tail call optimized.
Value * getCalledOperand() const
User::op_iterator arg_end()
Return the iterator pointing to the end of the argument list.
unsigned arg_size() const
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
This class represents a function call, abstracting a target machine's calling convention.
bool isTailCall() const
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
const Constant * getConstVal() const
uint64_t getZExtValue() const
const APInt & getAPIntValue() const
int64_t getSExtValue() const
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
A debug info location.
Definition DebugLoc.h:126
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition FastISel.h:67
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:699
const DataLayout & getDataLayout() const
Get the data layout of the module this function belongs to.
Definition Function.cpp:356
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
uint64_t getFnAttributeAsParsedInteger(StringRef Kind, uint64_t Default=0) const
For a string attribute Kind, parse attribute as an integer.
Definition Function.cpp:778
bool hasMinSize() const
Optimize this function for minimum size (-Oz).
Definition Function.h:696
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:273
AttributeList getAttributes() const
Return the attribute list for this Function.
Definition Function.h:329
arg_iterator arg_begin()
Definition Function.h:853
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
size_t arg_size() const
Definition Function.h:886
Type * getReturnType() const
Returns the type of the ret val.
Definition Function.h:217
const Argument * const_arg_iterator
Definition Function.h:74
bool isVarArg() const
isVarArg - Return true if this function takes a variable number of arguments.
Definition Function.h:230
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
const GlobalValue * getGlobal() const
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:730
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
void setThreadLocalMode(ThreadLocalMode Val)
bool hasHiddenVisibility() const
LLVM_ABI StringRef getSection() const
Definition Globals.cpp:264
Module * getParent()
Get the module that this global value is contained inside of...
bool isStrongDefinitionForLinker() const
Returns true if this global's definition will be the one chosen by the linker.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
bool hasComdat() const
Type * getValueType() const
bool hasProtectedVisibility() const
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI bool hasAtomicLoad() const LLVM_READONLY
Return true if this atomic instruction loads from memory.
static constexpr LLT scalar(unsigned SizeInBits)
Get a low-level scalar or aggregate "bag of bits".
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Base class for LoadSDNode and StoreSDNode.
Tracks which library functions to use for a particular subtarget or function.
An instruction for reading from memory.
bool isUnordered() const
This class is used to represent ISD::LOAD nodes.
const SDValue & getBasePtr() const
ISD::LoadExtType getExtensionType() const
Return whether this is a plain node, or one of the varieties of value-extending loads.
bool hasValue() const
TypeSize getValue() const
Context object for machine code objects.
Definition MCContext.h:83
Base class for the full range of assembler expressions which are needed for parsing.
Definition MCExpr.h:34
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MCSymbolXCOFF * getQualNameSymbol() const
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
Metadata node.
Definition Metadata.h:1081
Machine Value Type.
@ INVALID_SIMPLE_VALUE_TYPE
SimpleValueType SimpleTy
uint64_t getScalarSizeInBits() const
unsigned getVectorNumElements() const
bool isVector() const
Return true if this is a vector value type.
bool isInteger() const
Return true if this is an integer or a vector integer type.
static auto integer_valuetypes()
TypeSize getSizeInBits() const
Returns the size of the specified MVT in bits.
static auto fixedlen_vector_valuetypes()
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
bool isScalarInteger() const
Return true if this is an integer, not including vectors.
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
static MVT getIntegerVT(unsigned BitWidth)
static auto fp_valuetypes()
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
LLVM_ABI int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void setFrameAddressIsTaken(bool T)
void setHasTailCall(bool V=true)
void setReturnAddressIsTaken(bool s)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool hasVAStart() const
Returns true if the function calls the llvm.va_start intrinsic.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
MCSymbol * getPICBaseSymbol() const
getPICBaseSymbol - Return a function-local symbol to represent the PIC base.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MCContext & getContext() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC)
addLiveIn - Add the specified physical register as a live-in value and create a corresponding virtual...
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & addUse(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register use operand.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & setMIFlag(MachineInstr::MIFlag Flag) const
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & addRegMask(const uint32_t *Mask) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const MachineInstrBuilder & addDef(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a virtual register definition operand.
const MachineInstrBuilder & cloneMemRefs(const MachineInstr &OtherMI) const
const MachineInstrBuilder & addMemOperand(MachineMemOperand *MMO) const
Representation of each machine instruction.
@ EK_LabelDifference32
EK_LabelDifference32 - Each entry is the address of the block minus the address of the jump table.
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
AtomicOrdering getFailureOrdering() const
For cmpxchg atomic operations, return the atomic ordering requirements when store does not occur.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID for this memory operation.
Flags
Flags values. These may be or'd together.
@ MOVolatile
The memory access is volatile.
@ MODereferenceable
The memory access is dereferenceable (i.e., doesn't trap).
@ MOLoad
The memory access reads data.
@ MOInvariant
The memory access always returns the same value (or traps).
@ MOStore
The memory access writes data.
AtomicOrdering getSuccessOrdering() const
Return the atomic ordering requirements for this memory operation.
const MachinePointerInfo & getPointerInfo() const
Flags getFlags() const
Return the raw flags of the source value,.
LLVM_ABI Align getAlign() const
Return the minimum known alignment in bytes of the actual memory reference.
AAMDNodes getAAInfo() const
Return the AA tags for the memory reference.
MachineOperand class - Representation of each machine instruction operand.
static MachineOperand CreateImm(int64_t Val)
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
LLVM_ABI Register getLiveInVirtReg(MCRegister PReg) const
getLiveInVirtReg - If PReg is a live-in physical register, return the corresponding live-in virtual r...
This SDNode is used for target intrinsics that touch memory and need an associated MachineMemOperand.
This is an abstract virtual class for memory operations.
Align getAlign() const
AAMDNodes getAAInfo() const
Returns the AA info that describes the dereference.
MachineMemOperand * getMemOperand() const
Return the unique MachineMemOperand object describing the memory reference performed by operation.
const SDValue & getBasePtr() const
const MachinePointerInfo & getPointerInfo() const
const SDValue & getChain() const
EVT getMemoryVT() const
Return the type of the in-memory value.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
uint64_t getReturnSaveOffset() const
getReturnSaveOffset - Return the previous frame offset to save the return address.
unsigned getLinkageSize() const
getLinkageSize - Return the size of the PowerPC ABI linkage area.
uint64_t getTOCSaveOffset() const
getTOCSaveOffset - Return the previous frame offset to save the TOC register – 64-bit SVR4 ABI only.
PPCFunctionInfo - This class is derived from MachineFunction private PowerPC target-specific informat...
void setVarArgsNumFPR(unsigned Num)
void setVarArgsNumGPR(unsigned Num)
void appendParameterType(ParamType Type)
void setMinReservedArea(unsigned size)
unsigned getMinReservedArea() const
void setVarArgsStackOffset(int Offset)
void addLiveInAttr(Register VReg, ISD::ArgFlagsTy Flags)
This function associates attributes for each live-in virtual register.
static bool hasPCRelFlag(unsigned TF)
bool is32BitELFABI() const
unsigned descriptorTOCAnchorOffset() const
MVT getScalarIntVT() const
bool isAIXABI() const
MCRegister getGlueCodeDescriptorRegister() const
const PPCFrameLowering * getFrameLowering() const override
bool isUsingPCRelativeCalls() const
bool usesFunctionDescriptors() const
True if the ABI is descriptor based.
MCRegister getEnvironmentPointerRegister() const
bool isSVR4ABI() const
bool isLittleEndian() const
MCRegister getTOCPointerRegister() const
MCRegister getStackPointerRegister() const
bool is64BitELFABI() const
bool isELFv2ABI() const
const PPCTargetMachine & getTargetMachine() const
const PPCRegisterInfo * getRegisterInfo() const override
unsigned descriptorEnvironmentPointerOffset() const
MachineBasicBlock * emitEHSjLjLongJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
CCAssignFn * ccAssignFnForCall(CallingConv::ID CC, bool Return, bool IsVarArg) const
bool isTruncateFree(Type *Ty1, Type *Ty2) const override
isTruncateFree - Return true if it's free to truncate a value of type Ty1 to type Ty2.
Value * emitMaskedAtomicRMWIntrinsic(IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const override
Perform a masked atomicrmw using a target-specific intrinsic.
MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const override
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
bool isFPExtFree(EVT DestVT, EVT SrcVT) const override
Return true if an fpext operation is free (for instance, because single-precision floating-point numb...
PPC::AddrMode SelectForceXFormMode(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG) const
SelectForceXFormMode - Given the specified address, force it to be represented as an indexed [r+r] op...
Instruction * emitTrailingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
TargetLowering::AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *AI) const override
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
bool hasInlineStackProbe(const MachineFunction &MF) const override
MachineBasicBlock * emitEHSjLjSetJmp(MachineInstr &MI, MachineBasicBlock *MBB) const
bool supportsTailCallFor(const CallBase *CB) const
bool isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const override
Return true if folding a constant offset with the given GlobalAddress is legal.
MachineBasicBlock * emitProbedAlloca(MachineInstr &MI, MachineBasicBlock *MBB) const
bool isZExtFree(SDValue Val, EVT VT2) const override
Return true if zero-extending the specific node Val to type VT2 is free (either because it's implicit...
SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const override
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
bool SelectAddressRegImm(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, MaybeAlign EncodingAlignment) const
SelectAddressRegImm - Returns true if the address N can be represented by a base register plus a sign...
SDValue expandVSXLoadForLE(SDNode *N, DAGCombinerInfo &DCI) const
bool splitValueIntoRegisterParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, unsigned NumParts, MVT PartVT, std::optional< CallingConv::ID > CC) const override
Target-specific splitting of values into parts that fit a register storing a legal type.
void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const override
LowerAsmOperandForConstraint - Lower the specified operand into the Ops vector.
void ReplaceNodeResults(SDNode *N, SmallVectorImpl< SDValue > &Results, SelectionDAG &DAG) const override
ReplaceNodeResults - Replace the results of node with an illegal result type with new values built ou...
bool hasMultipleConditionRegisters(EVT VT) const override
Does the target have multiple (allocatable) condition registers that can be used to store the results...
Align getByValTypeAlignment(Type *Ty, const DataLayout &DL) const override
getByValTypeAlignment - Return the desired alignment for ByVal aggregate function arguments in the ca...
bool SelectAddressRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG, MaybeAlign EncodingAlignment=std::nullopt) const
SelectAddressRegReg - Given the specified addressed, check to see if it can be more efficiently repre...
SDValue BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, SmallVectorImpl< SDNode * > &Created) const override
Targets may override this function to provide custom SDIV lowering for power-of-2 denominators.
Value * emitStoreConditional(IRBuilderBase &Builder, Value *Val, Value *Addr, AtomicOrdering Ord) const override
Perform a store-conditional operation to Addr.
void computeKnownBitsForTargetNode(const SDValue Op, KnownBits &Known, const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth=0) const override
Determine which of the bits specified in Mask are known to be either zero or one and return them in t...
bool SelectAddressRegRegOnly(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const
SelectAddressRegRegOnly - Given the specified addressed, force it to be represented as an indexed [r+...
bool useSoftFloat() const override
SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const override
Returns relocation base for the given PIC jumptable.
Register getExceptionSelectorRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception typeid on entry to a la...
TargetLowering::AtomicExpansionKind shouldExpandAtomicCmpXchgInIR(const AtomicCmpXchgInst *AI) const override
Returns how the given atomic cmpxchg should be expanded by the IR-level AtomicExpand pass.
Value * emitMaskedAtomicCmpXchgIntrinsic(IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const override
Perform a masked cmpxchg using a target-specific intrinsic.
ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const override
Examine constraint string and operand type and determine a weight value.
bool enableAggressiveFMAFusion(EVT VT) const override
Return true if target always benefits from combining into FMA for a given value type.
Register getRegisterByName(const char *RegName, LLT VT, const MachineFunction &MF) const override
Return the register ID of the name passed in.
bool decomposeMulByConstant(LLVMContext &Context, EVT VT, SDValue C) const override
Return true if it is profitable to transform an integer multiplication-by-constant into simpler opera...
void getTgtMemIntrinsic(SmallVectorImpl< IntrinsicInfo > &Infos, const CallBase &I, MachineFunction &MF, unsigned Intrinsic) const override
Given an intrinsic, checks if on the target the intrinsic will need to map to a MemIntrinsicNode (tou...
unsigned getJumpTableEncoding() const override
Return the entry encoding for a jump table in the current function.
bool isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS, Instruction *I=nullptr) const override
isLegalAddressingMode - Return true if the addressing mode represented by AM is legal for this target...
bool preferIncOfAddToSubOfNot(EVT VT) const override
These two forms are equivalent: sub y, (xor x, -1) add (add x, 1), y The variant with two add's is IR...
bool shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const override
Returns true if it is beneficial to convert a load of a constant to just the constant itself.
const MCPhysReg * getScratchRegisters(CallingConv::ID CC) const override
Returns a 0 terminated array of registers that can be safely used as scratch registers.
bool getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const override
getPreIndexedAddressParts - returns true by value, base pointer and offset pointer and addressing mod...
FastISel * createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo, const LibcallLoweringInfo *LibcallLowering) const override
createFastISel - This method returns a target-specific FastISel object, or null if the target does no...
bool isProfitableToHoist(Instruction *I) const override
isProfitableToHoist - Check if it is profitable to hoist instruction I to its dominator block.
Value * emitLoadLinked(IRBuilderBase &Builder, Type *ValueTy, Value *Addr, AtomicOrdering Ord) const override
Perform a load-linked operation on Addr, returning a "Value *" with the corresponding pointee type.
ConstraintType getConstraintType(StringRef Constraint) const override
getConstraintType - Given a constraint, return the type of constraint it is for this target.
bool fenceClearsLoadLinkedReservation() const override
True unless the subtarget has FeatureFenceKeepsReservation.
const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const override
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
bool shallExtractConstSplatVectorElementToStore(Type *VectorTy, unsigned ElemSizeInBits, unsigned &Index) const override
Return true if the target shall perform extract vector element and store given that the vector is kno...
EVT getOptimalMemOpType(LLVMContext &Context, const MemOp &Op, const AttributeList &FuncAttributes) const override
It returns EVT::Other if the type should be determined using generic target-independent logic.
SDValue PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const override
This method will be invoked for all target nodes and for any target-independent nodes that the target...
SDValue expandVSXStoreForLE(SDNode *N, DAGCombinerInfo &DCI) const
void CollectTargetIntrinsicOperands(const CallInst &I, SmallVectorImpl< SDValue > &Ops, SelectionDAG &DAG) const override
unsigned getStackProbeSize(const MachineFunction &MF) const
Register getExceptionPointerRegister(ExceptionHandling EH, const Constant *PersonalityFn) const override
If a physical register, this returns the register that receives the exception address on entry to an ...
PPCTargetLowering(const PPCTargetMachine &TM, const PPCSubtarget &STI)
Align getPrefLoopAlignment(MachineLoop *ML, const MachineBasicBlock *BlockToAlign) const override
Return the preferred loop alignment.
bool useLoadStackGuardNode(const Module &M) const override
Override to support customized stack guard loading.
bool isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, EVT VT) const override
isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster than a pair of fmul and fadd i...
MachineBasicBlock * EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *MBB, unsigned BinOpcode, unsigned CmpOpcode=0, unsigned CmpPred=0) const
bool allowsMisalignedMemoryAccesses(EVT VT, unsigned AddrSpace, Align Alignment=Align(1), MachineMemOperand::Flags Flags=MachineMemOperand::MONone, unsigned *Fast=nullptr) const override
Is unaligned memory access allowed for the given type, and is it fast relative to software emulation.
bool shouldExpandBuildVectorWithShuffles(EVT VT, unsigned DefinedValues) const override
bool SelectAddressRegImm34(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG) const
Similar to the 16-bit case but for instructions that take a 34-bit displacement field (prefixed loads...
FPImmAction getFPImmAction(const APFloat &Imm, EVT VT, bool ForCodeSize) const override
Returns how the legalizer should materialize the specified FP immediate.
std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const override
Given a physical register constraint (e.g.
bool isJumpTableRelative() const override
SDValue LowerOperation(SDValue Op, SelectionDAG &DAG) const override
LowerOperation - Provide custom lowering hooks for some operations.
PPC::AddrMode SelectOptimalAddrMode(const SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, MaybeAlign Align) const
SelectOptimalAddrMode - Based on a node N and it's Parent (a MemSDNode), compute the address flags of...
bool SelectAddressPCRel(SDValue N, SDValue &Base) const
SelectAddressPCRel - Represent the specified address as pc relative to be represented as [pc+imm].
EVT getSetCCResultType(const DataLayout &DL, LLVMContext &Context, EVT VT) const override
getSetCCResultType - Return the ISD::SETCC ValueType
bool SelectAddressEVXRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const
SelectAddressEVXRegReg - Given the specified addressed, check to see if it can be more efficiently re...
bool isLegalICmpImmediate(int64_t Imm) const override
isLegalICmpImmediate - Return true if the specified immediate is legal icmp immediate,...
MachineBasicBlock * EmitPartwordAtomicBinary(MachineInstr &MI, MachineBasicBlock *MBB, unsigned Opcode, unsigned CmpOpcode=0, unsigned CmpPred=0) const
bool isAccessedAsGotIndirect(SDValue N) const
Instruction * emitLeadingFence(IRBuilderBase &Builder, Instruction *Inst, AtomicOrdering Ord) const override
Inserts in the IR a target-specific intrinsic specifying a fence.
bool isLegalAddImmediate(int64_t Imm) const override
isLegalAddImmediate - Return true if the specified immediate is legal add immediate,...
Common code between 32-bit and 64-bit PowerPC targets.
static PointerType * getUnqual(LLVMContext &C)
This constructs an opaque pointer to an object in the default address space (address space zero).
Wrapper class representing virtual and physical registers.
Definition Register.h:20
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
This class provides iterator support for SDUse operands that use a specific SDNode.
Represents one node in the SelectionDAG.
ArrayRef< SDUse > ops() const
LLVM_ABI void dump() const
Dump this node, for debugging.
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
bool hasOneUse() const
Return true if there is exactly one use of this node.
iterator_range< value_op_iterator > op_values() const
iterator_range< use_iterator > uses()
SDNodeFlags getFlags() const
uint64_t getAsZExtVal() const
Helper method returns the zero-extended integer value of a ConstantSDNode.
unsigned getNumValues() const
Return the number of values defined/returned by this operator.
unsigned getNumOperands() const
Return the number of values used by this operation.
const SDValue & getOperand(unsigned Num) const
uint64_t getConstantOperandVal(unsigned Num) const
Helper method returns the integer value of a ConstantSDNode operand.
bool hasNUsesOfValue(unsigned NUses, unsigned Value) const
Return true if there are exactly NUSES uses of the indicated value.
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
iterator_range< user_iterator > users()
user_iterator user_begin() const
Provide iteration support to walk over all users of an SDNode.
static use_iterator use_end()
Represents a use of a SDNode.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
bool isUndef() const
SDNode * getNode() const
get the SDNode which holds the desired result
bool hasOneUse() const
Return true if there is exactly one node using value ResNo of Node, in exactly one operand.
SDValue getValue(unsigned R) const
EVT getValueType() const
Return the ValueType of the referenced return value.
bool isMachineOpcode() const
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
const SDValue & getOperand(unsigned i) const
uint64_t getConstantOperandVal(unsigned i) const
MVT getSimpleValueType() const
Return the simple ValueType of the referenced return value.
unsigned getMachineOpcode() const
unsigned getOpcode() const
unsigned getNumOperands() const
static SectionKind getMetadata()
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
SDValue getTargetGlobalAddress(const GlobalValue *GV, const SDLoc &DL, EVT VT, int64_t offset=0, unsigned TargetFlags=0)
LLVM_ABI SDValue getStackArgumentTokenFactor(SDValue Chain)
Compute a TokenFactor to force all the incoming stack arguments to be loaded from the stack.
const TargetSubtargetInfo & getSubtarget() const
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, Register Reg, SDValue N)
LLVM_ABI SDValue getMergeValues(ArrayRef< SDValue > Ops, const SDLoc &dl)
Create a MERGE_VALUES node from the given operands.
LLVM_ABI SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
LLVM_ABI SDValue getAllOnesConstant(const SDLoc &DL, EVT VT, bool IsTarget=false, bool IsOpaque=false)
LLVM_ABI MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
LLVM_ABI SDValue getFreeze(SDValue V)
Return a freeze using the SDLoc of the value operand.
LLVM_ABI SDValue makeEquivalentMemoryOrdering(SDValue OldChain, SDValue NewMemOpChain)
If an existing load has uses of its chain, create a token factor node with that chain and the new mem...
LLVM_ABI SDValue getConstantFP(double Val, const SDLoc &DL, EVT VT, bool isTarget=false)
Create a ConstantFPSDNode wrapping a constant value.
LLVM_ABI SDValue getRegister(Register Reg, EVT VT)
LLVM_ABI SDValue getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef< SDValue > Ops, EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags Flags=MachineMemOperand::MOLoad|MachineMemOperand::MOStore, LocationSize Size=LocationSize::precise(0), const AAMDNodes &AAInfo=AAMDNodes())
Creates a MemIntrinsicNode that may produce a result and takes a list of operands.
SDValue getSetCC(const SDLoc &DL, EVT VT, SDValue LHS, SDValue RHS, ISD::CondCode Cond, SDValue Chain=SDValue(), bool IsSignaling=false, SDNodeFlags Flags={})
Helper function to make it easier to build SetCC's if you just have an ISD::CondCode instead of an SD...
bool willNotOverflowSub(bool IsSigned, SDValue N0, SDValue N1) const
Determine if the result of the sub of 2 nodes can never overflow.
LLVM_ABI Align getEVTAlign(EVT MemoryVT) const
Compute the default alignment value for the given type.
void addNoMergeSiteInfo(const SDNode *Node, bool NoMerge)
Set NoMergeSiteInfo to be associated with Node if NoMerge is true.
LLVM_ABI SDValue getNOT(const SDLoc &DL, SDValue Val, EVT VT)
Create a bitwise NOT operation as (XOR Val, -1).
LLVM_ABI SDValue getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst, SDValue Src, SDValue Size, Align DstAlign, Align SrcAlign, bool isVol, bool AlwaysInline, const CallInst *CI, std::optional< bool > OverrideTailCall, MachinePointerInfo DstPtrInfo, MachinePointerInfo SrcPtrInfo, const AAMDNodes &AAInfo=AAMDNodes(), BatchAAResults *BatchAA=nullptr)
const TargetLowering & getTargetLoweringInfo() const
static constexpr unsigned MaxRecursionDepth
SDValue getTargetJumpTable(int JTI, EVT VT, unsigned TargetFlags=0)
SDValue getUNDEF(EVT VT)
Return an UNDEF node. UNDEF does not have a useful SDLoc.
SDValue getCALLSEQ_END(SDValue Chain, SDValue Op1, SDValue Op2, SDValue InGlue, const SDLoc &DL)
Return a new CALLSEQ_END node, which always must have a glue result (to ensure it's not CSE'd).
SDValue getBuildVector(EVT VT, const SDLoc &DL, ArrayRef< SDValue > Ops)
Return an ISD::BUILD_VECTOR node.
LLVM_ABI bool isSplatValue(SDValue V, const APInt &DemandedElts, APInt &UndefElts, unsigned Depth=0) const
Test whether V has a splatted value for all the demanded elements.
LLVM_ABI SDValue getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, SDValue Offset, MachinePointerInfo PtrInfo, EVT SVT, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getBitcast(EVT VT, SDValue V)
Return a bitcast using the SDLoc of the value operand, and casting to the provided type.
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, Register Reg, EVT VT)
SDValue getSelect(const SDLoc &DL, EVT VT, SDValue Cond, SDValue LHS, SDValue RHS, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build Select's if you just have operands and don't want to check...
const DataLayout & getDataLayout() const
SDValue getTargetFrameIndex(int FI, EVT VT)
LLVM_ABI SDValue getTokenFactor(const SDLoc &DL, SmallVectorImpl< SDValue > &Vals)
Creates a new TokenFactor containing Vals.
LLVM_ABI SDValue getStore(SDValue Chain, const SDLoc &dl, SDValue Val, SDValue Ptr, MachinePointerInfo PtrInfo, Align Alignment, MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Helper function to build ISD::STORE nodes.
LLVM_ABI bool areNonVolatileConsecutiveLoads(LoadSDNode *LD, LoadSDNode *Base, unsigned Bytes, int Dist) const
Return true if loads are next to each other and can be merged.
LLVM_ABI SDValue getConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
Create a ConstantSDNode wrapping a constant value.
SDValue getSignedTargetConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI SDValue getMDNode(const MDNode *MD)
Return an MDNodeSDNode which holds an MDNode.
LLVM_ABI void ReplaceAllUsesWith(SDValue From, SDValue To)
Modify anything using 'From' to use 'To' instead.
LLVM_ABI SDValue getCommutedVectorShuffle(const ShuffleVectorSDNode &SV)
Returns an ISD::VECTOR_SHUFFLE node semantically equivalent to the shuffle node in input but with swa...
LLVM_ABI SDValue getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl, EVT VT, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, EVT MemVT, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
LLVM_ABI SDValue getSignedConstant(int64_t Val, const SDLoc &DL, EVT VT, bool isTarget=false, bool isOpaque=false)
SDValue getCALLSEQ_START(SDValue Chain, uint64_t InSize, uint64_t OutSize, const SDLoc &DL)
Return a new CALLSEQ_START node, that starts new call frame, in which InSize bytes are set up inside ...
LLVM_ABI bool SignBitIsZero(SDValue Op, unsigned Depth=0) const
Return true if the sign bit of Op is known to be zero.
SDValue getSelectCC(const SDLoc &DL, SDValue LHS, SDValue RHS, SDValue True, SDValue False, ISD::CondCode Cond, SDNodeFlags Flags=SDNodeFlags())
Helper function to make it easier to build SelectCC's if you just have an ISD::CondCode instead of an...
LLVM_ABI SDValue getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either sign-extending or trunca...
LLVM_ABI SDValue getLoad(EVT VT, const SDLoc &dl, SDValue Chain, SDValue Ptr, MachinePointerInfo PtrInfo, MaybeAlign Alignment=MaybeAlign(), MachineMemOperand::Flags MMOFlags=MachineMemOperand::MONone, const MMOMetadata &Metadata=MMOMetadata())
Loads are not normal binary operators: their result type is not determined by their operands,...
LLVM_ABI bool isKnownNeverZero(SDValue Op, unsigned Depth=0) const
Test whether the given SDValue is known to contain non-zero value(s).
LLVM_ABI SDValue getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT, EVT OpVT)
Convert Op, which must be of integer type, to the integer type VT, by using an extension appropriate ...
LLVM_ABI SDValue getExternalSymbol(const char *Sym, EVT VT)
const TargetMachine & getTarget() const
LLVM_ABI SDValue getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either any-extending or truncat...
LLVM_ABI SDValue getIntPtrConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI SDValue getValueType(EVT)
LLVM_ABI SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
SDValue getTargetConstant(uint64_t Val, const SDLoc &DL, EVT VT, bool isOpaque=false)
LLVM_ABI unsigned ComputeNumSignBits(SDValue Op, unsigned Depth=0) const
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI SDValue getBoolConstant(bool V, const SDLoc &DL, EVT VT, EVT OpVT)
Create a true or false constant of type VT using the target's BooleanContent for type OpVT.
SDValue getTargetBlockAddress(const BlockAddress *BA, EVT VT, int64_t Offset=0, unsigned TargetFlags=0)
LLVM_ABI bool isBaseWithConstantOffset(SDValue Op) const
Return true if the specified operand is an ISD::ADD with a ConstantSDNode on the right-hand side,...
LLVM_ABI SDValue getVectorIdxConstant(uint64_t Val, const SDLoc &DL, bool isTarget=false)
LLVM_ABI void ReplaceAllUsesOfValueWith(SDValue From, SDValue To)
Replace any uses of From with To, leaving uses of other values produced by From.getNode() alone.
MachineFunction & getMachineFunction() const
SDValue getSplatBuildVector(EVT VT, const SDLoc &DL, SDValue Op)
Return a splat ISD::BUILD_VECTOR node, consisting of Op splatted to all elements.
LLVM_ABI SDValue getFrameIndex(int FI, EVT VT, bool isTarget=false)
LLVM_ABI KnownBits computeKnownBits(SDValue Op, unsigned Depth=0) const
Determine which bits of Op are known to be either zero or one and return them in Known.
LLVM_ABI SDValue getRegisterMask(const uint32_t *RegMask)
LLVM_ABI SDValue getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT)
Convert Op, which must be of integer type, to the integer type VT, by either zero-extending or trunca...
LLVM_ABI SDValue getCondCode(ISD::CondCode Cond)
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
SDValue getObjectPtrOffset(const SDLoc &SL, SDValue Ptr, TypeSize Offset)
Create an add instruction with appropriate flags when used for addressing some offset of an object.
LLVMContext * getContext() const
LLVM_ABI SDValue getTargetExternalSymbol(const char *Sym, EVT VT, unsigned TargetFlags=0)
LLVM_ABI SDValue getMCSymbol(MCSymbol *Sym, EVT VT)
LLVM_ABI SDValue CreateStackTemporary(TypeSize Bytes, Align Alignment)
Create a stack temporary based on the size in bytes and the alignment.
SDValue getTargetConstantPool(const Constant *C, EVT VT, MaybeAlign Align=std::nullopt, int Offset=0, unsigned TargetFlags=0)
SDValue getEntryNode() const
Return the token chain corresponding to the entry of the function.
LLVM_ABI std::pair< SDValue, SDValue > SplitScalar(const SDValue &N, const SDLoc &DL, const EVT &LoVT, const EVT &HiVT)
Split the scalar node with EXTRACT_ELEMENT using the provided VTs and return the low/high part.
LLVM_ABI SDValue getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1, SDValue N2, ArrayRef< int > Mask)
Return an ISD::VECTOR_SHUFFLE node.
This SDNode is used to implement the code generator support for the llvm IR shufflevector instruction...
int getMaskElt(unsigned Idx) const
ArrayRef< int > getMask() const
size_type size() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class is used to represent ISD::STORE nodes.
const SDValue & getBasePtr() const
const SDValue & getValue() const
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Class to represent struct types.
Information about stack frame layout on the target.
unsigned getStackAlignment() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
TargetInstrInfo - Interface to description of machine instruction set.
Provides information about what library functions are available for the current target.
void setBooleanVectorContents(BooleanContent Ty)
Specify how the target extends the result of a vector boolean value from a vector of i1 to a wider ty...
void setOperationAction(unsigned Op, MVT VT, LegalizeAction Action)
Indicate that the specified operation does not work with the specified type and indicate what to do a...
bool PredictableSelectIsExpensive
Tells the code generator that select is more expensive than a branch if the branch is usually predict...
virtual bool isShuffleMaskLegal(ArrayRef< int >, EVT) const
Targets can use this to indicate that they only support some VECTOR_SHUFFLE operations,...
EVT getValueType(const DataLayout &DL, Type *Ty, bool AllowUnknown=false) const
Return the EVT corresponding to this LLVM type.
virtual bool shouldExpandBuildVectorWithShuffles(EVT, unsigned DefinedValues) const
void setMinimumBitTestCmps(unsigned Val)
Set the minimum of largest of number of comparisons to generate BitTest.
unsigned MaxStoresPerMemcpyOptSize
Likewise for functions with the OptSize attribute.
MachineBasicBlock * emitPatchPoint(MachineInstr &MI, MachineBasicBlock *MBB) const
Replace/modify any TargetFrameIndex operands with a targte-dependent sequence of memory operands that...
virtual const TargetRegisterClass * getRegClassFor(MVT VT, bool isDivergent=false) const
Return the register class that should be used for the specified value type.
virtual AtomicExpansionKind shouldExpandAtomicRMWInIR(const AtomicRMWInst *RMW) const
Returns how the IR-level AtomicExpand pass should expand the given AtomicRMW, if at all.
virtual Align getPrefLoopAlignment(MachineLoop *ML=nullptr, const MachineBasicBlock *BlockToAlign=nullptr) const
Return the preferred loop alignment.
void setMinStackArgumentAlignment(Align Alignment)
Set the minimum stack alignment of an argument.
MVT getVectorIdxTy(const DataLayout &DL) const
Returns the type to be used for the index operand of: ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT...
const TargetMachine & getTargetMachine() const
unsigned MaxLoadsPerMemcmp
Specify maximum number of load instructions per memcmp call.
virtual bool isZExtFree(Type *FromTy, Type *ToTy) const
Return true if any actual instruction that defines a value of type FromTy implicitly zero-extends the...
void setIndexedLoadAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed load does or does not work with the specified type and indicate w...
void setPrefLoopAlignment(Align Alignment)
Set the target's preferred loop alignment.
void setMaxAtomicSizeInBitsSupported(unsigned SizeInBits)
Set the maximum atomic operation size supported by the backend.
Sched::Preference getSchedulingPreference() const
Return target scheduling preference.
void setMinFunctionAlignment(Align Alignment)
Set the target's minimum function alignment.
bool isOperationCustom(unsigned Op, EVT VT) const
Return true if the operation uses custom lowering, regardless of whether the type is legal or not.
unsigned MaxStoresPerMemsetOptSize
Likewise for functions with the OptSize attribute.
bool hasBigEndianPartOrdering(EVT VT, const DataLayout &DL) const
When splitting a value of the specified type into parts, does the Lo or Hi part come first?
EVT getShiftAmountTy(EVT LHSTy, const DataLayout &DL) const
Returns the type for the shift amount of a shift opcode.
void setBooleanContents(BooleanContent Ty)
Specify how the target extends the result of integer and floating point boolean values from i1 to a w...
unsigned MaxStoresPerMemmove
Specify maximum number of store instructions per memmove call.
void computeRegisterProperties(const TargetRegisterInfo *TRI)
Once all of the register classes are added, this allows us to compute derived properties we expose.
unsigned MaxStoresPerMemmoveOptSize
Likewise for functions with the OptSize attribute.
void addRegisterClass(MVT VT, const TargetRegisterClass *RC)
Add the specified register class as an available regclass for the specified value type.
bool isTypeLegal(EVT VT) const
Return true if the target has native support for the specified value type.
void setIndexedStoreAction(ArrayRef< unsigned > IdxModes, MVT VT, LegalizeAction Action)
Indicate that the specified indexed store does or does not work with the specified type and indicate ...
virtual bool isJumpTableRelative() const
virtual MVT getPointerTy(const DataLayout &DL, uint32_t AS=0) const
Return the pointer type for the given address space, defaults to the pointer type from the data layou...
void setPrefFunctionAlignment(Align Alignment)
Set the target's preferred function alignment.
bool isOperationLegal(unsigned Op, EVT VT) const
Return true if the specified operation is legal on this target.
unsigned MaxStoresPerMemset
Specify maximum number of store instructions per memset call.
void setMinimumJumpTableEntries(unsigned Val)
Indicate the minimum number of blocks to generate jump tables.
void setPartialReduceMLAAction(unsigned Opc, MVT AccVT, MVT InputVT, LegalizeAction Action)
Indicate how a PARTIAL_REDUCE_U/SMLA node with Acc type AccVT and Input type InputVT should be treate...
FPImmAction
How the legalizer should materialize a floating-point immediate.
@ ConstantPool
Load the immediate from the constant pool.
@ Legal
The target can instruction select the immediate natively.
@ Bitcast
Build the immediate as a bitcast of an integer constant with the same bits.
void setTruncStoreAction(MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified truncating store does not work with the specified type and indicate what ...
bool isOperationLegalOrCustom(unsigned Op, EVT VT, bool LegalOnly=false) const
Return true if the specified operation is legal on this target or can be made legal with custom lower...
unsigned MaxLoadsPerMemcmpOptSize
Likewise for functions with the OptSize attribute.
void setMinCmpXchgSizeInBits(unsigned SizeInBits)
Sets the minimum cmpxchg or ll/sc size supported by the backend.
void setStackPointerRegisterToSaveRestore(Register R)
If set to a physical register, this specifies the register that llvm.savestack/llvm....
void AddPromotedToType(unsigned Opc, MVT OrigVT, MVT DestVT)
If Opc/OrigVT is specified as being promoted, the promotion code defaults to trying a larger integer/...
AtomicExpansionKind
Enum that specifies what an atomic load/AtomicRMWInst is expanded to, if at all.
void setCondCodeAction(ArrayRef< ISD::CondCode > CCs, MVT VT, LegalizeAction Action)
Indicate that the specified condition code is or isn't supported on the target and indicate what to d...
void setTargetDAGCombine(ArrayRef< ISD::NodeType > NTs)
Targets should invoke this method for each target independent node that they want to provide a custom...
void setLoadExtAction(unsigned ExtType, MVT ValVT, MVT MemVT, LegalizeAction Action)
Indicate that the specified load with extension does not work with the specified type and indicate wh...
unsigned GatherAllAliasesMaxDepth
Depth that GatherAllAliases should continue looking for chain dependencies when trying to find a more...
NegatibleCost
Enum that specifies when a float negation is beneficial.
virtual bool shouldSignExtendTypeInLibCall(Type *Ty, bool IsSigned) const
Returns true if arguments should be sign-extended in lib calls.
std::vector< ArgListEntry > ArgListTy
unsigned MaxStoresPerMemcpy
Specify maximum number of store instructions per memcpy call.
void setSchedulingPreference(Sched::Preference Pref)
Specify the target scheduling preference.
void setJumpIsExpensive(bool isExpensive=true)
Tells the code generator not to expand logic operations on comparison predicates into separate sequen...
virtual MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const
If supported, return the function entry point symbol.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
virtual const MCExpr * getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI, MCContext &Ctx) const
This returns the relocation base for the given PIC jumptable, the same as getPICJumpTableRelocBase,...
SDValue lowerCmpEqZeroToCtlzSrl(SDValue Op, SelectionDAG &DAG) const
void softenSetCCOperands(SelectionDAG &DAG, EVT VT, SDValue &NewLHS, SDValue &NewRHS, ISD::CondCode &CCCode, const SDLoc &DL, const SDValue OldLHS, const SDValue OldRHS) const
Soften the operands of a comparison.
SDValue getCheaperNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, unsigned Depth=0) const
This is the helper function to return the newly negated expression only when the cost is cheaper.
virtual ConstraintType getConstraintType(StringRef Constraint) const
Given a constraint, return the type of constraint it is for this target.
virtual SDValue LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA, SelectionDAG &DAG) const
Lower TLS global address SDNode for target independent emulated TLS model.
std::pair< SDValue, SDValue > LowerCallTo(CallLoweringInfo &CLI) const
This function lowers an abstract call to a function into an actual call.
bool isPositionIndependent() const
virtual SDValue getNegatedExpression(SDValue Op, SelectionDAG &DAG, bool LegalOps, bool OptForSize, NegatibleCost &Cost, unsigned Depth=0) const
Return the newly negated expression if the cost is not expensive and set the cost in Cost to indicate...
virtual ConstraintWeight getSingleConstraintMatchWeight(AsmOperandInfo &info, const char *constraint) const
Examine constraint string and operand type and determine a weight value.
virtual SDValue getPICJumpTableRelocBase(SDValue Table, SelectionDAG &DAG) const
Returns relocation base for the given PIC jumptable.
virtual std::pair< unsigned, const TargetRegisterClass * > getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const
Given a physical register constraint (e.g.
TargetLowering(const TargetLowering &)=delete
bool isInTailCallPosition(SelectionDAG &DAG, SDNode *Node, SDValue &Chain) const
Check whether a given call node is in tail position within its function.
virtual SDValue getSqrtResultForDenormInput(SDValue Operand, SelectionDAG &DAG) const
Return a target-dependent result if the input operand is not suitable for use with a square root esti...
virtual bool useLoadStackGuardNode(const Module &M) const
If this function returns true, SelectionDAGBuilder emits a LOAD_STACK_GUARD node when it is lowering ...
virtual unsigned combineRepeatedFPDivisors() const
Indicate whether this target prefers to combine FDIVs with the same divisor.
virtual void LowerAsmOperandForConstraint(SDValue Op, StringRef Constraint, std::vector< SDValue > &Ops, SelectionDAG &DAG) const
Lower the specified operand into the Ops vector.
virtual SDValue getSqrtInputTest(SDValue Operand, SelectionDAG &DAG, const DenormalMode &Mode, SDNodeFlags Flags={}) const
Return a target-dependent comparison result if the input operand is suitable for use with a square ro...
virtual bool isGAPlusOffset(SDNode *N, const GlobalValue *&GA, int64_t &Offset) const
Returns true (and the GlobalValue and the offset) if the node is a GlobalAddress + offset.
virtual unsigned getJumpTableEncoding() const
Return the entry encoding for a jump table in the current function.
std::pair< SDValue, SDValue > makeLibCall(SelectionDAG &DAG, RTLIB::LibcallImpl LibcallImpl, EVT RetVT, ArrayRef< SDValue > Ops, MakeLibCallOptions CallOptions, const SDLoc &dl, SDValue Chain=SDValue()) const
Returns a pair of (return value, chain).
Primary interface to the complete machine description for the target machine.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
TLSModel::Model getTLSModel(const GlobalValue *GV) const
Returns the TLS model which should be used for the given global variable.
const STC & getSubtarget(const Function &F) const
This method returns a pointer to the specified type of TargetSubtargetInfo.
bool useEmulatedTLS() const
Returns true if this target uses emulated TLS.
virtual TargetLoweringObjectFile * getObjFileLowering() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
bool shouldAssumeDSOLocal(const GlobalValue *GV) const
TargetOptions Options
CodeModel::Model getCodeModel() const
Returns the code model.
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
unsigned GuaranteedTailCallOpt
GuaranteedTailCallOpt - This flag is enabled when -tailcallopt is specified on the commandline.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:300
LLVM_ABI bool isEmptyTy() const
Return true if this type is empty, that is, it has no elements or all of its elements are empty.
Definition Type.cpp:170
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:272
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition Type.h:268
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
CallInst * Call
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ Cold
Attempts to make code in the caller as efficient as possible under the assumption that the call is no...
Definition CallingConv.h:47
@ Fast
Attempts to make calls as fast as possible (e.g.
Definition CallingConv.h:41
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
LLVM_ABI bool isConstantSplatVectorAllOnes(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are ~0 ...
bool isNON_EXTLoad(const SDNode *N)
Returns true if the specified node is a non-extending load.
NodeType
ISD::NodeType enum - This enum defines the target-independent operators for a SelectionDAG.
Definition ISDOpcodes.h:43
@ SETCC
SetCC operator - This evaluates to a true value iff the condition is true.
Definition ISDOpcodes.h:845
@ MERGE_VALUES
MERGE_VALUES - This node takes multiple discrete operands and returns them all as its individual resu...
Definition ISDOpcodes.h:263
@ STACKRESTORE
STACKRESTORE has two operands, an input chain and a pointer to restore to it returns an output chain.
@ STACKSAVE
STACKSAVE - STACKSAVE has one operand, an input chain.
@ TargetConstantPool
Definition ISDOpcodes.h:191
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition ISDOpcodes.h:516
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition ISDOpcodes.h:47
@ PARTIAL_REDUCE_SMLA
PARTIAL_REDUCE_[U|S]MLA(Accumulator, Input1, Input2) The partial reduction nodes sign or zero extend ...
@ EH_SJLJ_LONGJMP
OUTCHAIN = EH_SJLJ_LONGJMP(INCHAIN, buffer) This corresponds to the eh.sjlj.longjmp intrinsic.
Definition ISDOpcodes.h:170
@ SMUL_LOHI
SMUL_LOHI/UMUL_LOHI - Multiply two integers of type iN, producing a signed/unsigned value of type i[2...
Definition ISDOpcodes.h:277
@ INSERT_SUBVECTOR
INSERT_SUBVECTOR(VECTOR1, VECTOR2, IDX) - Returns a vector with VECTOR2 inserted into VECTOR1.
Definition ISDOpcodes.h:605
@ BSWAP
Byte Swap and Counting operators.
Definition ISDOpcodes.h:805
@ VAEND
VAEND, VASTART - VAEND and VASTART have three operands: an input chain, pointer, and a SRCVALUE.
@ ATOMIC_STORE
OUTCHAIN = ATOMIC_STORE(INCHAIN, val, ptr) This corresponds to "store atomic" instruction.
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ ANY_EXTEND
ANY_EXTEND - Used for integer types. The high bits are undefined.
Definition ISDOpcodes.h:879
@ FMA
FMA - Perform a * b + c with no intermediate rounding step.
Definition ISDOpcodes.h:523
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition ISDOpcodes.h:222
@ GlobalAddress
Definition ISDOpcodes.h:90
@ SINT_TO_FP
[SU]INT_TO_FP - These operators convert integers (whose interpreted sign depends on the first letter)...
Definition ISDOpcodes.h:906
@ CONCAT_VECTORS
CONCAT_VECTORS(VECTOR0, VECTOR1, ...) - Given a number of values of vector type with the same length ...
Definition ISDOpcodes.h:589
@ FADD
Simple binary floating point operators.
Definition ISDOpcodes.h:420
@ ABS
ABS - Determine the unsigned absolute value of a signed integer value of the same bitwidth.
Definition ISDOpcodes.h:765
@ SDIVREM
SDIVREM/UDIVREM - Divide two integers and produce both a quotient and remainder result.
Definition ISDOpcodes.h:282
@ FP16_TO_FP
FP16_TO_FP, FP_TO_FP16 - These operators are used to perform promotions and truncation for half-preci...
@ BITCAST
BITCAST - This operator converts between integer, vector and FP values, as if the value was stored to...
@ BUILD_PAIR
BUILD_PAIR - This is the opposite of EXTRACT_ELEMENT in some ways.
Definition ISDOpcodes.h:256
@ INIT_TRAMPOLINE
INIT_TRAMPOLINE - This corresponds to the init_trampoline intrinsic.
@ FLDEXP
FLDEXP - ldexp, inspired by libm (op0 * 2**op1).
@ STRICT_FSQRT
Constrained versions of libm-equivalent floating point intrinsics.
Definition ISDOpcodes.h:441
@ GlobalTLSAddress
Definition ISDOpcodes.h:91
@ SET_ROUNDING
Set rounding mode.
@ PARTIAL_REDUCE_UMLA
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:870
@ AVGCEILS
AVGCEILS/AVGCEILU - Rounding averaging add - Add two integers using an integer of type i[N+2],...
Definition ISDOpcodes.h:725
@ STRICT_UINT_TO_FP
Definition ISDOpcodes.h:490
@ SCALAR_TO_VECTOR
SCALAR_TO_VECTOR(VAL) - This represents the operation of loading a scalar value into element 0 of the...
Definition ISDOpcodes.h:675
@ TargetExternalSymbol
Definition ISDOpcodes.h:192
@ BR
Control flow instructions. These all have token chains.
@ TargetJumpTable
Definition ISDOpcodes.h:190
@ PREFETCH
PREFETCH - This corresponds to a prefetch intrinsic.
@ FSINCOS
FSINCOS - Compute both fsin and fcos as a single operation.
@ FNEG
Perform various unary floating-point operations inspired by libm.
@ BR_CC
BR_CC - Conditional branch.
@ SSUBO
Same for subtraction.
Definition ISDOpcodes.h:355
@ BR_JT
BR_JT - Jumptable branch.
@ FCANONICALIZE
Returns platform specific canonical encoding of a floating point number.
Definition ISDOpcodes.h:546
@ IS_FPCLASS
Performs a check of floating point class property, defined by IEEE-754.
Definition ISDOpcodes.h:553
@ SSUBSAT
RESULT = [US]SUBSAT(LHS, RHS) - Perform saturation subtraction on 2 integers with the same bit width ...
Definition ISDOpcodes.h:377
@ SELECT
Select(COND, TRUEVAL, FALSEVAL).
Definition ISDOpcodes.h:822
@ ATOMIC_LOAD
Val, OUTCHAIN = ATOMIC_LOAD(INCHAIN, ptr) This corresponds to "load atomic" instruction.
@ EXTRACT_ELEMENT
EXTRACT_ELEMENT - This is used to get the lower or upper (determined by a Constant,...
Definition ISDOpcodes.h:249
@ SPLAT_VECTOR
SPLAT_VECTOR(VAL) - Returns a vector with the scalar value VAL duplicated in all lanes.
Definition ISDOpcodes.h:682
@ VACOPY
VACOPY - VACOPY has 5 operands: an input chain, a destination pointer, a source pointer,...
@ SADDO
RESULT, BOOL = [SU]ADDO(LHS, RHS) - Overflow-aware nodes for addition.
Definition ISDOpcodes.h:351
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition ISDOpcodes.h:187
@ GET_ROUNDING
Returns current rounding mode: -1 Undefined 0 Round to 0 1 Round to nearest, ties to even 2 Round to ...
Definition ISDOpcodes.h:996
@ MULHU
MULHU/MULHS - Multiply high - Multiply two integers of type iN, producing an unsigned/signed value of...
Definition ISDOpcodes.h:714
@ SHL
Shift and rotation operations.
Definition ISDOpcodes.h:787
@ VECTOR_SHUFFLE
VECTOR_SHUFFLE(VEC1, VEC2) - Returns a vector, of the same type as VEC1/VEC2.
Definition ISDOpcodes.h:659
@ EXTRACT_SUBVECTOR
EXTRACT_SUBVECTOR(VECTOR, IDX) - Returns a subvector from VECTOR.
Definition ISDOpcodes.h:619
@ FMINNUM_IEEE
FMINNUM_IEEE/FMAXNUM_IEEE - Same as FMINNUM/FMAXNUM, except that a signaling NaN operand deterministi...
@ EXTRACT_VECTOR_ELT
EXTRACT_VECTOR_ELT(VECTOR, IDX) - Returns a single element from VECTOR identified by the (potentially...
Definition ISDOpcodes.h:581
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition ISDOpcodes.h:226
@ ZERO_EXTEND
ZERO_EXTEND - Used for integer types, zeroing the new bits.
Definition ISDOpcodes.h:876
@ SELECT_CC
Select with condition operator - This selects between a true value and a false value (ops #2 and #3) ...
Definition ISDOpcodes.h:837
@ ATOMIC_CMP_SWAP
Val, OUTCHAIN = ATOMIC_CMP_SWAP(INCHAIN, ptr, cmp, swap) For double-word atomic operations: ValLo,...
@ FMINNUM
FMINNUM/FMAXNUM - Same semantics as the llvm.minnum/maxnum intrinsics.
@ DYNAMIC_STACKALLOC
DYNAMIC_STACKALLOC - Allocate some number of bytes on the stack aligned to a specified boundary.
@ SIGN_EXTEND_INREG
SIGN_EXTEND_INREG - This operator atomically performs a SHL/SRA pair to sign extend a small value in ...
Definition ISDOpcodes.h:914
@ SMIN
[US]{MIN/MAX} - Binary minimum or maximum of signed or unsigned integers.
Definition ISDOpcodes.h:745
@ FP_EXTEND
X = FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
@ VSELECT
Select with a vector condition (op #0) and two vector operands (ops #1 and #2), returning a vector re...
Definition ISDOpcodes.h:831
@ UADDO_CARRY
Carry-using nodes for multiple precision addition and subtraction.
Definition ISDOpcodes.h:331
@ STRICT_SINT_TO_FP
STRICT_[US]INT_TO_FP - Convert a signed or unsigned integer to a floating point value.
Definition ISDOpcodes.h:489
@ INLINEASM_BR
INLINEASM_BR - Branching version of inline asm. Used by asm-goto.
@ EH_DWARF_CFA
EH_DWARF_CFA - This node represents the pointer to the DWARF Canonical Frame Address (CFA),...
Definition ISDOpcodes.h:152
@ FRAMEADDR
FRAMEADDR, RETURNADDR - These nodes represent llvm.frameaddress and llvm.returnaddress on the DAG.
Definition ISDOpcodes.h:112
@ STRICT_FP_TO_UINT
Definition ISDOpcodes.h:483
@ STRICT_FP_ROUND
X = STRICT_FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision ...
Definition ISDOpcodes.h:505
@ STRICT_FP_TO_SINT
STRICT_FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:482
@ FP_TO_SINT
FP_TO_[US]INT - Convert a floating point value to a signed or unsigned integer.
Definition ISDOpcodes.h:952
@ READCYCLECOUNTER
READCYCLECOUNTER - This corresponds to the readcyclecounter intrinsic.
@ STRICT_FP_EXTEND
X = STRICT_FP_EXTEND(Y) - Extend a smaller FP type into a larger FP type.
Definition ISDOpcodes.h:510
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition ISDOpcodes.h:757
@ TRAP
TRAP - Trapping instruction.
@ INTRINSIC_WO_CHAIN
RESULT = INTRINSIC_WO_CHAIN(INTRINSICID, arg1, arg2, ...) This node represents a target intrinsic fun...
Definition ISDOpcodes.h:207
@ SCMP
[US]CMP - 3-way comparison of signed or unsigned integers.
Definition ISDOpcodes.h:753
@ STRICT_FADD
Constrained versions of the binary floating point operators.
Definition ISDOpcodes.h:430
@ INSERT_VECTOR_ELT
INSERT_VECTOR_ELT(VECTOR, VAL, IDX) - Returns VECTOR with the element at IDX replaced with VAL.
Definition ISDOpcodes.h:570
@ TokenFactor
TokenFactor - This node takes multiple tokens as input and produces a single token result.
Definition ISDOpcodes.h:55
@ FP_ROUND
X = FP_ROUND(Y, TRUNC) - Rounding 'Y' from a larger floating point type down to the precision of the ...
Definition ISDOpcodes.h:985
@ INLINEASM
INLINEASM - Represents an inline asm block.
@ STRICT_FNEARBYINT
Definition ISDOpcodes.h:461
@ EH_SJLJ_SETJMP
RESULT, OUTCHAIN = EH_SJLJ_SETJMP(INCHAIN, buffer) This corresponds to the eh.sjlj....
Definition ISDOpcodes.h:164
@ TRUNCATE
TRUNCATE - Completely drop the high bits.
Definition ISDOpcodes.h:882
@ VAARG
VAARG - VAARG has four operands: an input chain, a pointer, a SRCVALUE, and the alignment.
@ BRCOND
BRCOND - Conditional branch.
@ SHL_PARTS
SHL_PARTS/SRA_PARTS/SRL_PARTS - These operators are used for expanded integer shift operations.
Definition ISDOpcodes.h:859
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition ISDOpcodes.h:64
@ FCOPYSIGN
FCOPYSIGN(X, Y) - Return the value of X with the sign of Y.
Definition ISDOpcodes.h:539
@ PARTIAL_REDUCE_SUMLA
@ SADDSAT
RESULT = [US]ADDSAT(LHS, RHS) - Perform saturation addition on 2 integers with the same bit width (W)...
Definition ISDOpcodes.h:368
@ CALLSEQ_START
CALLSEQ_START/CALLSEQ_END - These operators mark the beginning and end of a call sequence,...
@ GET_DYNAMIC_AREA_OFFSET
GET_DYNAMIC_AREA_OFFSET - get offset from native SP to the address of the most recent dynamic alloca.
@ ABDS
ABDS/ABDU - Absolute difference - Return the absolute difference between two numbers interpreted as s...
Definition ISDOpcodes.h:740
@ ADJUST_TRAMPOLINE
ADJUST_TRAMPOLINE - This corresponds to the adjust_trampoline intrinsic.
@ INTRINSIC_W_CHAIN
RESULT,OUTCHAIN = INTRINSIC_W_CHAIN(INCHAIN, INTRINSICID, arg1, ...) This node represents a target in...
Definition ISDOpcodes.h:215
@ TargetGlobalTLSAddress
Definition ISDOpcodes.h:188
@ BUILD_VECTOR
BUILD_VECTOR(ELT0, ELT1, ELT2, ELT3,...) - Return a fixed-width vector with the specified,...
Definition ISDOpcodes.h:561
bool isNormalStore(const SDNode *N)
Returns true if the specified node is a non-truncating and unindexed store.
bool isZEXTLoad(const SDNode *N)
Returns true if the specified node is a ZEXTLOAD.
bool isUNINDEXEDLoad(const SDNode *N)
Returns true if the specified node is an unindexed load.
bool isEXTLoad(const SDNode *N)
Returns true if the specified node is a EXTLOAD.
LLVM_ABI bool isBuildVectorAllZeros(const SDNode *N)
Return true if the specified node is a BUILD_VECTOR where all of the elements are 0 or undef.
bool isSignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs a signed comparison when used with integer o...
MemIndexedMode
MemIndexedMode enum - This enum defines the load / store indexed addressing modes.
bool isSEXTLoad(const SDNode *N)
Returns true if the specified node is a SEXTLOAD.
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
LoadExtType
LoadExtType enum - This enum defines the three variants of LOADEXT (load with extension).
bool isUnsignedIntSetCC(CondCode Code)
Return true if this is a setcc instruction that performs an unsigned comparison when used with intege...
bool isNormalLoad(const SDNode *N)
Returns true if the specified node is a non-extending and unindexed load.
This namespace contains an enum with a value for every intrinsic/builtin function known by LLVM.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
constexpr MCPhysReg SP
@ VecShuffle
Definition NVPTX.h:273
@ MO_TLSLDM_FLAG
MO_TLSLDM_FLAG - on AIX the ML relocation type is only valid for a reference to a TOC symbol from the...
Definition PPC.h:157
@ MO_PIC_LO_FLAG
MO_PIC_LO_FLAG = MO_PIC_FLAG | MO_LO.
Definition PPC.h:205
@ MO_TPREL_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TPREL_FLAG.
Definition PPC.h:208
@ MO_GOT_TPREL_PCREL_FLAG
MO_GOT_TPREL_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:183
@ MO_GOT_PCREL_FLAG
MO_GOT_PCREL_FLAG = MO_PCREL_FLAG | MO_GOT_FLAG.
Definition PPC.h:214
@ MO_TLSGDM_FLAG
MO_TLSGDM_FLAG - If this bit is set the symbol reference is relative to the region handle of TLS Gene...
Definition PPC.h:165
@ MO_PCREL_FLAG
MO_PCREL_FLAG - If this bit is set, the symbol reference is relative to the current instruction addre...
Definition PPC.h:132
@ MO_TLSLD_FLAG
MO_TLSLD_FLAG - If this bit is set the symbol reference is relative to TLS Local Dynamic model.
Definition PPC.h:161
@ MO_TLS_PCREL_FLAG
MO_TPREL_PCREL_FLAG = MO_PCREL_FLAG | MO_TLS.
Definition PPC.h:211
@ MO_TPREL_HA
Definition PPC.h:190
@ MO_PLT
On PPC, the 12 bits are not enough for all target operand flags.
Definition PPC.h:124
@ MO_TLS
Symbol for VK_TLS fixup attached to an ADD instruction.
Definition PPC.h:199
@ MO_TPREL_FLAG
MO_TPREL_FLAG - If this bit is set, the symbol reference is relative to the thread pointer and the sy...
Definition PPC.h:151
@ MO_TPREL_LO
Definition PPC.h:189
@ MO_LO
MO_LO, MO_HA - lo16(symbol) and ha16(symbol)
Definition PPC.h:186
@ MO_GOT_TLSLD_PCREL_FLAG
MO_GOT_TLSLD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:177
@ MO_PIC_HA_FLAG
MO_PIC_HA_FLAG = MO_PIC_FLAG | MO_HA.
Definition PPC.h:202
@ MO_TLSGD_FLAG
MO_TLSGD_FLAG - If this bit is set the symbol reference is relative to TLS General Dynamic model for ...
Definition PPC.h:146
@ MO_GOT_TLSGD_PCREL_FLAG
MO_GOT_TLSGD_PCREL_FLAG - A combintaion of flags, if these bits are set they should produce the reloc...
Definition PPC.h:171
@ MO_HA
Definition PPC.h:187
@ MO_PIC_FLAG
MO_PIC_FLAG - If this bit is set, the symbol reference is relative to the function's picbase,...
Definition PPC.h:128
@ MFOCRF
R32 = MFOCRF(CRREG, INFLAG) - Represents the MFOCRF instruction.
@ VADD_SPLAT
VRRC = VADD_SPLAT Elt, EltSize - Temporary node to be expanded during instruction selection to optimi...
@ PPC32_PICGOT
GPRC = address of GLOBAL_OFFSET_TABLE.
@ GlobalBaseReg
The result of the mflr at function entry, used for PIC code.
@ SRA_ADDZE
The combination of sra[wd]i and addze used to implemented signed integer division by a power of 2.
Define some predicates that are used for node matching.
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
SDValue get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG)
get_VSPLTI_elt - If this is a build_vector of constants which can be formed by using a vspltis[bhw] i...
bool isXXBRDShuffleMask(ShuffleVectorSDNode *N)
isXXBRDShuffleMask - Return true if this is a shuffle mask suitable for a XXBRD instruction.
bool isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for a VRGH* instruction with the ...
bool isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a VPKUDUM instruction.
bool isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGEOShuffleMask - Return true if this is a shuffle mask suitable for a VMRGEW or VMRGOW instructi...
bool isXXBRQShuffleMask(ShuffleVectorSDNode *N)
isXXBRQShuffleMask - Return true if this is a shuffle mask suitable for a XXBRQ instruction.
bool isXXBRWShuffleMask(ShuffleVectorSDNode *N)
isXXBRWShuffleMask - Return true if this is a shuffle mask suitable for a XXBRW instruction.
bool isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, bool &Swap, bool IsLE)
isXXPERMDIShuffleMask - Return true if this is a shuffle mask suitable for a XXPERMDI instruction.
bool isXXBRHShuffleMask(ShuffleVectorSDNode *N)
isXXBRHShuffleMask - Return true if this is a shuffle mask suitable for a XXBRH instruction.
unsigned getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize, SelectionDAG &DAG)
getSplatIdxForPPCMnemonics - Return the splat index as a value that is appropriate for PPC mnemonics ...
bool isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, bool &Swap, bool IsLE)
isXXSLDWIShuffleMask - Return true if this is a shuffle mask suitable for a XXSLDWI instruction.
FastISel * createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo, const LibcallLoweringInfo *LibcallLowering)
int isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift amount, otherwise return -1.
bool isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG)
isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for a VRGL* instruction with the ...
bool isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts, unsigned &InsertAtByte, bool &Swap, bool IsLE)
isXXINSERTWMask - Return true if this VECTOR_SHUFFLE can be handled by the XXINSERTW instruction intr...
bool isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize)
isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand specifies a splat of a singl...
bool isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a VPKUWUM instruction.
bool isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG)
isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a VPKUHUM instruction.
Invariant opcodes: All instruction sets have these as their low opcodes.
@ XMC_PR
Program Code.
Definition XCOFF.h:106
@ XTY_ER
External reference.
Definition XCOFF.h:242
initializer< Ty > init(const Ty &Val)
@ User
could "use" a pointer
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
iterator end() const
Definition BasicBlock.h:89
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
static bool isIndirectCall(const MachineInstr &MI)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
bool checkConvertToNonDenormSingle(APFloat &ArgAPFloat)
LLVM_ABI void GetReturnInfo(CallingConv::ID CC, Type *ReturnType, AttributeList attr, SmallVectorImpl< ISD::OutputArg > &Outs, const TargetLowering &TLI, const DataLayout &DL)
Given an LLVM IR type and return type attributes, compute the return value EVTs and flags,...
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
InstructionCost Cost
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
LLVM_ABI bool isNullConstant(SDValue V)
Returns true if V is a constant integer zero.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
@ Known
Known to have no common set bits.
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
bool CCAssignFn(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
CCAssignFn - This function assigns a location for Val, updating State to reflect the change.
bool isAligned(Align Lhs, uint64_t SizeInBytes)
Checks that SizeInBytes is a multiple of the alignment.
Definition Alignment.h:139
bool isIntS16Immediate(SDNode *N, int16_t &Imm)
isIntS16Immediate - This method tests to see if the node is either a 32-bit or 64-bit immediate,...
@ Load
The value being inserted comes from a load (InsertElement only).
@ Store
The extracted value is stored (ExtractElement only).
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
static bool isRunOfOnes64(uint64_t Val, unsigned &MB, unsigned &ME)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool RetCC_PPC(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
bool CC_PPC64_ELF(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
unsigned M1(unsigned Val)
Definition VE.h:394
bool isReleaseOrStronger(AtomicOrdering AO)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool convertToNonDenormSingle(APInt &ArgAPInt)
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
bool CC_PPC32_SVR4_ByVal(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
bool CC_PPC32_SVR4(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
constexpr RegState getDefRegState(bool B)
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
bool RetCC_PPC_Cold(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
@ Success
The lock was released successfully.
LLVM_ABI bool isOneOrOneSplat(SDValue V, bool AllowUndefs=false)
Return true if the value is a constant 1 integer or a splatted vector of a constant 1 integer (with n...
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
const unsigned PerfectShuffleTable[6561+1]
AtomicOrdering
Atomic ordering for LLVM's memory model.
bool isIntS34Immediate(SDNode *N, int64_t &Imm)
isIntS34Immediate - This method tests if value of node given can be accurately represented as a sign ...
To bit_cast(const From &from) noexcept
Definition bit.h:90
@ Mul
Product of integers.
@ Xor
Bitwise or logical XOR of integers.
@ And
Bitwise or logical AND of integers.
@ Sub
Subtraction of integers.
@ Add
Sum of integers.
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
@ Fast
Assign the register banks as fast as possible (default).
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
LLVM_ABI bool isPhysRegUsedAfter(Register Reg, MachineBasicBlock::iterator MBI)
Check if physical register Reg is used after MBI.
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI ConstantSDNode * isConstOrConstSplat(SDValue N, bool AllowUndefs=false, bool AllowTruncation=false)
Returns the SDNode if it is a constant splat BuildVector or constant int.
bool isAcquireOrStronger(AtomicOrdering AO)
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition MathExtras.h:554
constexpr unsigned BitWidth
bool CC_PPC32_SVR4_VarArg(unsigned ValNo, MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags, Type *OrigTy, CCState &State)
ExceptionHandling
Definition CodeGen.h:54
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition MathExtras.h:572
static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME)
Returns true iff Val consists of one contiguous run of 1s with any number of 0s on either side.
@ Increment
Incrementally increasing token ID.
Definition AllocToken.h:26
@ Enabled
Convert any .debug_str_offsets tables to DWARF64 if needed.
Definition DWP.h:31
T bit_floor(T Value)
Returns the largest integral power of two no greater than Value if Value is nonzero.
Definition bit.h:347
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
LLVM_ABI bool isAllOnesConstant(SDValue V)
Returns true if V is an integer constant with all bits set.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
#define N
This is used by foldLoadsRecursive() to capture a Root Load node which is of type or(load,...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
constexpr uint64_t value() const
This is a hole in the type system and should not be abused.
Definition Alignment.h:82
Represent subnormal handling kind for floating point instruction inputs and outputs.
Extended Value Type.
Definition ValueTypes.h:35
EVT changeVectorElementTypeToInteger() const
Return a vector with the same number of elements as this vector, but with the element type converted ...
Definition ValueTypes.h:90
TypeSize getStoreSize() const
Return the number of bytes overwritten by a store of the specified value type.
Definition ValueTypes.h:418
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition ValueTypes.h:145
static EVT getVectorVT(LLVMContext &Context, EVT VT, unsigned NumElements, bool IsScalable=false)
Returns the EVT that represents a vector NumElements in length, where each element is of type VT.
Definition ValueTypes.h:70
bool bitsGT(EVT VT) const
Return true if this has more bits than VT.
Definition ValueTypes.h:307
bool bitsLT(EVT VT) const
Return true if this has less bits than VT.
Definition ValueTypes.h:323
bool isFloatingPoint() const
Return true if this is a FP or a vector FP type.
Definition ValueTypes.h:155
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition ValueTypes.h:396
uint64_t getScalarSizeInBits() const
Definition ValueTypes.h:408
MVT getSimpleVT() const
Return the SimpleValueType held in the specified simple EVT.
Definition ValueTypes.h:339
static EVT getIntegerVT(LLVMContext &Context, unsigned BitWidth)
Returns the EVT that represents an integer with the given number of bits.
Definition ValueTypes.h:61
uint64_t getFixedSizeInBits() const
Return the size of the specified fixed width value type in bits.
Definition ValueTypes.h:404
bool isVector() const
Return true if this is a vector value type.
Definition ValueTypes.h:176
EVT getScalarType() const
If this is a vector type, return the element type, otherwise return this.
Definition ValueTypes.h:346
LLVM_ABI Type * getTypeForEVT(LLVMContext &Context) const
This method returns an LLVM type corresponding to the specified EVT.
EVT getVectorElementType() const
Given a vector type, return the type of each element.
Definition ValueTypes.h:351
bool isExtended() const
Test if the given EVT is extended (as opposed to being simple).
Definition ValueTypes.h:150
bool isScalarInteger() const
Return true if this is an integer, but not a vector.
Definition ValueTypes.h:165
unsigned getVectorNumElements() const
Given a vector type, return the number of elements it contains.
Definition ValueTypes.h:359
EVT getHalfNumVectorElementsVT(LLVMContext &Context) const
Definition ValueTypes.h:484
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition ValueTypes.h:160
unsigned getByValSize() const
void setByValSize(unsigned S)
Align getNonZeroByValAlign() const
OutputArg - This struct carries flags and a value for a single outgoing (actual) argument or outgoing...
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
const APInt & getConstant() const
Returns the value when all bits have a known value.
Definition KnownBits.h:58
This class contains a discriminated union of information about pointers in memory operands,...
static LLVM_ABI MachinePointerInfo getStack(MachineFunction &MF, int64_t Offset, uint8_t ID=0)
Stack pointer relative access.
MachinePointerInfo getWithOffset(int64_t O) const
static LLVM_ABI MachinePointerInfo getGOT(MachineFunction &MF)
Return a MachinePointerInfo record that refers to a GOT entry.
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Structure that collects some common arguments that get passed around between the functions for call l...
These are IR-level optimization flags that may be propagated to SDNodes.
void setNoFPExcept(bool b)
This represents a list of ValueType's that has been intern'd by a SelectionDAG.
This represents an addressing mode of: BaseGV + BaseOffs + BaseReg + Scale*ScaleReg + ScalableOffset*...
This contains information for each constraint that we are lowering.
This structure contains all information that is necessary for lowering calls.
CallLoweringInfo & setIsPostTypeLegalization(bool Value=true)
CallLoweringInfo & setLibCallee(CallingConv::ID CC, Type *ResultType, SDValue Target, ArgListTy &&ArgsList)
SmallVector< ISD::InputArg, 32 > Ins
CallLoweringInfo & setZExtResult(bool Value=true)
CallLoweringInfo & setDebugLoc(const SDLoc &dl)
CallLoweringInfo & setTailCall(bool Value=true)
CallLoweringInfo & setSExtResult(bool Value=true)
SmallVector< ISD::OutputArg, 32 > Outs
CallLoweringInfo & setChain(SDValue InChain)
LLVM_ABI void AddToWorklist(SDNode *N)
LLVM_ABI SDValue CombineTo(SDNode *N, ArrayRef< SDValue > To, bool AddTo=true)
This structure is used to pass arguments to makeLibCall function.